Spaces:
Running
Running
salomonsky
commited on
Commit
•
8b0fc18
1
Parent(s):
9f73f1a
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,7 @@
|
|
1 |
-
import os
|
|
|
|
|
|
|
2 |
from pathlib import Path
|
3 |
from PIL import Image
|
4 |
from insightface.app import FaceAnalysis
|
@@ -6,20 +9,23 @@ import streamlit as st
|
|
6 |
from huggingface_hub import InferenceClient, AsyncInferenceClient
|
7 |
from gradio_client import Client, handle_file
|
8 |
import yaml
|
9 |
-
import insightface
|
10 |
|
11 |
MAX_SEED = np.iinfo(np.int32).max
|
12 |
-
DATA_PATH = Path("./data")
|
|
|
13 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
14 |
client, llm_client = AsyncInferenceClient(), InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
15 |
|
16 |
try:
|
17 |
credentials = yaml.safe_load(open("config.yaml"))
|
18 |
except Exception as e:
|
19 |
-
st.error(f"Error al cargar config: {e}")
|
|
|
20 |
|
21 |
def prepare_face_app():
|
22 |
-
app = FaceAnalysis(name='buffalo_l')
|
|
|
23 |
return app, insightface.model_zoo.get_model('onix.onnx')
|
24 |
|
25 |
app, swapper = prepare_face_app()
|
@@ -33,18 +39,20 @@ def get_upscale_finegrain(prompt, img_path, upscale_factor):
|
|
33 |
try:
|
34 |
result = Client("finegrain/finegrain-image-enhancer", hf_token=HF_TOKEN_UPSCALER).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:
|
|
|
37 |
|
38 |
async def gen(prompt, basemodel, w, h, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
|
39 |
combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
|
40 |
image, seed = await generate_image(combined_prompt, basemodel, w, h, scales, steps, seed)
|
41 |
if image is None: return ["Error al generar imagen", None, combined_prompt]
|
42 |
-
image_path = save_image(image, seed)
|
|
|
43 |
if process_upscale:
|
44 |
upscale_image_path = get_upscale_finegrain(combined_prompt, image_path, upscale_factor)
|
45 |
if upscale_image_path:
|
46 |
Image.open(upscale_image_path).save(DATA_PATH / f"upscale_image_{seed}.jpg", format="JPEG")
|
47 |
-
image_path.unlink()
|
48 |
return [str(DATA_PATH / f"upscale_image_{seed}.jpg"), str(prompt_file_path)]
|
49 |
return [str(image_path), str(prompt_file_path)]
|
50 |
|
@@ -71,29 +79,38 @@ def get_storage():
|
|
71 |
|
72 |
def delete_image(image_path):
|
73 |
try:
|
74 |
-
Path(image_path).unlink()
|
75 |
-
|
|
|
|
|
76 |
|
77 |
def delete_all_images():
|
78 |
-
for file in DATA_PATH.glob("*.jpg"):
|
|
|
|
|
79 |
|
80 |
def authenticate_user(username, password, credentials):
|
81 |
return username == credentials["username"] and password == credentials["password"]
|
82 |
|
83 |
def login_form(credentials):
|
84 |
-
if 'authenticated' not in st.session_state:
|
|
|
85 |
if not st.session_state['authenticated']:
|
86 |
-
username = st.text_input("Usuario")
|
|
|
87 |
if st.button("Iniciar Sesión"):
|
88 |
if authenticate_user(username, password, credentials):
|
89 |
-
st.session_state['authenticated'] = True
|
90 |
-
|
|
|
|
|
91 |
|
92 |
def upload_image():
|
93 |
uploaded_file = st.sidebar.file_uploader("Sube una imagen", type=["png", "jpg", "jpeg"])
|
94 |
if uploaded_file:
|
95 |
image_path = DATA_PATH / uploaded_file.name
|
96 |
-
with open(image_path, "wb") as f:
|
|
|
97 |
st.sidebar.success(f"Imagen {uploaded_file.name} cargada correctamente.")
|
98 |
return image_path, save_prompt("#uploadedbyuser", image_path.stem)
|
99 |
return None
|
@@ -101,7 +118,8 @@ def upload_image():
|
|
101 |
def gallery():
|
102 |
files, usage = get_storage()
|
103 |
st.sidebar.write(f"{usage}")
|
104 |
-
if st.sidebar.button("Borrar Todas las Imágenes"):
|
|
|
105 |
cols = st.columns(6)
|
106 |
for idx, file in enumerate(files):
|
107 |
with cols[idx % 6]:
|
@@ -112,37 +130,51 @@ def gallery():
|
|
112 |
except FileNotFoundError:
|
113 |
st.write("Prompt no encontrado.")
|
114 |
st.button(f"Borrar Imagen {file.name}", on_click=delete_image, args=(file,))
|
115 |
-
if st.button(f"Swap Face en {file.name}"):
|
|
|
116 |
|
117 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
try:
|
119 |
img_dest, img_src = Image.open(image_path), Image.open(source_image_path)
|
120 |
faces = app.get(img_src)
|
121 |
-
if not faces:
|
122 |
-
|
|
|
|
|
123 |
swapped_img_path = DATA_PATH / f"swapped_{Path(image_path).stem}.jpg"
|
124 |
swapped_img.save(swapped_img_path, format="JPEG")
|
|
|
125 |
return swapped_img_path
|
126 |
-
except Exception as e:
|
127 |
-
|
128 |
-
|
129 |
-
source_image = st.file_uploader("Sube la imagen source para face swap", type=["png", "jpg", "jpeg"])
|
130 |
-
if source_image:
|
131 |
-
source_image_path = DATA_PATH / source_image.name
|
132 |
-
with open(source_image_path, "wb") as f: f.write(source_image.getbuffer())
|
133 |
-
st.success(f"Imagen source {source_image.name} cargada correctamente.")
|
134 |
-
swapped_image_path = face_swap(image_path, source_image_path)
|
135 |
-
if swapped_image_path: st.image(str(swapped_image_path), caption="Imagen con Face Swap", use_column_width=True)
|
136 |
|
137 |
async def main():
|
138 |
st.set_page_config(layout="wide")
|
139 |
login_form(credentials)
|
140 |
-
if not st.session_state['authenticated']:
|
|
|
|
|
|
|
141 |
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=900)
|
142 |
process_enhancer, language = st.sidebar.checkbox("Mejorar Prompt", value=False), st.sidebar.selectbox("Idioma", ["en", "es"])
|
143 |
basemodel, format_option, process_upscale = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"]), st.sidebar.selectbox("Formato", ["9:16", "16:9"]), st.sidebar.checkbox("Procesar Escalador", value=False)
|
144 |
upscale_factor, scales, steps, seed = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0), st.sidebar.slider("Escalado", 1, 20, 10), st.sidebar.slider("Pasos", 1, 100, 20), st.sidebar.number_input("Semilla", value=-1)
|
145 |
-
|
|
|
|
|
146 |
upload_image()
|
147 |
|
148 |
image_path, prompt_file_path = None, None
|
@@ -159,4 +191,4 @@ async def main():
|
|
159 |
gallery()
|
160 |
|
161 |
if __name__ == "__main__":
|
162 |
-
asyncio.run(main())
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
import asyncio
|
4 |
+
import numpy as np
|
5 |
from pathlib import Path
|
6 |
from PIL import Image
|
7 |
from insightface.app import FaceAnalysis
|
|
|
9 |
from huggingface_hub import InferenceClient, AsyncInferenceClient
|
10 |
from gradio_client import Client, handle_file
|
11 |
import yaml
|
12 |
+
import insightface
|
13 |
|
14 |
MAX_SEED = np.iinfo(np.int32).max
|
15 |
+
DATA_PATH = Path("./data")
|
16 |
+
DATA_PATH.mkdir(exist_ok=True)
|
17 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
18 |
client, llm_client = AsyncInferenceClient(), InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
19 |
|
20 |
try:
|
21 |
credentials = yaml.safe_load(open("config.yaml"))
|
22 |
except Exception as e:
|
23 |
+
st.error(f"Error al cargar config: {e}")
|
24 |
+
credentials = {"username": "", "password": ""}
|
25 |
|
26 |
def prepare_face_app():
|
27 |
+
app = FaceAnalysis(name='buffalo_l')
|
28 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
29 |
return app, insightface.model_zoo.get_model('onix.onnx')
|
30 |
|
31 |
app, swapper = prepare_face_app()
|
|
|
39 |
try:
|
40 |
result = Client("finegrain/finegrain-image-enhancer", hf_token=HF_TOKEN_UPSCALER).predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
|
41 |
return result[1] if isinstance(result, list) and len(result) > 1 else None
|
42 |
+
except Exception:
|
43 |
+
return None
|
44 |
|
45 |
async def gen(prompt, basemodel, w, h, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
|
46 |
combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
|
47 |
image, seed = await generate_image(combined_prompt, basemodel, w, h, scales, steps, seed)
|
48 |
if image is None: return ["Error al generar imagen", None, combined_prompt]
|
49 |
+
image_path = save_image(image, seed)
|
50 |
+
prompt_file_path = save_prompt(combined_prompt, seed)
|
51 |
if process_upscale:
|
52 |
upscale_image_path = get_upscale_finegrain(combined_prompt, image_path, upscale_factor)
|
53 |
if upscale_image_path:
|
54 |
Image.open(upscale_image_path).save(DATA_PATH / f"upscale_image_{seed}.jpg", format="JPEG")
|
55 |
+
image_path.unlink() # Borra la imagen original
|
56 |
return [str(DATA_PATH / f"upscale_image_{seed}.jpg"), str(prompt_file_path)]
|
57 |
return [str(image_path), str(prompt_file_path)]
|
58 |
|
|
|
79 |
|
80 |
def delete_image(image_path):
|
81 |
try:
|
82 |
+
Path(image_path).unlink()
|
83 |
+
st.success(f"Imagen {image_path} borrada.")
|
84 |
+
except Exception as e:
|
85 |
+
st.error(f"Error al borrar imagen: {e}")
|
86 |
|
87 |
def delete_all_images():
|
88 |
+
for file in DATA_PATH.glob("*.jpg"):
|
89 |
+
file.unlink()
|
90 |
+
st.success("Todas las imágenes han sido borradas.")
|
91 |
|
92 |
def authenticate_user(username, password, credentials):
|
93 |
return username == credentials["username"] and password == credentials["password"]
|
94 |
|
95 |
def login_form(credentials):
|
96 |
+
if 'authenticated' not in st.session_state:
|
97 |
+
st.session_state['authenticated'] = False
|
98 |
if not st.session_state['authenticated']:
|
99 |
+
username = st.text_input("Usuario")
|
100 |
+
password = st.text_input("Contraseña", type='password')
|
101 |
if st.button("Iniciar Sesión"):
|
102 |
if authenticate_user(username, password, credentials):
|
103 |
+
st.session_state['authenticated'] = True
|
104 |
+
st.success("Inicio de sesión exitoso.")
|
105 |
+
else:
|
106 |
+
st.error("Credenciales incorrectas.")
|
107 |
|
108 |
def upload_image():
|
109 |
uploaded_file = st.sidebar.file_uploader("Sube una imagen", type=["png", "jpg", "jpeg"])
|
110 |
if uploaded_file:
|
111 |
image_path = DATA_PATH / uploaded_file.name
|
112 |
+
with open(image_path, "wb") as f:
|
113 |
+
f.write(uploaded_file.getbuffer())
|
114 |
st.sidebar.success(f"Imagen {uploaded_file.name} cargada correctamente.")
|
115 |
return image_path, save_prompt("#uploadedbyuser", image_path.stem)
|
116 |
return None
|
|
|
118 |
def gallery():
|
119 |
files, usage = get_storage()
|
120 |
st.sidebar.write(f"{usage}")
|
121 |
+
if st.sidebar.button("Borrar Todas las Imágenes"):
|
122 |
+
delete_all_images()
|
123 |
cols = st.columns(6)
|
124 |
for idx, file in enumerate(files):
|
125 |
with cols[idx % 6]:
|
|
|
130 |
except FileNotFoundError:
|
131 |
st.write("Prompt no encontrado.")
|
132 |
st.button(f"Borrar Imagen {file.name}", on_click=delete_image, args=(file,))
|
133 |
+
if st.button(f"Swap Face en {file.name}"):
|
134 |
+
upload_source_and_swap(file)
|
135 |
|
136 |
+
def upload_source_and_swap(image_path):
|
137 |
+
source_image = st.file_uploader("Sube la imagen source para face swap", type=["png", "jpg", "jpeg"])
|
138 |
+
if source_image:
|
139 |
+
source_image_path = DATA_PATH / source_image.name
|
140 |
+
with open(source_image_path, "wb") as f:
|
141 |
+
f.write(source_image.getbuffer())
|
142 |
+
st.success(f"Imagen source {source_image.name} cargada correctamente.")
|
143 |
+
dest_face_index = st.slider("Selecciona la posición de la cara destino", 1, 4, 1)
|
144 |
+
swapped_image_path = face_swap(image_path, source_image_path, dest_face_index)
|
145 |
+
if swapped_image_path:
|
146 |
+
st.image(str(swapped_image_path), caption="Imagen con Face Swap", use_column_width=True)
|
147 |
+
|
148 |
+
def face_swap(image_path, source_image_path, dest_face_index):
|
149 |
try:
|
150 |
img_dest, img_src = Image.open(image_path), Image.open(source_image_path)
|
151 |
faces = app.get(img_src)
|
152 |
+
if not faces:
|
153 |
+
st.error("No se encontraron caras en la imagen source.")
|
154 |
+
return None
|
155 |
+
swapped_img = swapper.get(img_dest, faces[0], dest_index=dest_face_index - 1) # Convertir a índice base 0
|
156 |
swapped_img_path = DATA_PATH / f"swapped_{Path(image_path).stem}.jpg"
|
157 |
swapped_img.save(swapped_img_path, format="JPEG")
|
158 |
+
Path(image_path).unlink()
|
159 |
return swapped_img_path
|
160 |
+
except Exception as e:
|
161 |
+
st.error(f"Error en face swap: {e}")
|
162 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
async def main():
|
165 |
st.set_page_config(layout="wide")
|
166 |
login_form(credentials)
|
167 |
+
if not st.session_state['authenticated']:
|
168 |
+
st.warning("Por favor, inicia sesión para acceder a la aplicación.")
|
169 |
+
return
|
170 |
+
|
171 |
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=900)
|
172 |
process_enhancer, language = st.sidebar.checkbox("Mejorar Prompt", value=False), st.sidebar.selectbox("Idioma", ["en", "es"])
|
173 |
basemodel, format_option, process_upscale = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"]), st.sidebar.selectbox("Formato", ["9:16", "16:9"]), st.sidebar.checkbox("Procesar Escalador", value=False)
|
174 |
upscale_factor, scales, steps, seed = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0), st.sidebar.slider("Escalado", 1, 20, 10), st.sidebar.slider("Pasos", 1, 100, 20), st.sidebar.number_input("Semilla", value=-1)
|
175 |
+
destination_face_position = st.sidebar.slider("Posición de la Cara de Destino", 1, 4, 1)
|
176 |
+
|
177 |
+
w, h = (720, 1280) if format_option == "9:16" else (1280, 720)
|
178 |
upload_image()
|
179 |
|
180 |
image_path, prompt_file_path = None, None
|
|
|
191 |
gallery()
|
192 |
|
193 |
if __name__ == "__main__":
|
194 |
+
asyncio.run(main())
|