ECUiVADE commited on
Commit
a4f23a1
1 Parent(s): 45af92a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()