salomonsky commited on
Commit
18c1250
verified
1 Parent(s): 60a964a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -38
app.py CHANGED
@@ -4,33 +4,55 @@ import random
4
  from pathlib import Path
5
  from PIL import Image
6
  import streamlit as st
7
- import streamlit_authenticator as stauth
8
- from huggingface_hub import InferenceClient
9
-
10
- st.set_page_config(layout="wide")
11
-
12
- credentials = {
13
- "usernames": {
14
- "admin": {
15
- "name": "admin",
16
- "password": stauth.Hasher(["flux33"]).generate()[0]
17
- }
18
- }
19
- }
20
-
21
- authenticator = stauth.Authenticate(credentials, "imagen_gen_auth", "flux3", 30)
22
- client = InferenceClient()
23
  DATA_PATH = Path("./data")
24
  DATA_PATH.mkdir(exist_ok=True)
25
 
26
- def generate_image(prompt, width, height):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
- image = client.text_to_image(prompt=prompt, height=height, width=width, model="enhanceaiteam/Flux-uncensored")
29
- return image
 
 
30
  except Exception as e:
31
- st.error(f"Error al generar imagen: {e}")
32
  return None
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def save_image(image, seed):
35
  try:
36
  image_path = DATA_PATH / f"image_{seed}.jpg"
@@ -40,26 +62,69 @@ def save_image(image, seed):
40
  st.error(f"Error al guardar la imagen: {e}")
41
  return None
42
 
 
 
 
 
 
 
 
 
 
 
43
  def main():
44
- name, authentication_status, username = authenticator.login(
45
- "Login", "main", fields={"username": "Username", "password": "Password", "login": "Login"})
46
-
47
- if authentication_status:
48
- st.title("Generador de Im谩genes con FLUX")
49
-
50
- prompt = st.text_input("Introduce el prompt para generar la imagen")
51
- if st.button("Generar Imagen"):
52
- if prompt:
53
- imagen_generada = generate_image(prompt, 512, 512)
54
- if imagen_generada:
55
- st.image(imagen_generada, caption="Imagen Generada", use_column_width=True)
 
 
 
 
 
 
 
 
 
56
  else:
57
- st.error("Por favor, introduce un prompt.")
58
-
59
- elif authentication_status == False:
60
- st.error('Nombre de usuario/contrase帽a incorrectos')
61
- elif authentication_status == None:
62
- st.warning('Por favor, introduce tu nombre de usuario y contrase帽a')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  if __name__ == "__main__":
65
  main()
 
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
+ MAX_SEED = np.iinfo(np.int32).max
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 == -1:
20
+ seed = PREDEFINED_SEED
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
+ combined_prompt = prompt
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
+ if isinstance(image, str) and image.startswith("Error"):
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:
58
  image_path = DATA_PATH / f"image_{seed}.jpg"
 
62
  st.error(f"Error al guardar la imagen: {e}")
63
  return None
64
 
65
+ def get_storage():
66
+ files = [file for file in DATA_PATH.glob("*.jpg") if file.is_file()]
67
+ files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
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
+ prompt_files = [file for file in DATA_PATH.glob("*.txt") if file.is_file()]
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
+ format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
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 = result[0]
92
+ prompt_file = result[1]
93
+
94
+ if image_paths:
95
+ if Path(image_paths).exists():
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
+ prompt_file = prompts.get(Path(file).stem.replace("image_", ""), None)
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
+ os.remove(file)
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()