ECUiVADE commited on
Commit
784a0f4
1 Parent(s): a4f23a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -89
app.py CHANGED
@@ -1,144 +1,262 @@
 
1
  import gradio as gr
2
  import json
3
  from datetime import datetime
4
- import random
5
- import string
6
- import re
7
- from google.oauth2 import service_account
8
  from googleapiclient.discovery import build
 
9
  from googleapiclient.http import MediaFileUpload
 
 
10
  from huggingface_hub import snapshot_download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- class ChatbotApp:
13
- def __init__(self, repo_name, model_file, service_account_file, folder_id):
14
- self.repo_name = repo_name
15
- self.model_file = model_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  self.service_account_file = service_account_file
 
17
  self.folder_id = folder_id
 
18
  self.chat_history = []
19
  self.chat_log_history = []
20
  self.isFirstRun = True
21
- self.initContext = "Your initial context here"
22
  self.context = ""
23
- self.Name = ""
24
- self.Occupation = ""
25
- self.Ethnicity = ""
26
- self.Gender = ""
27
- self.Age = ""
28
- self.YearsOfExp = ""
29
  self.agreed = False
30
- self.unique_id = self.generate_unique_id()
31
  self.service = self.get_drive_service()
32
  self.app = self.create_app()
33
- self.snapshot_download_model()
34
-
35
- def snapshot_download_model(self):
36
- print(f'Fetching model: {self.repo_name}, {self.model_file}')
37
- snapshot_download(repo_id=self.repo_name, local_dir=".", allow_patterns=[self.model_file])
38
- print('Done fetching model.')
39
-
40
- def generate_unique_id(self):
41
- letters = ''.join(random.choices(string.ascii_letters, k=3))
42
- digits = ''.join(random.choices(string.digits, k=3))
43
- return letters + digits
44
 
45
  def get_drive_service(self):
46
  credentials = service_account.Credentials.from_service_account_file(
47
- self.service_account_file, scopes=['https://www.googleapis.com/auth/drive'])
48
- service = build('drive', 'v3', credentials=credentials)
49
- print("Google Drive service created.")
50
- return service
51
 
52
  def search_file(self):
 
53
  query = f"name = '{self.chat_log_name}' and '{self.folder_id}' in parents and trashed = false"
54
  response = self.service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
55
- return response.get('files', [])
56
-
57
- def strip_text(self, text):
 
 
 
 
 
 
58
  pattern = r"\(.*?\)|<.*?>.*"
 
 
59
  cleaned_text = re.sub(pattern, "", text)
 
60
  return cleaned_text
61
-
62
  def upload_to_google_drive(self):
63
- self.chat_log_name = f'chat_log_for_{self.unique_id}_{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.json'
64
- existing_files = self.search_file()
 
65
  data = {
66
- "Unique ID": self.unique_id,
67
- "chat_history": self.chat_log_history
68
- }
69
-
 
 
 
 
 
 
70
  with open(self.chat_log_name, "w") as log_file:
71
- json.dump(data, log_file, indent=4)
72
-
73
  if not existing_files:
 
74
  file_metadata = {
75
  'name': self.chat_log_name,
76
- 'parents': [self.folder_id],
77
- 'mimeType': 'application/json'
78
  }
79
  media = MediaFileUpload(self.chat_log_name, mimetype='application/json')
80
  file = self.service.files().create(body=file_metadata, media_body=media, fields='id').execute()
81
  print(f"Uploaded new file with ID: {file.get('id')}")
82
  else:
 
 
83
  file_id = existing_files[0]['id']
84
  media = MediaFileUpload(self.chat_log_name, mimetype='application/json')
85
  updated_file = self.service.files().update(fileId=file_id, media_body=media).execute()
86
  print(f"Updated existing file with ID: {updated_file.get('id')}")
87
 
88
- def generate(self, prompt, history):
89
- if not self.agreed:
90
- output = "Please agree to the terms and conditions to start chatting."
91
- self.chat_history.append(("System", output))
92
- else:
93
  if self.isFirstRun:
94
  self.context = self.initContext
95
  self.isFirstRun = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- cleaned_prompt = self.strip_text(prompt)
98
- cleaned_response = f"Simulated response for: {cleaned_prompt}" # Placeholder for actual model response
99
-
100
- self.chat_history.append((cleaned_prompt, cleaned_response))
101
- self.chat_log_history.append({"user": cleaned_prompt, "bot": cleaned_response})
102
- self.upload_to_google_drive()
103
-
104
- return self.chat_history
105
 
106
- def reset_all(self):
 
 
 
 
 
 
 
 
 
