salomonsky commited on
Commit
ea513a8
1 Parent(s): e141429

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -96
app.py CHANGED
@@ -1,131 +1,125 @@
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
- import insightface
11
 
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
- MAX_SEED = 2**31 - 1
19
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
20
- client = AsyncInferenceClient()
21
- llm_client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
22
- DATA_PATH = Path("./data").mkdir(exist_ok=True)
23
 
24
  def prepare_face_app():
25
  app = FaceAnalysis(name='buffalo_l')
26
  app.prepare(ctx_id=0, det_size=(640, 640))
27
- return app, insightface.model_zoo.get_model('onix.onnx')
 
28
 
29
  app, swapper = prepare_face_app()
30
 
31
- def run_async(func):
32
- loop = asyncio.new_event_loop()
33
- asyncio.set_event_loop(loop)
34
- return loop.run_until_complete(loop.run_in_executor(None, func))
35
-
36
- async def generate_image(prompt, model, width, height, scales, steps, seed):
37
  if seed == -1:
38
  seed = random.randint(0, MAX_SEED)
39
- try:
40
- return await client.text_to_image(prompt=prompt, height=height, width=width, guidance_scale=scales, num_inference_steps=steps, model=model), seed
41
- except Exception as e:
42
- return f"Error: {e}", None
43
-
44
- def upscale_image(image_path, factor):
45
- try:
46
- image = Image.open(image_path)
47
- new_size = (image.width * factor, image.height * factor)
48
- return image.resize(new_size, Image.LANCZOS)
49
- except Exception as e:
50
- st.error(f"Error: {e}")
51
-
52
- def save_image(image, seed):
53
- try:
54
- path = DATA_PATH / f"image_{seed}.jpg"
55
- image.save(path, format="JPEG")
56
- return path
57
- except Exception as e:
58
- st.error(f"Error: {e}")
59
-
60
- def save_prompt(prompt, seed):
61
- try:
62
- path = DATA_PATH / f"prompt_{seed}.txt"
63
- with open(path, 'w') as f:
64
- f.write(prompt)
65
- return path
66
- except Exception as e:
67
- st.error(f"Error: {e}")
68
-
69
- async def gen(prompt, model, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
70
- combined_prompt = f"{prompt} {await improve_prompt(prompt, language)}" if process_enhancer else prompt
71
- if seed == -1: seed = random.randint(0, MAX_SEED)
72
- progress_bar = st.progress(0)
73
- image, seed = await generate_image(combined_prompt, model, width, height, scales, steps, seed)
74
- progress_bar.progress(50)
75
- if isinstance(image, str) and image.startswith("Error"): return [image, None]
76
  image_path = save_image(image, seed)
77
- prompt_path = save_prompt(combined_prompt, seed)
78
- if process_upscale: image = upscale_image(image_path, upscale_factor)
79
- progress_bar.progress(100)
80
- return [str(image_path) if not process_upscale else str(save_image(image, seed)), str(prompt_path)]
 
 
 
 
 
 
 
 
 
81
 
82
  async def improve_prompt(prompt, language):
83
- instruction = "With this idea, describe in English a detailed txt2img prompt..." if language == "en" else "Con esta idea, describe en español un prompt detallado..."
84
  formatted_prompt = f"{prompt}: {instruction}"
85
- response = llm_client.text_generation(formatted_prompt, max_new_tokens=500)
86
- return response.get('generated_text', '').strip()[:500]
87
-
88
- def authenticate_user(username, password, credentials):
89
- return username == credentials["username"] and password == credentials["password"]
90
-
91
- def login_form(credentials):
92
- username, password = st.text_input("Usuario"), st.text_input("Contraseña", type="password")
93
- if st.button("Iniciar Sesión"):
94
- if authenticate_user(username, password, credentials):
95
- st.session_state['authenticated'] = True
96
- st.session_state['username'] = username
97
- else:
98
- st.error("Credenciales incorrectas")
 
 
 
99
 
100
  def main():
101
  st.set_page_config(layout="wide")
 
102
  if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
103
- st.title("Iniciar Sesión")
104
- login_form(credentials)
105
  return
106
-
107
- st.sidebar.text_input("Descripción de la imagen", max_chars=900, key='prompt')
108
  process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
109
  language = st.sidebar.selectbox("Idioma", ["en", "es"])
110
  basemodel = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"])
111
  format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
112
  process_upscale = st.sidebar.checkbox("Procesar Escalador", value=False)
113
  upscale_factor = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0)
