Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,8 @@
|
|
| 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
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
import os
|
| 10 |
|
|
@@ -12,8 +10,7 @@ import os
|
|
| 12 |
load_dotenv()
|
| 13 |
API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 14 |
|
| 15 |
-
# Конфигурация
|
| 16 |
-
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
|
| 17 |
MODELS = {
|
| 18 |
"Midjourney": "Jovie/Midjourney",
|
| 19 |
"FLUX.1 [dev]": "black-forest-labs/FLUX.1-dev",
|
|
@@ -23,66 +20,35 @@ MODELS = {
|
|
| 23 |
"Leonardo AI": "goofyai/Leonardo_Ai_Style_Illustration",
|
| 24 |
}
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
# Асинхронная функция для отправки запроса к API
|
| 31 |
-
async def query_model(prompt, model_name, model_url
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
else:
|
| 44 |
-
error_message = await response.json()
|
| 45 |
-
warnings = error_message.get("warnings", [])
|
| 46 |
-
print(f"Ошибка для модели {model_name}: {error_message.get('error', 'unknown error')}")
|
| 47 |
-
if warnings:
|
| 48 |
-
print(f"Предупреждения для модели {model_name}: {warnings}")
|
| 49 |
-
return model_name, None
|
| 50 |
-
except Exception as e:
|
| 51 |
-
print(f"Ошибка соединения с моделью {model_name}: {e}")
|
| 52 |
-
return model_name, None
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
# Асинхронная обработка запросов первой группы
|
| 56 |
-
async def handle_first_group(prompt):
|
| 57 |
-
semaphore = Semaphore(MAX_CONCURRENT_REQUESTS) # Создаём локальный семафор
|
| 58 |
-
tasks = [
|
| 59 |
-
query_model(prompt, model_name, model_url, semaphore)
|
| 60 |
-
for model_name, model_url in list(MODELS.items())[:3]
|
| 61 |
-
]
|
| 62 |
-
results = await asyncio.gather(*tasks)
|
| 63 |
-
return {model_name: image for model_name, image in results if image}
|
| 64 |
|
| 65 |
|
| 66 |
-
# Асинхронная обработка запросов
|
| 67 |
-
async def
|
| 68 |
-
await asyncio.sleep(GROUP_DELAY) # Задержка перед запросами ко второй группе
|
| 69 |
-
semaphore = Semaphore(MAX_CONCURRENT_REQUESTS) # Создаём локальный семафор
|
| 70 |
tasks = [
|
| 71 |
-
query_model(prompt, model_name, model_url
|
| 72 |
-
for model_name, model_url in
|
| 73 |
]
|
| 74 |
results = await asyncio.gather(*tasks)
|
| 75 |
return {model_name: image for model_name, image in results if image}
|
| 76 |
|
| 77 |
|
| 78 |
-
# Асинхронная обработка запросов
|
| 79 |
-
async def handle(prompt):
|
| 80 |
-
# Обработка двух групп моделей
|
| 81 |
-
first_group_results = await handle_first_group(prompt)
|
| 82 |
-
second_group_results = await handle_second_group(prompt)
|
| 83 |
-
return {**first_group_results, **second_group_results}
|
| 84 |
-
|
| 85 |
-
|
| 86 |
# Интерфейс Gradio
|
| 87 |
with gr.Blocks() as demo:
|
| 88 |
gr.Markdown("## Генерация изображений с использованием моделей Hugging Face")
|
|
@@ -116,9 +82,10 @@ with gr.Blocks() as demo:
|
|
| 116 |
# Ссылки на соцсети
|
| 117 |
with gr.Row():
|
| 118 |
with gr.Column(scale=1):
|
| 119 |
-
gr.Image(value=
|
| 120 |
with gr.Column(scale=4):
|
| 121 |
-
|
|
|
|
| 122 |
<p style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">
|
| 123 |
Эта демка была создана телеграм каналом <strong style="color: #007ACC;"><a href='https://t.me/mlphys'> mlphys</a></strong>. Другие мои социальные сети:
|
| 124 |
</p>
|
|
@@ -127,6 +94,7 @@ with gr.Blocks() as demo:
|
|
| 127 |
<a href="https://x.com/quensy23" target="_blank" style="color: #1DA1F2; text-decoration: none; font-weight: 500;">Twitter</a> |
|
| 128 |
<a href="https://github.com/freQuensy23-coder" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">GitHub</a>
|
| 129 |
</p>
|
| 130 |
-
</div>"""
|
|
|
|
| 131 |
|
| 132 |
demo.launch()
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import asyncio
|
| 3 |
from PIL import Image
|
| 4 |
from io import BytesIO
|
| 5 |
+
from huggingface_hub import AsyncInferenceClient
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
import os
|
| 8 |
|
|
|
|
| 10 |
load_dotenv()
|
| 11 |
API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 12 |
|
| 13 |
+
# Конфигурация моделей
|
|
|
|
| 14 |
MODELS = {
|
| 15 |
"Midjourney": "Jovie/Midjourney",
|
| 16 |
"FLUX.1 [dev]": "black-forest-labs/FLUX.1-dev",
|
|
|
|
| 20 |
"Leonardo AI": "goofyai/Leonardo_Ai_Style_Illustration",
|
| 21 |
}
|
| 22 |
|
| 23 |
+
# Инициализация клиента
|
| 24 |
+
client = AsyncInferenceClient(token=API_TOKEN)
|
| 25 |
+
|
| 26 |
|
| 27 |
# Асинхронная функция для отправки запроса к API
|
| 28 |
+
async def query_model(prompt, model_name, model_url):
|
| 29 |
+
try:
|
| 30 |
+
response = await client.text_to_image(
|
| 31 |
+
prompt=prompt, model=model_url, stream=False
|
| 32 |
+
)
|
| 33 |
+
# Декодирование изображения
|
| 34 |
+
image_data = response["images"][0]
|
| 35 |
+
image = Image.open(BytesIO(image_data))
|
| 36 |
+
return model_name, image
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Ошибка для модели {model_name}: {e}")
|
| 39 |
+
return model_name, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
+
# Асинхронная обработка запросов
|
| 43 |
+
async def handle(prompt):
|
|
|
|
|
|
|
| 44 |
tasks = [
|
| 45 |
+
query_model(prompt, model_name, model_url)
|
| 46 |
+
for model_name, model_url in MODELS.items()
|
| 47 |
]
|
| 48 |
results = await asyncio.gather(*tasks)
|
| 49 |
return {model_name: image for model_name, image in results if image}
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# Интерфейс Gradio
|
| 53 |
with gr.Blocks() as demo:
|
| 54 |
gr.Markdown("## Генерация изображений с использованием моделей Hugging Face")
|
|
|
|
| 82 |
# Ссылки на соцсети
|
| 83 |
with gr.Row():
|
| 84 |
with gr.Column(scale=1):
|
| 85 |
+
gr.Image(value="icon.jpg")
|
| 86 |
with gr.Column(scale=4):
|
| 87 |
+
gr.HTML(
|
| 88 |
+
"""<div style="text-align: center; font-family: 'Helvetica Neue', sans-serif; padding: 10px; color: #333333;">
|
| 89 |
<p style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">
|
| 90 |
Эта демка была создана телеграм каналом <strong style="color: #007ACC;"><a href='https://t.me/mlphys'> mlphys</a></strong>. Другие мои социальные сети:
|
| 91 |
</p>
|
|
|
|
| 94 |
<a href="https://x.com/quensy23" target="_blank" style="color: #1DA1F2; text-decoration: none; font-weight: 500;">Twitter</a> |
|
| 95 |
<a href="https://github.com/freQuensy23-coder" target="_blank" style="color: #0088cc; text-decoration: none; font-weight: 500;">GitHub</a>
|
| 96 |
</p>
|
| 97 |
+
</div>"""
|
| 98 |
+
)
|
| 99 |
|
| 100 |
demo.launch()
|