salomonsky commited on
Commit
f693d07
1 Parent(s): 9faf979

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -73
app.py CHANGED
@@ -1,101 +1,138 @@
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
- image = await client.text_to_image(prompt=prompt, height=height, width=width, model="enhanceaiteam/Flux-uncensored")
11
- return image, seed
 
 
 
12
  except Exception as e:
13
- return f"Error al generar imagen: {e}", None
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: prompt_file.write(prompt_text)
19
- return prompt_file_path
 
20
  except Exception as e:
21
- st.error(f"Error al guardar el prompt: {e}"); return None
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}"); return None
 
37
 
 
38
  def get_storage():
39
- files = sorted(DATA_PATH.glob("*.jpg"), key=lambda x: x.stat().st_mtime, reverse=True)
40
- usage = sum(file.stat().st_size for file in files)
 
41
  return [str(file.resolve()) for file in files], f"Uso total: {usage/(1024.0 ** 3):.3f}GB"
42
 
43
- def get_prompts():
44
- return {file.stem.replace("prompt_", ""): file for file in DATA_PATH.glob("*.txt") if file.is_file()}
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def main():
47
  st.set_page_config(layout="wide")
48
  st.title("Generador de Imágenes FLUX")
49
 
50
- if "logged_in" not in st.session_state: st.session_state.logged_in = False
51
-
52
  if not st.session_state.logged_in:
53
- st.sidebar.header("Inicio de Sesión")
54
- input_username = st.sidebar.text_input("Usuario")
55
- input_password = st.sidebar.text_input("Contraseña", type="password")
56
 
57
  if st.sidebar.button("Iniciar Sesión"):
58
- if input_username == username and input_password == password:
59
  st.session_state.logged_in = True
60
- st.sidebar.success("Inicio de sesión exitoso!")
61
  else:
62
- st.sidebar.error("Usuario o contraseña incorrectos.")
63
- else:
64
- prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=500)
65
- width, height = (720, 1280) if st.sidebar.selectbox("Formato", ["9:16", "16:9"]) == "9:16" else (1280, 720)
66
-
67
- if st.sidebar.button("Generar Imagen"):
68
- with st.spinner("Generando imagen..."):
69
- result = asyncio.run(gen(prompt, width, height))
70
- image_paths = result[0]
71
- prompt_file = result[1]
72
-
73
- if image_paths and Path(image_paths).exists():
74
- st.image(image_paths, caption="Imagen Generada")
75
- else:
76
- st.error("El archivo de imagen no existe.")
77
- if prompt_file and Path(prompt_file).exists():
78
- st.write(f"Prompt utilizado: {Path(prompt_file).read_text()}")
79
- else:
80
- st.write("El archivo del prompt no está disponible.")
81
-
82
- files, usage = get_storage()
83
- st.text(usage)
84
- cols = st.columns(6)
85
- prompts = get_prompts()
86
-
87
- for idx, file in enumerate(files):
88
- with cols[idx % 6]:
89
- image = Image.open(file)
90
- prompt_file = prompts.get(Path(file).stem.replace("image_", ""), None)
91
- st.image(image, caption=f"Imagen {idx+1}")
92
- st.write(f"Prompt: {Path(prompt_file).read_text() if prompt_file else 'No disponible'}")
93
- if st.button(f"Borrar Imagen {idx+1}", key=f"delete_{idx}"):
94
- try:
95
- os.remove(file)
96
- os.remove(prompt_file) if prompt_file else None
97
- st.success(f"Imagen {idx+1} y su prompt fueron borrados.")
98
- except Exception as e:
99
- st.error(f"Error al borrar la imagen o prompt: {e}")
100
-
101
- if __name__ == "__main__": main()
 
 
 
 
 
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()