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