salomonsky commited on
Commit
1d05019
1 Parent(s): fd4cf6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -20
app.py CHANGED
@@ -1,16 +1,21 @@
1
- import os, random, asyncio
 
 
2
  from pathlib import Path
3
  from PIL import Image
4
  from insightface.app import FaceAnalysis
5
  import streamlit as st
6
  from huggingface_hub import InferenceClient, AsyncInferenceClient
7
  import yaml
8
- import insightface
9
 
10
- try:
11
- with open("config.yaml", "r") as file: credentials = yaml.safe_load(file)
12
- except Exception: credentials = {"username": "", "password": ""}
 
 
 
13
 
 
14
  MAX_SEED = 2**31 - 1
15
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
16
  client = AsyncInferenceClient()
@@ -30,31 +35,37 @@ def run_async(func):
30
  return loop.run_until_complete(loop.run_in_executor(None, func))
31
 
32
  async def generate_image(prompt, model, width, height, scales, steps, seed):
33
- if seed == -1: seed = random.randint(0, MAX_SEED)
 
34
  try:
35
  return await client.text_to_image(prompt=prompt, height=height, width=width, guidance_scale=scales, num_inference_steps=steps, model=model), seed
36
- except Exception as e: return f"Error: {e}", None
 
37
 
38
  def upscale_image(image_path, factor):
39
  try:
40
  image = Image.open(image_path)
41
  new_size = (image.width * factor, image.height * factor)
42
  return image.resize(new_size, Image.LANCZOS)
43
- except Exception as e: st.error(f"Error: {e}")
 
44
 
45
  def save_image(image, seed):
46
  try:
47
  path = DATA_PATH / f"image_{seed}.jpg"
48
  image.save(path, format="JPEG")
49
  return path
50
- except Exception as e: st.error(f"Error: {e}")
 
51
 
52
  def save_prompt(prompt, seed):
53
  try:
54
  path = DATA_PATH / f"prompt_{seed}.txt"
55
- with open(path, 'w') as f: f.write(prompt)
 
56
  return path
57
- except Exception as e: st.error(f"Error: {e}")
 
58
 
