salomonsky commited on
Commit
8372f4c
verified
1 Parent(s): 4ff1d41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -36
app.py CHANGED
@@ -1,8 +1,8 @@
1
  from pathlib import Path
2
  from PIL import Image
3
  import streamlit as st
4
- import os, random, numpy as np, yaml, time, logging
5
- from dataclasses import dataclass, field
6
  from typing import List
7
  from huggingface_hub import InferenceClient
8
 
@@ -21,16 +21,28 @@ class AppConfig:
21
  CLEANUP_DAYS: int = 7
22
 
23
  MAX_SEED = AppConfig.MAX_SEED
24
- client = InferenceClient()
 
 
 
 
 
 
25
  DATA_PATH = Path("./data")
26
  DATA_PATH.mkdir(exist_ok=True)
27
- HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN")
28
 
29
- def cleanup_old_images(max_age_days=AppConfig.CLEANUP_DAYS):
30
- current_time = time.time()
31
- for image_file in DATA_PATH.glob("*.jpg"):
32
- if current_time - image_file.stat().st_mtime > max_age_days * 86400:
33
- os.remove(image_file)
 
 
 
 
 
 
 
34
 
35
  def authenticate_user(username, password):
36
  return username == credentials["username"] and password == credentials["password"]
@@ -38,15 +50,36 @@ def authenticate_user(username, password):
38
  def list_saved_images():
39
  return sorted(DATA_PATH.glob("*.jpg"), key=lambda x: x.stat().st_mtime, reverse=True)
40
 
