ivanoctaviogaitansantos commited on
Commit
3cf28fb
·
verified ·
1 Parent(s): 88530b6

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +430 -0
main.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py - PARTE 1/3
2
+ import gradio as gr
3
+ import torch
4
+ import asyncio
5
+ import aiohttp
6
+ import random
7
+ from typing import List, Dict, Any
8
+ from datetime import datetime
9
+
10
+ # ============================================================================
11
+ # 1. SISTEMA DE APRENDIZAJE
12
+ # ============================================================================
13
+ class LearningSystem:
14
+ def __init__(self):
15
+ self.user_profile = {
16
+ 'preferred_technologies': {},
17
+ 'skill_level': 'intermediate',
18
+ 'preferred_image_styles': {},
19
+ 'interaction_count': 0
20
+ }
21
+
22
+ def analyze_interaction(self, user_input: str):
23
+ self.user_profile['interaction_count'] += 1
24
+ self.learn_skill_level(user_input)
25
+ self.learn_technology_preferences(user_input)
26
+ self.learn_image_preferences(user_input)
27
+
28
+ def learn_skill_level(self, user_input: str):
29
+ beginner_terms = ['cómo empezar', 'tutorial básico', 'principiante']
30
+ advanced_terms = ['optimización', 'arquitectura', 'avanzado']
31
+
32
+ if any(term in user_input.lower() for term in beginner_terms):
33
+ self.user_profile['skill_level'] = 'beginner'
34
+ elif any(term in user_input.lower() for term in advanced_terms):
35
+ self.user_profile['skill_level'] = 'advanced'
36
+
37
+ def learn_technology_preferences(self, user_input: str):
38
+ tech_mappings = {
39
+ 'react': 'frontend', 'vue': 'frontend',
40
+ 'node': 'backend', 'python': 'backend',
41
+ 'mongodb': 'database', 'docker': 'devops'
42
+ }
43
+
44
+ for tech, category in tech_mappings.items():
45
+ if tech in user_input.lower():
46
+ if category not in self.user_profile['preferred_technologies']:
47
+ self.user_profile['preferred_technologies'][category] = {}
48
+ self.user_profile['preferred_technologies'][category][tech] = \
49
+ self.user_profile['preferred_technologies'][category].get(tech, 0) + 1
50
+
51
+ def learn_image_preferences(self, user_input: str):
52
+ image_styles = {
53
+ 'hyperrealistic': ['hiperrealista', 'foto real'],
54
+ 'anime': ['anime', 'manga'],
55
+ 'cinematic': ['cinematográfico', 'película']
56
+ }
57
+
58
+ for style, keywords in image_styles.items():
59
+ if any(keyword in user_input.lower() for keyword in keywords):
60
+ self.user_profile['preferred_image_styles'][style] = \
61
+ self.user_profile['preferred_image_styles'].get(style, 0) + 1
62
+
63
+ def get_personalized_suggestions(self) -> str:
64
+ suggestions = []
65
+
66
+ if self.user_profile['preferred_technologies']:
67
+ frontend_techs = self.user_profile['preferred_technologies'].get('frontend', {})
68
+ if frontend_techs:
69
+ top_tech = max(frontend_techs.items(), key=lambda x: x[1])[0]
70
+ suggestions.append(f"💡 Veo que usas {top_tech}. ¿Te interesa Next.js o React Native?")
71
+
72
+ if self.user_profile['skill_level'] == 'beginner':
73
+ suggestions.append("🎯 Te recomiendo empezar con proyectos simples como un todo-list")
74
+ elif self.user_profile['skill_level'] == 'advanced':
75
+ suggestions.append("🚀 Podrías explorar microservicios o GraphQL")
76
+
77
+ return "\n".join(suggestions) if suggestions else ""
78
+
79
+ def get_recommended_image_style(self) -> str:
80
+ if self.user_profile['preferred_image_styles']:
81
+ return max(self.user_profile['preferred_image_styles'].items(), key=lambda x: x[1])[0]
82
+ return "hyperrealistic"
83
+
84
+ # ============================================================================
85
+ # 2. CLIENTE TAVILY
86
+ # ============================================================================
87
+ class TavilyExpertClient:
88
+ def __init__(self, api_key: str):
89
+ self.api_key = api_key
90
+ self.base_url = "https://api.tavily.com"
91
+
92
+ async def search_technical(self, query: str) -> Dict[str, Any]:
93
+ payload = {
94
+ "api_key": self.api_key,
95
+ "query": f"{query} programming code examples 2024",
96
+ "search_depth": "advanced",
97
+ "max_results": 6,
98
+ "include_answer": True
99
+ }
100
+
101
+ try:
102
+ async with aiohttp.ClientSession() as session:
103
+ async with session.post(f"{self.base_url}/search", json=payload) as response:
104
+ if response.status == 200:
105
+ return await response.json()
106
+ else:
107
+ return {"error": f"HTTP {response.status}"}
108
+ except Exception as e:
109
+ return {"error": str(e)}
110
+
111
+ # ============================================================================
112
+ # 3. GENERADOR DE PROMPTS DE IMAGEN
113
+ # ============================================================================
114
+ class HyperRealisticPromptGenerator:
115
+ def __init__(self):
116
+ self.FEMALE_ROLES = [
117
+ {"role": "executive secretary", "uniform": "form-fitting black dress", "environment": "luxurious office"},
118
+ {"role": "salsa dancer", "uniform": "flowing red dress", "environment": "Latin dance hall"},
119
+ {"role": "fashion manager", "uniform": "chic designer dress", "environment": "boutique"},
120
+ {"role": "hotel manager", "uniform": "elegant blazer", "environment": "hotel lobby"}
121
+ ]
122
+
123
+ self.ART_STYLES = {
124
+ "Hyperrealistic": "hyperrealistic, photorealistic, 8K UHD",
125
+ "Cinematic": "cinematic lighting, dramatic",
126
+ "Anime": "anime style, manga"
127
+ }
128
+
129
+ def generate_prompt(self, role: str, style: str = "Hyperrealistic") -> str:
130
+ role_data = next((r for r in self.FEMALE_ROLES if r['role'] == role), self.FEMALE_ROLES[0])
131
+
132
+ prompt = f"{self.ART_STYLES[style]} photo of elegant Latina {role_data['role']}, "
133
+ prompt += f"wearing {role_data['uniform']} in {role_data['environment']}. "
134
+ prompt += "Professional photography, detailed, 9:16 aspect ratio."
135
+
136
+ return prompt
137
+
138
+ def get_available_roles(self):
139
+ return [role['role'] for role in self.FEMALE_ROLES]# main.py - PARTE 2/3
140
+
141
+ # ============================================================================
142
+ # 4. GENERADOR DE IMÁGENES
143
+ # ============================================================================
144
+ class ImageGenerator:
145
+ def __init__(self):
146
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
147
+ self.pipe = None
148
+
149
+ def load_model(self):
150
+ if self.pipe is not None:
151
+ return True
152
+
153
+ try:
154
+ from diffusers import StableDiffusionPipeline
155
+ print("🔄 Cargando modelo de imágenes...")
156
+ self.pipe = StableDiffusionPipeline.from_pretrained(
157
+ "stabilityai/stable-diffusion-2-1-base",
158
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
159
+ safety_checker=None
160
+ )
161
+ self.pipe = self.pipe.to(self.device)
162
+ print("✅ Modelo de imágenes cargado")
163
+ return True
164
+ except Exception as e:
165
+ print(f"❌ Error cargando modelo: {e}")
166
+ return False
167
+
168
+ def generate_image(self, prompt: str):
169
+ if not self.load_model():
170
+ return None, "Modelo no disponible"
171
+
172
+ try:
173
+ result = self.pipe(prompt, num_inference_steps=20, height=512, width=384)
174
+ return result.images[0], "✅ Imagen generada"
175
+ except Exception as e:
176
+ return None, f"❌ Error: {e}"
177
+
178
+ # ============================================================================
179
+ # 5. PROCESADOR DE CHAT PRINCIPAL
180
+ # ============================================================================
181
+ class ChatProcessor:
182
+ def __init__(self, tavily_api_key: str):
183
+ self.tavily_client = TavilyExpertClient(tavily_api_key)
184
+ self.prompt_generator = HyperRealisticPromptGenerator()
185
+ self.image_generator = ImageGenerator()
186
+ self.learning_system = LearningSystem()
187
+
188
+ async def process_message(self, user_input: str) -> dict:
189
+ # Análisis de aprendizaje
190
+ self.learning_system.analyze_interaction(user_input)
191
+
192
+ # Determinar tipo de solicitud
193
+ request_type = self.analyze_request_type(user_input)
194
+
195
+ response_data = {
196
+ "text": "",
197
+ "image": None,
198
+ "type": "conversation"
199
+ }
200
+
201
+ try:
202
+ if request_type == "image_generation":
203
+ image_result = await self.handle_image_request(user_input)
204
+ response_data.update(image_result)
205
+
206
+ elif request_type == "technical_help":
207
+ search_result = await self.handle_technical_request(user_input)
208
+ response_data.update(search_result)
209
+
210
+ else:
211
+ conversation_result = await self.handle_conversation(user_input)
212
+ response_data.update(conversation_result)
213
+
214
+ # Añadir sugerencias personalizadas
215
+ suggestions = self.learning_system.get_personalized_suggestions()
216
+ if suggestions:
217
+ response_data["text"] += f"\n\n🎓 **Sugerencias:**\n{suggestions}"
218
+
219
+ except Exception as e:
220
+ response_data["text"] = f"❌ Error: {str(e)}"
221
+ response_data["type"] = "error"
222
+
223
+ return response_data
224
+
225
+ def analyze_request_type(self, user_input: str) -> str:
226
+ user_input_lower = user_input.lower()
227
+
228
+ if any(keyword in user_input_lower for keyword in ['imagen', 'generar', 'crear']):
229
+ return "image_generation"
230
+ elif any(keyword in user_input_lower for keyword in ['código', 'programar', 'error', 'cómo']):
231
+ return "technical_help"
232
+ else:
233
+ return "conversation"
234
+
235
+ async def handle_image_request(self, user_input: str) -> dict:
236
+ preferred_style = self.learning_system.get_recommended_image_style()
237
+ available_roles = self.prompt_generator.get_available_roles()
238
+
239
+ # Buscar rol mencionado
240
+ selected_role = available_roles[0]
241
+ for role in available_roles:
242
+ if role in user_input.lower():
243
+ selected_role = role
244
+ break
245
+
246
+ prompt = self.prompt_generator.generate_prompt(selected_role, preferred_style)
247
+ image, message = self.image_generator.generate_image(prompt)
248
+
249
+ return {
250
+ "text": f"🎨 **Imagen generada:**\n\n**Prompt:** {prompt}\n\n{message}",
251
+ "image": image,
252
+ "type": "image_generation"
253
+ }
254
+
255
+ async def handle_technical_request(self, user_input: str) -> dict:
256
+ search_results = await self.tavily_client.search_technical(user_input)
257
+
258
+ if "error" in search_results:
259
+ return {
260
+ "text": f"❌ No encontré información sobre: {user_input}",
261
+ "type": "error"
262
+ }
263
+
264
+ formatted_results = self.format_search_results(search_results, user_input)
265
+ return {
266
+ "text": formatted_results,
267
+ "type": "technical_help"
268
+ }
269
+
270
+ async def handle_conversation(self, user_input: str) -> dict:
271
+ return {
272
+ "text": f"🤖 **DevCreator AI:**\n\nHe procesado: '{user_input}'\n\n¿Te gustaría que:\n- 🔍 Busque información\n- 🎨 Genere una imagen\n- 💻 Ayude con código",
273
+ "type": "conversation"
274
+ }
275
+
276
+ def format_search_results(self, search_data: dict, original_query: str) -> str:
277
+ if "results" not in search_data or not search_data["results"]:
278
+ return f"🔍 **Búsqueda para '{original_query}':**\n\nNo encontré resultados."
279
+
280
+ results = search_data["results"]
281
+ answer = search_data.get("answer", "")
282
+
283
+ response = f"🔍 **Resultados para '{original_query}':**\n\n"
284
+
285
+ if answer:
286
+ response += f"**Respuesta:** {answer}\n\n"
287
+
288
+ response += "**Fuentes:**\n"
289
+ for i, result in enumerate(results[:4], 1):
290
+ title = result.get('title', 'Sin título')
291
+ content = result.get('content', '')[:120] + "..."
292
+
293
+ response += f"\n{i}. **{title}**\n"
294
+ response += f" {content}\n"
295
+
296
+ return response# main.py - PARTE 3/3
297
+
298
+ # ============================================================================
299
+ # 6. INTERFAZ GRADIO
300
+ # ============================================================================
301
+ class DevCreatorAI:
302
+ def __init__(self, tavily_api_key: str):
303
+ self.chat_processor = ChatProcessor(tavily_api_key)
304
+
305
+ def create_interface(self):
306
+ with gr.Blocks(theme=gr.themes.Soft(), title="DevCreator AI") as demo:
307
+ gr.Markdown("""
308
+ # 🚀 DevCreator AI
309
+ **Tu Asistente de Desarrollo Inteligente**
310
+ """)
311
+
312
+ with gr.Row():
313
+ with gr.Column(scale=2):
314
+ chatbot = gr.Chatbot(
315
+ label="💬 Conversación",
316
+ height=500,
317
+ show_copy_button=True
318
+ )
319
+
320
+ with gr.Row():
321
+ msg = gr.Textbox(
322
+ placeholder="💭 Escribe tu mensaje aquí...",
323
+ lines=3,
324
+ scale=4
325
+ )
326
+ send_btn = gr.Button("🚀 Enviar", variant="primary", scale=1)
327
+
328
+ with gr.Row():
329
+ clear_btn = gr.Button("🗑️ Limpiar")
330
+ image_btn = gr.Button("🎨 Imagen")
331
+ search_btn = gr.Button("🔍 Buscar")
332
+
333
+ with gr.Column(scale=1):
334
+ image_output = gr.Image(
335
+ label="🖼️ Imagen Generada",
336
+ height=400
337
+ )
338
+
339
+ status_output = gr.Textbox(
340
+ label="📊 Estado",
341
+ value="✅ Sistema listo"
342
+ )
343
+
344
+ chat_history = gr.State([])
345
+
346
+ # Ejemplos
347
+ gr.Examples(
348
+ examples=[
349
+ ["Genera imagen de executive secretary"],
350
+ ["Cómo hacer una API REST con Node.js"],
351
+ ["Buscar machine learning Python"],
352
+ ["Genera imagen de salsa dancer"]
353
+ ],
354
+ inputs=msg
355
+ )
356
+
357
+ # Event handlers
358
+ def handle_message(user_input, history):
359
+ history = history or []
360
+
361
+ if not user_input.strip():
362
+ return history, None, "⚠️ Escribe un mensaje"
363
+
364
+ # Procesar mensaje
365
+ response = asyncio.run(self.chat_processor.process_message(user_input))
366
+
367
+ # Actualizar historial
368
+ history.append(("👤 Tú", user_input))
369
+ history.append(("🤖 AI", response["text"]))
370
+
371
+ return history, response["image"], f"✅ {response['type']}"
372
+
373
+ msg.submit(
374
+ handle_message,
375
+ [msg, chat_history],
376
+ [chatbot, image_output, status_output]
377
+ ).then(lambda: "", None, [msg])
378
+
379
+ send_btn.click(
380
+ handle_message,
381
+ [msg, chat_history],
382
+ [chatbot, image_output, status_output]
383
+ ).then(lambda: "", None, [msg])
384
+
385
+ clear_btn.click(
386
+ lambda: ([], None, "🔄 Chat limpiado"),
387
+ None,
388
+ [chatbot, image_output, status_output]
389
+ )
390
+
391
+ image_btn.click(
392
+ lambda text: asyncio.run(self.chat_processor.process_message(f"generar imagen {text}")),
393
+ [msg],
394
+ [chatbot, image_output, status_output]
395
+ ).then(lambda: "", None, [msg])
396
+
397
+ search_btn.click(
398
+ lambda text: asyncio.run(self.chat_processor.process_message(f"buscar {text}")),
399
+ [msg],
400
+ [chatbot, image_output, status_output]
401
+ ).then(lambda: "", None, [msg])
402
+
403
+ return demo
404
+
405
+ # ============================================================================
406
+ # CONFIGURACIÓN PRINCIPAL
407
+ # ============================================================================
408
+ def main():
409
+ # TU API KEY DE TAVILY - ¡IMPORTANTE!
410
+ TAVILY_API_KEY = "tu_api_key_aqui" # ⚠️ REEMPLAZA ESTO
411
+
412
+ if TAVILY_API_KEY == "tu_api_key_aqui":
413
+ print("⚠️ CONFIGURA TU API KEY:")
414
+ print("1. Ve a https://tavily.com")
415
+ print("2. Regístrate y obtén tu API key gratis")
416
+ print("3. Reemplaza 'tu_api_key_aqui' con tu key real")
417
+ return
418
+
419
+ print("🚀 Iniciando DevCreator AI...")
420
+ app = DevCreatorAI(TAVILY_API_KEY)
421
+ demo = app.create_interface()
422
+
423
+ demo.launch(
424
+ server_name="0.0.0.0",
425
+ server_port=7860,
426
+ share=False
427
+ )
428
+
429
+ if __name__ == "__main__":
430
+ main()