Spaces:
Running
Running
salomonsky
commited on
Commit
•
7e94dda
1
Parent(s):
26719a4
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,6 @@ import os, zipfile, yaml, numpy as np, random, asyncio
|
|
2 |
from pathlib import Path
|
3 |
from PIL import Image
|
4 |
import streamlit as st
|
5 |
-
import gradio as gr
|
6 |
from huggingface_hub import AsyncInferenceClient
|
7 |
from moviepy.editor import ImageSequenceClip
|
8 |
|
@@ -16,64 +15,81 @@ MAX_SEED, client, DATA_PATH, PREDEFINED_SEED = np.iinfo(np.int32).max, AsyncInfe
|
|
16 |
DATA_PATH.mkdir(exist_ok=True)
|
17 |
|
18 |
async def generate_image(prompt, width, height, seed, model_name):
|
19 |
-
try:
|
20 |
-
|
|
|
|
|
21 |
|
22 |
def save_prompt(prompt_text, seed):
|
23 |
-
try:
|
24 |
-
|
|
|
|
|
|
|
|
|
25 |
|
26 |
async def gen(prompt, width, height, model_name):
|
27 |
seed, progress_bar = PREDEFINED_SEED, st.progress(0)
|
28 |
image, seed = await generate_image(prompt, width, height, seed, model_name)
|
29 |
progress_bar.progress(100)
|
30 |
-
if isinstance(image, str) and image.startswith("Error"):
|
|
|
31 |
return [str(save_image(image, seed)), str(save_prompt(prompt, seed))]
|
32 |
|
33 |
def save_image(image, seed):
|
34 |
-
try:
|
35 |
-
|
|
|
|
|
|
|
|
|
36 |
|
37 |
def get_storage():
|
38 |
files = sorted([file for file in DATA_PATH.glob("*.jpg")], key=lambda x: x.stat().st_mtime, reverse=True)
|
39 |
return [str(file.resolve()) for file in files], f"Uso total: {sum([file.stat().st_size for file in files])/(1024.0 ** 3):.3f}GB"
|
40 |
|
41 |
-
def get_prompts():
|
|
|
42 |
|
43 |
def delete_all_images():
|
44 |
-
try:
|
45 |
-
|
|
|
|
|
|
|
46 |
|
47 |
def download_images_as_zip():
|
48 |
-
zip_path = DATA_PATH / "images.zip"
|
|
|
49 |
[zipf.write(file, arcname=file.name) for file in DATA_PATH.glob("*.jpg")]
|
50 |
-
with open(zip_path, "rb") as zip_file:
|
|
|
51 |
|
52 |
def create_video_from_images():
|
53 |
-
try:
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
56 |
video_path = DATA_PATH / "output_video.mp4"
|
57 |
ImageSequenceClip([np.array(img) for img in image_sequence], fps=1).write_videofile(str(video_path), codec="libx264")
|
58 |
return video_path
|
59 |
|
60 |
-
def image_slider(original, escalada):
|
61 |
-
def compare_images(image_1, image_2):
|
62 |
-
return gr.ImageSlider(image_1=image_1, image_2=image_2)
|
63 |
-
demo = gr.Interface(fn=compare_images, inputs=["image", "image"], outputs="slider")
|
64 |
-
return demo.launch()
|
65 |
-
|
66 |
def main():
|
67 |
st.set_page_config(layout="wide")
|
68 |
st.title("Generador de Imágenes Flux")
|
69 |
|
70 |
-
if "authenticated" not in st.session_state:
|
|
|
71 |
|
72 |
if not st.session_state.authenticated:
|
73 |
username, password = st.text_input("Usuario"), st.text_input("Contraseña", type="password")
|
74 |
if st.button("Ingresar") and username == credentials["username"] and password == credentials["password"]:
|
75 |
-
st.session_state.authenticated
|
76 |
-
|
|
|
|
|
77 |
return
|
78 |
|
79 |
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=500)
|
@@ -87,10 +103,8 @@ def main():
|
|
87 |
image_paths, prompt_file = result[0], result[1]
|
88 |
if Path(image_paths).exists():
|
89 |
st.image(image_paths, caption="Imagen Generada")
|
90 |
-
|
91 |
-
|
92 |
-
image_slider(original_image, scaled_image)
|
93 |
-
if prompt_file and Path(prompt_file).exists(): st.write(f"Prompt utilizado: {Path(prompt_file).read_text()}")
|
94 |
|
95 |
files, usage = get_storage()
|
96 |
st.text(usage)
|
@@ -107,10 +121,14 @@ def main():
|
|
107 |
if prompt_file: os.remove(prompt_file)
|
108 |
st.success(f"Imagen {idx+1} y su prompt fueron borrados.")
|
109 |
|
110 |
-
if st.sidebar.button("Borrar todas las imágenes"):
|
111 |
-
|
|
|
|
|
112 |
if st.button("Generar video con las imágenes"):
|
113 |
video_path = create_video_from_images()
|
114 |
-
if video_path:
|
|
|
115 |
|
116 |
-
if __name__ == "__main__":
|
|
|
|
2 |
from pathlib import Path
|
3 |
from PIL import Image
|
4 |
import streamlit as st
|
|
|
5 |
from huggingface_hub import AsyncInferenceClient
|
6 |
from moviepy.editor import ImageSequenceClip
|
7 |
|
|
|
15 |
DATA_PATH.mkdir(exist_ok=True)
|
16 |
|
17 |
async def generate_image(prompt, width, height, seed, model_name):
|
18 |
+
try:
|
19 |
+
return await client.text_to_image(prompt=prompt, height=height, width=width, model=model_name), int(seed)
|
20 |
+
except Exception as e:
|
21 |
+
return f"Error al generar imagen: {e}", None
|
22 |
|
23 |
def save_prompt(prompt_text, seed):
|
24 |
+
try:
|
25 |
+
prompt_file_path = DATA_PATH / f"prompt_{seed}.txt"
|
26 |
+
open(prompt_file_path, "w").write(prompt_text)
|
27 |
+
return prompt_file_path
|
28 |
+
except Exception as e:
|
29 |
+
st.error(f"Error al guardar el prompt: {e}")
|
30 |
|
31 |
async def gen(prompt, width, height, model_name):
|
32 |
seed, progress_bar = PREDEFINED_SEED, st.progress(0)
|
33 |
image, seed = await generate_image(prompt, width, height, seed, model_name)
|
34 |
progress_bar.progress(100)
|
35 |
+
if isinstance(image, str) and image.startswith("Error"):
|
36 |
+
return [image, None]
|
37 |
return [str(save_image(image, seed)), str(save_prompt(prompt, seed))]
|
38 |
|
39 |
def save_image(image, seed):
|
40 |
+
try:
|
41 |
+
image_path = DATA_PATH / f"image_{seed}.jpg"
|
42 |
+
image.save(image_path, format="JPEG")
|
43 |
+
return image_path
|
44 |
+
except Exception as e:
|
45 |
+
st.error(f"Error al guardar la imagen: {e}")
|
46 |
|
47 |
def get_storage():
|
48 |
files = sorted([file for file in DATA_PATH.glob("*.jpg")], key=lambda x: x.stat().st_mtime, reverse=True)
|
49 |
return [str(file.resolve()) for file in files], f"Uso total: {sum([file.stat().st_size for file in files])/(1024.0 ** 3):.3f}GB"
|
50 |
|
51 |
+
def get_prompts():
|
52 |
+
return {file.stem.replace("prompt_", ""): file for file in DATA_PATH.glob("*.txt")}
|
53 |
|
54 |
def delete_all_images():
|
55 |
+
try:
|
56 |
+
[os.remove(file) for file in DATA_PATH.glob("*.jpg") + DATA_PATH.glob("*.txt")]
|
57 |
+
st.success("Todas las imágenes y prompts han sido borrados.")
|
58 |
+
except Exception as e:
|
59 |
+
st.error(f"Error al borrar archivos: {e}")
|
60 |
|
61 |
def download_images_as_zip():
|
62 |
+
zip_path = DATA_PATH / "images.zip"
|
63 |
+
zipf = zipfile.ZipFile(zip_path, 'w')
|
64 |
[zipf.write(file, arcname=file.name) for file in DATA_PATH.glob("*.jpg")]
|
65 |
+
with open(zip_path, "rb") as zip_file:
|
66 |
+
st.download_button(label="Descargar imágenes en .zip", data=zip_file, file_name="images.zip", mime="application/zip")
|
67 |
|
68 |
def create_video_from_images():
|
69 |
+
try:
|
70 |
+
image_files = sorted(DATA_PATH.glob("*.jpg"))
|
71 |
+
image_sequence = [Image.open(image_file) for image_file in image_files]
|
72 |
+
except:
|
73 |
+
st.error("No hay imágenes disponibles para crear un video.")
|
74 |
+
return
|
75 |
video_path = DATA_PATH / "output_video.mp4"
|
76 |
ImageSequenceClip([np.array(img) for img in image_sequence], fps=1).write_videofile(str(video_path), codec="libx264")
|
77 |
return video_path
|
78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
def main():
|
80 |
st.set_page_config(layout="wide")
|
81 |
st.title("Generador de Imágenes Flux")
|
82 |
|
83 |
+
if "authenticated" not in st.session_state:
|
84 |
+
st.session_state.authenticated = False
|
85 |
|
86 |
if not st.session_state.authenticated:
|
87 |
username, password = st.text_input("Usuario"), st.text_input("Contraseña", type="password")
|
88 |
if st.button("Ingresar") and username == credentials["username"] and password == credentials["password"]:
|
89 |
+
st.session_state.authenticated = True
|
90 |
+
st.success("Inicio de sesión exitoso.")
|
91 |
+
elif st.button("Ingresar"):
|
92 |
+
st.error("Usuario o contraseña incorrectos.")
|
93 |
return
|
94 |
|
95 |
prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=500)
|
|
|
103 |
image_paths, prompt_file = result[0], result[1]
|
104 |
if Path(image_paths).exists():
|
105 |
st.image(image_paths, caption="Imagen Generada")
|
106 |
+
if prompt_file and Path(prompt_file).exists():
|
107 |
+
st.write(f"Prompt utilizado: {Path(prompt_file).read_text()}")
|
|
|
|
|
108 |
|
109 |
files, usage = get_storage()
|
110 |
st.text(usage)
|
|
|
121 |
if prompt_file: os.remove(prompt_file)
|
122 |
st.success(f"Imagen {idx+1} y su prompt fueron borrados.")
|
123 |
|
124 |
+
if st.sidebar.button("Borrar todas las imágenes"):
|
125 |
+
delete_all_images()
|
126 |
+
if st.sidebar.button("Descargar imágenes en .zip"):
|
127 |
+
download_images_as_zip()
|
128 |
if st.button("Generar video con las imágenes"):
|
129 |
video_path = create_video_from_images()
|
130 |
+
if video_path:
|
131 |
+
st.video(str(video_path), format="video/mp4")
|
132 |
|
133 |
+
if __name__ == "__main__":
|
134 |
+
main()
|