Spaces:
Running
Running
salomonsky
commited on
Commit
•
ea513a8
1
Parent(s):
e141429
Update app.py
Browse files
app.py
CHANGED
@@ -1,131 +1,125 @@
|
|
1 |
-
import os
|
2 |
-
import random
|
3 |
-
import asyncio
|
4 |
from pathlib import Path
|
5 |
from PIL import Image
|
6 |
from insightface.app import FaceAnalysis
|
7 |
import streamlit as st
|
8 |
-
from huggingface_hub import InferenceClient
|
|
|
|
|
9 |
import yaml
|
10 |
-
import insightface
|
11 |
|
12 |
-
|
13 |
-
with open("config.yaml", "r") as file:
|
14 |
-
credentials = yaml.safe_load(file)
|
15 |
-
except Exception:
|
16 |
-
credentials = {"username": "", "password": ""}
|
17 |
-
|
18 |
-
MAX_SEED = 2**31 - 1
|
19 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
20 |
-
client =
|
21 |
-
|
22 |
-
DATA_PATH
|
23 |
|
24 |
def prepare_face_app():
|
25 |
app = FaceAnalysis(name='buffalo_l')
|
26 |
app.prepare(ctx_id=0, det_size=(640, 640))
|
27 |
-
|
|
|
28 |
|
29 |
app, swapper = prepare_face_app()
|
30 |
|
31 |
-
def
|
32 |
-
loop = asyncio.new_event_loop()
|
33 |
-
asyncio.set_event_loop(loop)
|
34 |
-
return loop.run_until_complete(loop.run_in_executor(None, func))
|
35 |
-
|
36 |
-
async def generate_image(prompt, model, width, height, scales, steps, seed):
|
37 |
if seed == -1:
|
38 |
seed = random.randint(0, MAX_SEED)
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
f.write(prompt)
|
65 |
-
return path
|
66 |
-
except Exception as e:
|
67 |
-
st.error(f"Error: {e}")
|
68 |
-
|
69 |
-
async def gen(prompt, model, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
|
70 |
-
combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
|
71 |
-
if seed == -1: seed = random.randint(0, MAX_SEED)
|
72 |
-
progress_bar = st.progress(0)
|
73 |
-
image, seed = await generate_image(combined_prompt, model, width, height, scales, steps, seed)
|
74 |
-
progress_bar.progress(50)
|
75 |
-
if isinstance(image, str) and image.startswith("Error"): return [image, None]
|
76 |
image_path = save_image(image, seed)
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
async def improve_prompt(prompt, language):
|
83 |
-
instruction = "With this idea, describe in English a detailed txt2img prompt..." if language == "en" else "Con esta idea, describe en español un prompt detallado..."
|
84 |
formatted_prompt = f"{prompt}: {instruction}"
|
85 |
-
response =
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
99 |
|
100 |
def main():
|
101 |
st.set_page_config(layout="wide")
|
|
|
102 |
if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
|
103 |
-
st.
|
104 |
-
login_form(credentials)
|
105 |
return
|
106 |
-
|
107 |
-
st.sidebar.text_input("Descripción de la imagen", max_chars=900
|
108 |
process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
|
109 |
language = st.sidebar.selectbox("Idioma", ["en", "es"])
|
110 |
basemodel = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"])
|
111 |
format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
|
112 |
process_upscale = st.sidebar.checkbox("Procesar Escalador", value=False)
|
113 |
upscale_factor = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0)
|
114 |
-
scales
|
115 |
-
|
|
|
|
|
|
|
116 |
if st.sidebar.button("Generar Imagen"):
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
129 |
|
130 |
if __name__ == "__main__":
|
131 |
main()
|
|
|
1 |
+
import os, numpy as np, random, asyncio, insightface
|
|
|
|
|
2 |
from pathlib import Path
|
3 |
from PIL import Image
|
4 |
from insightface.app import FaceAnalysis
|
5 |
import streamlit as st
|
6 |
+
from huggingface_hub import InferenceClient
|
7 |
+
from gradio_client import Client, handle_file
|
8 |
+
from concurrent.futures import ThreadPoolExecutor
|
9 |
import yaml
|
|
|
10 |
|
11 |
+
MAX_SEED = np.iinfo(np.int32).max
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
|
13 |
+
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
14 |
+
DATA_PATH = Path("./data")
|
15 |
+
DATA_PATH.mkdir(exist_ok=True)
|
16 |
|
17 |
def prepare_face_app():
|
18 |
app = FaceAnalysis(name='buffalo_l')
|
19 |
app.prepare(ctx_id=0, det_size=(640, 640))
|
20 |
+
swapper = insightface.model_zoo.get_model('onix.onnx')
|
21 |
+
return app, swapper
|
22 |
|
23 |
app, swapper = prepare_face_app()
|
24 |
|
25 |
+
async def generate_image(combined_prompt, model, width, height, scales, steps, seed):
|
|
|
|
|
|
|
|
|
|
|
26 |
if seed == -1:
|
27 |
seed = random.randint(0, MAX_SEED)
|
28 |
+
seed = int(seed)
|
29 |
+
image = await client.text_to_image(prompt=combined_prompt, height=height, width=width, guidance_scale=scales, num_inference_steps=steps, model=model)
|
30 |
+
return image, seed
|
31 |
+
|
32 |
+
def get_upscale_finegrain(prompt, img_path, upscale_factor):
|
33 |
+
client = Client("finegrain/finegrain-image-enhancer", hf_token=HF_TOKEN_UPSCALER)
|
34 |
+
result = 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 |
+
|
37 |
+
def save_prompt(prompt_text, seed):
|
38 |
+
prompt_file_path = DATA_PATH / f"prompt_{seed}.txt"
|
39 |
+
with open(prompt_file_path, "w") as prompt_file:
|
40 |
+
prompt_file.write(prompt_text)
|
41 |
+
return prompt_file_path
|
42 |
+
|
43 |
+
async def gen(prompt, basemodel, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
|
44 |
+
combined_prompt = prompt
|
45 |
+
if process_enhancer:
|
46 |
+
improved_prompt = await improve_prompt(prompt, language)
|
47 |
+
combined_prompt = f"{prompt} {improved_prompt}"
|
48 |
+
|
49 |
+
if seed == -1:
|
50 |
+
seed = random.randint(0, MAX_SEED)
|
51 |
+
seed = int(seed)
|
52 |
+
image, seed = await generate_image(combined_prompt, basemodel, width, height, scales, steps, seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
image_path = save_image(image, seed)
|
54 |
+
prompt_file_path = save_prompt(combined_prompt, seed)
|
55 |
+
|
56 |
+
if process_upscale:
|
57 |
+
upscale_image_path = get_upscale_finegrain(combined_prompt, image_path, upscale_factor)
|
58 |
+
if upscale_image_path:
|
59 |
+
upscale_image = Image.open(upscale_image_path)
|
60 |
+
upscale_image.save(DATA_PATH / f"upscale_image_{seed}.jpg", format="JPEG")
|
61 |
+
image_path.unlink()
|
62 |
+
return [str(DATA_PATH / f"upscale_image_{seed}.jpg"), str(prompt_file_path)]
|
63 |
+
else:
|
64 |
+
return [str(image_path), str(prompt_file_path)]
|
65 |
+
else:
|
66 |
+
return [str(image_path), str(prompt_file_path)]
|
67 |
|
68 |
async def improve_prompt(prompt, language):
|
69 |
+
instruction = "With this idea, describe in English a detailed txt2img prompt in 500 characters..." if language == "en" else "Con esta idea, describe en español un prompt detallado de txt2img en 500 caracteres..."
|
70 |
formatted_prompt = f"{prompt}: {instruction}"
|
71 |
+
response = client.text_generation(formatted_prompt, max_new_tokens=500)
|
72 |
+
improved_text = response['generated_text'].strip() if 'generated_text' in response else response.strip()
|
73 |
+
return improved_text[:500] if len(improved_text) > 500 else improved_text
|
74 |
+
|
75 |
+
def save_image(image, seed):
|
76 |
+
image_path = DATA_PATH / f"image_{seed}.jpg"
|
77 |
+
image.save(image_path, format="JPEG")
|
78 |
+
return image_path
|
79 |
+
|
80 |
+
def get_storage():
|
81 |
+
files = [file for file in DATA_PATH.glob("*.jpg") if file.is_file()]
|
82 |
+
files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
|
83 |
+
return [str(file.resolve()) for file in files]
|
84 |
+
|
85 |
+
def delete_image(image_path):
|
86 |
+
if Path(image_path).exists():
|
87 |
+
Path(image_path).unlink()
|
88 |
|
89 |
def main():
|
90 |
st.set_page_config(layout="wide")
|
91 |
+
|
92 |
if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
|
93 |
+
st.warning("Por favor, inicia sesión para acceder a la aplicación.")
|
|
|
94 |
return
|
95 |
+
|
96 |
+
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=900)
|
97 |
process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
|
98 |
language = st.sidebar.selectbox("Idioma", ["en", "es"])
|
99 |
basemodel = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"])
|
100 |
format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
|
101 |
process_upscale = st.sidebar.checkbox("Procesar Escalador", value=False)
|
102 |
upscale_factor = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0)
|
103 |
+
scales = st.sidebar.slider("Escalado", 1, 20, 10)
|
104 |
+
steps = st.sidebar.slider("Pasos", 1, 100, 20)
|
105 |
+
seed = st.sidebar.number_input("Semilla", value=-1)
|
106 |
+
width, height = (1080, 1920) if format_option == "9:16" else (1920, 1080)
|
107 |
+
|
108 |
if st.sidebar.button("Generar Imagen"):
|
109 |
+
with st.spinner("Generando..."):
|
110 |
+
image_path, prompt_file_path = asyncio.run(gen(prompt, basemodel, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language))
|
111 |
+
if image_path:
|
112 |
+
st.image(image_path, caption="Imagen Generada", use_column_width=True)
|
113 |
+
st.download_button("Descargar Imagen", image_path)
|
114 |
+
|
115 |
+
files = get_storage()
|
116 |
+
for file in files:
|
117 |
+
st.image(file)
|
118 |
+
st.text(f"Prompt: {file.stem}")
|
119 |
+
if st.button(f"Swap Face {file.stem}"):
|
120 |
+
pass
|
121 |
+
if st.button(f"Borrar {file.stem}"):
|
122 |
+
delete_image(file)
|
123 |
|
124 |
if __name__ == "__main__":
|
125 |
main()
|