salomonsky commited on
Commit
4babdf6
·
verified ·
1 Parent(s): 2658989

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -74
app.py CHANGED
@@ -9,8 +9,12 @@ import random
9
  import numpy as np
10
  import yaml
11
 
12
- with open("config.yaml", "r") as file:
13
- credentials = yaml.safe_load(file)
 
 
 
 
14
 
15
  MAX_SEED = np.iinfo(np.int32).max
16
  client = InferenceClient()
@@ -19,17 +23,28 @@ DATA_PATH.mkdir(exist_ok=True)
19
  PREDEFINED_SEED = random.randint(0, MAX_SEED)
20
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN")
21
 
 
 
 
22
  def get_upscale_finegrain(prompt, img_path, upscale_factor):
23
- upscale_client = InferenceClient("fal/AuraSR-v2", hf_token=HF_TOKEN_UPSCALER)
24
- result = upscale_client.predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
25
- return result[1] if isinstance(result, list) and len(result) > 1 else None
 
 
 
 
26
 
27
  def authenticate_user(username, password):
28
  return username == credentials["username"] and password == credentials["password"]
29
 
30
  def list_saved_images():
31
- image_files = sorted(DATA_PATH.glob("*.jpg"))
32
- return image_files
 
 
 
 
33
 
34
  def prepare_face_app():
35
  app = FaceAnalysis(name='buffalo_l')
@@ -43,29 +58,31 @@ def sort_faces(faces):
43
  return sorted(faces, key=lambda x: x.bbox[0])
44
 
45
  def get_face(faces, face_id):
 
 
46
  return faces[face_id - 1]
47
 
48
  def swap_faces(source_image, source_face_index, destination_image, destination_face_index):
49
  faces = sort_faces(app.get(source_image))
50
- if not faces:
51
- st.warning("No se encontraron caras en la imagen de origen.")
52
- return None
53
  source_face = get_face(faces, source_face_index)
54
-
55
  res_faces = sort_faces(app.get(destination_image))
56
- if not res_faces:
57
- st.warning("No se encontraron caras en la imagen de destino.")
58
- return None
59
  res_face = get_face(res_faces, destination_face_index)
60
-
61
  result = swapper.get(destination_image, res_face, source_face, paste_back=True)
62
  return result
63
 
64
  def generate_image(prompt, width, height, seed, model_name):
65
  if seed == -1:
66
  seed = random.randint(0, MAX_SEED)
67
- image = client.text_to_image(prompt=prompt, height=height, width=width, model=model_name)
68
- return image, seed
 
 
 
 
 
 
69
 
70
  def display_gallery():
71
  st.header("Galería de Imágenes Guardadas")
@@ -84,67 +101,74 @@ def display_gallery():
84
  if image_file.exists():
85
  os.remove(image_file)
86
  st.success("Imagen borrada")
 
87
  else:
88
  st.warning("La imagen no existe.")
89
  else:
90
  st.info("No hay imágenes guardadas.")
91
 
92
- def get_prompt_for_image(image_name):
93
- prompts = {}
94
- prompt_file = DATA_PATH / "prompts.txt"
95
- if prompt_file.exists():
96
- with open(prompt_file, "r") as f:
97
- for line in f:
98
- if line.startswith(image_name):
99
- prompts[image_name] = line.split(": ", 1)[1].strip()
100
- return prompts.get(image_name, "No hay prompt asociado.")
101
 
102
  def generate_variations(prompt, num_variants, use_enhanced):
103
- if not use_enhanced:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  return [prompt] * num_variants
105
-
106
- instructions = [
107
- "With this words, create a photorealistic description for a detailed txt2img prompt in English in 200 characters maximum",
108
- "With this idea, write a creative, realistic, and detailed text-to-image prompt in English in 200 characters maximum",
109
- "With this text, generate a descriptive and True to life txt2img prompt in English in 200 characters maximum",
110
- "With my idea, describe a photorealistic scene with detailed illumination for a txt2img prompt in English in 200 characters maximum",
111
- "With this concept, give a realistic, elegant txt2img prompt in English, emphasizing photorealism in 200 characters maximum",
112
- "With this perspective, conform a visually dynamic and hyperrealistic txt2img prompt in English in 200 characters maximum",
113
- "With this inspiration, realize a cinematic txt2img prompt in English with hyperrealistic elements in 200 characters maximum",
114
- "With my idea, make a lifelike and txt2img prompt in English, focusing on photorealistic depth in 200 characters maximum"
115
- ]
116
-
117
- prompts = set()
118
- while len(prompts) < num_variants:
119
- instruction = random.choice(instructions)
120
- enhanced_prompt = f"{instruction}: {prompt}"
121
- prompts.add(enhanced_prompt)
122
-
123
- return list(prompts)
124
 
