Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -9,7 +9,6 @@ import urllib.parse
|
|
9 |
import hashlib
|
10 |
from deep_translator import GoogleTranslator
|
11 |
from langdetect import detect
|
12 |
-
import time
|
13 |
|
14 |
app = Flask(__name__)
|
15 |
|
@@ -32,6 +31,7 @@ def generate_cache_key(prompt, width, height, seed, model_name):
|
|
32 |
# Создаем уникальный ключ на основе всех параметров
|
33 |
return hashlib.md5(f"{prompt}_{width}_{height}_{seed}_{model_name}".encode()).hexdigest()
|
34 |
|
|
|
35 |
def scale_dimensions(width, height, max_width, max_height):
|
36 |
"""Масштабирует размеры изображения, сохраняя соотношение сторон, и округляет до чисел, кратных 8."""
|
37 |
aspect_ratio = width / height
|
@@ -48,7 +48,8 @@ def scale_dimensions(width, height, max_width, max_height):
|
|
48 |
height = (height + 3) // 8 * 8
|
49 |
return width, height
|
50 |
|
51 |
-
|
|
|
52 |
headers = {
|
53 |
"Authorization": f"Bearer {api_key}",
|
54 |
"Content-Type": "application/json"
|
@@ -83,23 +84,12 @@ def generate_image(prompt, width, height, seed, model_name, api_key):
|
|
83 |
app.logger.error(f"Request error occurred: {req_err}")
|
84 |
return None
|
85 |
|
86 |
-
def generate_with_retry(prompt, width, height, seed, model_name, api_key):
|
87 |
-
max_retries = 2 # Максимальное количество повторных попыток
|
88 |
-
for attempt in range(max_retries):
|
89 |
-
image = generate_image(prompt, width, height, seed, model_name, api_key)
|
90 |
-
if image:
|
91 |
-
return image
|
92 |
-
else:
|
93 |
-
app.logger.warning(f"Retrying image generation (attempt {attempt + 1}/{max_retries})...")
|
94 |
-
time.sleep(1) # Небольшая задержка перед повторной попыткой
|
95 |
-
return None # Возвращаем None, если все попытки не удались
|
96 |
-
|
97 |
@app.route('/prompt/<path:prompt>')
|
98 |
def get_image(prompt):
|
99 |
width = request.args.get('width', type=int, default=512)
|
100 |
height = request.args.get('height', type=int, default=512)
|
101 |
seed = request.args.get('seed', type=int, default=25)
|
102 |
-
model_name = request.args.get('model', default="black-forest-labs
|
103 |
api_key = request.args.get('key', default=None)
|
104 |
|
105 |
# Декодируем URL-кодированный prompt
|
@@ -128,19 +118,10 @@ def get_image(prompt):
|
|
128 |
if api_key is None:
|
129 |
api_key = get_random_key()
|
130 |
|
131 |
-
# Генерируем уникальный ключ для кэша
|
132 |
-
cache_key = generate_cache_key(prompt, width, height, seed, model_name)
|
133 |
-
|
134 |
try:
|
135 |
-
|
136 |
-
image = cache.get(cache_key)
|
137 |
if image is None:
|
138 |
-
|
139 |
-
image = generate_with_retry(prompt, width, height, seed, model_name, api_key)
|
140 |
-
if image:
|
141 |
-
cache[cache_key] = image # Кэшируем только успешное изображение
|
142 |
-
else:
|
143 |
-
return send_error_image()
|
144 |
except Exception as e:
|
145 |
app.logger.error(f"Error generating image: {e}")
|
146 |
return send_error_image()
|
|
|
9 |
import hashlib
|
10 |
from deep_translator import GoogleTranslator
|
11 |
from langdetect import detect
|
|
|
12 |
|
13 |
app = Flask(__name__)
|
14 |
|
|
|
31 |
# Создаем уникальный ключ на основе всех параметров
|
32 |
return hashlib.md5(f"{prompt}_{width}_{height}_{seed}_{model_name}".encode()).hexdigest()
|
33 |
|
34 |
+
|
35 |
def scale_dimensions(width, height, max_width, max_height):
|
36 |
"""Масштабирует размеры изображения, сохраняя соотношение сторон, и округляет до чисел, кратных 8."""
|
37 |
aspect_ratio = width / height
|
|
|
48 |
height = (height + 3) // 8 * 8
|
49 |
return width, height
|
50 |
|
51 |
+
@cached(cache, key=lambda prompt, width, height, seed, model_name: generate_cache_key(prompt, width, height, seed, model_name))
|
52 |
+
def generate_cached_image(prompt, width, height, seed, model_name, api_key):
|
53 |
headers = {
|
54 |
"Authorization": f"Bearer {api_key}",
|
55 |
"Content-Type": "application/json"
|
|
|
84 |
app.logger.error(f"Request error occurred: {req_err}")
|
85 |
return None
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
@app.route('/prompt/<path:prompt>')
|
88 |
def get_image(prompt):
|
89 |
width = request.args.get('width', type=int, default=512)
|
90 |
height = request.args.get('height', type=int, default=512)
|
91 |
seed = request.args.get('seed', type=int, default=25)
|
92 |
+
model_name = request.args.get('model', default="black-forest-labs/FLUX.1-schnell").replace('+', '/')
|
93 |
api_key = request.args.get('key', default=None)
|
94 |
|
95 |
# Декодируем URL-кодированный prompt
|
|
|
118 |
if api_key is None:
|
119 |
api_key = get_random_key()
|
120 |
|
|
|
|
|
|
|
121 |
try:
|
122 |
+
image = generate_cached_image(prompt, width, height, seed, model_name, api_key)
|
|
|
123 |
if image is None:
|
124 |
+
return send_error_image()
|
|
|
|
|
|
|
|
|
|
|
125 |
except Exception as e:
|
126 |
app.logger.error(f"Error generating image: {e}")
|
127 |
return send_error_image()
|