salomonsky commited on
Commit
df23192
verified
1 Parent(s): d6c0a0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -82
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
- # 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("config.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()
 
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()