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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
from clip_interrogator import Config, Interrogator
|
6 |
+
import logging
|
7 |
+
import os
|
8 |
+
from datetime import datetime
|
9 |
+
import json
|
10 |
+
|
11 |
+
# Configurar logging
|
12 |
+
logging.basicConfig(level=logging.INFO)
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
# Configuración de modelos
|
16 |
+
CLIP_MODELS = {
|
17 |
+
"general": "ViT-L-14/openai",
|
18 |
+
"flux": "ViT-L-14/openai",
|
19 |
+
"midjourney": "ViT-H-14/laion2b_s32b_b79k",
|
20 |
+
"stable_diffusion": "ViT-L-14/openai"
|
21 |
+
}
|
22 |
+
|
23 |
+
# Modos de interrogación
|
24 |
+
INTERROGATION_MODES = {
|
25 |
+
"fast": "Rápido (menos detallado)",
|
26 |
+
"classic": "Clásico (equilibrado)",
|
27 |
+
"best": "Mejor (más detallado)",
|
28 |
+
"negative": "Negativo (lo que NO es)"
|
29 |
+
}
|
30 |
+
|
31 |
+
class ImagePromptGenerator:
|
32 |
+
def __init__(self):
|
33 |
+
self.interrogators = {}
|
34 |
+
self.usage_count = 0
|
35 |
+
self.setup_models()
|
36 |
+
|
37 |
+
def setup_models(self):
|
38 |
+
"""Inicializar modelos CLIP Interrogator"""
|
39 |
+
try:
|
40 |
+
logger.info("Inicializando modelos CLIP...")
|
41 |
+
|
42 |
+
# Configurar modelo principal primero
|
43 |
+
config = Config(
|
44 |
+
clip_model_name="ViT-L-14/openai",
|
45 |
+
download_cache=True,
|
46 |
+
chunk_size=2048,
|
47 |
+
quiet=False
|
48 |
+
)
|
49 |
+
self.interrogators["general"] = Interrogator(config)
|
50 |
+
logger.info("Modelo general inicializado")
|
51 |
+
|
52 |
+
except Exception as e:
|
53 |
+
logger.error(f"Error inicializando modelos: {e}")
|
54 |
+
# Fallback simple
|
55 |
+
config = Config(clip_model_name="ViT-L-14/openai")
|
56 |
+
self.interrogators["general"] = Interrogator(config)
|
57 |
+
|
58 |
+
def generate_prompt(self, image, model_type="general", mode="best"):
|
59 |
+
"""Generar prompt desde imagen"""
|
60 |
+
try:
|
61 |
+
if image is None:
|
62 |
+
return "❌ Por favor, sube una imagen primero.", ""
|
63 |
+
|
64 |
+
# Incrementar contador de uso
|
65 |
+
self.usage_count += 1
|
66 |
+
|
67 |
+
# Convertir imagen
|
68 |
+
if isinstance(image, np.ndarray):
|
69 |
+
image = Image.fromarray(image)
|
70 |
+
elif not isinstance(image, Image.Image):
|
71 |
+
image = Image.open(image)
|
72 |
+
|
73 |
+
# Asegurar RGB
|
74 |
+
if image.mode != 'RGB':
|
75 |
+
image = image.convert('RGB')
|
76 |
+
|
77 |
+
# Usar interrogator general por ahora
|
78 |
+
interrogator = self.interrogators["general"]
|
79 |
+
|
80 |
+
# Generar prompt según el modo
|
81 |
+
if mode == "fast":
|
82 |
+
prompt = interrogator.interrogate_fast(image)
|
83 |
+
elif mode == "classic":
|
84 |
+
prompt = interrogator.interrogate_classic(image)
|
85 |
+
else: # best y negative
|
86 |
+
prompt = interrogator.interrogate(image)
|
87 |
+
|
88 |
+
# Información adicional
|
89 |
+
info = f"""
|
90 |
+
**✅ Prompt generado exitosamente con IA para todos**
|
91 |
+
- **Modelo:** {model_type.title()}
|
92 |
+
- **Modo:** {INTERROGATION_MODES.get(mode, mode)}
|
93 |
+
- **Usos totales:** {self.usage_count}
|
94 |
+
- **Hora:** {datetime.now().strftime('%H:%M:%S')}
|
95 |
+
|
96 |
+
*"Porque cuando no tienes nada en la cabeza, te preocupas de la tipografía?"* 😄
|
97 |
+
"""
|
98 |
+
|
99 |
+
return prompt, info
|
100 |
+
|
101 |
+
except Exception as e:
|
102 |
+
logger.error(f"Error generando prompt: {e}")
|
103 |
+
error_msg = f"❌ Error: {str(e)}"
|
104 |
+
error_info = "*Cuando falla la IA, al menos la tipografía sigue siendo bonita* 📝"
|
105 |
+
return error_msg, error_info
|
106 |
+
|
107 |
+
# Inicializar generador
|
108 |
+
generator = ImagePromptGenerator()
|
109 |
+
|
110 |
+
def process_image(image, model_type, mode):
|
111 |
+
"""Función principal para procesar imagen"""
|
112 |
+
prompt, info = generator.generate_prompt(image, model_type, mode)
|
113 |
+
return prompt, info
|
114 |
+
|
115 |
+
# Crear interfaz Gradio
|
116 |
+
def create_interface():
|
117 |
+
# CSS personalizado para mejor tipografía
|
118 |
+
custom_css = """
|
119 |
+
.gradio-container {
|
120 |
+
max-width: 1200px !important;
|
121 |
+
font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
122 |
+
}
|
123 |
+
.prompt-output {
|
124 |
+
font-family: 'JetBrains Mono', 'Courier New', monospace !important;
|
125 |
+
font-size: 14px !important;
|
126 |
+
line-height: 1.6 !important;
|
127 |
+
background: #f8f9fa !important;
|
128 |
+
border-radius: 8px !important;
|
129 |
+
padding: 16px !important;
|
130 |
+
}
|
131 |
+
.main-title {
|
132 |
+
text-align: center;
|
133 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
134 |
+
-webkit-background-clip: text;
|
135 |
+
-webkit-text-fill-color: transparent;
|
136 |
+
font-size: 2.5em !important;
|
137 |
+
font-weight: bold !important;
|
138 |
+
margin-bottom: 0.5em !important;
|
139 |
+
}
|
140 |
+
.subtitle {
|
141 |
+
text-align: center;
|
142 |
+
font-style: italic;
|
143 |
+
color: #666;
|
144 |
+
font-size: 1.1em;
|
145 |
+
margin-bottom: 2em;
|
146 |
+
}
|
147 |
+
"""
|
148 |
+
|
149 |
+
with gr.Blocks(
|
150 |
+
theme=gr.themes.Soft(),
|
151 |
+
title="IA para todos - Image to Prompt",
|
152 |
+
css=custom_css
|
153 |
+
) as interface:
|
154 |
+
|
155 |
+
# Header personalizado
|
156 |
+
gr.HTML("""
|
157 |
+
<div class="main-title">
|
158 |
+
🤖 IA para todos
|
159 |
+
</div>
|
160 |
+
""")
|
161 |
+
|
162 |
+
gr.HTML("""
|
163 |
+
<div class="subtitle">
|
164 |
+
"Porque cuando no tienes nada en la cabeza, te preocupas de la tipografía?"
|
165 |
+
</div>
|
166 |
+
""")
|
167 |
+
|
168 |
+
gr.Markdown("""
|
169 |
+
### 🎨 Convierte cualquier imagen en prompts detallados para IA
|
170 |
+
Sube una imagen y obtén prompts optimizados para Stable Diffusion, Midjourney, Flux y más.
|
171 |
+
""")
|
172 |
+
|
173 |
+
with gr.Row():
|
174 |
+
with gr.Column(scale=1):
|
175 |
+
# Input section
|
176 |
+
gr.Markdown("## 📤 Subir Imagen")
|
177 |
+
image_input = gr.Image(
|
178 |
+
label="Arrastra o selecciona una imagen",
|
179 |
+
type="pil",
|
180 |
+
height=300
|
181 |
+
)
|
182 |
+
|
183 |
+
# Configuración
|
184 |
+
gr.Markdown("## ⚙️ Configuración")
|
185 |
+
model_selector = gr.Dropdown(
|
186 |
+
choices=["general", "stable_diffusion", "midjourney", "flux"],
|
187 |
+
value="general",
|
188 |
+
label="Modelo de IA objetivo",
|
189 |
+
info="Selecciona la plataforma donde usarás el prompt"
|
190 |
+
)
|
191 |
+
|
192 |
+
mode_selector = gr.Dropdown(
|
193 |
+
choices=["fast", "classic", "best"],
|
194 |
+
value="best",
|
195 |
+
label="Modo de análisis",
|
196 |
+
info="Equilibrio entre velocidad y precisión"
|
197 |
+
)
|
198 |
+
|
199 |
+
# Botón generar
|
200 |
+
generate_btn = gr.Button(
|
201 |
+
"🚀 Generar Prompt Mágico",
|
202 |
+
variant="primary",
|
203 |
+
size="lg"
|
204 |
+
)
|
205 |
+
|
206 |
+
with gr.Column(scale=1):
|
207 |
+
# Output section
|
208 |
+
gr.Markdown("## 📝 Tu Prompt Está Listo")
|
209 |
+
prompt_output = gr.Textbox(
|
210 |
+
label="Prompt generado (listo para copiar)",
|
211 |
+
placeholder="Tu prompt aparecerá aquí... ✨",
|
212 |
+
lines=8,
|
213 |
+
max_lines=15,
|
214 |
+
elem_classes=["prompt-output"],
|
215 |
+
show_copy_button=True
|
216 |
+
)
|
217 |
+
|
218 |
+
info_output = gr.Markdown(
|
219 |
+
label="Información del proceso",
|
220 |
+
value=""
|
221 |
+
)
|
222 |
+
|
223 |
+
# Botones de acción
|
224 |
+
with gr.Row():
|
225 |
+
clear_btn = gr.Button("🗑️ Limpiar", size="sm")
|
226 |
+
|
227 |
+
# Footer con tu frase
|
228 |
+
gr.Markdown("""
|
229 |
+
---
|
230 |
+
### 💡 Consejos de Uso:
|
231 |
+
- **General:** Para prompts universales que funcionan en cualquier lado
|
232 |
+
- **Stable Diffusion:** Optimizado para SD 1.x, SDXL y derivados
|
233 |
+
- **Midjourney:** Perfecto para estilos artísticos y creativos
|
234 |
+
- **Flux:** Para el revolucionario modelo Flux de Black Forest Labs
|
235 |
+
|
236 |
+
### 🔧 Modos de Análisis:
|
237 |
+
- **Rápido:** Análisis express, menos detallado pero veloz ⚡
|
238 |
+
- **Clásico:** El equilibrio perfecto entre velocidad y calidad ⚖️
|
239 |
+
- **Mejor:** Máxima precisión y detalle (recomendado) ⭐
|
240 |
+
|
241 |
+
---
|
242 |
+
|
243 |
+
### 🎭 Hecho con amor (y buena tipografía) por IA para todos
|
244 |
+
*"La IA nos ayuda con las ideas, nosotros nos preocupamos de que se vean bonitas"* ✨
|
245 |
+
""")
|
246 |
+
|
247 |
+
# Event handlers
|
248 |
+
generate_btn.click(
|
249 |
+
fn=process_image,
|
250 |
+
inputs=[image_input, model_selector, mode_selector],
|
251 |
+
outputs=[prompt_output, info_output]
|
252 |
+
)
|
253 |
+
|
254 |
+
clear_btn.click(
|
255 |
+
fn=lambda: ("", ""),
|
256 |
+
outputs=[prompt_output, info_output]
|
257 |
+
)
|
258 |
+
|
259 |
+
return interface
|
260 |
+
|
261 |
+
# Lanzar aplicación
|
262 |
+
if __name__ == "__main__":
|
263 |
+
interface = create_interface()
|
264 |
+
interface.launch(
|
265 |
+
server_name="0.0.0.0",
|
266 |
+
server_port=7860,
|
267 |
+
show_error=True
|
268 |
+
)
|