Yhhxhfh commited on
Commit
2914676
1 Parent(s): 89c316f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +349 -0
app.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import uvicorn
4
+ from fastapi import FastAPI, Query
5
+ from fastapi.responses import HTMLResponse
6
+ from starlette.middleware.cors import CORSMiddleware
7
+ from datasets import load_dataset, list_datasets
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
9
+ from loguru import logger
10
+ import concurrent.futures
11
+ import psutil
12
+ import asyncio
13
+ import torch
14
+ from tenacity import retry, stop_after_attempt, wait_fixed
15
+ from huggingface_hub import HfApi, RepositoryNotFoundError
16
+ from dotenv import load_dotenv
17
+
18
+ load_dotenv()
19
+
20
+ HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
21
+ if not HUGGINGFACE_TOKEN:
22
+ logger.error("Hugging Face token not found. Please set the HUGGINGFACE_TOKEN environment variable.")
23
+ sys.exit(1)
24
+
25
+ datasets_dict = {}
26
+ example_usage_list = []
27
+
28
+ CACHE_DIR = os.path.expanduser("~/.cache/huggingface")
29
+ os.makedirs(CACHE_DIR, exist_ok=True)
30
+ os.environ["HF_HOME"] = CACHE_DIR
31
+ os.environ["HF_TOKEN"] = HUGGINGFACE_TOKEN
32
+
33
+ def initialize_model():
34
+ try:
35
+ logger.info("Initializing the base model and tokenizer.")
36
+ base_model_repo = "Yhhxhfh/test"
37
+ model = AutoModelForCausalLM.from_pretrained(base_model_repo, cache_dir=CACHE_DIR)
38
+ tokenizer = AutoTokenizer.from_pretrained(base_model_repo, cache_dir=CACHE_DIR)
39
+ if tokenizer.pad_token is None:
40
+ tokenizer.pad_token = tokenizer.eos_token
41
+ pipeline_instance = pipeline(
42
+ "text-generation",
43
+ model=model,
44
+ tokenizer=tokenizer,
45
+ device=0 if torch.cuda.is_available() else -1
46
+ )
47
+ logger.info("Model and tokenizer initialized successfully.")
48
+ return pipeline_instance
49
+ except Exception as e:
50
+ logger.error(f"Error initializing model and tokenizer: {e}", exc_info=True)
51
+ sys.exit(1)
52
+
53
+ pipeline_instance = initialize_model()
54
+
55
+ @retry(stop=stop_after_attempt(3), wait=wait_fixed(5))
56
+ def download_dataset(dataset_name):
57
+ try:
58
+ logger.info(f"Starting download for dataset: {dataset_name}")
59
+ datasets_dict[dataset_name] = load_dataset(dataset_name, trust_remote_code=True, cache_dir=CACHE_DIR)
60
+ create_example_usage(dataset_name)
61
+ except Exception as e:
62
+ logger.error(f"Error loading dataset {dataset_name}: {e}", exc_info=True)
63
+ raise
64
+
65
+ def upload_model_to_hub():
66
+ try:
67
+ api = HfApi()
68
+ model_repo = "Yhhxhfh/test"
69
+ try:
70
+ api.repo_info(repo_id=model_repo)
71
+ logger.info(f"Model repository {model_repo} already exists.")
72
+ except RepositoryNotFoundError:
73
+ api.create_repo(repo_id=model_repo, private=False, token=HUGGINGFACE_TOKEN)
74
+ logger.info(f"Created model repository {model_repo}.")
75
+ logger.info(f"Pushing the model and tokenizer to {model_repo}.")
76
+ pipeline_instance.model.push_to_hub(model_repo, use_auth_token=HUGGINGFACE_TOKEN)
77
+ pipeline_instance.tokenizer.push_to_hub(model_repo, use_auth_token=HUGGINGFACE_TOKEN)
78
+ logger.info(f"Successfully pushed the model and tokenizer to {model_repo}.")
79
+ except Exception as e:
80
+ logger.error(f"Error uploading model to Hugging Face Hub: {e}", exc_info=True)
81
+
82
+ def create_example_usage(dataset_name):
83
+ try:
84
+ logger.info(f"Creating example usage for dataset {dataset_name}")
85
+ example_prompts = [
86
+ "Translate the following catering menu from English to French:",
87
+ "Generate a catering menu for a wedding with vegetarian options:",
88
+ "Convert the following catering menu to a gluten-free version:",
89
+ "Provide a detailed catering menu for a corporate event including desserts:",
90
+ "Generate a children's birthday party catering menu with allergen-free items:"
91
+ ]
92
+ examples = []
93
+ for prompt in example_prompts:
94
+ generated_text = pipeline_instance(prompt, max_length=50, num_return_sequences=1)[0]['generated_text']
95
+ examples.append({"prompt": prompt, "response": generated_text})
96
+ example_usage_list.append({"dataset_name": dataset_name, "examples": examples})
97
+ logger.info(f"Example usage created for dataset {dataset_name}")
98
+ except Exception as e:
99
+ logger.error(f"Error creating example usage for dataset {dataset_name}: {e}", exc_info=True)
100
+
101
+ def unify_datasets():
102
+ try:
103
+ logger.info("Starting to unify datasets")
104
+ unified_dataset = None
105
+ for dataset in datasets_dict.values():
106
+ if unified_dataset is None:
107
+ unified_dataset = dataset
108
+ else:
109
+ unified_dataset = unified_dataset.concatenate(dataset)
110
+ datasets_dict['unified'] = unified_dataset
111
+ logger.info("Datasets successfully unified.")
112
+ except Exception as e:
113
+ logger.error(f"Error unifying datasets: {e}", exc_info=True)
114
+
115
+ cpu_count = psutil.cpu_count(logical=False) or 1
116
+ memory_available_mb = psutil.virtual_memory().available / (1024 * 1024)
117
+ memory_per_download_mb = 100
118
+ memory_available = int(memory_available_mb / memory_per_download_mb)
119
+ gpu_count = torch.cuda.device_count()
120
+ max_concurrent_downloads = min(cpu_count, memory_available, gpu_count * 2 if gpu_count else cpu_count)
121
+ max_concurrent_downloads = max(1, max_concurrent_downloads)
122
+ max_concurrent_downloads = min(10, max_concurrent_downloads)
123
+
124
+ logger.info(f"Using up to {max_concurrent_downloads} concurrent workers for downloading datasets.")
125
+
126
+ executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_concurrent_downloads)
127
+
128
+ async def download_and_process_datasets():
129
+ dataset_names = list_datasets()
130
+ logger.info(f"Found {len(dataset_names)} datasets to download.")
131
+ loop = asyncio.get_event_loop()
132
+ tasks = []
133
+ for dataset_name in dataset_names:
134
+ task = loop.run_in_executor(executor, download_dataset, dataset_name)
135
+ tasks.append(task)
136
+ await asyncio.gather(*tasks)
137
+ unify_datasets()
138
+ upload_model_to_hub()
139
+
140
+ async def main():
141
+ await download_and_process_datasets()
142
+
143
+ asyncio.run(main())
144
+
145
+ app = FastAPI()
146
+
147
+ app.add_middleware(
148
+ CORSMiddleware,
149
+ allow_origins=["*"],
150
+ allow_credentials=True,
151
+ allow_methods=["*"],
152
+ allow_headers=["*"]
153
+ )
154
+
155
+ message_history = []
156
+
157
+ @app.get('/')
158
+ async def index():
159
+ html_code = """
160
+ <!DOCTYPE html>
161
+ <html lang="en">
162
+ <head>
163
+ <meta charset="UTF-8">
164
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
165
+ <title>ChatGPT Chatbot</title>
166
+ <style>
167
+ body {
168
+ font-family: Arial, sans-serif;
169
+ margin: 0;
170
+ padding: 0;
171
+ background-color: #f4f4f4;
172
+ }
173
+ .container {
174
+ max-width: 800px;
175
+ margin: auto;
176
+ padding: 20px;
177
+ }
178
+ .chat-container {
179
+ background-color: #fff;
180
+ border-radius: 8px;
181
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
182
+ overflow: hidden;
183
+ margin-bottom: 20px;
184
+ animation: fadeInUp 0.5s ease forwards;
185
+ display: flex;
186
+ flex-direction: column;
187
+ }
188
+ .chat-box {
189
+ flex: 1;
190
+ overflow-y: auto;
191
+ padding: 10px;
192
+ }
193
+ .chat-input {
194
+ width: calc(100% - 20px);
195
+ border: none;
196
+ border-top: 1px solid #ddd;
197
+ padding: 10px;
198
+ font-size: 16px;
199
+ outline: none;
200
+ }
201
+ .chat-input:focus {
202
+ border-top: 1px solid #007bff;
203
+ }
204
+ .user-message {
205
+ margin-bottom: 10px;
206
+ padding: 8px 12px;
207
+ border-radius: 8px;
208
+ background-color: #007bff;
209
+ color: #fff;
210
+ max-width: 70%;
211
+ word-wrap: break-word;
212
+ align-self: flex-end;
213
+ }
214
+ .bot-message {
215
+ margin-bottom: 10px;
216
+ padding: 8px 12px;
217
+ border-radius: 8px;
218
+ background-color: #4CAF50;
219
+ color: #fff;
220
+ max-width: 70%;
221
+ word-wrap: break-word;
222
+ }
223
+ .toggle-history {
224
+ text-align: center;
225
+ cursor: pointer;
226
+ color: #007bff;
227
+ margin-bottom: 10px;
228
+ }
229
+ .history-container {
230
+ display: none;
231
+ }
232
+ .history-container.show {
233
+ display: block;
234
+ }
235
+ .history-container .history-content {
236
+ max-height: 200px;
237
+ overflow-y: auto;
238
+ }
239
+ @keyframes fadeInUp {
240
+ from {
241
+ opacity: 0;
242
+ transform: translateY(20px);
243
+ }
244
+ to {
245
+ opacity: 1;
246
+ transform: translateY(0);
247
+ }
248
+ }
249
+ </style>
250
+ </head>
251
+ <body>
252
+ <div class="container">
253
+ <h1 style="text-align: center;">ChatGPT Chatbot</h1>
254
+ <div class="chat-container" id="chat-container">
255
+ <div class="chat-box" id="chat-box">
256
+ </div>
257
+ <input type="text" class="chat-input" id="user-input" placeholder="Type your message...">
258
+ <button onclick="retryLastMessage()">Retry Last Message</button>
259
+ </div>
260
+ <div class="toggle-history" onclick="toggleHistory()">Toggle History</div>
261
+ <div class="history-container" id="history-container">
262
+ <h2>Chat History</h2>
263
+ <div class="history-content" id="history-content"></div>
264
+ </div>
265
+ </div>
266
+ <script>
267
+ function toggleHistory() {
268
+ const historyContainer = document.getElementById('history-container');
269
+ historyContainer.classList.toggle('show');
270
+ }
271
+
272
+ function saveMessage(sender, message) {
273
+ const historyContent = document.getElementById('history-content');
274
+ const messageElement = document.createElement('div');
275
+ messageElement.className = `${sender}-message`;
276
+ messageElement.innerText = message;
277
+ historyContent.appendChild(messageElement);
278
+ }
279
+
280
+ function appendMessage(sender, message) {
281
+ const chatBox = document.getElementById('chat-box');
282
+ const messageElement = document.createElement('div');
283
+ messageElement.className = `${sender}-message`;
284
+ messageElement.innerText = message;
285
+ chatBox.appendChild(messageElement);
286
+ chatBox.scrollTop = chatBox.scrollHeight;
287
+ }
288
+
289
+ const chatContainer = document.getElementById('chat-container');
290
+ const chatBox = document.getElementById('chat-box');
291
+ const userInput = document.getElementById('user-input');
292
+
293
+ userInput.addEventListener('keyup', function(event) {
294
+ if (event.keyCode === 13) {
295
+ event.preventDefault();
296
+ sendMessage();
297
+ }
298
+ });
299
+
300
+ function sendMessage() {
301
+ const userMessage = userInput.value.trim();
302
+ if (userMessage === '') return;
303
+
304
+ saveMessage('user', userMessage);
305
+ appendMessage('user', userMessage);
306
+ userInput.value = '';
307
+
308
+ fetch(`/autocomplete?q=${encodeURIComponent(userMessage)}`)
309
+ .then(response => response.json())
310
+ .then(data => {
311
+ const botMessages = data.result;
312
+ botMessages.forEach(message => {
313
+ saveMessage('bot', message);
314
+ appendMessage('bot', message);
315
+ });
316
+ })
317
+ .catch(error => {
318
+ console.error('Error:', error);
319
+ });
320
+ }
321
+
322
+ function retryLastMessage() {
323
+ const lastUserMessage = document.querySelector('.user-message:last-of-type');
324
+ if (lastUserMessage) {
325
+ userInput.value = lastUserMessage.innerText;
326
+ sendMessage();
327
+ }
328
+ }
329
+ </script>
330
+ </body>
331
+ </html>
332
+ """
333
+ return HTMLResponse(content=html_code, status_code=200)
334
+
335
+ @app.get('/autocomplete')
336
+ async def autocomplete(q: str = Query(..., title='query')):
337
+ global message_history
338
+ message_history.append(('user', q))
339
+ try:
340
+ response = pipeline_instance(q, max_length=50, num_return_sequences=1)[0]['generated_text']
341
+ logger.debug(f"Successfully autocomplete, q:{q}, res:{response}")
342
+ return {"result": [response]}
343
+ except Exception as e:
344
+ logger.error(f"Ignored error in autocomplete: {e}", exc_info=True)
345
+ return {"result": []}
346
+
347
+ if __name__ == '__main__':
348
+ port = int(os.getenv("PORT", 443))
349
+ uvicorn.run(app=app, host='0.0.0.0', port=port)