Spaces:
Runtime error
Runtime error
delete old code and rest api
Browse files- app.py +1 -144
- requirements.txt +0 -3
app.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
import os
|
2 |
-
import io
|
3 |
import time
|
4 |
from datetime import datetime
|
5 |
import pytz
|
@@ -7,16 +6,12 @@ import spaces
|
|
7 |
import torch
|
8 |
import gradio as gr
|
9 |
import traceback
|
10 |
-
import asyncio
|
11 |
import threading
|
12 |
from transformers import pipeline
|
13 |
from huggingface_hub import login
|
14 |
from diffusers import FluxPipeline
|
15 |
from aura_sr import AuraSR
|
16 |
from deep_translator import GoogleTranslator
|
17 |
-
from fastapi import FastAPI, Response, Request, HTTPException, status
|
18 |
-
import uvicorn
|
19 |
-
from pydantic import BaseModel
|
20 |
|
21 |
def log(*args, **kwargs):
|
22 |
tid = threading.get_ident()
|
@@ -148,15 +143,6 @@ def generate_image_stable(prompt, steps):
|
|
148 |
num_images_per_prompt=1
|
149 |
).images[0]
|
150 |
|
151 |
-
async def generate_image_async(object_name: str, remove_bg: bool, upscale: bool):
|
152 |
-
# Выносим синхронную функцию в отдельный поток
|
153 |
-
return await asyncio.to_thread(
|
154 |
-
generate_image,
|
155 |
-
object_name,
|
156 |
-
remove_bg,
|
157 |
-
upscale
|
158 |
-
)
|
159 |
-
|
160 |
def create_template_prompt(object_name):
|
161 |
template = load_text("prompt.txt")
|
162 |
return template.format(object_name = object_name)
|
@@ -181,35 +167,6 @@ def load_text(file_name):
|
|
181 |
with open(file_name, 'r', encoding='utf-8') as f:
|
182 |
return f.read()
|
183 |
|
184 |
-
fastapi_app = FastAPI()
|
185 |
-
|
186 |
-
# Модель данных для POST-запроса
|
187 |
-
class GenerateRequest(BaseModel):
|
188 |
-
object_name: str
|
189 |
-
remove_bg: bool
|
190 |
-
upscale: bool
|
191 |
-
|
192 |
-
@fastapi_app.post("/api/generate_image")
|
193 |
-
async def api_generate_image(rq: GenerateRequest, rest_request: Request):
|
194 |
-
client_ip = rest_request.headers.get('X-Forwarded-For', rest_request.client.host)
|
195 |
-
log("Получили запрос через рест АПИ.")
|
196 |
-
log(f"Client IP: {client_ip}")
|
197 |
-
rq_token = rest_request.headers.get('Authorization')
|
198 |
-
if not rq_token:
|
199 |
-
raise HTTPException(
|
200 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
201 |
-
detail="Not authorized"
|
202 |
-
)
|
203 |
-
login(token = rq_token)
|
204 |
-
image = await generate_image_async(rq.object_name, rq.remove_bg, rq.upscale)
|
205 |
-
log(f"Подготовка ответа для рест АПИ.")
|
206 |
-
img_byte_arr = io.BytesIO()
|
207 |
-
image.save(img_byte_arr, format='WEBP')
|
208 |
-
img_byte_arr = img_byte_arr.getvalue()
|
209 |
-
log(f"Возвращаем ответ для рест АПИ.")
|
210 |
-
return Response(content=img_byte_arr, media_type="image/webp")
|
211 |
-
|
212 |
-
|
213 |
custom_css = load_text("style.css")
|
214 |
|
215 |
# Создание интерфейса Gradio
|
@@ -296,106 +253,6 @@ with gr.Blocks(title="3D Icon Generator", css=custom_css, theme=gr.themes.Defaul
|
|
296 |
outputs=[output_image]
|
297 |
)
|
298 |
|
299 |
-
|
300 |
-
main_app = gr.mount_gradio_app(fastapi_app, app, path="/")
|
301 |
-
|
302 |
# Запуск приложения
|
303 |
if __name__ == "__main__":
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
### OLD UNUSED CODE!!! BE CAREFUL!!! ###
|
310 |
-
|
311 |
-
# Создаем необходимые директории
|
312 |
-
# os.makedirs("models", exist_ok=True)
|
313 |
-
# os.makedirs("models/checkpoints", exist_ok=True)
|
314 |
-
# os.makedirs("models/loras", exist_ok=True)
|
315 |
-
# os.makedirs("models/upscale_models", exist_ok=True)
|
316 |
-
# os.makedirs("models/rembg", exist_ok=True)
|
317 |
-
# os.makedirs("outputs", exist_ok=True)
|
318 |
-
# os.makedirs("temp_uploads", exist_ok=True)
|
319 |
-
|
320 |
-
|
321 |
-
# Загрузка моделей с Hugging Face
|
322 |
-
# def download_model(repo_id, filename, local_dir):
|
323 |
-
# """Загрузка модели с Hugging Face Hub"""
|
324 |
-
# local_path = os.path.join(local_dir, filename)
|
325 |
-
# if not os.path.exists(local_path):
|
326 |
-
# print(f"Загрузка {filename} из {repo_id}...")
|
327 |
-
# try:
|
328 |
-
# file_path = hf_hub_download(
|
329 |
-
# repo_id=repo_id,
|
330 |
-
# filename=filename,
|
331 |
-
# local_dir=local_dir,
|
332 |
-
# local_dir_use_symlinks=False
|
333 |
-
# )
|
334 |
-
# print(f"Модель успешно загружена: {file_path}")
|
335 |
-
# return file_path
|
336 |
-
# except Exception as e:
|
337 |
-
# print(f"Ошибка при загрузке модели {filename}: {e}")
|
338 |
-
# return None
|
339 |
-
# else:
|
340 |
-
# print(f"Модель {filename} уже присутствует: {local_path}")
|
341 |
-
# return local_path
|
342 |
-
|
343 |
-
# Вынесем загрузку моделей за пределы функции generate_image
|
344 |
-
# это критично для работы на ZeroGPU в Hugging Face Spaces
|
345 |
-
# def download_all_models():
|
346 |
-
# models = {
|
347 |
-
# "flux": download_model(
|
348 |
-
# "lllyasviel/flux1_dev",
|
349 |
-
# "flux1-dev-fp8.safetensors",
|
350 |
-
# "models/checkpoints"
|
351 |
-
# ),
|
352 |
-
# # "upscale": download_model(
|
353 |
-
# # "gemasai/4x_NMKD-Superscale-SP_178000_G",
|
354 |
-
# # "4x_NMKD-Superscale-SP_178000_G.pth",
|
355 |
-
# # "models/upscale_models"
|
356 |
-
# # ),
|
357 |
-
# # "rembg": "briaai/RMBG-1.4" # Используем модель RMBG-1.4 через transformers pipeline
|
358 |
-
# }
|
359 |
-
# return models
|
360 |
-
|
361 |
-
# def save_uploaded_file(file):
|
362 |
-
# """Сохранение загруженного файла"""
|
363 |
-
# if file is None:
|
364 |
-
# return None
|
365 |
-
#
|
366 |
-
# filename = os.path.join("temp_uploads", f"{random.randint(1000000, 9999999)}{os.path.splitext(file.name)[1]}")
|
367 |
-
# with open(filename, "wb") as f:
|
368 |
-
# f.write(file.read())
|
369 |
-
# return filename
|
370 |
-
|
371 |
-
# Функция для получения значения по индексу (используется в ComfyUI)
|
372 |
-
# def get_value_at_index(obj, index):
|
373 |
-
# """Получение значения из объекта по индексу из экспортированного ComfyUI кода"""
|
374 |
-
# if isinstance(obj, list):
|
375 |
-
# return obj[index]
|
376 |
-
# elif isinstance(obj, tuple):
|
377 |
-
# return obj[index]
|
378 |
-
# elif isinstance(obj, dict):
|
379 |
-
# return list(obj.values())[index]
|
380 |
-
# else:
|
381 |
-
# return obj[index]
|
382 |
-
|
383 |
-
# Загрузка моделей при запуске
|
384 |
-
#models = download_all_models()
|
385 |
-
|
386 |
-
# Инициализация pipeline для удаления фона
|
387 |
-
# try:
|
388 |
-
# rembg_pipeline = pipeline("image-segmentation", model=models["rembg"], trust_remote_code=True)
|
389 |
-
# print(f"Модель удаления фона успешно загружена: {models['rembg']}")
|
390 |
-
# except Exception as e:
|
391 |
-
# print(f"Ошибка при загрузке модели удаления фона: {e}")
|
392 |
-
# rembg_pipeline = None
|
393 |
-
|
394 |
-
# Укажите абсолютный путь к модели
|
395 |
-
# model_path = os.path.abspath("models/checkpoints/flux1-dev-fp8.safetensors")
|
396 |
-
|
397 |
-
# Проверьте существование ключевого файла
|
398 |
-
# if not os.path.exists(os.path.join(model_path, "model_index.json")):
|
399 |
-
# raise FileNotFoundError(f"Модель не найдена по пути: {model_path}")
|
400 |
-
|
401 |
-
# local_path = os.path.join("models/checkpoints", "")
|
|
|
1 |
import os
|
|
|
2 |
import time
|
3 |
from datetime import datetime
|
4 |
import pytz
|
|
|
6 |
import torch
|
7 |
import gradio as gr
|
8 |
import traceback
|
|
|
9 |
import threading
|
10 |
from transformers import pipeline
|
11 |
from huggingface_hub import login
|
12 |
from diffusers import FluxPipeline
|
13 |
from aura_sr import AuraSR
|
14 |
from deep_translator import GoogleTranslator
|
|
|
|
|
|
|
15 |
|
16 |
def log(*args, **kwargs):
|
17 |
tid = threading.get_ident()
|
|
|
143 |
num_images_per_prompt=1
|
144 |
).images[0]
|
145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
def create_template_prompt(object_name):
|
147 |
template = load_text("prompt.txt")
|
148 |
return template.format(object_name = object_name)
|
|
|
167 |
with open(file_name, 'r', encoding='utf-8') as f:
|
168 |
return f.read()
|
169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
custom_css = load_text("style.css")
|
171 |
|
172 |
# Создание интерфейса Gradio
|
|
|
253 |
outputs=[output_image]
|
254 |
)
|
255 |
|
|
|
|
|
|
|
256 |
# Запуск приложения
|
257 |
if __name__ == "__main__":
|
258 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -18,7 +18,4 @@ scikit-image
|
|
18 |
rembg
|
19 |
aura-sr
|
20 |
deep_translator
|
21 |
-
fastapi
|
22 |
-
uvicorn
|
23 |
-
pydantic
|
24 |
pytz
|
|
|
18 |
rembg
|
19 |
aura-sr
|
20 |
deep_translator
|
|
|
|
|
|
|
21 |
pytz
|