125
  def gen(prompts, width, height, model_name, num_variants=1):
126
  images = []
127
- seeds = random.sample(range(MAX_SEED), num_variants)
128
- for idx, (prompt, seed) in enumerate(zip(prompts[:num_variants], seeds)):
129
- clean_prompt = prompt.split(": ", 1)[-1]
130
- image, _ = generate_image(clean_prompt, width, height, seed, model_name)
131
- image_path = save_image(image, f"generated_image_{seed}.jpg")
132
- if image_path:
133
- save_prompt(f"generated_image_{seed}.jpg: {clean_prompt}")
134
- st.success(f"Imagen {idx + 1} generada")
135
- images.append(str(image_path))
 
 
 
 
 
 
 
 
136
  return images
137
 
138
- def save_prompt(prompt):
139
- clean_prompt = prompt.split(": ", 1)[-1]
140
- with open(DATA_PATH / "prompts.txt", "a") as f:
141
- f.write(clean_prompt + "\n")
142
- st.success("Prompt guardado.")
 
 
 
 
 
143
 
144
  def login_form():
145
  st.title("Iniciar Sesión")
146
  username = st.text_input("Usuario", value="admin")
147
- password = st.text_input("Contraseña", value="flux3x", type="password")
148
  if st.button("Iniciar Sesión"):
149
  if authenticate_user(username, password):
150
  st.success("Autenticación exitosa.")
@@ -153,24 +177,42 @@ def login_form():
153
  st.error("Credenciales incorrectas. Intenta de nuevo.")
154
 
155
  def save_image(image, filename):
156
- image_path = DATA_PATH / filename
157
- if isinstance(image, bytes):
158
- with open(image_path, "wb") as f:
159
- f.write(image)
160
- else:
161
- image.save(image_path)
162
- return image_path
 
 
 
 
163
 
164
  def upload_image_to_gallery():
165
  uploaded_image = st.sidebar.file_uploader("Sube una imagen a la galería", type=["jpg", "jpeg", "png"])
166
  if uploaded_image:
167
  image = Image.open(uploaded_image)
168
- unique_filename = f"{random.randint(100000, 999999)}_{uploaded_image.name}"
169
- image_path = save_image(image, unique_filename)
170
  if image_path:
171
- save_prompt(f"{unique_filename}: uploaded by user")
172
  st.sidebar.success(f"Imagen subida: {image_path}")
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  def main():
175
  st.set_page_config(layout="wide")
176
  if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
@@ -185,16 +227,20 @@ def main():
185
  prompt_enhance = st.sidebar.checkbox("Mejorar Prompt", True)
186
  num_variants = st.sidebar.slider("Número de imágenes", 1, 8, 8)
187
  width, height = (720, 1280) if format_option == "9:16" else (1280, 720) if format_option == "16:9" else (1280, 1280)
188
- if prompt or st.sidebar.button("Generar Imágenes", key="force_generate"):
 
189
  prompts = generate_variations(prompt, num_variants=num_variants, use_enhanced=prompt_enhance)
190
- images = gen(prompts, width, height, model_option, num_variants)
 
 
191
  if generated_image_path and upscale_checkbox:
192
  upscale_factor = st.sidebar.slider("Factor de Escalado", 1, 4, 2)
193
  improved_image = get_upscale_finegrain(prompt, generated_image_path, upscale_factor)
194
  if improved_image:
195
  st.image(improved_image, caption="Imagen Escalada", use_column_width=True)
 
196
  upload_image_to_gallery()
197
  display_gallery()
198
 
199
  if __name__ == "__main__":
200
- main()
 
9
  import numpy as np
10
  import yaml
11
 
12
+ try:
13
+ with open("config.yaml", "r") as file:
14
+ credentials = yaml.safe_load(file)
15
+ except Exception as e:
16
+ st.error(f"Error al cargar el archivo de configuración: {e}")
17
+ credentials = {"username": "", "password": ""}
18
 
19
  MAX_SEED = np.iinfo(np.int32).max
20
  client = InferenceClient()
 
23
  PREDEFINED_SEED = random.randint(0, MAX_SEED)
24
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN")
25
 
26
+ if not HF_TOKEN_UPSCALER:
27
+ st.warning("HF_TOKEN no está configurado. Algunas funcionalidades pueden no funcionar.")
28
+
29
  def get_upscale_finegrain(prompt, img_path, upscale_factor):
