Spaces:
Runtime error
Runtime error
salomonsky
commited on
Commit
•
b99630c
1
Parent(s):
cfcfa32
Update app.py
Browse files
app.py
CHANGED
@@ -25,12 +25,16 @@ DATA_PATH.mkdir(exist_ok=True)
|
|
25 |
PREDEFINED_SEED = random.randint(0, MAX_SEED)
|
26 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
27 |
|
|
|
|
|
|
|
28 |
def get_upscale_finegrain(prompt, img_path, upscale_factor):
|
29 |
try:
|
30 |
-
upscale_client =
|
31 |
result = upscale_client.predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
|
32 |
return result[1] if isinstance(result, list) and len(result) > 1 else None
|
33 |
-
except Exception:
|
|
|
34 |
return None
|
35 |
|
36 |
def authenticate_user(username, password):
|
@@ -70,11 +74,19 @@ async def generate_image(prompt, width, height, seed, model_name):
|
|
70 |
image = await client.text_to_image(prompt=prompt, height=height, width=width, model=model_name)
|
71 |
return image, seed
|
72 |
|
73 |
-
async def gen(
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
def list_saved_images():
|
80 |
return list(DATA_PATH.glob("*.jpg"))
|
@@ -95,9 +107,12 @@ def display_gallery():
|
|
95 |
st.success("Imagen seleccionada")
|
96 |
|
97 |
if st.button(f"Borrar", key=f"delete_{i}_{image_file.name}"):
|
98 |
-
os.
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
101 |
else:
|
102 |
st.info("No hay imágenes guardadas.")
|
103 |
|
@@ -111,23 +126,32 @@ def run_async(func, *args):
|
|
111 |
|
112 |
async def improve_prompt(prompt):
|
113 |
try:
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
formatted_prompt = f"{prompt}: {instruction}"
|
116 |
-
response = llm_client.text_generation(formatted_prompt, max_new_tokens=
|
117 |
-
return response['generated_text'][:
|
118 |
except Exception as e:
|
119 |
return f"Error mejorando el prompt: {e}"
|
120 |
|
121 |
-
def
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
return image_path
|
131 |
|
132 |
def get_prompt_for_image(image_name):
|
133 |
prompts = {}
|
@@ -152,6 +176,15 @@ def login_form():
|
|
152 |
else:
|
153 |
st.error("Credenciales incorrectas. Intenta de nuevo.")
|
154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
def upload_image_to_gallery():
|
156 |
uploaded_image = st.sidebar.file_uploader("Sube una imagen a la galería", type=["jpg", "jpeg", "png"])
|
157 |
if uploaded_image:
|
@@ -176,27 +209,27 @@ async def main():
|
|
176 |
model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev"])
|
177 |
prompt_checkbox = st.sidebar.checkbox("Prompt Enhancer")
|
178 |
upscale_checkbox = st.sidebar.checkbox("Escalar imagen")
|
179 |
-
width, height = (
|
180 |
-
|
|
|
181 |
|
182 |
if prompt_checkbox:
|
183 |
-
with st.spinner("
|
184 |
-
|
185 |
-
improved_prompt = run_async(improve_prompt, prompt)
|
186 |
-
except Exception as e:
|
187 |
-
st.error(f"Error al mejorar el prompt: {str(e)}")
|
188 |
-
improved_prompt = prompt
|
189 |
else:
|
190 |
-
|
|
|
|
|
191 |
|
192 |
-
if st.sidebar.button("Generar
|
193 |
-
with st.spinner("Generando
|
194 |
try:
|
195 |
-
|
196 |
-
st.session_state['
|
197 |
-
|
|
|
198 |
except Exception as e:
|
199 |
-
st.error(f"Error al generar
|
200 |
|
201 |
if generated_image_path:
|
202 |
if upscale_checkbox:
|
|
|
25 |
PREDEFINED_SEED = random.randint(0, MAX_SEED)
|
26 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
27 |
|
28 |
+
if not HF_TOKEN_UPSCALER:
|
29 |
+
st.warning("HF_TOKEN_UPSCALER no está configurado. Algunas funcionalidades pueden no funcionar.")
|
30 |
+
|
31 |
def get_upscale_finegrain(prompt, img_path, upscale_factor):
|
32 |
try:
|
33 |
+
upscale_client = InferenceClient("finegrain/finegrain-image-enhancer", hf_token=HF_TOKEN_UPSCALER)
|
34 |
result = upscale_client.predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
|
35 |
return result[1] if isinstance(result, list) and len(result) > 1 else None
|
36 |
+
except Exception as e:
|
37 |
+
st.error(f"Error al mejorar la imagen: {e}")
|
38 |
return None
|
39 |
|
40 |
def authenticate_user(username, password):
|
|
|
74 |
image = await client.text_to_image(prompt=prompt, height=height, width=width, model=model_name)
|
75 |
return image, seed
|
76 |
|
77 |
+
async def gen(prompts, width, height, model_name, num_variants=1, use_enhanced=True):
|
78 |
+
images = []
|
79 |
+
try:
|
80 |
+
for idx, prompt in enumerate(prompts):
|
81 |
+
seed = random.randint(0, MAX_SEED)
|
82 |
+
image, seed = await generate_image(prompt, width, height, seed, model_name)
|
83 |
+
image_path = save_image(image, f"generated_image_{seed}.jpg")
|
84 |
+
if image_path:
|
85 |
+
st.success(f"Imagen {idx + 1} generada")
|
86 |
+
images.append(str(image_path))
|
87 |
+
except Exception as e:
|
88 |
+
st.error(f"Error al generar imágenes: {e}")
|
89 |
+
return images
|
90 |
|
91 |
def list_saved_images():
|
92 |
return list(DATA_PATH.glob("*.jpg"))
|
|
|
107 |
st.success("Imagen seleccionada")
|
108 |
|
109 |
if st.button(f"Borrar", key=f"delete_{i}_{image_file.name}"):
|
110 |
+
if os.path.exists(image_file):
|
111 |
+
os.remove(image_file)
|
112 |
+
st.success("Imagen borrada")
|
113 |
+
display_gallery()
|
114 |
+
else:
|
115 |
+
st.warning("La imagen no existe.")
|
116 |
else:
|
117 |
st.info("No hay imágenes guardadas.")
|
118 |
|
|
|
126 |
|
127 |
async def improve_prompt(prompt):
|
128 |
try:
|
129 |
+
instructions = [
|
130 |
+
"With my idea create a vibrant description for a detailed txt2img prompt, 300 characters max.",
|
131 |
+
"With my idea write a creative and detailed text-to-image prompt in English, 300 characters max.",
|
132 |
+
"With my idea generate a descriptive and visual txt2img prompt in English, 300 characters max.",
|
133 |
+
"With my idea describe a photorealistic with illumination txt2img prompt in English, 300 characters max.",
|
134 |
+
"With my idea give a realistic and elegant txt2img prompt in English, 300 characters max.",
|
135 |
+
"With my idea conform a visually dynamic and surreal txt2img prompt in English, 300 characters max.",
|
136 |
+
"With my idea realize an artistic and cinematic txt2img prompt in English, 300 characters max.",
|
137 |
+
"With my idea make a narrative and immersive txt2img prompt in English, 300 characters max."
|
138 |
+
]
|
139 |
+
instruction = random.choice(instructions)
|
140 |
formatted_prompt = f"{prompt}: {instruction}"
|
141 |
+
response = llm_client.text_generation(formatted_prompt, max_new_tokens=100)
|
142 |
+
return response['generated_text'][:100] if 'generated_text' in response else response.strip()
|
143 |
except Exception as e:
|
144 |
return f"Error mejorando el prompt: {e}"
|
145 |
|
146 |
+
async def generate_variations(prompt, num_variants, use_enhanced):
|
147 |
+
prompts = set()
|
148 |
+
while len(prompts) < num_variants:
|
149 |
+
if use_enhanced:
|
150 |
+
enhanced_prompt = await improve_prompt(prompt)
|
151 |
+
prompts.add(enhanced_prompt)
|
152 |
+
else:
|
153 |
+
prompts.add(prompt)
|
154 |
+
return list(prompts)
|
|
|
155 |
|
156 |
def get_prompt_for_image(image_name):
|
157 |
prompts = {}
|
|
|
176 |
else:
|
177 |
st.error("Credenciales incorrectas. Intenta de nuevo.")
|
178 |
|
179 |
+
def save_image(image, filename):
|
180 |
+
try:
|
181 |
+
image_path = DATA_PATH / filename
|
182 |
+
image.save(image_path)
|
183 |
+
return image_path
|
184 |
+
except Exception as e:
|
185 |
+
st.error(f"Error al guardar la imagen: {e}")
|
186 |
+
return None
|
187 |
+
|
188 |
def upload_image_to_gallery():
|
189 |
uploaded_image = st.sidebar.file_uploader("Sube una imagen a la galería", type=["jpg", "jpeg", "png"])
|
190 |
if uploaded_image:
|
|
|
209 |
model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev"])
|
210 |
prompt_checkbox = st.sidebar.checkbox("Prompt Enhancer")
|
211 |
upscale_checkbox = st.sidebar.checkbox("Escalar imagen")
|
212 |
+
width, height = (360, 640) if format_option == "9:16" else (640, 360) if format_option == "16:9" else (640, 640)
|
213 |
+
|
214 |
+
num_variants = st.sidebar.slider("Número de imágenes a generar", 1, 8, 1) if prompt_checkbox else 1
|
215 |
|
216 |
if prompt_checkbox:
|
217 |
+
with st.spinner("Generando prompts mejorados..."):
|
218 |
+
prompts = await generate_variations(prompt, num_variants, True)
|
|
|
|
|
|
|
|
|
219 |
else:
|
220 |
+
prompts = [prompt]
|
221 |
+
|
222 |
+
upload_image_to_gallery()
|
223 |
|
224 |
+
if st.sidebar.button("Generar Imágenes"):
|
225 |
+
with st.spinner("Generando imágenes..."):
|
226 |
try:
|
227 |
+
results = await gen(prompts, width, height, model_option, num_variants, prompt_checkbox)
|
228 |
+
st.session_state['generated_image_paths'] = results
|
229 |
+
for result in results:
|
230 |
+
st.image(result, caption="Imagen Generada")
|
231 |
except Exception as e:
|
232 |
+
st.error(f"Error al generar las imágenes: {str(e)}")
|
233 |
|
234 |
if generated_image_path:
|
235 |
if upscale_checkbox:
|