Anonym26 commited on
Commit
9abae96
·
verified ·
1 Parent(s): e012117

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -133
app.py CHANGED
@@ -1,133 +1,101 @@
1
- import gradio
2
- import gradio as gr
3
- import aiohttp
4
- import asyncio
5
- from PIL import Image
6
- from io import BytesIO
7
- from asyncio import Semaphore
8
- from dotenv import load_dotenv
9
- import os
10
-
11
- # Загрузка токена из .env файла
12
- load_dotenv()
13
- API_TOKEN = os.getenv("HF_API_TOKEN")
14
-
15
- # Конфигурация API
16
- HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
17
- MODELS = {
18
- "Midjourney": "Jovie/Midjourney",
19
- "FLUX.1 [dev]": "black-forest-labs/FLUX.1-dev",
20
- "Stable Diffusion v2.1": "stabilityai/stable-diffusion-2-1",
21
- "Stable Diffusion v3.5 Large": "stabilityai/stable-diffusion-3.5-large",
22
- "Stable Diffusion v1.0 Large": "stabilityai/stable-diffusion-xl-base-1.0",
23
- "Leonardo AI": "goofyai/Leonardo_Ai_Style_Illustration",
24
- }
25
-
26
- # Настройки
27
- MAX_CONCURRENT_REQUESTS = 3
28
- GROUP_DELAY = 1 # Задержка в секундах между группами запросов
29
-
30
-
31
- # Асинхронная функция для отправки запроса к API
32
- async def query_model(prompt, model_name, model_url, semaphore):
33
- async with semaphore: # Ограничиваем количество одновременно выполняемых задач
34
- try:
35
- async with aiohttp.ClientSession() as session:
36
- async with session.post(
37
- f"https://api-inference.huggingface.co/models/{model_url}",
38
- headers=HEADERS,
39
- json={"inputs": prompt},
40
- ) as response:
41
- if response.status == 200:
42
- image_data = await response.read()
43
- return model_name, Image.open(BytesIO(image_data))
44
- else:
45
- error_message = await response.json()
46
- warnings = error_message.get("warnings", [])
47
- print(f"Ошибка для модели {model_name}: {error_message.get('error', 'unknown error')}")
48
- if warnings:
49
- print(f"Предупреждения для модели {model_name}: {warnings}")
50
- return model_name, None
51
- except Exception as e:
52
- print(f"Ошибка соединения с моделью {model_name}: {e}")
53
- return model_name, None
54
-
55
-
56
- # Асинхронная обработка запросов первой группы
57
- async def handle_first_group(prompt):
58
- semaphore = Semaphore(MAX_CONCURRENT_REQUESTS) # Создаём локальный семафор
59
- tasks = [
60
- query_model(prompt, model_name, model_url, semaphore)
61
- for model_name, model_url in list(MODELS.items())[:3]
62
- ]
63
- results = await asyncio.gather(*tasks)
64
- return {model_name: image for model_name, image in results if image}
65
-
66
-
67
- # Асинхронная обработка запросов второй группы
68
- async def handle_second_group(prompt):
69
- await asyncio.sleep(GROUP_DELAY) # Задержка перед запросами ко второй группе
70
- semaphore = Semaphore(MAX_CONCURRENT_REQUESTS) # Создаём локальный семафор
71
- tasks = [
72
- query_model(prompt, model_name, model_url, semaphore)
73
- for model_name, model_url in list(MODELS.items())[3:]
74
- ]
75
- results = await asyncio.gather(*tasks)
76
- return {model_name: image for model_name, image in results if image}
77
-
78
-
79
- # Асинхронная обработка запросов
80
- async def handle(prompt):
81
- # Обработка двух групп моделей
82
- first_group_results = await handle_first_group(prompt)
83
- second_group_results = await handle_second_group(prompt)
84
- return {**first_group_results, **second_group_results}
85
-
86
-
87
- # Интерфейс Gradio
88
- with gr.Blocks() as demo:
89
- gr.Markdown("## Генерация изображений с использованием моделей Hugging Face")
90
-
91
- # Поле ввода
92
- user_input = gr.Textbox(label="Введите описание изображения", placeholder="Например, 'Красный автомобиль в лесу'")
93
-
94
- # Вывод изображений
95
- with gr.Row():
96
- outputs = {name: gr.Image(label=name) for name in MODELS.keys()}
97
-
98
- # Кнопка генерации
99
- generate_button = gr.Button("Сгенерировать")
100
-
101
- # Асинхронная обработка ввода
102
- async def on_submit(prompt):
103
- results = await handle(prompt)
104
- return [results.get(name, None) for name in MODELS.keys()]
105
-
106
- generate_button.click(
107
- fn=on_submit,
108
- inputs=[user_input],
109
- outputs=list(outputs.values()),
110
- )
111
- user_input.submit(
112
- fn=on_submit,
113
- inputs=[user_input],
114
- outputs=list(outputs.values()),
115
- )
116
-
117
- # Ссылки на соцсети
118
- with gr.Row():
119
- with gr.Column(scale=1):
120
- gr.Image(value='icon.jpg')
121
- with gr.Column(scale=4):
122
- gradio.HTML("""<div style="text-align: center; font-family: 'Helvetica Neue', sans-serif; padding: 10px; color: #333333;">
123
- <p style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">
124
- Эта демка была создана телеграм каналом <strong style="color: #007ACC;"><a href='https://t.me/mlphys'> mlphys</a></strong>. Другие мои социальные сети:
125
- </p>
126
- <p style="font-size: 16px;">
127
- <a href="https://t.me/mlphys" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">Telegram</a> |
128
- <a href="https://x.com/quensy23" target="_blank" style="color: #1DA1F2; text-decoration: none; font-weight: 500;">Twitter</a> |
129
- <a href="https://github.com/freQuensy23-coder" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">GitHub</a>
130
- </p>
131
- </div>""")
132
-
133
- demo.launch()
 