30
+ try:
31
+ upscale_client = InferenceClient("fal/AuraSR-v2", hf_token=HF_TOKEN_UPSCALER)
32
+ result = upscale_client.predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
33
+ return result[1] if isinstance(result, list) and len(result) > 1 else None
34
+ except Exception as e:
35
+ st.error(f"Error al mejorar la imagen: {e}")
36
+ return None
37
 
38
  def authenticate_user(username, password):
39
  return username == credentials["username"] and password == credentials["password"]
40
 
41
  def list_saved_images():
42
+ try:
43
+ image_files = sorted(DATA_PATH.glob("*.jpg"))
44
+ return image_files
45
+ except Exception as e:
46
+ st.error(f"Error al listar imágenes guardadas: {e}")
47
+ return []
48
 
49
  def prepare_face_app():
50
  app = FaceAnalysis(name='buffalo_l')
 
58
  return sorted(faces, key=lambda x: x.bbox[0])
59
 
60
  def get_face(faces, face_id):
61
+ if not faces or len(faces) < face_id:
62
+ raise ValueError("Rostro no disponible.")
63
  return faces[face_id - 1]
64
 
65
  def swap_faces(source_image, source_face_index, destination_image, destination_face_index):
66
  faces = sort_faces(app.get(source_image))
 
 
 
67
  source_face = get_face(faces, source_face_index)
 
68
  res_faces = sort_faces(app.get(destination_image))
69
+ if destination_face_index > len(res_faces) or destination_face_index < 1:
70
+ raise ValueError("Índice de rostro de destino no válido.")
 
71
  res_face = get_face(res_faces, destination_face_index)
 
72
  result = swapper.get(destination_image, res_face, source_face, paste_back=True)
73
  return result
74
 
75
  def generate_image(prompt, width, height, seed, model_name):
76
  if seed == -1:
77
  seed = random.randint(0, MAX_SEED)
78
+ try:
79
+ image = client.text_to_image(prompt=prompt, height=height, width=width, model=model_name)
80
+ return image, seed
81
+ except Exception as e:
82
+ st.error(f"Error al generar imagen: {e}")
83
+ if hasattr(e, 'response') and e.response is not None:
84
+ st.error(f"Detalles del error: {e.response.text}")
85
+ return None, seed
86
 
87
  def display_gallery():
88
  st.header("Galería de Imágenes Guardadas")
 
101
  if image_file.exists():
102
  os.remove(image_file)
103
  st.success("Imagen borrada")
104
+ display_gallery()
105
  else:
106
  st.warning("La imagen no existe.")
107
  else:
108
  st.info("No hay imágenes guardadas.")
109
 
110
+ def save_prompt(prompt):
111
+ with open(DATA_PATH / "prompts.txt", "a") as f:
112
+ f.write(prompt + "\n")
113
+ st.success("Prompt guardado.")
 
 
 
 
 
114
 
115
  def generate_variations(prompt, num_variants, use_enhanced):
116
+ if use_enhanced:
117
+ instructions = [
118
+ "With this words, create a photorealistic description for a detailed txt2img prompt in English in 200 characters maximum",
119
+ "With this idea, write a creative, realistic, and detailed text-to-image prompt in English in 200 characters maximum",
120
+ "With this text, generate a descriptive and True to life txt2img prompt in English in 200 characters maximum",
121
+ "With my idea, describe a photorealistic scene with detailed illumination for a txt2img prompt in English in 200 characters maximum",
122
+ "With this concept, give a realistic, elegant txt2img prompt in English, emphasizing photorealism in 200 characters maximum",
123
+ "With this perspective, conform a visually dynamic and hyperrealistic txt2img prompt in English in 200 characters maximum",
124
+ "With this inspiration, realize a cinematic txt2img prompt in English with hyperrealistic elements in 200 characters maximum",
125
+ "With my idea, make a lifelike and txt2img prompt in English, focusing on photorealistic depth in 200 characters maximum"
126
+ ]
127
+ prompts = set()
128
+ while len(prompts) < num_variants:
129
+ instruction = random.choice(instructions)
130
+ enhanced_prompt = f"{instruction}: {prompt}"
131
+ prompts.add(enhanced_prompt)
132
+ return list(prompts)
133
+ else:
134
  return [prompt] * num_variants
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  def gen(prompts, width, height, model_name, num_variants=1):
137
  images = []