114
- scales, steps, seed = 7.5, 50, -1
115
-
 
 
 
116
  if st.sidebar.button("Generar Imagen"):
117
- result = run_async(gen(st.session_state['prompt'], basemodel, 512, 512, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language))
118
- if result[0] and isinstance(result[0], str):
119
- st.image(result[0], caption='Imagen Generada')
120
- st.write(f"Prompt: {result[1]}")
121
- if st.button("Borrar Imagen"):
122
- os.remove(result[0])
123
- st.success("Imagen borrada.")
124
- if st.button("Face Swap"):
125
- st.write("Funcionalidad de Face Swap no implementada")
126
-
127
- if st.sidebar.button("Cerrar Sesión"):
128
- st.session_state.clear()
 
 
129
 
130
  if __name__ == "__main__":
131
  main()
 
1
+ import os, numpy as np, random, asyncio, insightface
 
 
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
7
+ from gradio_client import Client, handle_file
8
+ from concurrent.futures import ThreadPoolExecutor
9
  import yaml
 
10
 
11
+ MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
 
 
12
  HF_TOKEN_UPSCALER = os.environ.get("HF_TOKEN_UPSCALER")
13
+ client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
14
+ DATA_PATH = Path("./data")
15
+ DATA_PATH.mkdir(exist_ok=True)
16
 
17
  def prepare_face_app():
18
  app = FaceAnalysis(name='buffalo_l')
19
  app.prepare(ctx_id=0, det_size=(640, 640))
20
+ swapper = insightface.model_zoo.get_model('onix.onnx')
21
+ return app, swapper
22
 
23
  app, swapper = prepare_face_app()
24
 
25
+ async def generate_image(combined_prompt, model, width, height, scales, steps, seed):
 
 
 
 
 
26
  if seed == -1:
27
  seed = random.randint(0, MAX_SEED)
28
+ seed = int(seed)
29
+ image = await client.text_to_image(prompt=combined_prompt, height=height, width=width, guidance_scale=scales, num_inference_steps=steps, model=model)
30
+ return image, seed
31
+
32
+ def get_upscale_finegrain(prompt, img_path, upscale_factor):
33
+ client = Client("finegrain/finegrain-image-enhancer", hf_token=HF_TOKEN_UPSCALER)
34
+ result = client.predict(input_image=handle_file(img_path), prompt=prompt, upscale_factor=upscale_factor)
35
+ return result[1] if isinstance(result, list) and len(result) > 1 else None
36
+
37
+ def save_prompt(prompt_text, seed):
38
+ prompt_file_path = DATA_PATH / f"prompt_{seed}.txt"
39
+ with open(prompt_file_path, "w") as prompt_file:
40
+ prompt_file.write(prompt_text)
41
+ return prompt_file_path
42
+
43
+ async def gen(prompt, basemodel, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language):
44
+ combined_prompt = prompt
45
+ if process_enhancer:
46
+ improved_prompt = await improve_prompt(prompt, language)
47
+ combined_prompt = f"{prompt} {improved_prompt}"
48
+
49
+ if seed == -1:
50
+ seed = random.randint(0, MAX_SEED)
51
+ seed = int(seed)
52
+ image, seed = await generate_image(combined_prompt, basemodel, width, height, scales, steps, seed)
 
 
 
 
 
 
 
 
 
 
 
 
53
  image_path = save_image(image, seed)