1
+ import gradio as gr
2
+ import aiohttp
3
+ import asyncio
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ from dotenv import load_dotenv
7
+ import os
8
+
9
+ # Загрузка токена из .env файла
10
+ load_dotenv()
11
+ API_TOKEN = os.getenv("HF_API_TOKEN")
12
+
13
+ # Конфигурация API
14
+ HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
15
+ MODELS = {
16
+ "Midjourney": "Jovie/Midjourney",
17
+ "FLUX.1 [dev]": "black-forest-labs/FLUX.1-dev",
18
+ "Stable Diffusion v2.1": "stabilityai/stable-diffusion-2-1",
19
+ "Stable Diffusion v3.5 Large": "stabilityai/stable-diffusion-3.5-large",
20
+ "Stable Diffusion v1.0 Large": "stabilityai/stable-diffusion-xl-base-1.0",
21
+ "Leonardo AI": "goofyai/Leonardo_Ai_Style_Illustration",
22
+ }
23
+
24
+ # Асинхронная функция для отправки запроса к API
25
+ async def query_model(prompt, model_name, model_url, session):
26
+ try:
27
+ async with session.post(
28
+ f"https://api-inference.huggingface.co/models/{model_url}",
29
+ headers=HEADERS,
30
+ json={"inputs": prompt},
31
+ ) as response:
32
+ if response.status == 200:
33
+ image_data = await response.read()
34
+ return model_name, Image.open(BytesIO(image_data))
35
+ else:
36
+ error_message = await response.json()
37
+ warnings = error_message.get("warnings", [])
38
+ print(f"Ошибка для модели {model_name}: {error_message.get('error', 'unknown error')}")
39
+ if warnings:
40
+ print(f"Предупреждения для модели {model_name}: {warnings}")
41
+ return model_name, None
42
+ except Exception as e:
43
+ print(f"Ошибка соединения с моделью {model_name}: {e}")
44
+ return model_name, None
45
+
46
+ # Асинхронная обработка всех запросов
47
+ async def handle(prompt):
48
+ async with aiohttp.ClientSession() as session: # Создаём единый клиент для всех запросов
49
+ tasks = [
50
+ query_model(prompt, model_name, model_url, session)
51
+ for model_name, model_url in MODELS.items()
52
+ ]
53
+ results = await asyncio.gather(*tasks)
54
+ return {model_name: image for model_name, image in results if image}
55
+
56
+ # Интерфейс Gradio
57
+ with gr.Blocks() as demo:
58
+ gr.Markdown("## Генерация изображений с использованием моделей Hugging Face")
59
+
60
+ # Поле ввода
61
+ user_input = gr.Textbox(label="Введите описание изображения", placeholder="Например, 'Красный автомобиль в лесу'")
62
+
63
+ # Вывод изображений
64
+ with gr.Row():
65
+ outputs = {name: gr.Image(label=name) for name in MODELS.keys()}
66
+
67
+ # Асинхронная обработка ввода
68
+ async def on_submit(prompt):
69
+ results = await handle(prompt)
70
+ return [results.get(name, None) for name in MODELS.keys()]
71
+
72
+ # Кнопка генерации
73
+ generate_button = gr.Button("Сгенерировать")
74
+ generate_button.click(
75
+ fn=on_submit,
76
+ inputs=[user_input],
77
+ outputs=list(outputs.values()),
78
+ )
79
+ user_input.submit(
80
+ fn=on_submit,
81
+ inputs=[user_input],
82
+ outputs=list(outputs.values()),
83
+ )
84
+
85
+ # Ссылки на соцсети
86
+ with gr.Row():
87
+ with gr.Column(scale=1):
88
+ gr.Image(value='icon.jpg')
89
+ with gr.Column(scale=4):
90
+ gradio.HTML("""<div style="text-align: center; font-family: 'Helvetica Neue', sans-serif; padding: 10px; color: #333333;">
91
+ <p style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">
92
+ Эта демка была создана телеграм каналом <strong style="color: #007ACC;"><a href='https://t.me/mlphys'> mlphys</a></strong>. Другие мои социальные се��и:
93
+ </p>
94
+ <p style="font-size: 16px;">
95
+ <a href="https://t.me/mlphys" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">Telegram</a> |
96
+ <a href="https://x.com/quensy23" target="_blank" style="color: #1DA1F2; text-decoration: none; font-weight: 500;">Twitter</a> |
97
+ <a href="https://github.com/freQuensy23-coder" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">GitHub</a>
98
+ </p>
99
+ </div>""")
100
+
101
+ demo.launch()