59
  async def gen(prompt, model, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
60
  combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
@@ -64,7 +75,7 @@ async def gen(prompt, model, width, height, scales, steps, seed, upscale_factor,
64
  progress_bar.progress(50)
65
  if isinstance(image, str) and image.startswith("Error"): return [image, None]
66
  image_path = save_image(image, seed)
67
- prompt_path = save_prompt(combined_prompt, seed)
68
  if process_upscale: image = upscale_image(image_path, upscale_factor)
69
  progress_bar.progress(100)
70
  return [str(image_path) if not process_upscale else str(save_image(image, seed)), str(prompt_path)]
@@ -75,13 +86,17 @@ async def improve_prompt(prompt, language):
75
  response = llm_client.text_generation(formatted_prompt, max_new_tokens=500)
76
  return response.get('generated_text', '').strip()[:500]
77
 
78
- def authenticate_user(username, password, credentials):
79
  return username == credentials["username"] and password == credentials["password"]
80
 
81
  def login_form(credentials):
82
  username, password = st.text_input("Usuario"), st.text_input("Contraseña", type="password")
83
- if st.button("Iniciar Sesión") and authenticate_user(username, password, credentials):
84
- st.session_state['authenticated'] = True
 
 
 
 
85
 
86
  def main():
87
  st.set_page_config(layout="wide")
@@ -89,7 +104,8 @@ def main():
89
  st.title("Iniciar Sesión")
90
  login_form(credentials)
91
  return
92
-
 
93
  st.sidebar.text_input("Descripción de la imagen", max_chars=900, key='prompt')
94
  process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
95
  language = st.sidebar.selectbox("Idioma", ["en", "es"])
@@ -103,11 +119,14 @@ def main():
103
  result = run_async(gen(st.session_state['prompt'], basemodel, 512, 512, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language))
104
  if result[0] and isinstance(result[0], str):
105
  st.image(result[0], caption='Imagen Generada')
106
- st.write(f"Prompt: {result[1]}")
107
- st.button("Borrar Imagen", on_click=lambda: st.session_state.clear())
108
- st.button("Face Swap", on_click=lambda: st.write("Funcionalidad de Face Swap no implementada"))
 
 
 
109
 
110
- if 'authenticated' in st.session_state and st.session_state['authenticated']:
111
  st.session_state.clear()
112
 
113
  if __name__ == "__main__":
 
1
+ import os
2
+ import random
3
+ import asyncio
4
  from pathlib import Path
5
  from PIL import Image
6
  from insightface.app import FaceAnalysis
7
  import streamlit as st
8
  from huggingface_hub import InferenceClient, AsyncInferenceClient
9
  import yaml
 
10
 
11
+ # Cargar credenciales
12
+ try:
13
+ with open("config.yaml", "r") as file:
14
+ credentials = yaml.safe_load(file)
15
+ except Exception:
16
+ credentials = {"username": "", "password": ""}
17
 
18
+ # Configuraciones iniciales
19
  MAX_SEED = 2**31 - 1
20
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
21
  client = AsyncInferenceClient()
 
35
  return loop.run_until_complete(loop.run_in_executor(None, func))
36
 
37
  async def generate_image(prompt, model, width, height, scales, steps, seed):
38
+ if seed == -1:
39
+ seed = random.randint(0, MAX_SEED)
40
  try:
41
  return await client.text_to_image(prompt=prompt, height=height, width=width, guidance_scale=scales, num_inference_steps=steps, model=model), seed
42
+ except Exception as e:
43
+ return f"Error: {e}", None
44
 
45
  def upscale_image(image_path, factor):
46
  try:
47
  image = Image.open(image_path)
48
  new_size = (image.width * factor, image.height * factor)
49
  return image.resize(new_size, Image.LANCZOS)
50
+ except Exception as e:
51
+ st.error(f"Error: {e}")
52
 
53
  def save_image(image, seed):
54
  try:
55
  path = DATA_PATH / f"image_{seed}.jpg"
56
  image.save(path, format="JPEG")
57
  return path
58
+ except Exception as e:
59
+ st.error(f"Error: {e}")
60
 
61
  def save_prompt(prompt, seed):
62
  try:
63
  path = DATA_PATH / f"prompt_{seed}.txt"
64
+ with open(path, 'w') as f:
65
+ f.write(prompt)
66
  return path
67
+ except Exception as e:
68
+ st.error(f"Error: {e}")
69
 
70
  async def gen(prompt, model, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
71
  combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
 
75
  progress_bar.progress(50)
76
  if isinstance(image, str) and image.startswith("Error"): return [image, None]
77
  image_path = save_image(image, seed)
78
+ prompt_path = save_prompt(combined_prompt, seed)
79
  if process_upscale: image = upscale_image(image_path, upscale_factor)
80
  progress_bar.progress(100)
81
  return [str(image_path) if not process_upscale else str(save_image(image, seed)), str(prompt_path)]
 
86
  response = llm_client.text_generation(formatted_prompt, max_new_tokens=500)
87
  return response.get('generated_text', '').strip()[:500]
88
 
89
+ def authenticate_user(username, password, credentials):
90
  return username == credentials["username"] and password == credentials["password"]
91
 
92
  def login_form(credentials):
93
  username, password = st.text_input("Usuario"), st.text_input("Contraseña", type="password")
94
+ if st.button("Iniciar Sesión"):
95
+ if authenticate_user(username, password, credentials):
96
+ st.session_state['authenticated'] = True
97
+ st.session_state['username'] = username
98
+ else:
99
+ st.error("Credenciales incorrectas")
100
 
101
  def main():
102
  st.set_page_config(layout="wide")
 
104
  st.title("Iniciar Sesión")
105
  login_form(credentials)
106
  return
107
+
108
+ # Mantener la sesión activa
109
  st.sidebar.text_input("Descripción de la imagen", max_chars=900, key='prompt')
110
  process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
111
  language = st.sidebar.selectbox("Idioma", ["en", "es"])
 
119
  result = run_async(gen(st.session_state['prompt'], basemodel, 512, 512, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language))
120
  if result[0] and isinstance(result[0], str):
121
  st.image(result[0], caption='Imagen Generada')
122
+ st.write(f"Prompt: {result[1]}")
123
+ if st.button("Borrar Imagen"):
124
+ os.remove(result[0])
125
+ st.success("Imagen borrada.")
126
+ if st.button("Face Swap"):
127
+ st.write("Funcionalidad de Face Swap no implementada")
128
 
129
+ if st.sidebar.button("Cerrar Sesión"):
130
  st.session_state.clear()
131
 
132
  if __name__ == "__main__":