54
+ prompt_file_path = save_prompt(combined_prompt, seed)
55
+
56
+ if process_upscale:
57
+ upscale_image_path = get_upscale_finegrain(combined_prompt, image_path, upscale_factor)
58
+ if upscale_image_path:
59
+ upscale_image = Image.open(upscale_image_path)
60
+ upscale_image.save(DATA_PATH / f"upscale_image_{seed}.jpg", format="JPEG")
61
+ image_path.unlink()
62
+ return [str(DATA_PATH / f"upscale_image_{seed}.jpg"), str(prompt_file_path)]
63
+ else:
64
+ return [str(image_path), str(prompt_file_path)]
65
+ else:
66
+ return [str(image_path), str(prompt_file_path)]
67
 
68
  async def improve_prompt(prompt, language):
69
+ instruction = "With this idea, describe in English a detailed txt2img prompt in 500 characters..." if language == "en" else "Con esta idea, describe en español un prompt detallado de txt2img en 500 caracteres..."
70
  formatted_prompt = f"{prompt}: {instruction}"
71
+ response = client.text_generation(formatted_prompt, max_new_tokens=500)
72
+ improved_text = response['generated_text'].strip() if 'generated_text' in response else response.strip()
73
+ return improved_text[:500] if len(improved_text) > 500 else improved_text
74
+
75
+ def save_image(image, seed):
76
+ image_path = DATA_PATH / f"image_{seed}.jpg"
77
+ image.save(image_path, format="JPEG")
78
+ return image_path
79
+
80
+ def get_storage():
81
+ files = [file for file in DATA_PATH.glob("*.jpg") if file.is_file()]
82
+ files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
83
+ return [str(file.resolve()) for file in files]
84
+
85
+ def delete_image(image_path):
86
+ if Path(image_path).exists():
87
+ Path(image_path).unlink()
88
 
89
  def main():
90
  st.set_page_config(layout="wide")
91
+
92
  if 'authenticated' not in st.session_state or not st.session_state['authenticated']:
93
+ st.warning("Por favor, inicia sesión para acceder a la aplicación.")
 
94
  return
95
+
96
+ prompt = st.sidebar.text_input("Descripción de la imagen", max_chars=900)
97
  process_enhancer = st.sidebar.checkbox("Mejorar Prompt", value=False)
98
  language = st.sidebar.selectbox("Idioma", ["en", "es"])
99
  basemodel = st.sidebar.selectbox("Modelo Base", ["black-forest-labs/FLUX.1-DEV", "black-forest-labs/FLUX.1-schnell"])
100
  format_option = st.sidebar.selectbox("Formato", ["9:16", "16:9"])
101
  process_upscale = st.sidebar.checkbox("Procesar Escalador", value=False)
102
  upscale_factor = st.sidebar.selectbox("Factor de Escala", [2, 4, 8], index=0)
103
+ scales = st.sidebar.slider("Escalado", 1, 20, 10)
104
+ steps = st.sidebar.slider("Pasos", 1, 100, 20)
105
+ seed = st.sidebar.number_input("Semilla", value=-1)
106
+ width, height = (1080, 1920) if format_option == "9:16" else (1920, 1080)
107
+
108
  if st.sidebar.button("Generar Imagen"):
109
+ with st.spinner("Generando..."):
110
+ image_path, prompt_file_path = asyncio.run(gen(prompt, basemodel, width, height, scales, steps, seed, upscale_factor, process_upscale, process_enhancer, language))
111
+ if image_path:
112
+ st.image(image_path, caption="Imagen Generada", use_column_width=True)
113
+ st.download_button("Descargar Imagen", image_path)
114
+
115
+ files = get_storage()
116
+ for file in files:
117
+ st.image(file)
118
+ st.text(f"Prompt: {file.stem}")
119
+ if st.button(f"Swap Face {file.stem}"):
120
+ pass
121
+ if st.button(f"Borrar {file.stem}"):
122
+ delete_image(file)
123
 
124
  if __name__ == "__main__":
125
  main()