Spaces:
Running
Running
salomonsky
commited on
Commit
•
f693d07
1
Parent(s):
9faf979
Update app.py
Browse files
app.py
CHANGED
@@ -1,101 +1,138 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
async def generate_image(prompt, width, height, seed):
|
8 |
try:
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
12 |
except Exception as e:
|
13 |
-
return f"Error al generar imagen: {e}"
|
14 |
|
|
|
15 |
def save_prompt(prompt_text, seed):
|
16 |
try:
|
17 |
prompt_file_path = DATA_PATH / f"prompt_{seed}.txt"
|
18 |
-
with open(prompt_file_path, "w") as prompt_file:
|
19 |
-
|
|
|
20 |
except Exception as e:
|
21 |
-
st.error(f"Error al guardar el prompt: {e}")
|
22 |
-
|
23 |
-
async def gen(prompt, width, height):
|
24 |
-
seed = PREDEFINED_SEED; progress_bar = st.progress(0)
|
25 |
-
image, seed = await generate_image(prompt, width, height, seed)
|
26 |
-
progress_bar.progress(100)
|
27 |
-
if isinstance(image, str) and image.startswith("Error"): progress_bar.empty(); return [image, None]
|
28 |
-
return [save_image(image, seed), save_prompt(prompt, seed)]
|
29 |
|
|
|
30 |
def save_image(image, seed):
|
31 |
try:
|
32 |
image_path = DATA_PATH / f"image_{seed}.jpg"
|
33 |
image.save(image_path, format="JPEG")
|
34 |
-
return image_path
|
35 |
except Exception as e:
|
36 |
-
st.error(f"Error al guardar la imagen: {e}")
|
|
|
37 |
|
|
|
38 |
def get_storage():
|
39 |
-
files =
|
40 |
-
|
|
|
41 |
return [str(file.resolve()) for file in files], f"Uso total: {usage/(1024.0 ** 3):.3f}GB"
|
42 |
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
def main():
|
47 |
st.set_page_config(layout="wide")
|
48 |
st.title("Generador de Imágenes FLUX")
|
49 |
|
50 |
-
|
51 |
-
|
52 |
if not st.session_state.logged_in:
|
53 |
-
st.sidebar.
|
54 |
-
|
55 |
-
input_password = st.sidebar.text_input("Contraseña", type="password")
|
56 |
|
57 |
if st.sidebar.button("Iniciar Sesión"):
|
58 |
-
if
|
59 |
st.session_state.logged_in = True
|
60 |
-
st.sidebar.success("Inicio de sesión exitoso!")
|
61 |
else:
|
62 |
-
st.
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import random
|
4 |
+
from pathlib import Path
|
5 |
+
from PIL import Image
|
6 |
+
import streamlit as st
|
7 |
+
from huggingface_hub import AsyncInferenceClient
|
8 |
+
import asyncio
|
9 |
+
import yaml
|
10 |
+
|
11 |
+
# Configuración de cliente de inferencia
|
12 |
+
client = AsyncInferenceClient()
|
13 |
+
DATA_PATH = Path("./data")
|
14 |
+
DATA_PATH.mkdir(exist_ok=True)
|
15 |
+
|
16 |
+
# Cargar credenciales desde archivo YAML
|
17 |
+
with open("credentials.yaml", "r") as file:
|
18 |
+
credentials = yaml.safe_load(file)
|
19 |
+
|
20 |
+
# Variables de estado
|
21 |
+
if 'logged_in' not in st.session_state:
|
22 |
+
st.session_state.logged_in = False
|
23 |
+
if 'prompt' not in st.session_state:
|
24 |
+
st.session_state.prompt = ""
|
25 |
+
|
26 |
+
# Función de generación de imágenes
|
27 |
async def generate_image(prompt, width, height, seed):
|
28 |
try:
|
29 |
+
if seed == -1:
|
30 |
+
seed = random.randint(0, np.iinfo(np.int32).max)
|
31 |
+
image = await client.text_to_image(
|
32 |
+
prompt=prompt, height=height, width=width, model="enhanceaiteam/Flux-uncensored"
|
33 |
+
)
|
34 |
+
return image
|
35 |
except Exception as e:
|
36 |
+
return f"Error al generar imagen: {e}"
|
37 |
|
38 |
+
# Función para guardar prompts
|
39 |
def save_prompt(prompt_text, seed):
|
40 |
try:
|
41 |
prompt_file_path = DATA_PATH / f"prompt_{seed}.txt"
|
42 |
+
with open(prompt_file_path, "w") as prompt_file:
|
43 |
+
prompt_file.write(prompt_text)
|
44 |
+
return str(prompt_file_path)
|
45 |
except Exception as e:
|
46 |
+
st.error(f"Error al guardar el prompt: {e}")
|
47 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
+
# Función para guardar imágenes
|
50 |
def save_image(image, seed):
|
51 |
try:
|
52 |
image_path = DATA_PATH / f"image_{seed}.jpg"
|
53 |
image.save(image_path, format="JPEG")
|
54 |
+
return str(image_path)
|
55 |
except Exception as e:
|
56 |
+
st.error(f"Error al guardar la imagen: {e}")
|
57 |
+
return None
|
58 |
|
59 |
+
# Función para obtener archivos almacenados
|
60 |
def get_storage():
|
61 |
+
files = [file for file in DATA_PATH.glob("*.jpg") if file.is_file()]
|
62 |
+
files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
|
63 |
+
usage = sum([file.stat().st_size for file in files])
|
64 |
return [str(file.resolve()) for file in files], f"Uso total: {usage/(1024.0 ** 3):.3f}GB"
|
65 |
|
66 |
+
# Función principal
|
67 |
+
async def gen(prompt, width, height):
|
68 |
+
seed = random.randint(0, np.iinfo(np.int32).max)
|
69 |
+
progress_bar = st.progress(0)
|
70 |
+
image = await generate_image(prompt, width, height, seed)
|
71 |
+
progress_bar.progress(100)
|
72 |
+
|
73 |
+
if isinstance(image, str) and image.startswith("Error"):
|
74 |
+
progress_bar.empty()
|
75 |
+
return [image, None]
|
76 |
+
|
77 |
+
image_path = save_image(image, seed)
|
78 |
+
prompt_file_path = save_prompt(prompt, seed)
|
79 |
+
|
80 |
+
return [image_path, prompt_file_path]
|
81 |
|
82 |
def main():
|
83 |
st.set_page_config(layout="wide")
|
84 |
st.title("Generador de Imágenes FLUX")
|
85 |
|
86 |
+
# Inicio de sesión
|
|
|
87 |
if not st.session_state.logged_in:
|
88 |
+
username = st.sidebar.text_input("Usuario")
|
89 |
+
password = st.sidebar.text_input("Contraseña", type="password")
|
|
|
90 |
|
91 |
if st.sidebar.button("Iniciar Sesión"):
|
92 |
+
if username == credentials["username"] and password == credentials["password"]:
|
93 |
st.session_state.logged_in = True
|
|
|
94 |
else:
|
95 |
+
st.error("Credenciales incorrectas.")
|
96 |
+
return
|
97 |
+
|
98 |
+
# Opciones después de iniciar sesión
|
99 |
+
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=500)
|
100 |
+
format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
|
101 |
+
|
102 |
+
width, height = (720, 1280) if format_option == "9:16" else (1280, 720)
|
103 |
+
|
104 |
+
if st.sidebar.button("Generar Imagen"):
|
105 |
+
with st.spinner("Generando imagen..."):
|
106 |
+
result = asyncio.run(gen(prompt, width, height))
|
107 |
+
image_paths = result[0]
|
108 |
+
prompt_file = result[1]
|
109 |
+
|
110 |
+
if image_paths and Path(image_paths).exists():
|
111 |
+
st.image(image_paths, caption="Imagen Generada")
|
112 |
+
if prompt_file and Path(prompt_file).exists():
|
113 |
+
prompt_text = Path(prompt_file).read_text()
|
114 |
+
st.write(f"Prompt utilizado: {prompt_text}")
|
115 |
+
else:
|
116 |
+
st.error("El archivo de imagen no existe.")
|
117 |
+
|
118 |
+
files, usage = get_storage()
|
119 |
+
st.text(usage)
|
120 |
+
cols = st.columns(6)
|
121 |
+
|
122 |
+
for idx, file in enumerate(files):
|
123 |
+
with cols[idx % 6]:
|
124 |
+
image = Image.open(file)
|
125 |
+
prompt_text = Path(DATA_PATH / f"prompt_{file.stem.replace('image_', '')}.txt").read_text() if Path(DATA_PATH / f"prompt_{file.stem.replace('image_', '')}.txt").exists() else "No disponible"
|
126 |
+
st.image(image, caption=f"Imagen {idx+1}")
|
127 |
+
st.write(f"Prompt: {prompt_text}")
|
128 |
+
|
129 |
+
if st.button(f"Borrar Imagen {idx+1}", key=f"delete_{idx}"):
|
130 |
+
try:
|
131 |
+
os.remove(file)
|
132 |
+
os.remove(DATA_PATH / f"prompt_{file.stem.replace('image_', '')}.txt")
|
133 |
+
st.success(f"Imagen {idx+1} y su prompt fueron borrados.")
|
134 |
+
except Exception as e:
|
135 |
+
st.error(f"Error al borrar la imagen o prompt: {e}")
|
136 |
+
|
137 |
+
if __name__ == "__main__":
|
138 |
+
main()
|