X commited on
Commit
e7ce0cf
·
verified ·
1 Parent(s): 11202ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +382 -23
app.py CHANGED
@@ -1,37 +1,396 @@
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
 
 
 
3
 
4
- # Загрузка модели
 
5
  model_id = "OpenRussianAI/OpenAirAI-X"
6
  tokenizer = AutoTokenizer.from_pretrained(model_id)
7
  model = AutoModelForCausalLM.from_pretrained(model_id)
 
 
 
8
 
9
- def chat(message, history):
10
- # Формируем промпт из истории
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  prompt = ""
12
  for user_msg, ai_msg in history:
13
- prompt += f"Пользователь: {user_msg}\nAI: {ai_msg}\n"
14
- prompt += f"Пользователь: {message}\nAI:"
 
 
15
 
16
- # Генерация
17
- inputs = tokenizer(prompt, return_tensors="pt")
18
- outputs = model.generate(
19
- **inputs,
20
- max_new_tokens=256,
21
- temperature=0.7,
22
- do_sample=True
23
- )
24
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
25
 
26
- # Извлекаем только ответ AI
27
  ai_response = response.split("AI:")[-1].strip()
28
- return ai_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # Создаем интерфейс
31
- demo = gr.ChatInterface(
32
- fn=chat,
33
- title="OpenAirAI-X Chat",
34
- description="Чат с моделью OpenRussianAI/OpenAirAI-X"
35
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- demo.launch()
 
 
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from datetime import datetime
8
 
9
+ # === ЗАГРУЗКА МОДЕЛИ ===
10
+ print("🚀 Загрузка модели...")
11
  model_id = "OpenRussianAI/OpenAirAI-X"
12
  tokenizer = AutoTokenizer.from_pretrained(model_id)
13
  model = AutoModelForCausalLM.from_pretrained(model_id)
14
+ device = "cuda" if torch.cuda.is_available() else "cpu"
15
+ model = model.to(device).eval()
16
+ print(f"✅ Модель загружена на {device}")
17
 
18
+ # === ХРАНИЛИЩЕ ИСТОРИИ ===
19
+ HISTORY_DIR = Path("chat_history")
20
+ HISTORY_DIR.mkdir(exist_ok=True)
21
+
22
+ def get_history_path(username):
23
+ return HISTORY_DIR / f"{username}.json"
24
+
25
+ def load_history(username):
26
+ """Загружает историю чатов пользователя"""
27
+ path = get_history_path(username)
28
+ if path.exists():
29
+ with open(path, "r", encoding="utf-8") as f:
30
+ return json.load(f)
31
+ return {} # {chat_id: {"title": str, "messages": [[user, ai], ...]}}
32
+
33
+ def save_history(username, history_data):
34
+ """Сохраняет историю чатов пользователя"""
35
+ path = get_history_path(username)
36
+ with open(path, "w", encoding="utf-8") as f:
37
+ json.dump(history_data, f, ensure_ascii=False, indent=2)
38
+
39
+ def check_if_pro(token):
40
+ """Проверяет, является ли пользователь PRO-подписчиком"""
41
+ if not token:
42
+ return False
43
+ try:
44
+ import requests
45
+ response = requests.get(
46
+ "https://huggingface.co/api/whoami-v2",
47
+ headers={"Authorization": f"Bearer {token}"},
48
+ timeout=5
49
+ )
50
+ if response.status_code == 200:
51
+ data = response.json()
52
+ return data.get("isPro", False) or data.get("plan", {}).get("name") == "PRO"
53
+ except Exception as e:
54
+ print(f"Ошибка проверки PRO: {e}")
55
+ return False
56
+
57
+ # === ГЕНЕРАЦИЯ ОТВЕТА ===
58
+ def generate_response(message, history, username, current_chat_id):
59
+ if not username:
60
+ gr.Warning("Пожалуйста, войдите через Hugging Face")
61
+ return history, history, gr.update(), current_chat_id
62
+
63
+ if not message.strip():
64
+ return history, history, gr.update(), current_chat_id
65
+
66
+ # Добавляем сообщение пользователя
67
+ history = history + [[message, None]]
68
+
69
+ # Формируем промпт
70
  prompt = ""
71
  for user_msg, ai_msg in history:
72
+ prompt += f"Пользователь: {user_msg}\n"
73
+ if ai_msg:
74
+ prompt += f"AI: {ai_msg}\n"
75
+ prompt += "AI:"
76
 
77
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
78
+ with torch.no_grad():
79
+ outputs = model.generate(
80
+ **inputs,
81
+ max_new_tokens=256,
82
+ temperature=0.7,
83
+ top_p=0.9,
84
+ do_sample=True,
85
+ pad_token_id=tokenizer.eos_token_id
86
+ )
87
 
88
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
89
  ai_response = response.split("AI:")[-1].strip()
90
+
91
+ # Обновляем последнее сообщение
92
+ history[-1][1] = ai_response
93
+
94
+ # Сохраняем в хранилище
95
+ history_data = load_history(username)
96
+ if current_chat_id not in history_data:
97
+ history_data[current_chat_id] = {
98
+ "title": message[:40] + ("..." if len(message) > 40 else ""),
99
+ "created": datetime.now().isoformat(),
100
+ "messages": []
101
+ }
102
+ history_data[current_chat_id]["messages"] = history
103
+ save_history(username, history_data)
104
+
105
+ return history, history, gr.update(value=""), current_chat_id
106
+
107
+ # === УПРАВЛЕНИЕ ЧАТАМИ ===
108
+ def new_chat(username):
109
+ if not username:
110
+ return [], {}, None
111
+ chat_id = datetime.now().strftime("%Y%m%d_%H%M%S")
112
+ history_data = load_history(username)
113
+ history_data[chat_id] = {
114
+ "title": "Новый чат",
115
+ "created": datetime.now().isoformat(),
116
+ "messages": []
117
+ }
118
+ save_history(username, history_data)
119
+ return [], history_data, chat_id
120
+
121
+ def load_chat(chat_title, username, current_chat_id):
122
+ if not username or not chat_title:
123
+ return [], current_chat_id
124
+ history_data = load_history(username)
125
+ # Находим chat_id по заголовку
126
+ for cid, data in history_data.items():
127
+ if data["title"] == chat_title:
128
+ return data["messages"], cid
129
+ return [], current_chat_id
130
+
131
+ def get_chat_list(username):
132
+ if not username:
133
+ return []
134
+ history_data = load_history(username)
135
+ # Сортируем по дате (новые сверху)
136
+ sorted_chats = sorted(
137
+ history_data.items(),
138
+ key=lambda x: x[1].get("created", ""),
139
+ reverse=True
140
+ )
141
+ return [data["title"] for _, data in sorted_chats]
142
+
143
+ def delete_chat(chat_title, username):
144
+ if not username or not chat_title:
145
+ return [], {}, None, []
146
+ history_data = load_history(username)
147
+ # Находим и удаляем чат
148
+ for cid, data in list(history_data.items()):
149
+ if data["title"] == chat_title:
150
+ del history_data[cid]
151
+ break
152
+ save_history(username, history_data)
153
+ return [], history_data, None, get_chat_list(username)
154
+
155
+ # === ВХОД/ВЫХОД ===
156
+ def login_event(request: gr.Request):
157
+ """Вызывается после успешного входа через OAuth"""
158
+ if request.username:
159
+ username = request.username
160
+ token = request.oauth_token.get("access_token") if request.oauth_token else None
161
+ is_pro = check_if_pro(token)
162
+ history_data = load_history(username)
163
+ chat_list = get_chat_list(username)
164
+
165
+ # Создаем новый чат, если история пуста
166
+ current_chat_id = None
167
+ if not history_data:
168
+ chat_id = datetime.now().strftime("%Y%m%d_%H%M%S")
169
+ history_data[chat_id] = {
170
+ "title": "Новый чат",
171
+ "created": datetime.now().isoformat(),
172
+ "messages": []
173
+ }
174
+ save_history(username, history_data)
175
+ current_chat_id = chat_id
176
+ chat_list = get_chat_list(username)
177
+
178
+ pro_badge = "👑 PRO" if is_pro else ""
179
+ return (
180
+ gr.update(visible=True), # main_interface
181
+ gr.update(visible=False), # login_screen
182
+ gr.update(value=f"👤 {username} {pro_badge}".strip()), # user_info
183
+ [], # chatbot
184
+ history_data, # state
185
+ current_chat_id,
186
+ chat_list, # список чатов
187
+ gr.update(visible=is_pro) # PRO бейдж
188
+ )
189
+ return (gr.update(), gr.update(), gr.update(), [], {}, None, [], gr.update())
190
+
191
+ def logout_event():
192
+ return (
193
+ gr.update(visible=False),
194
+ gr.update(visible=True),
195
+ "Не авторизован",
196
+ [],
197
+ {},
198
+ None,
199
+ [],
200
+ gr.update(visible=False)
201
+ )
202
+
203
+ # === CSS ===
204
+ CUSTOM_CSS = """
205
+ .main-header {
206
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
207
+ color: white;
208
+ padding: 20px;
209
+ border-radius: 12px;
210
+ margin-bottom: 20px;
211
+ text-align: center;
212
+ }
213
+ .main-header h1 {
214
+ margin: 0;
215
+ font-size: 2em;
216
+ }
217
+ .pro-badge {
218
+ background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
219
+ color: #333;
220
+ padding: 4px 12px;
221
+ border-radius: 20px;
222
+ font-weight: bold;
223
+ display: inline-block;
224
+ margin-left: 10px;
225
+ box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
226
+ }
227
+ .sidebar {
228
+ background: #f7f7f9;
229
+ padding: 15px;
230
+ border-radius: 12px;
231
+ height: calc(100vh - 200px);
232
+ overflow-y: auto;
233
+ }
234
+ .chat-item {
235
+ padding: 8px 12px;
236
+ margin: 4px 0;
237
+ background: white;
238
+ border-radius: 8px;
239
+ cursor: pointer;
240
+ border: 1px solid #e0e0e0;
241
+ }
242
+ .user-info {
243
+ padding: 10px;
244
+ background: white;
245
+ border-radius: 8px;
246
+ margin-bottom: 10px;
247
+ text-align: center;
248
+ font-weight: 600;
249
+ }
250
+ """
251
 
252
+ # === ИНТЕРФЕЙС ===
253
+ with gr.Blocks(css=CUSTOM_CSS, title="OpenAirAI-X Chat") as demo:
254
+
255
+ # Состояния
256
+ history_state = gr.State({})
257
+ current_chat_id_state = gr.State(None)
258
+
259
+ with gr.Column(visible=False) as main_interface:
260
+ # Шапка
261
+ gr.HTML("""
262
+ <div class="main-header">
263
+ <h1>🤖 OpenAirAI-X Chat</h1>
264
+ <p>Русскоязычный AI-ассистент</p>
265
+ </div>
266
+ """)
267
+
268
+ with gr.Row():
269
+ # Боковая панель с историей
270
+ with gr.Column(scale=1, elem_classes="sidebar"):
271
+ user_info = gr.Textbox(
272
+ label="Пользователь",
273
+ value="Не авторизован",
274
+ interactive=False,
275
+ elem_classes="user-info"
276
+ )
277
+ pro_badge = gr.HTML(
278
+ '<div class="pro-badge">👑 PRO</div>',
279
+ visible=False
280
+ )
281
+ new_chat_btn = gr.Button("➕ Новый чат", variant="primary")
282
+ gr.Markdown("### 📚 История чатов")
283
+ chat_list = gr.Radio(
284
+ choices=[],
285
+ label="Ваши чаты",
286
+ interactive=True
287
+ )
288
+ delete_chat_btn = gr.Button("🗑️ Удалить выбранный чат", variant="stop", size="sm")
289
+ logout_btn = gr.Button("🚪 Выйти", size="sm")
290
+
291
+ # Основная область чата
292
+ with gr.Column(scale=3):
293
+ chatbot = gr.Chatbot(
294
+ label="Диалог",
295
+ height=500,
296
+ type="tuples",
297
+ show_copy_button=True,
298
+ avatar_images=(None, "https://huggingface.co/datasets/huggingface/badges/resolve/main/model-icon.png")
299
+ )
300
+ with gr.Row():
301
+ msg_input = gr.Textbox(
302
+ placeholder="Напишите сообщение...",
303
+ lines=2,
304
+ scale=5,
305
+ show_label=False
306
+ )
307
+ send_btn = gr.Button("📤 Отправить", variant="primary", scale=1)
308
+
309
+ # Экран входа
310
+ with gr.Column(visible=True) as login_screen:
311
+ gr.HTML("""
312
+ <div class="main-header">
313
+ <h1>🤖 OpenAirAI-X Chat</h1>
314
+ <p>Войдите через Hugging Face, чтобы начать</p>
315
+ </div>
316
+ """)
317
+ gr.Markdown("""
318
+ ### 🔐 Вход в систему
319
+
320
+ Для использования чата необходимо войти через аккаунт Hugging Face.
321
+
322
+ **Преимущества входа:**
323
+ - 💾 Сохранение истории чатов
324
+ - 👑 PRO-статус для подписчиков
325
+ - 🔄 Доступ к предыдущим диалогам
326
+ """)
327
+ gr.LoginButton(value="🔑 Войти через Hugging Face", variant="primary")
328
+
329
+ # === ОБРАБОТЧИКИ СОБЫТИЙ ===
330
+
331
+ # Вход
332
+ main_interface_ref = main_interface
333
+ login_screen_ref = login_screen
334
+
335
+ # После OAuth
336
+ demo.load(
337
+ fn=lambda request: login_event(request) if request.username else (gr.update(), gr.update(), gr.update(), [], {}, None, [], gr.update()),
338
+ inputs=None,
339
+ outputs=[main_interface, login_screen, user_info, chatbot, history_state, current_chat_id_state, chat_list, pro_badge]
340
+ )
341
+
342
+ # Отправка сообщения
343
+ send_btn.click(
344
+ fn=generate_response,
345
+ inputs=[msg_input, chatbot, user_info, current_chat_id_state],
346
+ outputs=[chatbot, chatbot, msg_input, current_chat_id_state]
347
+ ).then(
348
+ fn=lambda username: get_chat_list(username),
349
+ inputs=[user_info],
350
+ outputs=[chat_list]
351
+ )
352
+
353
+ msg_input.submit(
354
+ fn=generate_response,
355
+ inputs=[msg_input, chatbot, user_info, current_chat_id_state],
356
+ outputs=[chatbot, chatbot, msg_input, current_chat_id_state]
357
+ ).then(
358
+ fn=lambda username: get_chat_list(username),
359
+ inputs=[user_info],
360
+ outputs=[chat_list]
361
+ )
362
+
363
+ # Новый чат
364
+ new_chat_btn.click(
365
+ fn=lambda username: new_chat(username),
366
+ inputs=[user_info],
367
+ outputs=[chatbot, history_state, current_chat_id_state]
368
+ ).then(
369
+ fn=lambda username: get_chat_list(username),
370
+ inputs=[user_info],
371
+ outputs=[chat_list]
372
+ )
373
+
374
+ # Загрузка чата
375
+ chat_list.change(
376
+ fn=load_chat,
377
+ inputs=[chat_list, user_info, current_chat_id_state],
378
+ outputs=[chatbot, current_chat_id_state]
379
+ )
380
+
381
+ # Удаление чата
382
+ delete_chat_btn.click(
383
+ fn=delete_chat,
384
+ inputs=[chat_list, user_info],
385
+ outputs=[chatbot, history_state, current_chat_id_state, chat_list]
386
+ )
387
+
388
+ # Выход
389
+ logout_btn.click(
390
+ fn=logout_event,
391
+ inputs=None,
392
+ outputs=[main_interface, login_screen, user_info, chatbot, history_state, current_chat_id_state, chat_list, pro_badge]
393
+ )
394
 
395
+ # Запуск
396
+ demo.launch(server_name="0.0.0.0", server_port=7860)