vlasdadsda commited on
Commit
4d39bd7
·
verified ·
1 Parent(s): b4db1bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -737
app.py CHANGED
@@ -1,740 +1,8 @@
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
- # Обновляем JavaScript, уберем проблемный код
517
- js = """
518
- document.addEventListener('DOMContentLoaded', function() {
519
- // Добавляем стили
520
- var style = document.createElement('style');
521
- style.textContent = '.particle { position: absolute; background: white; width: 3px; height: 3px; border-radius: 50%; pointer-events: none; }';
522
- document.head.appendChild(style);
523
-
524
- // Функция для создания частиц
525
- function addParticles(event) {
526
- var btn = event.currentTarget;
527
- for(var i = 0; i < 8; i++) {
528
- var p = document.createElement('div');
529
- p.className = 'particle';
530
- p.style.left = event.offsetX + 'px';
531
- p.style.top = event.offsetY + 'px';
532
-
533
- // Случайное движение
534
- var x = (Math.random() - 0.5) * 50;
535
- var y = (Math.random() - 0.5) * 50;
536
-
537
- p.animate([
538
- { transform: 'translate(0, 0)', opacity: 1 },
539
- { transform: 'translate(' + x + 'px, ' + y + 'px)', opacity: 0 }
540
- ], {
541
- duration: 500,
542
- easing: 'ease-out'
543
- }).onfinish = function() { p.remove(); };
544
-
545
- btn.appendChild(p);
546
- }
547
- }
548
-
549
- // Добвляем обработчики на кнопки
550
- var buttons = document.querySelectorAll('.submit-btn, .analyze-btn, .run-btn');
551
- buttons.forEach(function(btn) {
552
- btn.style.position = 'relative';
553
- btn.style.overflow = 'hidden';
554
- btn.addEventListener('click', addParticles);
555
- });
556
- });
557
- """
558
-
559
- with gr.Blocks(theme=theme, css=css) as demo:
560
- # gr.Markdown("# 💬 AI Chat Assistant")
561
-
562
- current_code = gr.State("")
563
-
564
- with gr.Row():
565
- with gr.Column(scale=4):
566
- chatbot = gr.Chatbot(
567
- height="600px",
568
- show_label=False,
569
- container=True,
570
- show_copy_button=True,
571
- elem_classes="chatbot",
572
- type="messages",
573
- render_markdown=True
574
- )
575
-
576
- # Добавляем компоненты для вывода
577
- output_text = gr.Textbox(
578
- label="Вывод",
579
- interactive=False,
580
- visible=False
581
- )
582
- error_text = gr.Textbox(
583
- label="⚠️ Ошибки",
584
- interactive=False,
585
- visible=False
586
- )
587
- ask_help_btn = gr.Button(
588
- "❓ Спросить почему возникла ошибка",
589
- visible=False
590
- )
591
-
592
- with gr.Row(elem_classes="input-row"):
593
- msg = gr.Textbox(
594
- placeholder="Спросите что-нибудь...",
595
- container=False,
596
- scale=4,
597
- show_label=False,
598
- lines=1, # Явно указываем одну строку
599
- elem_classes="input-textbox"
600
- )
601
- submit = gr.Button(
602
- "Отправить",
603
- variant="primary",
604
- scale=1,
605
- elem_classes="submit-btn"
606
- )
607
- clear = gr.Button("Очистить", scale=1)
608
-
609
- with gr.Column(scale=1, visible=True) as sidebar:
610
- model = gr.Dropdown(
611
- choices=list(AVAILABLE_MODELS.keys()),
612
- value="GPT-4o",
613
- label="Модель"
614
- )
615
- direct_mode = gr.Checkbox(
616
- label="Прямая генерация (без обрботки прмпта)",
617
- value=False
618
- )
619
- file_output = gr.File(label="Загрузить файл")
620
-
621
- # Добавляем примеры ипользования в виде кнопок
622
-
623
-
624
- # Добавляем кнопки анализа и запуска кода
625
- analyze_btn = gr.Button(
626
- "Анализировать",
627
- visible=False,
628
- elem_classes="analyze-btn"
629
- )
630
-
631
- run_btn = gr.Button(
632
- "▶️ Запустить код",
633
- visible=False,
634
- elem_classes="run-btn"
635
- )
636
-
637
- def run_code(code):
638
- if not code:
639
- return {
640
- output_text: gr.update(value=" Нет кода для выполнения", visible=True),
641
- error_text: gr.update(visible=False),
642
- ask_help_btn: gr.update(visible=False)
643
- }
644
-
645
- result = test_code(code)
646
-
647
- return {
648
- output_text: gr.update(value=result["output"] if result["success"] else "", visible=True),
649
- error_text: gr.update(value=result["error"], visible=bool(result["error"])),
650
- # ask_help_btn: gr.update(visible=bool(result["error"]))
651
- }
652
-
653
- def handle_error_question(error_message, code_block):
654
- """Обработчик кнопки помощи с ошибкой"""
655
- error_prompt = f"""Объясните ошибку и как её исправить:
656
-
657
- Код:
658
- ```
659
- {code_block}
660
- ```
661
-
662
- Ошибка:
663
- {error_message}"""
664
-
665
- try:
666
- response = g4f.ChatCompletion.create(
667
- model="gpt-3.5-turbo",
668
- messages=[{"role": "user", "content": error_prompt}],
669
- stream=False
670
- )
671
- return [{"role": "assistant", "content": response if isinstance(response, str) else "Не удалось получиь ответ"}]
672
- except Exception as e:
673
- return [{"role": "assistant", "content": f"Ошибка при получнии объяснения: {str(e)}"}]
674
-
675
- # Обработчики событий
676
- msg.submit(
677
- fn=chat_response,
678
- inputs=[msg, chatbot, model, direct_mode, file_output],
679
- outputs=[chatbot, output_text, error_text, ask_help_btn, current_code, analyze_btn, run_btn],
680
- api_name=None, # Изменим с False на None
681
- show_progress=True
682
- ).then(
683
- fn=lambda: gr.update(value=""),
684
- outputs=[msg]
685
- )
686
-
687
- submit.click(
688
- fn=chat_response,
689
- inputs=[msg, chatbot, model, direct_mode, file_output],
690
- outputs=[chatbot, output_text, error_text, ask_help_btn, current_code, analyze_btn, run_btn],
691
- api_name=None, # Изменим с False на None
692
- show_progress=True
693
- ).then(
694
- fn=lambda: gr.update(value=""),
695
- outputs=[msg]
696
- )
697
-
698
- ask_help_btn.click(
699
- fn=handle_error_question,
700
- inputs=[error_text, current_code],
701
- outputs=chatbot
702
- )
703
-
704
- analyze_btn.click(
705
- fn=analyze_code,
706
- inputs=[current_code],
707
- outputs=[chatbot]
708
- )
709
-
710
- run_btn.click(
711
- fn=run_code,
712
- inputs=[current_code],
713
- outputs=[output_text, error_text, ask_help_btn]
714
- )
715
-
716
- clear.click(
717
- fn=lambda: (None, "", "", False, ""),
718
- outputs=[chatbot, output_text, error_text, ask_help_btn, current_code]
719
- )
720
-
721
- return demo
722
-
723
-
724
- if __name__ == "__main__":
725
- demo = create_interface()
726
- demo.queue() # Добавим параметр concurrency_count
727
-
728
- # Запускаем мониторинг изменений в тдельном потоке
729
-
730
-
731
- demo.launch(
732
- show_api=False,
733
- show_error=True,
734
- server_name="127.0.0.1",
735
- server_port=7860,
736
- favicon_path=None,
737
- auth=None,
738
- # quiet=True, # Добавим этот параметр
739
-
740
- )
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ def greet(img):
4
+ print(img)
5
+ return "Hello World"
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ iface = gr.Interface(fn=greet, inputs="image", outputs="text")
8
+ iface.launch()