107
  self.chat_history = []
108
  self.chat_log_history = []
109
  self.isFirstRun = True
110
- self.unique_id = self.generate_unique_id()
111
- print("All components have been reset.")
112
- return "Reset completed."
113
-
114
- def create_app(self):
115
- with gr.Blocks() as app:
116
- gr.Markdown("## Chatbot Interface")
117
- agree_status = gr.Checkbox(label="I agree to the terms and conditions.")
118
- chatbot_interface = gr.Chatbot()
119
- msg_input = gr.Textbox(label="Type your message here")
120
- send_button = gr.Button("Send")
121
- reset_button = gr.Button("Reset")
122
-
123
- def update_agreed_status(status):
124
- self.agreed = status
125
- return "You can now start chatting."
126
 
127
- agree_status.change(update_agreed_status, inputs=[agree_status], outputs=[])
 
 
 
 
128
 
129
- send_button.click(self.generate, inputs=[msg_input, chatbot_interface], outputs=chatbot_interface)
130
- reset_button.click(self.reset_all, inputs=[], outputs=[])
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  return app
133
 
134
- def launch(self):
135
- self.app.launch(debug=True)
136
-
137
- # Example usage
138
- repo_name = 'YourRepoName/YourModelName'
139
- model_file = "YourModelFileName"
140
- service_account_file = '/path/to/your/service_account_creds.json'
141
- folder_id = 'YourGoogleDriveFolderID'
142
-
143
- chatbot_app = ChatbotApp(repo_name, model_file, service_account_file, folder_id)
144
- chatbot_app.launch()
 
1
+ from huggingface_hub import InferenceClient
2
  import gradio as gr
3
  import json
4
  from datetime import datetime
5
+ import os
6
+ from google_auth_oauthlib.flow import InstalledAppFlow
 
 
7
  from googleapiclient.discovery import build
8
+ from google.oauth2 import service_account
9
  from googleapiclient.http import MediaFileUpload
10
+ from pathlib import Path
11
+ import argparse
12
  from huggingface_hub import snapshot_download
13
+ import random
14
+ import string
15
+ import re
16
+ from llama_cpp import Llama
17
+
18
+
19
+ repo_name = 'TheBloke/OpenHermes-2.5-Mistral-7B-GGUF'
20
+ model_file = "openhermes-2.5-mistral-7b.Q4_K_M.gguf"
21
+ SCOPES = ['https://www.googleapis.com/auth/drive']
22
+ SERVICE_ACCOUNT_FILE = '/home/user/app/service_account_creds.json'
23
+ folder_id = '1Hjbu7FmuVs0Yz8y_veo6SzY_2tc48OWt'
24
+
25
+ initContext = """<|im_start|>You are playing the role of an aggressive patient called Barry Lawson. Barry has been waiting for hours at the hospital with severe pain in his chest and hasn't been seen yet. You are incredibly frustrated and angry that things are taking so long, you will only calm down if your concerns are addressed. Waiting will only make you more angry and aggressive towards the staff. At any moment you could break into a RAGE! Make sure you don't censor swear words. Make sure to explain your emotional state and thinking before responding, for example, Barry: (tired of waiting and very angry) What the fuck do I have to do around here to get some treatment!"""
26
+ unique_id = ""
27
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
28
 
29
+
30
+ def load_model():
31
+ llm = Llama(model_path=model_file, model_type="mistral",n_gpu_layers=-1,n_ctx = 2048)
32
+ return llm
33
+
34
+ def generate_unique_id():
35
+ # Generate a random sequence of 3 letters and 3 digits
36
+ letters = ''.join(random.choices(string.ascii_letters, k=3))
37
+ digits = ''.join(random.choices(string.digits, k=3))
38
+ unique_id = letters + digits
39
+ return unique_id
40
+
41
+ print('Fetching model:', repo_name, model_file)
42
+ snapshot_download(repo_id=repo_name, local_dir=".", allow_patterns=model_file)
43
+ print('Done fetching model:')
44
+
45
+
46
+ class ChatbotAPP:
47
+ def __init__(self,model,service_account_file,scopes,folder_id,unique_id,initContext):
48
+ self.llm = model
49
  self.service_account_file = service_account_file
50
+ self.scopes = scopes
51
  self.folder_id = folder_id
52
+ self.unique_id = unique_id
53
  self.chat_history = []
54
  self.chat_log_history = []
55
  self.isFirstRun = True
56
+ self.initContext = initContext
57
  self.context = ""
 
 
 
 
 
 
58
  self.agreed = False
 
59
  self.service = self.get_drive_service()
