vlasdadsda commited on
Commit
73f5316
·
verified ·
1 Parent(s): 3451861

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +697 -23
app.py CHANGED
@@ -1,26 +1,700 @@
1
- import cv2
2
  import gradio as gr
 
 
 
 
 
 
 
 
3
  from ultralytics import YOLO
 
 
 
 
4
 
5
- def process_frame(model, frame):
6
- results = model(frame)
7
- for result in results:
8
- for box in result.boxes.data.tolist():
9
- x1, y1, x2, y2, confidence, class_id = box
10
- label = f"{model.names[int(class_id)]} {confidence:.2f}"
11
- cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 3)
12
- cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
13
- return frame
14
-
15
- def detect_objects(image):
16
- model = YOLO("s.pt") # Путь к вашей модели
17
- processed_image = process_frame(model, image)
18
- return processed_image
19
-
20
- # Интерфейс Gradio
21
- iface = gr.Interface(fn=detect_objects,
22
- inputs=gr.Image(type="numpy"),
23
- outputs=gr.Image(type="numpy"),
24
- live=True)
25
-
26
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import g4f
2
  import gradio as gr
3
+ import tempfile
4
+ import os
5
+ from pathlib import Path
6
+ from g4f.client import Client
7
+ from PIL import Image
8
+ import io
9
+ import requests
10
+ import numpy as np
11
  from ultralytics import YOLO
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from typing import Dict, Any, Optional
16
 
