Spaces:
Running
Running
salomonsky
commited on
Commit
•
d18852a
1
Parent(s):
c6afe27
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from pathlib import Path
|
2 |
from PIL import Image
|
3 |
import streamlit as st
|
4 |
import insightface
|
@@ -28,20 +28,6 @@ HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
|
28 |
if not HF_TOKEN_UPSCALER:
|
29 |
st.warning("HF_TOKEN_UPSCALER no está configurado. Algunas funcionalidades pueden no funcionar.")
|
30 |
|
31 |
-
def login_form():
|
32 |
-
st.title("Iniciar Sesión")
|
33 |
-
username = st.text_input("Usuario", value="admin")
|
34 |
-
password = st.text_input("Contraseña", value="flux3x", type="password")
|
35 |
-
if st.button("Iniciar Sesión"):
|
36 |
-
if authenticate_user(username, password):
|
37 |
-
st.success("Autenticación exitosa.")
|
38 |
-
st.session_state['authenticated'] = True
|
39 |
-
else:
|
40 |
-
st.error("Credenciales incorrectas. Intenta de nuevo.")
|
41 |
-
|
42 |
-
def list_saved_images():
|
43 |
-
return list(DATA_PATH.glob("*.jpg"))
|
44 |
-
|
45 |
def get_upscale_finegrain(prompt, img_path, upscale_factor):
|
46 |
try:
|
47 |
upscale_client = InferenceClient("fal/AuraSR-v2", hf_token=HF_TOKEN_UPSCALER)
|
@@ -82,18 +68,18 @@ def swap_faces(source_image, source_face_index, destination_image, destination_f
|
|
82 |
result = swapper.get(destination_image, res_face, source_face, paste_back=True)
|
83 |
return result
|
84 |
|
85 |
-
def generate_image(prompt, width, height, seed, model_name):
|
86 |
if seed == -1:
|
87 |
seed = random.randint(0, MAX_SEED)
|
88 |
-
image = client.text_to_image(prompt=prompt, height=height, width=width, model=model_name)
|
89 |
return image, seed
|
90 |
|
91 |
-
def gen(prompts, width, height, model_name, num_variants=1, use_enhanced=True):
|
92 |
images = []
|
93 |
try:
|
94 |
for idx, prompt in enumerate(prompts):
|
95 |
seed = random.randint(0, MAX_SEED)
|
96 |
-
image, seed = generate_image(prompt, width, height, seed, model_name)
|
97 |
image_path = save_image(image, f"generated_image_{seed}.jpg")
|
98 |
if image_path:
|
99 |
st.success(f"Imagen {idx + 1} generada")
|
@@ -130,7 +116,15 @@ def display_gallery():
|
|
130 |
else:
|
131 |
st.info("No hay imágenes guardadas.")
|
132 |
|
133 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
try:
|
135 |
instructions = [
|
136 |
"With my idea create a vibrant description for a detailed txt2img prompt, 300 characters max.",
|
@@ -139,7 +133,8 @@ def improve_prompt(prompt):
|
|
139 |
"With my idea describe a photorealistic with illumination txt2img prompt in English, 300 characters max.",
|
140 |
"With my idea give a realistic and elegant txt2img prompt in English, 300 characters max.",
|
141 |
"With my idea conform a visually dynamic and surreal txt2img prompt in English, 300 characters max.",
|
142 |
-
"With my idea realize an artistic and cinematic txt2img prompt in English, 300 characters max."
|
|
|
143 |
]
|
144 |
instruction = random.choice(instructions)
|
145 |
formatted_prompt = f"{prompt}: {instruction}"
|
@@ -148,35 +143,58 @@ def improve_prompt(prompt):
|
|
148 |
except Exception as e:
|
149 |
return f"Error mejorando el prompt: {e}"
|
150 |
|
151 |
-
def generate_variations(prompt, num_variants, use_enhanced):
|
152 |
prompts = set()
|
153 |
while len(prompts) < num_variants:
|
154 |
if use_enhanced:
|
155 |
-
enhanced_prompt = improve_prompt(prompt)
|
156 |
prompts.add(enhanced_prompt)
|
157 |
else:
|
158 |
prompts.add(prompt)
|
159 |
return list(prompts)
|
160 |
|
161 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
try:
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
except Exception as e:
|
167 |
-
st.error(f"Error al
|
168 |
-
|
169 |
-
def upload_images_to_gallery():
|
170 |
-
uploaded_images = st.sidebar.file_uploader("Sube imágenes a la galería", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
|
171 |
-
if uploaded_images:
|
172 |
-
for uploaded_image in uploaded_images:
|
173 |
-
image = Image.open(uploaded_image)
|
174 |
-
image_path = save_image(image, f"{uploaded_image.name}")
|
175 |
-
if image_path:
|
176 |
-
save_prompt("uploaded by user")
|
177 |
-
st.sidebar.success(f"Imagen subida: {image_path}")
|
178 |
|
179 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
180 |
st.set_page_config(layout="wide")
|
181 |
|
182 |
if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
|
@@ -184,32 +202,26 @@ def main():
|
|
184 |
return
|
185 |
|
186 |
st.title("Flux +Upscale +Prompt Enhancer +FaceSwap")
|
187 |
-
|
188 |
-
if st.sidebar.button("Borrar todas las imágenes"):
|
189 |
-
delete_all_images()
|
190 |
-
|
191 |
generated_image_path = st.session_state.get('generated_image_path')
|
192 |
prompt = st.sidebar.text_area("Descripción de la imagen", height=150, max_chars=500)
|
193 |
format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
|
194 |
model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev", "enhanceaiteam/Flux-Uncensored-V2", "enhanceaiteam/Flux-Uncensored"])
|
195 |
-
prompt_checkbox = st.sidebar.checkbox("Prompt Enhancer")
|
196 |
-
upscale_checkbox = st.sidebar.checkbox("Escalar imagen")
|
197 |
-
|
198 |
width, height = (360, 640) if format_option == "9:16" else (640, 360) if format_option == "16:9" else (640, 640)
|
199 |
num_variants = st.sidebar.slider("Número de imágenes a generar", 1, 8, 1) if prompt_checkbox else 1
|
200 |
|
201 |
if prompt_checkbox:
|
202 |
with st.spinner("Generando prompts mejorados..."):
|
203 |
-
prompts = generate_variations(prompt, num_variants, True)
|
204 |
else:
|
205 |
prompts = [prompt]
|
206 |
|
207 |
-
|
208 |
|
209 |
if st.sidebar.button("Generar Imágenes"):
|
210 |
with st.spinner("Generando imágenes..."):
|
211 |
try:
|
212 |
-
results = gen(prompts, width, height, model_option, num_variants, prompt_checkbox)
|
213 |
st.session_state['generated_image_paths'] = results
|
214 |
for result in results:
|
215 |
st.image(result, caption="Imagen Generada")
|
@@ -259,4 +271,4 @@ def main():
|
|
259 |
display_gallery()
|
260 |
|
261 |
if __name__ == "__main__":
|
262 |
-
main()
|
|
|
1 |
+
from pathlib import Path
|
2 |
from PIL import Image
|
3 |
import streamlit as st
|
4 |
import insightface
|
|
|
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("fal/AuraSR-v2", hf_token=HF_TOKEN_UPSCALER)
|
|
|
68 |
result = swapper.get(destination_image, res_face, source_face, paste_back=True)
|
69 |
return result
|
70 |
|
71 |
+
async def generate_image(prompt, width, height, seed, model_name):
|
72 |
if seed == -1:
|
73 |
seed = random.randint(0, MAX_SEED)
|
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")
|
|
|
116 |
else:
|
117 |
st.info("No hay imágenes guardadas.")
|
118 |
|
119 |
+
def save_prompt(prompt):
|
120 |
+
with open(DATA_PATH / "prompts.txt", "a") as f:
|
121 |
+
f.write(prompt + "\n")
|
122 |
+
st.success("Prompt guardado.")
|
123 |
+
|
124 |
+
def run_async(func, *args):
|
125 |
+
return asyncio.run(func(*args))
|
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.",
|
|
|
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}"
|
|
|
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 = {}
|
158 |
+
try:
|
159 |
+
with open(DATA_PATH / "prompts.txt", "r") as f:
|
160 |
+
for line in f:
|
161 |
+
if line.startswith(image_name):
|
162 |
+
prompts[image_name] = line.split(": ", 1)[1].strip()
|
163 |
+
except FileNotFoundError:
|
164 |
+
return "No hay prompt asociado."
|
165 |
+
|
166 |
+
return prompts.get(image_name, "No hay prompt asociado.")
|
167 |
+
|
168 |
+
def login_form():
|
169 |
+
st.title("Iniciar Sesión")
|
170 |
+
username = st.text_input("Usuario", value="admin")
|
171 |
+
password = st.text_input("Contraseña", value="flux3x", type="password")
|
172 |
+
if st.button("Iniciar Sesión"):
|
173 |
+
if authenticate_user(username, password):
|
174 |
+
st.success("Autenticación exitosa.")
|
175 |
+
st.session_state['authenticated'] = True
|
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:
|
191 |
+
image = Image.open(uploaded_image)
|
192 |
+
image_path = save_image(image, f"{uploaded_image.name}")
|
193 |
+
if image_path:
|
194 |
+
save_prompt("uploaded by user")
|
195 |
+
st.sidebar.success(f"Imagen subida: {image_path}")
|
196 |
+
|
197 |
+
async def main():
|
198 |
st.set_page_config(layout="wide")
|
199 |
|
200 |
if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
|
|
|
202 |
return
|
203 |
|
204 |
st.title("Flux +Upscale +Prompt Enhancer +FaceSwap")
|
|
|
|
|
|
|
|
|
205 |
generated_image_path = st.session_state.get('generated_image_path')
|
206 |
prompt = st.sidebar.text_area("Descripción de la imagen", height=150, max_chars=500)
|
207 |
format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
|
208 |
model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev", "enhanceaiteam/Flux-Uncensored-V2", "enhanceaiteam/Flux-Uncensored"])
|
209 |
+
prompt_checkbox = st.sidebar.checkbox("Prompt Enhancer"), upscale_checkbox = st.sidebar.checkbox("Escalar imagen")
|
|
|
|
|
210 |
width, height = (360, 640) if format_option == "9:16" else (640, 360) if format_option == "16:9" else (640, 640)
|
211 |
num_variants = st.sidebar.slider("Número de imágenes a generar", 1, 8, 1) if prompt_checkbox else 1
|
212 |
|
213 |
if prompt_checkbox:
|
214 |
with st.spinner("Generando prompts mejorados..."):
|
215 |
+
prompts = await generate_variations(prompt, num_variants, True)
|
216 |
else:
|
217 |
prompts = [prompt]
|
218 |
|
219 |
+
upload_image_to_gallery()
|
220 |
|
221 |
if st.sidebar.button("Generar Imágenes"):
|
222 |
with st.spinner("Generando imágenes..."):
|
223 |
try:
|
224 |
+
results = await gen(prompts, width, height, model_option, num_variants, prompt_checkbox)
|
225 |
st.session_state['generated_image_paths'] = results
|
226 |
for result in results:
|
227 |
st.image(result, caption="Imagen Generada")
|
|
|
271 |
display_gallery()
|
272 |
|
273 |
if __name__ == "__main__":
|
274 |
+
asyncio.run(main())
|