60
  self.app = self.create_app()
61
+ self.chat_log_name = ""
 
 
 
 
 
 
 
 
 
 
62
 
63
  def get_drive_service(self):
64
  credentials = service_account.Credentials.from_service_account_file(
65
+ self.service_account_file, scopes=self.scopes)
66
+ self.service = build('drive', 'v3', credentials=credentials)
67
+ print("Google Service Created")
68
+ return self.service
69
 
70
  def search_file(self):
71
+ #Search for a file by name in the specified Google Drive folder.
72
  query = f"name = '{self.chat_log_name}' and '{self.folder_id}' in parents and trashed = false"
73
  response = self.service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
74
+ files = response.get('files', [])
75
+ if not files:
76
+ print(f"Chat log {self.chat_log_name} does not exist")
77
+ else:
78
+ print(f"Chat log {self.chat_log_name} exist")
79
+ return files
80
+
81
+ def strip_text(self,text):
82
+ # Pattern to match text inside parentheses or angle brackets and any text following angle brackets
83
  pattern = r"\(.*?\)|<.*?>.*"
84
+
85
+ # Use re.sub() to replace the matched text with an empty string
86
  cleaned_text = re.sub(pattern, "", text)
87
+
88
  return cleaned_text
89
+
90
  def upload_to_google_drive(self):
91
+ existing_files = search_file()
92
+ print(existing_files)
93
+
94
  data = {
95
+ #"name": Name,
96
+ #"occupation": Occupation,
97
+ #"years of experience": YearsOfExp,
98
+ #"ethnicity": Ethnicity,
99
+ #"gender": Gender,
100
+ #"age": Age,
101
+ "Unique ID": self.unique_id,
102
+ "chat_history": self.chat_log_history
103
+ }
104
+
105
  with open(self.chat_log_name, "w") as log_file:
106
+ json.dump(data, log_file, indent=4)
107
+
108
  if not existing_files:
109
+ # If the file does not exist, upload it
110
  file_metadata = {
111
  'name': self.chat_log_name,
112
+ 'parents': [self.folder_id],'mimeType': 'application/json'
 
113
  }
114
  media = MediaFileUpload(self.chat_log_name, mimetype='application/json')
115
  file = self.service.files().create(body=file_metadata, media_body=media, fields='id').execute()
116
  print(f"Uploaded new file with ID: {file.get('id')}")
117
  else:
118
+ print(f"File '{self.chat_log_name}' already exists.")
119
+ # Example: Update the file content
120
  file_id = existing_files[0]['id']
121
  media = MediaFileUpload(self.chat_log_name, mimetype='application/json')
122
  updated_file = self.service.files().update(fileId=file_id, media_body=media).execute()
123
  print(f"Updated existing file with ID: {updated_file.get('id')}")
124
 
125
+ def generate(self,prompt, history):
126
+
127
+ #if not len(Name) == 0 and not len(Occupation) == 0 and not len(Ethnicity) == 0 and not len(Gender) == 0 and not len(Age) == 0 and not len(YearsOfExp):
128
+ if self.agreed:
129
+ firstmsg =""
130
  if self.isFirstRun:
131
  self.context = self.initContext
132
  self.isFirstRun = False
133
+ firstmsg = prompt
134
+
135
+
136
+ self.context += """
137
+ <|im_start|>nurse
138
+ Nurse:"""+prompt+"""
139
+ <|im_start|>barry
140
+ Barry:
141
+ """
142
+
143
+ response = ""
144
+
145
+ while(len(response) < 1):
146
+ output = self.llm(context, max_tokens=400, stop=["Nurse:"], echo=False)
147
+ response = output["choices"][0]["text"]
148
+ response = response.strip()
149
+ #yield response
150
+
151
+
152
+ # for output in llm(input, stream=True, max_tokens=100, ):
153
+ # piece = output['choices'][0]['text']
154
+ # response += piece
155
+ # chatbot[-1] = (chatbot[-1][0], response)
156
+
157
+ # yield response
158
+
159
+ cleaned_response = self.strip_text(response)
160
+
161
+ self.chat_history.append((prompt,cleaned_response))
162
+ if not self.isFirstRun:
163
+ self.chat_log_history.append({"user": prompt, "bot": cleaned_response})
164
+ self.upload_to_google_drive()
165
+
166
+ else:
167
+ self.chat_log_history.append({"user": firstmsg, "bot": cleaned_response})
168
+
169
+ context += response
170
+
171
+ print (context)
172
+ return self.chat_history
173
+
174
+ else:
175
+ output = "Did you forget to Agree to the Terms and Conditions?"
176
+ self.chat_history.append((prompt,output))
177
+ return self.chat_history
178
 
 
 
 
 
 
 
 
 