41
- def enhance_prompt(text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
  enhanced = client.text_generation(
44
- "With this text, generate a descriptive and photorealistic txt2img prompt in English in 200 characters maximum: " + text,
45
  model="mistralai/Mixtral-8x7B-v0.1",
46
  max_length=200
47
  )
48
  return enhanced[:200]
49
- except:
 
50
  return text[:200]
51
 
52
  def save_prompt(image_name, prompt):
@@ -55,14 +88,14 @@ def save_prompt(image_name, prompt):
55
 
56
  def generate_variations(prompt, num_variants=8, use_enhanced=True):
57
  instructions = [
58
- "Create a photorealistic description for a detailed txt2img prompt in English: ",
59
- "Write a creative, realistic, and detailed text-to-image prompt in English: ",
60
- "Generate a descriptive and true to life txt2img prompt in English: ",
61
- "Describe a photorealistic scene with detailed illumination for a txt2img prompt: ",
62
- "Give a realistic, elegant txt2img prompt in English, emphasizing photorealism: ",
63
- "Create a visually dynamic and hyperrealistic txt2img prompt in English: ",
64
- "Write a cinematic txt2img prompt in English with hyperrealistic elements: ",
65
- "Make a lifelike txt2img prompt in English, focusing on photorealistic depth: "
66
  ]
67
  if use_enhanced:
68
  prompts = [enhance_prompt(f"{instructions[i % len(instructions)]}{prompt}") for i in range(num_variants)]
@@ -70,15 +103,25 @@ def generate_variations(prompt, num_variants=8, use_enhanced=True):
70
  prompts = [prompt] * num_variants
71
  return prompts
72
 
73
- def generate_image(prompt, width, height, seed, model_name):
 
 
 
 
74
  try:
75
  with st.spinner("Generando imagen..."):
76
  seed = int(seed) if seed != -1 else random.randint(0, AppConfig.MAX_SEED)
77
  enhanced_prompt = enhance_prompt(prompt)
78
- image = client.text_to_image(prompt=enhanced_prompt, height=height, width=width, model=model_name, seed=seed)
 
 
 
 
 
 
79
  return image, seed, enhanced_prompt
80
  except Exception as e:
81
- st.error(f"Error al generar imagen: {e}")
82
  return None, seed, None
83
 
84
  def gen(prompts, width, height, model_name, num_variants=8):
@@ -101,6 +144,22 @@ def gen(prompts, width, height, model_name, num_variants=8):
101
  st.success(f"Imagen {i+1} generada")
102
  return images
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  def display_gallery():
105
  st.header("Galer铆a de Im谩genes Guardadas")
106
  images = list_saved_images()
@@ -111,27 +170,17 @@ def display_gallery():
111
  with cols[i % 4]:
112
  st.image(str(image_file), use_column_width=True)
113
  prompt = get_prompt_for_image(image_file.name)
114
- st.caption(prompt[:100])
115
  if st.button(f"Borrar", key=f"delete_{i}_{image_file}"):
116
  if image_file.exists():
117
  os.remove(image_file)
118
  st.success("Imagen borrada")
119
  st.rerun()
120
 
121
- def get_prompt_for_image(image_name):
122
- try:
123
- with open(DATA_PATH / "prompts.txt", "r") as f:
124
- for line in f:
125
- if line.startswith(image_name):
126
- return line.split(": ", 1)[1].strip()
127
- except FileNotFoundError:
128
- return "No hay prompt asociado"
129
- return "No hay prompt asociado"
130
-
131
  def login_form():
132
  st.title("Iniciar Sesi贸n")
133
  username = st.text_input("Usuario", value="admin")
134
- password = st.text_input("Contrase帽a", value="flux3x", type="password")
135
  if st.button("Iniciar Sesi贸n"):
136
  if authenticate_user(username, password):
137
  st.session_state['authenticated'] = True
@@ -155,6 +204,10 @@ def main():
155
 
156
  st.title("Flux +Upscale +Prompt Enhancer")
157
 
 
 
 
 
158
  prompt = st.sidebar.text_area("Descripci贸n de la imagen", height=150, max_chars=500)
159
  format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9", "1:1"])
160
  model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev"])
@@ -168,7 +221,6 @@ def main():
168
  if st.sidebar.button("Generar Im谩genes"):
169
  generated_images = gen(prompts, width, height, model_option, num_variants)
170
 
171
- # Display generated images with their prompts
172
  st.header("Im谩genes Generadas")
173
  cols = st.columns(4)
174
  for i, (image_path, image_prompt) in enumerate(generated_images):
 
1
  from pathlib import Path
2
  from PIL import Image
3
  import streamlit as st
4
+ import os, random, numpy as np, yaml, time
5
+ from dataclasses import dataclass
6
  from typing import List
7
  from huggingface_hub import InferenceClient
8
 
 
21
  CLEANUP_DAYS: int = 7
22
 
23
  MAX_SEED = AppConfig.MAX_SEED
24
+
25
+ HF_TOKENS = [
26
+ os.environ.get("HF_TOKEN1"),
27
+ os.environ.get("HF_TOKEN2"),
28
+ os.environ.get("HF_TOKEN3")
29
+ ]
30
+
31
  DATA_PATH = Path("./data")
32
  DATA_PATH.mkdir(exist_ok=True)
 
33
 
34
+ def get_inference_client(tokens=HF_TOKENS):
35
+ for token in tokens:
36
+ try:
37
+ client = InferenceClient(token=token)
38
+ client.text_generation("Test", max_length=10)
39
+ return client
40
+ except Exception as e:
41
+ st.warning(f"Token fallido: {token[:5]}...")
42
+ st.error("Todos los tokens de HuggingFace han fallado")
43
+ return None
44
+
45
+ client = get_inference_client()
46
 
47
  def authenticate_user(username, password):
48
  return username == credentials["username"] and password == credentials["password"]
 
50
  def list_saved_images():
51
  return sorted(DATA_PATH.glob("*.jpg"), key=lambda x: x.stat().st_mtime, reverse=True)
52
 
53
+ def get_image_description(image_path, original_prompt):
54
+ if not client:
55
+ return original_prompt
56
+
57
+ try:
58
+ description_prompt = f"Analyze this image in great detail. The original prompt was: {original_prompt}. Provide a comprehensive and creative description focusing on visual elements, mood, and artistic style."
59
+
60
+ description = client.text_generation(
61
+ description_prompt,
62
+ model="mistralai/Mixtral-8x7B-v0.1",
63
+ max_new_tokens=150
64
+ )
65
+
66
+ return description.strip()
67
+ except Exception as e:
68
+ st.warning(f"Image description generation error: {e}")
69
+ return original_prompt
70
+
71
+ def enhance_prompt(text, client=client):
72
+ if not client:
73
+ return text[:200]
74
  try:
75
  enhanced = client.text_generation(
76
+ "Generate a photorealistic, detailed txt2img prompt in 200 characters maximum: " + text,
77
  model="mistralai/Mixtral-8x7B-v0.1",
78
  max_length=200
79
  )
80
  return enhanced[:200]
81
+ except Exception as e:
82
+ st.warning(f"Prompt enhancement error: {e}")
83
  return text[:200]
84
 
85
  def save_prompt(image_name, prompt):
 
88
 
89
  def generate_variations(prompt, num_variants=8, use_enhanced=True):
90
  instructions = [
91
+ "Photorealistic description for txt2img: ",
92
+ "Creative, realistic text-to-image prompt: ",
93
+ "Descriptive, true-to-life txt2img prompt: ",
94
+ "Photorealistic scene with detailed illumination: ",
95
+ "Realistic, elegant txt2img prompt: ",
96
+ "Visually dynamic, hyperrealistic prompt: ",
97
+ "Cinematic txt2img with hyperrealistic elements: ",
98
+ "Lifelike txt2img, focusing on photorealistic depth: "
99
  ]
100
  if use_enhanced:
101
  prompts = [enhance_prompt(f"{instructions[i % len(instructions)]}{prompt}") for i in range(num_variants)]
 
103
  prompts = [prompt] * num_variants
104
  return prompts
105
 
106
+ def generate_image(prompt, width, height, seed, model_name, client=client):
107
+ if not client:
108
+ st.error("No Hugging Face client available")
109
+ return None, seed, None
110
+
111
  try:
112
  with st.spinner("Generando imagen..."):
113
  seed = int(seed) if seed != -1 else random.randint(0, AppConfig.MAX_SEED)
114
  enhanced_prompt = enhance_prompt(prompt)
115
+ image = client.text_to_image(
116
+ prompt=enhanced_prompt,
117
+ height=height,
118
+ width=width,
119
+ model=model_name,
120
+ seed=seed
121
+ )
122
  return image, seed, enhanced_prompt
123
  except Exception as e:
124
+ st.error(f"Image generation error: {e}")
125
  return None, seed, None
126
 
127
  def gen(prompts, width, height, model_name, num_variants=8):
 
144
  st.success(f"Imagen {i+1} generada")
145
  return images
146
 
147
+ def get_prompt_for_image(image_name):
148
+ try:
149
+ with open(DATA_PATH / "prompts.txt", "r") as f:
150
+ for line in f:
151
+ if line.startswith(image_name):
152
+ original_prompt = line.split(": ", 1)[1].strip()
153
+ image_path = DATA_PATH / image_name
154
+
155
+ if image_path.exists():
156
+ return get_image_description(str(image_path), original_prompt)
157
+
158
+ return original_prompt
159
+ except FileNotFoundError:
160
+ return "No hay prompt asociado"
161
+ return "No hay prompt asociado"
162
+
163
  def display_gallery():
164
  st.header("Galer铆a de Im谩genes Guardadas")
165
  images = list_saved_images()
 
170
  with cols[i % 4]:
171
  st.image(str(image_file), use_column_width=True)
172
  prompt = get_prompt_for_image(image_file.name)
173
+ st.caption(prompt[:250])
174
  if st.button(f"Borrar", key=f"delete_{i}_{image_file}"):
175
  if image_file.exists():
176
  os.remove(image_file)
177
  st.success("Imagen borrada")
178
  st.rerun()
179
 
 
 
 
 
 
 
 
 
 
 
180
  def login_form():
181
  st.title("Iniciar Sesi贸n")
182
  username = st.text_input("Usuario", value="admin")
183
+ password = st.text_input("Contrase帽a", value="", type="password")
184
  if st.button("Iniciar Sesi贸n"):
185
  if authenticate_user(username, password):
186
  st.session_state['authenticated'] = True
 
204
 
205
  st.title("Flux +Upscale +Prompt Enhancer")
206
 
207
+ if not client:
208
+ st.error("No se pudo establecer conexi贸n con Hugging Face. Verifique sus tokens.")
209
+ return
210
+
211
  prompt = st.sidebar.text_area("Descripci贸n de la imagen", height=150, max_chars=500)
212
  format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9", "1:1"])
213
  model_option = st.sidebar.selectbox("Modelo", ["black-forest-labs/FLUX.1-schnell", "black-forest-labs/FLUX.1-dev"])
 
221
  if st.sidebar.button("Generar Im谩genes"):
222
  generated_images = gen(prompts, width, height, model_option, num_variants)
223
 
 
224
  st.header("Im谩genes Generadas")
225
  cols = st.columns(4)
226
  for i, (image_path, image_prompt) in enumerate(generated_images):