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