# main.py - PARTE 1/3 import gradio as gr import torch import asyncio import aiohttp import random from typing import List, Dict, Any from datetime import datetime # ============================================================================ # 1. SISTEMA DE APRENDIZAJE # ============================================================================ class LearningSystem: def __init__(self): self.user_profile = { 'preferred_technologies': {}, 'skill_level': 'intermediate', 'preferred_image_styles': {}, 'interaction_count': 0 } def analyze_interaction(self, user_input: str): self.user_profile['interaction_count'] += 1 self.learn_skill_level(user_input) self.learn_technology_preferences(user_input) self.learn_image_preferences(user_input) def learn_skill_level(self, user_input: str): beginner_terms = ['cómo empezar', 'tutorial básico', 'principiante'] advanced_terms = ['optimización', 'arquitectura', 'avanzado'] if any(term in user_input.lower() for term in beginner_terms): self.user_profile['skill_level'] = 'beginner' elif any(term in user_input.lower() for term in advanced_terms): self.user_profile['skill_level'] = 'advanced' def learn_technology_preferences(self, user_input: str): tech_mappings = { 'react': 'frontend', 'vue': 'frontend', 'node': 'backend', 'python': 'backend', 'mongodb': 'database', 'docker': 'devops' } for tech, category in tech_mappings.items(): if tech in user_input.lower(): if category not in self.user_profile['preferred_technologies']: self.user_profile['preferred_technologies'][category] = {} self.user_profile['preferred_technologies'][category][tech] = \ self.user_profile['preferred_technologies'][category].get(tech, 0) + 1 def learn_image_preferences(self, user_input: str): image_styles = { 'hyperrealistic': ['hiperrealista', 'foto real'], 'anime': ['anime', 'manga'], 'cinematic': ['cinematográfico', 'película'] } for style, keywords in image_styles.items(): if any(keyword in user_input.lower() for keyword in keywords): self.user_profile['preferred_image_styles'][style] = \ self.user_profile['preferred_image_styles'].get(style, 0) + 1 def get_personalized_suggestions(self) -> str: suggestions = [] if self.user_profile['preferred_technologies']: frontend_techs = self.user_profile['preferred_technologies'].get('frontend', {}) if frontend_techs: top_tech = max(frontend_techs.items(), key=lambda x: x[1])[0] suggestions.append(f"💡 Veo que usas {top_tech}. ¿Te interesa Next.js o React Native?") if self.user_profile['skill_level'] == 'beginner': suggestions.append("🎯 Te recomiendo empezar con proyectos simples como un todo-list") elif self.user_profile['skill_level'] == 'advanced': suggestions.append("🚀 Podrías explorar microservicios o GraphQL") return "\n".join(suggestions) if suggestions else "" def get_recommended_image_style(self) -> str: if self.user_profile['preferred_image_styles']: return max(self.user_profile['preferred_image_styles'].items(), key=lambda x: x[1])[0] return "hyperrealistic" # ============================================================================ # 2. CLIENTE TAVILY # ============================================================================ class TavilyExpertClient: def __init__(self, api_key: str): self.api_key = api_key self.base_url = "https://api.tavily.com" async def search_technical(self, query: str) -> Dict[str, Any]: payload = { "api_key": self.api_key, "query": f"{query} programming code examples 2024", "search_depth": "advanced", "max_results": 6, "include_answer": True } try: async with aiohttp.ClientSession() as session: async with session.post(f"{self.base_url}/search", json=payload) as response: if response.status == 200: return await response.json() else: return {"error": f"HTTP {response.status}"} except Exception as e: return {"error": str(e)} # ============================================================================ # 3. GENERADOR DE PROMPTS DE IMAGEN # ============================================================================ class HyperRealisticPromptGenerator: def __init__(self): self.FEMALE_ROLES = [ {"role": "executive secretary", "uniform": "form-fitting black dress", "environment": "luxurious office"}, {"role": "salsa dancer", "uniform": "flowing red dress", "environment": "Latin dance hall"}, {"role": "fashion manager", "uniform": "chic designer dress", "environment": "boutique"}, {"role": "hotel manager", "uniform": "elegant blazer", "environment": "hotel lobby"} ] self.ART_STYLES = { "Hyperrealistic": "hyperrealistic, photorealistic, 8K UHD", "Cinematic": "cinematic lighting, dramatic", "Anime": "anime style, manga" } def generate_prompt(self, role: str, style: str = "Hyperrealistic") -> str: role_data = next((r for r in self.FEMALE_ROLES if r['role'] == role), self.FEMALE_ROLES[0]) prompt = f"{self.ART_STYLES[style]} photo of elegant Latina {role_data['role']}, " prompt += f"wearing {role_data['uniform']} in {role_data['environment']}. " prompt += "Professional photography, detailed, 9:16 aspect ratio." return prompt def get_available_roles(self): return [role['role'] for role in self.FEMALE_ROLES]# main.py - PARTE 2/3 # ============================================================================ # 4. GENERADOR DE IMÁGENES # ============================================================================ class ImageGenerator: def __init__(self): self.device = "cuda" if torch.cuda.is_available() else "cpu" self.pipe = None def load_model(self): if self.pipe is not None: return True try: from diffusers import StableDiffusionPipeline print("🔄 Cargando modelo de imágenes...") self.pipe = StableDiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1-base", torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, safety_checker=None ) self.pipe = self.pipe.to(self.device) print("✅ Modelo de imágenes cargado") return True except Exception as e: print(f"❌ Error cargando modelo: {e}") return False def generate_image(self, prompt: str): if not self.load_model(): return None, "Modelo no disponible" try: result = self.pipe(prompt, num_inference_steps=20, height=512, width=384) return result.images[0], "✅ Imagen generada" except Exception as e: return None, f"❌ Error: {e}" # ============================================================================ # 5. PROCESADOR DE CHAT PRINCIPAL # ============================================================================ class ChatProcessor: def __init__(self, tavily_api_key: str): self.tavily_client = TavilyExpertClient(tavily_api_key) self.prompt_generator = HyperRealisticPromptGenerator() self.image_generator = ImageGenerator() self.learning_system = LearningSystem() async def process_message(self, user_input: str) -> dict: # Análisis de aprendizaje self.learning_system.analyze_interaction(user_input) # Determinar tipo de solicitud request_type = self.analyze_request_type(user_input) response_data = { "text": "", "image": None, "type": "conversation" } try: if request_type == "image_generation": image_result = await self.handle_image_request(user_input) response_data.update(image_result) elif request_type == "technical_help": search_result = await self.handle_technical_request(user_input) response_data.update(search_result) else: conversation_result = await self.handle_conversation(user_input) response_data.update(conversation_result) # Añadir sugerencias personalizadas suggestions = self.learning_system.get_personalized_suggestions() if suggestions: response_data["text"] += f"\n\n🎓 **Sugerencias:**\n{suggestions}" except Exception as e: response_data["text"] = f"❌ Error: {str(e)}" response_data["type"] = "error" return response_data def analyze_request_type(self, user_input: str) -> str: user_input_lower = user_input.lower() if any(keyword in user_input_lower for keyword in ['imagen', 'generar', 'crear']): return "image_generation" elif any(keyword in user_input_lower for keyword in ['código', 'programar', 'error', 'cómo']): return "technical_help" else: return "conversation" async def handle_image_request(self, user_input: str) -> dict: preferred_style = self.learning_system.get_recommended_image_style() available_roles = self.prompt_generator.get_available_roles() # Buscar rol mencionado selected_role = available_roles[0] for role in available_roles: if role in user_input.lower(): selected_role = role break prompt = self.prompt_generator.generate_prompt(selected_role, preferred_style) image, message = self.image_generator.generate_image(prompt) return { "text": f"🎨 **Imagen generada:**\n\n**Prompt:** {prompt}\n\n{message}", "image": image, "type": "image_generation" } async def handle_technical_request(self, user_input: str) -> dict: search_results = await self.tavily_client.search_technical(user_input) if "error" in search_results: return { "text": f"❌ No encontré información sobre: {user_input}", "type": "error" } formatted_results = self.format_search_results(search_results, user_input) return { "text": formatted_results, "type": "technical_help" } async def handle_conversation(self, user_input: str) -> dict: return { "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", "type": "conversation" } def format_search_results(self, search_data: dict, original_query: str) -> str: if "results" not in search_data or not search_data["results"]: return f"🔍 **Búsqueda para '{original_query}':**\n\nNo encontré resultados." results = search_data["results"] answer = search_data.get("answer", "") response = f"🔍 **Resultados para '{original_query}':**\n\n" if answer: response += f"**Respuesta:** {answer}\n\n" response += "**Fuentes:**\n" for i, result in enumerate(results[:4], 1): title = result.get('title', 'Sin título') content = result.get('content', '')[:120] + "..." response += f"\n{i}. **{title}**\n" response += f" {content}\n" return response# main.py - PARTE 3/3 # ============================================================================ # 6. INTERFAZ GRADIO # ============================================================================ class DevCreatorAI: def __init__(self, tavily_api_key: str): self.chat_processor = ChatProcessor(tavily_api_key) def create_interface(self): with gr.Blocks(theme=gr.themes.Soft(), title="DevCreator AI") as demo: gr.Markdown(""" # 🚀 DevCreator AI **Tu Asistente de Desarrollo Inteligente** """) with gr.Row(): with gr.Column(scale=2): chatbot = gr.Chatbot( label="💬 Conversación", height=500, show_copy_button=True ) with gr.Row(): msg = gr.Textbox( placeholder="💭 Escribe tu mensaje aquí...", lines=3, scale=4 ) send_btn = gr.Button("🚀 Enviar", variant="primary", scale=1) with gr.Row(): clear_btn = gr.Button("🗑️ Limpiar") image_btn = gr.Button("🎨 Imagen") search_btn = gr.Button("🔍 Buscar") with gr.Column(scale=1): image_output = gr.Image( label="🖼️ Imagen Generada", height=400 ) status_output = gr.Textbox( label="📊 Estado", value="✅ Sistema listo" ) chat_history = gr.State([]) # Ejemplos gr.Examples( examples=[ ["Genera imagen de executive secretary"], ["Cómo hacer una API REST con Node.js"], ["Buscar machine learning Python"], ["Genera imagen de salsa dancer"] ], inputs=msg ) # Event handlers def handle_message(user_input, history): history = history or [] if not user_input.strip(): return history, None, "⚠️ Escribe un mensaje" # Procesar mensaje response = asyncio.run(self.chat_processor.process_message(user_input)) # Actualizar historial history.append(("👤 Tú", user_input)) history.append(("🤖 AI", response["text"])) return history, response["image"], f"✅ {response['type']}" msg.submit( handle_message, [msg, chat_history], [chatbot, image_output, status_output] ).then(lambda: "", None, [msg]) send_btn.click( handle_message, [msg, chat_history], [chatbot, image_output, status_output] ).then(lambda: "", None, [msg]) clear_btn.click( lambda: ([], None, "🔄 Chat limpiado"), None, [chatbot, image_output, status_output] ) image_btn.click( lambda text: asyncio.run(self.chat_processor.process_message(f"generar imagen {text}")), [msg], [chatbot, image_output, status_output] ).then(lambda: "", None, [msg]) search_btn.click( lambda text: asyncio.run(self.chat_processor.process_message(f"buscar {text}")), [msg], [chatbot, image_output, status_output] ).then(lambda: "", None, [msg]) return demo # ============================================================================ # CONFIGURACIÓN PRINCIPAL # ============================================================================ def main(): # TU API KEY DE TAVILY - ¡IMPORTANTE! TAVILY_API_KEY = "tu_api_key_aqui" # ⚠️ REEMPLAZA ESTO if TAVILY_API_KEY == "tu_api_key_aqui": print("⚠️ CONFIGURA TU API KEY:") print("1. Ve a https://tavily.com") print("2. Regístrate y obtén tu API key gratis") print("3. Reemplaza 'tu_api_key_aqui' con tu key real") return print("🚀 Iniciando DevCreator AI...") app = DevCreatorAI(TAVILY_API_KEY) demo = app.create_interface() demo.launch( server_name="0.0.0.0", server_port=7860, share=False ) if __name__ == "__main__": main()