17
+ AVAILABLE_MODELS = {
18
+ "GPT-4": "gpt-4",
19
+ "GPT-4 Turbo": "gpt-4-turbo",
20
+ "GPT-4o": "gpt-4o",
21
+ }
22
+
23
+ SYSTEM_PROMPT = """
24
+ 1. Всегда используйте кодировку UTF-8
25
+ 2. Используйте обработку ошибок
26
+ 3. Если пользователь просит нарисовать или сгенерировать изображение:
27
+ - Начните ответ с [GENERATE_IMAGE]
28
+ - Напишите детальный промпт на английском языке
29
+ - Завершите промпт строкой [/GENERATE_IMAGE]
30
+ - Продолжите обычный ответ на русском языке
31
+ """
32
+
33
+ def test_code(code: str, file_type: str = ".py") -> Dict[str, Any]:
34
+ """Тестирование кода в безопасной среде"""
35
+ start_time = time.time()
36
+ result = {
37
+ "success": False,
38
+ "output": "",
39
+ "error": "",
40
+ "execution_time": 0
41
+ }
42
+
43
+ try:
44
+ code = "# -*- coding: utf-8 -*-\n" + code
45
+
46
+ with tempfile.NamedTemporaryFile(suffix=file_type, mode='w', encoding='utf-8', delete=False) as tmp:
47
+ tmp.write(code)
48
+ tmp_path = tmp.name
49
+
50
+ process = subprocess.Popen(
51
+ [sys.executable, tmp_path],
52
+ stdout=subprocess.PIPE,
53
+ stderr=subprocess.PIPE,
54
+ text=True,
55
+ encoding='utf-8'
56
+ )
57
+
58
+ try:
59
+ stdout, stderr = process.communicate(timeout=10)
60
+ result["success"] = process.returncode == 0
61
+ result["output"] = stdout
62
+ result["error"] = stderr
63
+
64
+ except subprocess.TimeoutExpired:
65
+ process.kill()
66
+ result["error"] = "Превышено время выполнения (10 сек)"
67
+
68
+ finally:
69
+ os.unlink(tmp_path)
70
+
71
+ except Exception as e:
72
+ result["error"] = str(e)
73
+
74
+ result["execution_time"] = time.time() - start_time
75
+ return result
76
+
77
+ def process_file(file):
78
+ """Обработка загруженного файла"""
79
+ if not file:
80
+ return None
81
+
82
+ try:
83
+ # Получаем расширение файла
84
+ file_extension = file.name.lower().split('.')[-1] if hasattr(file, 'name') else ''
85
+
86
+ # Список поддерживаемых форматов изображений
87
+ image_extensions = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}
88
+
89
+ # Если это изображение
90
+ if file_extension in image_extensions:
91
+ try:
92
+ # Открываем изображение
93
+ if isinstance(file, str):
94
+ image = Image.open(file)
95
+ else:
96
+ image = Image.open(io.BytesIO(file.read()))
97
+
98
+ # Анализируем изображение
99
+ return process_image(image)
100
+ except Exception as e:
101
+ return f"[Ошибка обработки изображения: {str(e)}]"
102
+
103
+ # Если это текстовый файл
104
+ if isinstance(file, str):
105
+ with open(file, 'r', encoding='utf-8') as f:
106
+ return f.read()
107
+ else:
108
+ return file.read().decode('utf-8')
109
+
110
+ except UnicodeDecodeError:
111
+ return "[Бинарный файл]"
112
+ except Exception as e:
113
+ return f"[Ошибка чтения файла: {str(e)}]"
114
+ def process_audio(file_path: str, operation: str) -> Optional[str]:
115
+ """Обработка аудио файлов"""
116
+ try:
117
+ from pydub import AudioSegment
118
+ audio = AudioSegment.from_file(file_path)
119
+
120
+ if "гр��мкость" in operation.lower():
121
+ audio = audio + 10
122
+
123
+ output_path = os.path.join(tempfile.gettempdir(), f"processed_{int(time.time())}.mp3")
124
+ audio.export(output_path, format="mp3")
125
+ return output_path
126
+
127
+ except Exception as e:
128
+ return f"Ошибка обработки аудио: {str(e)}"
129
+
130
+ def generate_image(prompt: str) -> str:
131
+ """Генерация изображения через g4f"""
132
+ try:
133
+ client = Client()
134
+ response = client.images.generate(
135
+ model="flux",
136
+ prompt=prompt,
137
+ response_format="url"
138
+ )
139
+ return response.data[0].url
140
+ except Exception as e:
141
+ return f"Ошибка при генерации изобраения: {str(e)}"
142
+
143
+ def process_image(image_input) -> str:
144
+ """Обработка изображения и распознавание объектов через YOLOv8"""
145
+ try:
146
+ # Загружаем модель YOLOv8n
147
+ model = YOLO('yolov11x.pt')
148
+
149
+ # Если передан URL
150
+ if isinstance(image_input, str):
151
+ response = requests.get(image_input)
152
+ image = Image.open(io.BytesIO(response.content))
153
+ # Если передан объект изображения
154
+ elif isinstance(image_input, Image.Image):
155
+ image = image_input
156
+ else:
157
+ return "❌ Неподдерживаемый формат изображения"
158
+
159
+ # Конвертируем изображение в RGB если оно в RGBA
160
+ if image.mode == 'RGBA':
161
+ image = image.convert('RGB')
162
+
163
+ # Сохраняем изображение во временный файл для обработки
164
+ with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
165
+ image.save(tmp.name, format='JPEG')
166
+ # Запускаем распознавание
167
+ results = model(tmp.name)
168
+
169
+ # Собираем найденные объекты
170
+ detected_objects = []
171
+ for r in results:
172
+ for box in r.boxes:
173
+ class_id = int(box.cls)
174
+ class_name = model.names[class_id]
175
+ detected_objects.append(class_name)
176
+
177
+ if not detected_objects:
178
+ return "Я ничего не вижу на этом изображении."
179
+
180
+ # Переводим объекты на русский
181
+ objects_str = ", ".join(detected_objects)
182
+
183
+ messages = [
184
+ {
185
+ "role": "system",
186
+ "content": """Ты - система компьютерного зрения.
187
+ Тебе нужно:
188
+ 1. Перевести названия объектов на русский язык
189
+ 2. Описать что ты видишь простыми словами
190
+ 3. Всегда отвечать на русском языке
191
+ 4. Начинать ответ со слов "Я на этом изображении вижу..."
192
+ 5. Никогда не говри "Похоже,что у вас есть описание изображения..."
193
+ """
194
+ },
195
+ {
196
+ "role": "user",
197
+ "content": f"Переведи и опиши эти объекты: {objects_str}"
198
+ }
199
+ ]
200
+
201
+ response = g4f.ChatCompletion.create(
202
+ model="gpt-4o",
203
+ messages=messages,
204
+ # provider=g4f.Provider.Airforce
205
+ )
206
+
207
+ # Сохраняем результат в истории чата
208
+ if isinstance(response, str):
209
+ return response
210
+ elif isinstance(response, dict) and "content" in response:
211
+ return response["content"]
212
+ else:
213
+ # Если что-то пошло не так, хотя бы покажем список объектов
214
+ return f"Я на этом изображении вижу: {objects_str}"
215
+
216
+ except Exception as e:
217
+ return f"❌ Ошибка при обработке изображения: {str(e)}"
218
+ finally:
219
+ if 'tmp' in locals():
220
+ Path(tmp.name).unlink(missing_ok=True)
221
+
222
+ def chat_response(message, history, model_name, direct_mode, uploaded_file=None):
223
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
224
+ history = history or []
225
+ history.append({"role": "user", "content": message})
226
+ history.append({"role": "assistant", "content": ""})
227
+ print(f"Получено сообщение: {message}")
228
+ print(f"Модель: {model_name}")
229
+ print(f"Прямая генерация: {direct_mode}")
230
+ print(f"Загруженный файл: {uploaded_file}")
231
+ try:
232
+ if direct_mode:
233
+ # Прямая отправка в нейронку для генерации изображения
234
+ image_url = generate_image(message)
235
+ if not image_url.startswith("Ошибка"):
236
+ # Анализируем изображение на наличие текста
237
+ image_analysis = process_image(image_url)
238
+ history[-1]["content"] = f"![Generated Image]({image_url})\n\n{image_analysis}"
239
+ else:
240
+ history[-1]["content"] = f"��� {image_url}"
241
+ yield history, *[gr.update(visible=False) for _ in range(6)]
242
+ return
243
+
244
+ # Начальные значения
245
+ yield (
246
+ history,
247
+ gr.update(visible=False),
248
+ gr.update(visible=False),
249
+ gr.update(visible=False),
250
+ "",
251
+ gr.update(visible=False),
252
+ gr.update(visible=False)
253
+ )
254
+
255
+ if uploaded_file:
256
+ file_content = process_file(uploaded_file)
257
+ if file_content:
258
+ message = f"Файл содержит:\n```\n{file_content}\n```\n\n{message}"
259
+
260
+ # Формируем историю сообщений
261
+ for msg in history[:-2]:
262
+ messages.append({"role": msg["role"], "content": msg["content"]})
263
+ messages.append({"role": "user", "content": str(message)})
264
+
265
+ partial_message = ""
266
+ code_block = None
267
+
268
+ response = g4f.ChatCompletion.create(
269
+ model=AVAILABLE_MODELS.get(model_name, "gpt-4o"),
270
+ messages=messages,
271
+ stream=True,
272
+ provider=g4f.Provider.Airforce
273
+ )
274
+
275
+ for chunk in response:
276
+ if chunk:
277
+ if isinstance(chunk, str):
278
+ partial_message += chunk
279
+
280
+ # Проверяем на запрос генерации изображения
281
+ if "[GENERATE_IMAGE]" in partial_message and "[/GENERATE_IMAGE]" in partial_message:
282
+ start_idx = partial_message.find("[GENERATE_IMAGE]") + len("[GENERATE_IMAGE]")
283
+ end_idx = partial_message.find("[/GENERATE_IMAGE]")
284
+ image_prompt = partial_message[start_idx:end_idx].strip()
285
+
286
+ # Показываем статус генерации
287
+ history[-1]["content"] = """
288
+ <div class="generating-animation">
289
+ <div class="generating-text">Генерация изображения...</div>
290
+ </div>
291
+ """
292
+ yield history, *[gr.update(visible=False) for _ in range(6)]
293
+
294
+ # Генерируем изображение
295
+ image_url = generate_image(image_prompt)
296
+
297
+ if not image_url.startswith("Ошибка"):
298
+ # Анализируем изображение на наличие текста
299
+ image_analysis = process_image(image_url)
300
+ explanation_text = partial_message[end_idx + len("[/GENERATE_IMAGE]"):].strip()
301
+ partial_message = f"![Generated Image]({image_url})\n\n{image_analysis}\n\n{explanation_text}"
302
+ else:
303
+ partial_message = f"❌ {image_url}"
304
+
305
+ history[-1]["content"] = partial_message + "▓"
306
+ yield history, *[gr.update(visible=False) for _ in range(6)]
307
+
308
+ # Проверяем наличие кода
309
+ if "```" in partial_message:
310
+ code_start = partial_message.rfind("```") + 3
311
+ code_end = partial_message.find("```", code_start)
312
+ if code_end != -1:
313
+ code_block = partial_message[code_start:code_end].strip()
314
+
315
+ # В конце убираем курсор
316
+ history[-1]["content"] = partial_message
317
+ yield history, *[gr.update(visible=True if code_block else False) for _ in range(6)]
318
+
319
+ except Exception as e:
320
+ print(f"Error: {e}")
321
+ history[-1]["content"] = f"❌ Произошла ошибка: {str(e)}"
322
+ yield (
323
+ history,
324
+ gr.update(visible=False),
325
+ gr.update(visible=True, value=str(e)),
326
+ gr.update(visible=True),
327
+ "",
328
+ gr.update(visible=False),
329
+ gr.update(visible=False)
330
+ )
331
+
332
+ def analyze_code(code):
333
+ """Анализ кода и получение объяснения"""
334
+ if not code:
335
+ return [{"role": "assistant", "content": "❌ Нет кода для анализа"}]
336
+
337
+ prompt = f"""Проанализируй этот код и объясни:
338
+ 1. Что он делает
339
+ 2. Возможные проблемы или ошибки
340
+ 3. Как можно улучшить
341
+ 4. Примеры исп��льзования
342
+
343
+ Код:
344
+ ```
345
+ {code}
346
+ ```"""
347
+
348
+ try:
349
+ response = g4f.ChatCompletion.create(
350
+ model="gpt-4o",
351
+ messages=[{"role": "user", "content": prompt}],
352
+ stream=False
353
+ )
354
+ return [{"role": "assistant", "content": response if isinstance(response, str) else "Не удалось получить анализ"}]
355
+ except Exception as e:
356
+ return [{"role": "assistant", "content": f"❌ Ошибка при анализе: {str(e)}"}]
357
+
358
+ def create_interface():
359
+ # Обновляем тему на темную
360
+ theme = gr.themes.Soft(
361
+ primary_hue="slate",
362
+ secondary_hue="gray",
363
+ ).set(
364
+ body_background_fill="#1a1a1a",
365
+ body_text_color="#ffffff",
366
+ button_primary_background_fill="#2d2d2d",
367
+ button_primary_background_fill_hover="#3d3d3d",
368
+ button_primary_text_color="white",
369
+ block_label_background_fill="#2d2d2d",
370
+ block_title_text_color="#ffffff",
371
+ input_background_fill="#2d2d2d",
372
+ )
373
+
374
+ # Обновляем CSS стили для управления цветом кода
375
+ css = """
376
+ .gradio-container {
377
+ background-color: #1a1a1a !important;
378
+ }
379
+ .chatbot {
380
+ background-color: #2d2d2d !important;
381
+ border-radius: 10px;
382
+ box-shadow: 0 2px 6px rgba(0,0,0,0.15);
383
+ }
384
+ .message.user {
385
+ background-color: #3d3d3d !important;
386
+ color: white !important;
387
+ border-radius: 15px;
388
+ }
389
+ .message.bot {
390
+ background-color: #2d2d2d !important;
391
+ color: white !important;
392
+ border-radius: 15px;
393
+ position: relative;
394
+ transition: all 0.3s ease;
395
+ }
396
+ /* Добавляем стиль для блоков кода */
397
+ .message.bot pre {
398
+ background-color: #1a1a1a !important;
399
+ border-radius: 8px;
400
+ padding: 10px;
401
+ }
402
+ .message.bot.typing::after {
403
+ content: '|';
404
+ animation: cursor 1s infinite;
405
+ }
406
+ @keyframes cursor {
407
+ 0% { opacity: 0; }
408
+ 50% { opacity: 1; }
409
+ 100% { opacity: 0; }
410
+ }
411
+
412
+ .message.bot:last-child {
413
+ animation: fadeIn 0.3s ease-in-out;
414
+ }
415
+
416
+ /* Убираем дублирующиеся стили курсора */
417
+ .message.bot:last-child:not(:empty)::after {
418
+ content: '';
419
+ }
420
+
421
+ /* Анимация появления текста */
422
+ @keyframes fadeIn {
423
+ from {
424
+ opacity: 0;
425
+ transform: translateY(10px);
426
+ }
427
+ to {
428
+ opacity: 1;
429
+ transform: translateY(0);
430
+ }
431
+ }
432
+
433
+ @keyframes cursor {
434
+ 0% { opacity: 0; }
435
+ 50% { opacity: 1; }
436
+ 100% { opacity: 0; }
437
+ }
438
+ .footer {
439
+ display: none !important;
440
+ }
441
+
442
+ .generating-animation {
443
+ position: relative;
444
+ width: 100%;
445
+ height: 120px;
446
+ background: linear-gradient(45deg, #1a1a1a, #2d2d2d);
447
+ border-radius: 15px;
448
+ overflow: hidden;
449
+ display: flex;
450
+ align-items: center;
451
+ justify-content: center;
452
+ }
453
+
454
+ .generating-text {
455
+ color: white;
456
+ font-size: 16px;
457
+ z-index: 2;
458
+ animation: pulse 1.5s infinite;
459
+ }
460
+
461
+ .generating-animation::before {
462
+ content: '';
463
+ position: absolute;
464
+ width: 200%;
465
+ height: 200%;
466
+ top: -50%;
467
+ left: -50%;
468
+ background:
469
+ radial-gradient(2px 2px at 20% 30%, rgba(255,255,255,0.8), rgba(0,0,0,0)),
470
+ radial-gradient(2px 2px at 40% 70%, rgba(255,255,255,0.8), rgba(0,0,0,0)),
471
+ radial-gradient(2px 2px at 50% 40%, rgba(255,255,255,0.8), rgba(0,0,0,0)),
472
+ radial-gradient(2px 2px at 60% 60%, rgba(255,255,255,0.8), rgba(0,0,0,0));
473
+ background-repeat: repeat;
474
+ animation: rotate 8s linear infinite;
475
+ }
476
+
477
+ @keyframes rotate {
478
+ from {
479
+ transform: rotate(0deg);
480
+ }
481
+ to {
482
+ transform: rotate(360deg);
483
+ }
484
+ }
485
+
486
+ @keyframes pulse {
487
+ 0% { opacity: 0.6; }
488
+ 50% { opacity: 1; }
489
+ 100% { opacity: 0.6; }
490
+ }
491
+
492
+ .submit-btn {
493
+ min-width: 100px !important;
494
+ cursor: pointer !important;
495
+ background-color: #4a4a4a !important;
496
+ transition: all 0.2s ease;
497
+ }
498
+
499
+ .submit-btn:hover {
500
+ background-color: #5a5a5a !important;
501
+ }
502
+
503
+ .input-row {
504
+ gap: 8px;
505
+ padding: 8px;
506
+ background: #2d2d2d;
507
+ border-radius: 8px;
508
+ margin-top: 8px;
509
+ }
510
+
511
+ .footer {
512
+ display: none !important;
513
+ }
514
+ """
515
+
516
+
517
+
518
+ with gr.Blocks(theme=theme, css=css) as demo:
519
+ # gr.Markdown("# 💬 AI Chat Assistant")
520
+
521
+ current_code = gr.State("")
522
+
523
+ with gr.Row():
524
+ with gr.Column(scale=4):
525
+ chatbot = gr.Chatbot(
526
+ height="600px",
527
+ show_label=False,
528
+ container=True,
529
+ show_copy_button=True,
530
+ elem_classes="chatbot",
531
+ type="messages",
532
+ render_markdown=True
533
+ )
534
+
535
+ # Добавляем компоненты для вывода
536
+ output_text = gr.Textbox(
537
+ label="Вывод",
538
+ interactive=False,
539
+ visible=False
540
+ )
541
+ error_text = gr.Textbox(
542
+ label="⚠️ Ошибки",
543
+ interactive=False,
544
+ visible=False
545
+ )
546
+ ask_help_btn = gr.Button(
547
+ "❓ Спросить почему возникла ошибка",
548
+ visible=False
549
+ )
550
+
551
+ with gr.Row(elem_classes="input-row"):
552
+ msg = gr.Textbox(
553
+ placeholder="Спросите что-нибудь...",
554
+ container=False,
555
+ scale=4,
556
+ show_label=False,
557
+ lines=1, # Явно указываем одну строку
558
+ elem_classes="input-textbox"
559
+ )
560
+ submit = gr.Button(
561
+ "Отправить",
562
+ variant="primary",
563
+ scale=1,
564
+ elem_classes="submit-btn"
565
+ )
566
+ clear = gr.Button("Очистить", scale=1)
567
+
568
+ with gr.Column(scale=1, visible=True) as sidebar:
569
+ model = gr.Dropdown(
570
+ choices=list(AVAILABLE_MODELS.keys()),
571
+ value="GPT-4o",
572
+ label="Модель"
573
+ )
574
+ direct_mode = gr.Checkbox(
575
+ label="Прямая генерация (без обрботки прмпта)",
576
+ value=False
577
+ )
578
+ file_output = gr.File(label="Загрузить файл")
579
+
580
+ # Добавляем примеры ипользования в виде кнопок
581
+
582
+
583
+ # Добавляем кнопки анализа и запуска кода
584
+ analyze_btn = gr.Button(
585
+ "Анализировать",
586
+ visible=False,
587
+ elem_classes="analyze-btn"
588
+ )
589
+
590
+ run_btn = gr.Button(
591
+ "▶️ Запустить код",
592
+ visible=False,
593
+ elem_classes="run-btn"
594
+ )
595
+
596
+ def run_code(code):
597
+ if not code:
598
+ return {
599
+ output_text: gr.update(value=" Нет кода для выполнения", visible=True),
600
+ error_text: gr.update(visible=False),
601
+ ask_help_btn: gr.update(visible=False)
602
+ }
603
+
604
+ result = test_code(code)
605
+
606
+ return {
607
+ output_text: gr.update(value=result["output"] if result["success"] else "", visible=True),
608
+ error_text: gr.update(value=result["error"], visible=bool(result["error"])),
609
+ # ask_help_btn: gr.update(visible=bool(result["error"]))
610
+ }
611
+
612
+ def handle_error_question(error_message, code_block):
613
+ """Обработчик кнопки помощи с ошибкой"""
614
+ error_prompt = f"""Объясните ошибку и как её исправить:
615
+
616
+ Код:
617
+ ```
618
+ {code_block}
619
+ ```
620
+
621
+ Ошибка:
622
+ {error_message}"""
623
+
624
+ try:
625
+ response = g4f.ChatCompletion.create(
626
+ model="gpt-3.5-turbo",
627
+ messages=[{"role": "user", "content": error_prompt}],
628
+ stream=False
629
+ )
630
+ return [{"role": "assistant", "content": response if isinstance(response, str) else "Не удалось получиь ответ"}]
631
+ except Exception as e:
632
+ return [{"role": "assistant", "content": f"Ошибка при получнии объяснения: {str(e)}"}]
633
+
634
+ # Обработчики событий
635
+ msg.submit(
636
+ fn=chat_response,
637
+ inputs=[msg, chatbot, model, direct_mode, file_output],
638
+ outputs=[chatbot, output_text, error_text, ask_help_btn, current_code, analyze_btn, run_btn],
639
+ api_name=None, # Изменим с False на None
640
+ show_progress=True
641
+ ).then(
642
+ fn=lambda: gr.update(value=""),
643
+ outputs=[msg]
644
+ )
645
+
646
+ submit.click(
647
+ fn=chat_response,
648
+ inputs=[msg, chatbot, model, direct_mode, file_output],
649
+ outputs=[chatbot, output_text, error_text, ask_help_btn, current_code, analyze_btn, run_btn],
650
+ api_name=None, # Изменим с False ��а None
651
+ show_progress=True
652
+ ).then(
653
+ fn=lambda: gr.update(value=""),
654
+ outputs=[msg]
655
+ )
656
+
657
+ ask_help_btn.click(
658
+ fn=handle_error_question,
659
+ inputs=[error_text, current_code],
660
+ outputs=chatbot
661
+ )
662
+
663
+ analyze_btn.click(
664
+ fn=analyze_code,
665
+ inputs=[current_code],
666
+ outputs=[chatbot]
667
+ )
668
+
669
+ run_btn.click(
670
+ fn=run_code,
671
+ inputs=[current_code],
672
+ outputs=[output_text, error_text, ask_help_btn]
673
+ )
674
+
675
+ clear.click(
676
+ fn=lambda: (None, "", "", False, ""),
677
+ outputs=[chatbot, output_text, error_text, ask_help_btn, current_code]
678
+ )
679
+
680
+ return demo
681
+
682
+
683
+ if __name__ == "__main__":
684
+ demo = create_interface()
685
+ demo.queue() # Добавим параметр concurrency_count
686
+
687
+ # Запускаем мониторинг изменений в тдельном потоке
688
+
689
+
690
+ demo.launch(
691
+ show_api=False,
692
+ show_error=True,
693
+ server_name="127.0.0.1",
694
+ server_port=7860,
695
+ favicon_path=None,
696
+ auth=None,
697
+ # quiet=True, # Добавим этот параметр
698
+
699
+
700
+ )