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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 |
+
|
14 |
+
#TODO : Cleanup and comment
|
15 |
+
|
16 |
+
|
17 |
+
repo_name = 'TheBloke/OpenHermes-2.5-Mistral-7B-GGUF'
|
18 |
+
model_file = "openhermes-2.5-mistral-7b.Q4_K_M.gguf"
|
19 |
+
|
20 |
+
print('Fetching model:', repo_name, model_file)
|
21 |
+
snapshot_download(repo_id=repo_name, local_dir=".", allow_patterns=model_file)
|
22 |
+
print('Done fetching model:')
|
23 |
+
|
24 |
+
DEFAULT_MODEL_PATH = model_file
|
25 |
+
|
26 |
+
chat_history = []
|
27 |
+
chat_log_history = []
|
28 |
+
isFirstRun = True
|
29 |
+
dir_path = os.path.dirname(os.path.realpath(__file__))
|
30 |
+
directory = '/home/user/app'
|
31 |
+
if not os.path.exists(directory):
|
32 |
+
print("directory dont exist")
|
33 |
+
else: print("path exists")
|
34 |
+
|
35 |
+
file_path = '/home/user/app/test.txt'
|
36 |
+
with open(file_path, 'w') as file:
|
37 |
+
# Write "Hello World" to the file
|
38 |
+
file.write("Hello World")
|
39 |
+
print("file written")
|
40 |
+
|
41 |
+
print(dir_path)
|
42 |
+
|
43 |
+
SCOPES = ['https://www.googleapis.com/auth/drive']
|
44 |
+
SERVICE_ACCOUNT_FILE = '/home/user/app/service_account_creds.json'
|
45 |
+
|
46 |
+
#initContext = "You are a hospital patient nameed Barry Lawson. You have an injured arm and are in great pain. You are frustrated because you have been waiting for a long time. Every time I prompt you you get more agressive and violent in your responses. Your responses should use excessive profanity. You will provide only one response to each of my prompts. I am a nurse and you are angry at me. Nurse: "
|
47 |
+
|
48 |
+
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!"""
|
49 |
+
|
50 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
51 |
+
folder_id = '1Hjbu7FmuVs0Yz8y_veo6SzY_2tc48OWt'
|
52 |
+
|
53 |
+
Name = ""
|
54 |
+
Occupation = ""
|
55 |
+
Ethnicity = ""
|
56 |
+
Gender = ""
|
57 |
+
Age=""
|
58 |
+
|
59 |
+
chat_log_name =""
|
60 |
+
|
61 |
+
from llama_cpp import Llama
|
62 |
+
llm = Llama(model_path=model_file, model_type="mistral")
|
63 |
+
|
64 |
+
def get_drive_service():
|
65 |
+
credentials = service_account.Credentials.from_service_account_file(
|
66 |
+
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
|
67 |
+
service = build('drive', 'v3', credentials=credentials)
|
68 |
+
print("Google Service Created")
|
69 |
+
return service
|
70 |
+
|
71 |
+
service = get_drive_service()
|
72 |
+
|
73 |
+
def search_file():
|
74 |
+
#Search for a file by name in the specified Google Drive folder.
|
75 |
+
query = f"name = '{chat_log_name}' and '{folder_id}' in parents and trashed = false"
|
76 |
+
response = service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
|
77 |
+
files = response.get('files', [])
|
78 |
+
if not files:
|
79 |
+
print(f"Chat log {chat_log_name} does not exist")
|
80 |
+
else:
|
81 |
+
print(f"Chat log {chat_log_name} exist")
|
82 |
+
return files
|
83 |
+
|
84 |
+
|
85 |
+
def format_prompt(message, history):
|
86 |
+
|
87 |
+
global isFirstRun
|
88 |
+
|
89 |
+
if not isFirstRun:
|
90 |
+
print("reg prompt")
|
91 |
+
prompt = "<s>"
|
92 |
+
for i, (user_prompt,bot_response) in enumerate(chat_history):
|
93 |
+
if i == 0:
|
94 |
+
prompt += f"[INST]{user_prompt}[/INST]"
|
95 |
+
else:
|
96 |
+
prompt += f"Nurse : {user_prompt}"
|
97 |
+
prompt += f" Barry: {bot_response}"
|
98 |
+
prompt += f"Nurse: {message} Barry:</s>"
|
99 |
+
|
100 |
+
else:
|
101 |
+
prompt = "<s>"
|
102 |
+
isFirstRun = False
|
103 |
+
prompt += f"[INST] {message} [/INST] Barry:</s>"
|
104 |
+
print("init prompt")
|
105 |
+
|
106 |
+
return prompt
|
107 |
+
|
108 |
+
def strip_special_tokens(text):
|
109 |
+
# List of special tokens to be removed
|
110 |
+
special_tokens = ["</s>", "<s>", "[INST]", "[/INST]"]
|
111 |
+
|
112 |
+
# Iterate over the list of special tokens and replace each with an empty string
|
113 |
+
for token in special_tokens:
|
114 |
+
text = text.replace(token, "")
|
115 |
+
|
116 |
+
return text
|
117 |
+
|
118 |
+
def upload_to_google_drive():
|
119 |
+
|
120 |
+
existing_files = search_file()
|
121 |
+
print(existing_files)
|
122 |
+
|
123 |
+
data = {
|
124 |
+
"name": Name,
|
125 |
+
"occupation": Occupation,
|
126 |
+
"ethnicity": Ethnicity,
|
127 |
+
"gender": Gender,
|
128 |
+
"age": Age,
|
129 |
+
"chat_history": chat_log_history
|
130 |
+
}
|
131 |
+
|
132 |
+
with open(chat_log_name, "w") as log_file:
|
133 |
+
json.dump(data, log_file, indent=4)
|
134 |
+
|
135 |
+
if not existing_files:
|
136 |
+
# If the file does not exist, upload it
|
137 |
+
file_metadata = {
|
138 |
+
'name': chat_log_name,
|
139 |
+
'parents': [folder_id],'mimeType': 'application/json'
|
140 |
+
}
|
141 |
+
media = MediaFileUpload(chat_log_name, mimetype='application/json')
|
142 |
+
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
143 |
+
print(f"Uploaded new file with ID: {file.get('id')}")
|
144 |
+
else:
|
145 |
+
print(f"File '{chat_log_name}' already exists.")
|
146 |
+
# Example: Update the file content
|
147 |
+
file_id = existing_files[0]['id']
|
148 |
+
media = MediaFileUpload(chat_log_name, mimetype='application/json')
|
149 |
+
updated_file = service.files().update(fileId=file_id, media_body=media).execute()
|
150 |
+
print(f"Updated existing file with ID: {updated_file.get('id')}")
|
151 |
+
|
152 |
+
|
153 |
+
def generate(prompt, history):
|
154 |
+
|
155 |
+
global isFirstRun,initContext,Name,Occupation,Ethnicity,Gender,Age
|
156 |
+
|
157 |
+
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:
|
158 |
+
|
159 |
+
firstmsg =""
|
160 |
+
if not isFirstRun:
|
161 |
+
formatted_prompt = format_prompt(prompt, history)
|
162 |
+
else:
|
163 |
+
firstmsg = prompt
|
164 |
+
initContext += prompt
|
165 |
+
prompt = initContext
|
166 |
+
formatted_prompt=format_prompt(initContext,history)
|
167 |
+
print("init Context added")
|
168 |
+
print(f"\n THE PROMPT IS,\n {formatted_prompt} \n PROMPT END")
|
169 |
+
|
170 |
+
stream = client.text_generation(formatted_prompt, max_new_tokens = 2048,repetition_penalty = 1.4,temperature = 0.8,stream=True, details=True, return_full_text=False )
|
171 |
+
output = ""
|
172 |
+
|
173 |
+
#print(chat_history)
|
174 |
+
for response in stream:
|
175 |
+
output += response.token.text
|
176 |
+
yield output
|
177 |
+
|
178 |
+
output = strip_special_tokens(output)
|
179 |
+
chat_history.append([prompt, output])
|
180 |
+
if not isFirstRun:
|
181 |
+
chat_log_history.append({"user": prompt, "bot": output})
|
182 |
+
upload_to_google_drive()
|
183 |
+
else:
|
184 |
+
chat_log_history.append({"user": firstmsg, "bot": output})
|
185 |
+
|
186 |
+
return output
|
187 |
+
else:
|
188 |
+
output = "Did you forget to enter your Details? Please go to the User Info Tab and Input your data. "
|
189 |
+
yield output
|
190 |
+
|
191 |
+
def predict(input, chatbot, max_length, top_p, temperature, history):
|
192 |
+
chatbot.append((input, ""))
|
193 |
+
response = ""
|
194 |
+
history.append(input)
|
195 |
+
|
196 |
+
for output in llm(input, stream=True, temperature=temperature, top_p=top_p, max_tokens=max_length, ):
|
197 |
+
piece = output['choices'][0]['text']
|
198 |
+
response += piece
|
199 |
+
chatbot[-1] = (chatbot[-1][0], response)
|
200 |
+
|
201 |
+
yield chatbot, history
|
202 |
+
|
203 |
+
history.append(response)
|
204 |
+
yield chatbot, history
|
205 |
+
|
206 |
+
|
207 |
+
chat_bot=gr.ChatInterface(
|
208 |
+
fn=generate,
|
209 |
+
chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
|
210 |
+
title="""AI Chat Bot - ECU IVADE"""
|
211 |
+
)
|
212 |
+
|
213 |
+
def name_interface(name,occupation,ethnicity,gender,age):
|
214 |
+
global Name, Occupation,Ethnicity,Gender,Age,chat_log_name
|
215 |
+
|
216 |
+
Name = name
|
217 |
+
Occupation = occupation
|
218 |
+
Ethnicity=ethnicity
|
219 |
+
Gender=gender
|
220 |
+
Age=age
|
221 |
+
|
222 |
+
if name and occupation and ethnicity and gender and age:
|
223 |
+
chat_log_name = f'chat_log_for_{Name}_{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.json'
|
224 |
+
return f"You can start chatting now {Name}"
|
225 |
+
else:
|
226 |
+
return "Enter ALL the details to start chatting"
|
227 |
+
|
228 |
+
|
229 |
+
name_interface = gr.Interface(
|
230 |
+
fn=name_interface,
|
231 |
+
inputs=[
|
232 |
+
gr.Textbox(label="Name", placeholder="Enter your name here..."),
|
233 |
+
gr.Textbox(label="Occupation", placeholder="Enter your occupation here..."),
|
234 |
+
gr.Textbox(label="Ethnicity", placeholder="Enter your Ethnicity here..."),
|
235 |
+
gr.Textbox(label="Gender", placeholder="Enter your Gender here..."),
|
236 |
+
gr.Textbox(label="Age", placeholder="Enter your Age here...")
|
237 |
+
],outputs="text",
|
238 |
+
title="ECU-IVADE : User Information",
|
239 |
+
description="Please enter your name and occupation."
|
240 |
+
)
|
241 |
+
|
242 |
+
tabs = gr.TabbedInterface([name_interface, chat_bot], ["User Info", "Chat Bot"])
|
243 |
+
|
244 |
+
if __name__ == "__main__":
|
245 |
+
tabs.launch(debug=True,share=False,inbrowser=True)
|