138
+ seeds = []
139
+
140
+ while len(seeds) < num_variants:
141
+ new_seed = random.randint(0, MAX_SEED)
142
+ if new_seed not in seeds:
143
+ seeds.append(new_seed)
144
+
145
+ try:
146
+ for idx, (prompt, seed) in enumerate(zip(prompts[:num_variants], seeds)):
147
+ image, _ = generate_image(prompt, width, height, seed, model_name)
148
+ image_path = save_image(image, f"generated_image_{seed}.jpg")
149
+ if image_path:
150
+ save_prompt(f"generated_image_{seed}.jpg: {prompt}")
151
+ st.success(f"Imagen {idx + 1} generada")
152
+ images.append(str(image_path))
153
+ except Exception as e:
154
+ st.error(f"Error al generar imágenes: {e}")
155
  return images
156
 
157
+ def get_prompt_for_image(image_name):
158
+ prompts = {}
159
+ try:
160
+ with open(DATA_PATH / "prompts.txt", "r") as f:
161
+ for line in f:
162
+ if line.startswith(image_name):
163
+ prompts[image_name] = line.split(": ", 1)[1].strip()
164
+ except FileNotFoundError:
165
+ return "No hay prompt asociado."
166
+ return prompts.get(image_name, "No hay prompt asociado.")
167
 
168
  def login_form():
169
  st.title("Iniciar Sesión")
170
  username = st.text_input("Usuario", value="admin")
171
+ password = st.text_input("Contraseña", value="flux3", type="password")
172
  if st.button("Iniciar Sesión"):
173
  if authenticate_user(username, password):
174
  st.success("Autenticación exitosa.")
 
177
  st.error("Credenciales incorrectas. Intenta de nuevo.")
178
 
179
  def save_image(image, filename):
180
+ try:
181
+ image_path = DATA_PATH / filename
182
+ if isinstance(image, bytes):
183
+ with open(image_path, "wb") as f:
184
+ f.write(image)
185
+ else:
186
+ image.save(image_path)
187
+ return image_path
188
+ except Exception as e:
189
+ st.error(f"Error al guardar la imagen: {e}")
190
+ return None
191
 
192
  def upload_image_to_gallery():
193
  uploaded_image = st.sidebar.file_uploader("Sube una imagen a la galería", type=["jpg", "jpeg", "png"])
194
  if uploaded_image:
195
  image = Image.open(uploaded_image)
196
+ image_path = save_image(image, f"{uploaded_image.name}")
 
197
  if image_path:
198
+ save_prompt(f"{uploaded_image.name}: uploaded by user")
199
  st.sidebar.success(f"Imagen subida: {image_path}")
200
 
201
+ def gen(prompts, width, height, model_name, num_variants=1):
202
+ images = []
203
+ try:
204
+ for idx, prompt in enumerate(prompts[:num_variants]):
205
+ seed = random.randint(0, MAX_SEED)
206
+ image, seed = generate_image(prompt, width, height, seed, model_name)
207
+ image_path = save_image(image, f"generated_image_{seed}.jpg")
208
+ if image_path:
209
+ save_prompt(f"generated_image_{seed}.jpg: {prompt}")
210
+ st.success(f"Imagen {idx + 1} generada")
211
+ images.append(str(image_path))
212
+ except Exception as e:
213
+ st.error(f"Error al generar imágenes: {e}")
214
+ return images
215
+
216
  def main():
217
  st.set_page_config(layout="wide")
218
  if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
 
227
  prompt_enhance = st.sidebar.checkbox("Mejorar Prompt", True)
228
  num_variants = st.sidebar.slider("Número de imágenes", 1, 8, 8)
229
  width, height = (720, 1280) if format_option == "9:16" else (1280, 720) if format_option == "16:9" else (1280, 1280)
230
+
231
+ if prompt:
232
  prompts = generate_variations(prompt, num_variants=num_variants, use_enhanced=prompt_enhance)
233
+ if st.sidebar.button("Generar Imágenes"):
234
+ images = gen(prompts, width, height, model_option, num_variants)
235
+
236
  if generated_image_path and upscale_checkbox:
237
  upscale_factor = st.sidebar.slider("Factor de Escalado", 1, 4, 2)
238
  improved_image = get_upscale_finegrain(prompt, generated_image_path, upscale_factor)
239
  if improved_image:
240
  st.image(improved_image, caption="Imagen Escalada", use_column_width=True)
241
+
242
  upload_image_to_gallery()
243
  display_gallery()
244
 
245
  if __name__ == "__main__":
246
+ main()