179
 
180
+ def start_chat_button_fn(self,agree_status):
181
+
182
+ if agree_status:
183
+ self.agreed = agree_status
184
+ self.chat_log_name = f'chat_log_for_{self.unique_id}_{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.json'
185
+ return f"You can start chatting now"
186
+ else:
187
+ return "You must agree to the terms and conditions to proceed"
188
+
189
+ def reset_chat_interface(self):
190
  self.chat_history = []
191
  self.chat_log_history = []
192
  self.isFirstRun = True
193
+ return "Chat has been reset."
194
+
195
+ def reset_name_interface(self):
196
+ Name = ""
197
+ Occupation = ""
198
+ YearsOfExp = ""
199
+ Ethnicity = ""
200
+ Gender = ""
201
+ Age = ""
202
+ chat_log_name = ""
203
+ return "User info has been reset."
204
+
205
+ def reset_all(self):
 
 
 
206
 
207
+ message1 = reset_chat_interface()
208
+ #message2 = reset_name_interface()
209
+ message3 = load_model()
210
+ self.unique_id = generate_unique_id()
211
+ return f"All Chat components have been rest. Uniqe ID for this session is, {self.unique_id}. Please note this down.",self.unique_id
212
 
 
 
213
 
214
+ def create_app(self):
215
+ with gr.Blocks() as app:
216
+ gr.Markdown("# ECU-IVADE: Conversational AI Model for Aggressive Patient Behavior (Beta Testing)")
217
+ unique_id_display = gr.Textbox(value=unique_id, label="Session Unique ID", interactive=False,show_copy_button = True)
218
+
219
+ with gr.Tab("Terms and Conditions"):
220
+ #name = gr.Textbox(label="Name")
221
+ #occupation = gr.Textbox(label="Occupation")
222
+ #yearsofexp = gr.Textbox(label="Years of Experience")
223
+ #ethnicity = gr.Textbox(label="Ethnicity")
224
+ #gender = gr.Dropdown(choices=["Male", "Female", "Other", "Prefer Not To Say"], label="Gender")
225
+ #age = gr.Textbox(label="Age")
226
+ #submit_info = gr.Button("Submit")
227
+ gr.Markdown("## Terms and Conditions")
228
+ gr.Markdown("""
229
+ Before using our chatbot, please read the following terms and conditions carefully:
230
+
231
+ - **Data Collection**: Our chatbot collects chat logs for the purpose of improving our services and user experience.
232
+ - **Privacy**: We ensure the confidentiality and security of your data, in line with our privacy policy.
233
+ - **Survey**: At the end of the chat session, you will be asked to participate in a short survey to gather feedback about your experience.
234
+ - **Consent**: By checking the box below and initiating the chat, you agree to these terms and the collection of chat logs, and consent to take part in the survey upon completing your session.
235
+
236
+ Please check the box below to acknowledge your agreement and proceed.
237
+ """)
238
+ agree_status = gr.Checkbox(label="I have read and understand the terms and conditions.")
239
+ status_label = gr.Markdown()
240
+ start_chat_button = gr.Button("Start Chat with Chatlog")
241
+ #submit_info.click(submit_user_info, inputs=[name, occupation, yearsofexp, ethnicity, gender, age], outputs=[status_textbox])
242
+ start_chat_button.click(start_chat_button_fn, inputs=[agree_status], outputs=[status_label])
243
+ #status_textbox = gr.Textbox(interactive = False)
244
+
245
+ with gr.Tab("Chat Bot"):
246
+ chatbot = gr.Chatbot()
247
+ msg = gr.Textbox(label="Type your message")
248
+ send = gr.Button("Send")
249
+ clear = gr.Button("Clear Chat")
250
+ send.click(generate, inputs=[msg], outputs=chatbot)
251
+ clear.click(lambda: chatbot.clear(), inputs=[], outputs=chatbot)
252
+
253
+ with gr.Tab("Reset"):
254
+ reset_button = gr.Button("Reset ChatBot Instance")
255
+ reset_output = gr.Textbox(label="Reset Output", interactive=False)
256
+ reset_button.click(reset_all, inputs=[], outputs=[reset_output,unique_id_display])
257
  return app
258
 
259
+ llm = load_model()
260
+ chatbot_app = ChatbotApp(llm,SERVICE_ACCOUNT_FILE,SCOPES,folder_id,unique_id,initContext)
261
+ app = chatbot_app.create_app()
262
+ app.launch(debug=True)