Spaces:
Sleeping
Sleeping
Download app.py from manummc/chatbot-marta: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/spaces/manummc/chatbot-marta/resolve/main/app.py
- Command line
-
hf download hf://spaces/manummc/chatbot-marta/app.py
-
curl -L -o app.py https://huggingface.co/spaces/manummc/chatbot-marta/resolve/main/app.py
14.3 kB
| import os, json, re, time | |
| import gradio as gr | |
| import torch | |
| from dotenv import load_dotenv | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_openai import ChatOpenAI | |
| from transformers import pipeline | |
| import scipy.io.wavfile | |
| import numpy as np | |
| import uuid | |
| # ---------------------------------------------------- | |
| # CONFIG | |
| # ---------------------------------------------------- | |
| load_dotenv() | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| OPENROUTER_KEY = os.getenv("OPENROUTER_API_KEY") | |
| OPENROUTER_BASE = os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/v1") | |
| ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") | |
| HELICONE = os.getenv("HELICONE_API_KEY") | |
| EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2" | |
| USE_CUDA_EMBED = False | |
| WEB_FAISS_DIR, PDF_FAISS_DIR = "web_faiss", "faiss_index" | |
| RESPONSES_AUDIO = "bot_response.wav" | |
| CONTACTO_MARTA_URL = "#" | |
| UPSELL_URL = "#" | |
| # ---------------------------------------------------- | |
| # PLANES DE USUARIO Y FILTROS ESTRICTOS | |
| # ---------------------------------------------------- | |
| TIER_ORDER = {"no_registrado": 0, "basico": 1, "intermedio": 2, "gold": 3} | |
| FEATURES = { | |
| "website_navigation": {"min_tier": "no_registrado"}, | |
| "basic_concepts": {"min_tier": "no_registrado"}, | |
| "loan_calculators": {"min_tier": "basico"}, | |
| "advanced_concepts": {"min_tier": "intermedio"}, | |
| "investment_assistance_generic": {"min_tier": "intermedio"}, | |
| "financial_form_helper": {"min_tier": "gold"}, | |
| "personal_financial_tracker": {"min_tier": "gold"}, | |
| "gold_investment_planner": {"min_tier": "gold"}, | |
| } | |
| # Palabras clave que indican una consulta personalizada y deben ser escaladas | |
| PERSONALIZATION_TRIGGERS = [ | |
| "mi caso", "mi situaci贸n", "mi hipoteca", "mi pr茅stamo", "mi deuda", | |
| "mi inversi贸n", "mi cartera", "mi perfil", "mi empresa", "mi familia", | |
| "mis ingresos", "mis gastos", "tengo", "gano", "me recomiendas", | |
| "qu茅 compro", "qu茅 vendo", "cu谩ndo entrar", "cu谩ndo vender", | |
| "rentabilidad garantizada", "seguro que", "asegurado", "predice", | |
| "predecir", "garant铆a" | |
| ] | |
| # Palabras clave que indican una consulta demasiado compleja y deben ser escaladas | |
| COMPLEXITY_TRIGGERS = [ | |
| "derivados", "apalancamiento", "opciones", "options", "futuros", "swaps", | |
| "cfds", "optimizaci贸n fiscal", "planificaci贸n fiscal avanzada", "engineering", | |
| "backtesting", "modelo predictivo", "script", "trading algor铆tmico", | |
| "enmascarar impuestos", "evadir impuestos" | |
| ] | |
| def is_allowed(feature: str, user_tier: str) -> bool: | |
| needed = FEATURES.get(feature, {}).get("min_tier", "gold") | |
| return TIER_ORDER.get(user_tier, 0) >= TIER_ORDER.get(needed, 0) | |
| def upsell_msg(required_tier: str, plan_actual: str): | |
| return ( | |
| f"鈿狅笍 Esa funci贸n no est谩 disponible en tu plan actual (**{plan_actual}**). " | |
| f"Requiere el plan **{required_tier}**.\n\n" | |
| f"馃憠 [Ver planes y mejorar]({UPSELL_URL})" | |
| ) | |
| def escalate_to_marta_msg(): | |
| return ( | |
| f"Esta consulta requiere **asistencia personalizada** o es **demasiado compleja** para el chatbot.\n\n" | |
| f"Por favor, contacta con un asesor humano para obtener ayuda.\n\n" | |
| f"馃憠 [Contactar con Marta]({CONTACTO_MARTA_URL})" | |
| ) | |
| def classify_intent(message: str): | |
| """Clasificador de intenci贸n mejorado con filtros de seguridad.""" | |
| m = message.lower() | |
| # Filtro de m谩xima prioridad: Personalizaci贸n o Complejidad | |
| if any(tok in m for tok in PERSONALIZATION_TRIGGERS): | |
| return {"intent": "escalate_marta", "feature": None, "reason": "personalized"} | |
| if any(tok in m for tok in COMPLEXITY_TRIGGERS): | |
| return {"intent": "escalate_marta", "feature": None, "reason": "complex"} | |
| # Clasificaci贸n por caracter铆sticas | |
| if "calculadora" in m or "calcular cuota" in m or "pr茅stamo" in m or "prestamo" in m: | |
| return {"intent": "loan_calculators", "feature": "loan_calculators"} | |
| invest_cues = ["inversi贸n", "cartera", "estrategia", "asset allocation", "diversificaci贸n", "riesgo bajo"] | |
| if any(c in m for c in invest_cues): | |
| return {"intent": "investment_assistance_generic", "feature": "investment_assistance_generic"} | |
| basic_cues = ["qu茅 es", "definici贸n", "concepto", "b谩sico", "principiante", "glosario"] | |
| if any(c in m for c in basic_cues): | |
| return {"intent": "basic_concepts", "feature": "basic_concepts"} | |
| # Intenci贸n por defecto | |
| return {"intent": "generic_rag", "feature": "website_navigation"} | |
| # ---------------------------------------------------- | |
| # ### NUEVO Y OPTIMIZADO PARA GPU ###: Speech-to-Text (ASR) | |
| # ---------------------------------------------------- | |
| device = "cuda:0" if torch.cuda.is_available() else "cpu" | |
| torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 | |
| MODEL_NAME = "openai/whisper-medium" | |
| print(f"Cargando modelo de transcripci贸n '{MODEL_NAME}' en el dispositivo: {device}") | |
| try: | |
| transcriber = pipeline( | |
| "automatic-speech-recognition", model=MODEL_NAME, torch_dtype=torch_dtype, device=device, | |
| model_kwargs={"attn_implementation": "flash_attention_2"} if device.startswith("cuda") else {} | |
| ) | |
| _HAVE_ASR = True | |
| print("Modelo de transcripci贸n cargado con 茅xito.") | |
| except (ImportError, RuntimeError): | |
| print("Flash Attention 2 no disponible. Volviendo a implementaci贸n est谩ndar.") | |
| transcriber = pipeline( | |
| "automatic-speech-recognition", model=MODEL_NAME, torch_dtype=torch_dtype, device=device | |
| ) | |
| _HAVE_ASR = True | |
| print("Modelo de transcripci贸n cargado (sin Flash Attention).") | |
| except Exception as e: | |
| print(f"Error al cargar el modelo de transcripci贸n: {e}. Funcionalidad de audio deshabilitada.") | |
| _HAVE_ASR = False | |
| transcriber = None | |
| # ---------------------------------------------------- | |
| # Embeddings & Vectorstores | |
| # ---------------------------------------------------- | |
| embeddings = HuggingFaceEmbeddings( | |
| model_name=EMBED_MODEL, model_kwargs={"device": "cuda" if USE_CUDA_EMBED else "cpu"} | |
| ) | |
| def safe_load_faiss(path): | |
| if not os.path.exists(path): return None | |
| try: return FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True) | |
| except: return None | |
| vectorstore = safe_load_faiss(PDF_FAISS_DIR) | |
| web_store = safe_load_faiss(WEB_FAISS_DIR) | |
| # ---------------------------------------------------- | |
| # TTS | |
| # ---------------------------------------------------- | |
| try: | |
| from elevenlabs import generate as eleven_generate, set_api_key as eleven_set_api_key | |
| if ELEVENLABS_API_KEY: eleven_set_api_key(ELEVENLABS_API_KEY) | |
| _HAVE_ELEVEN = True | |
| except: _HAVE_ELEVEN = False | |
| def tts_generate(text: str, outdir="responses_audio"): | |
| if not text or not text.strip(): | |
| print("[TTS] Texto vac铆o, no se genera audio.") | |
| return None | |
| os.makedirs(outdir, exist_ok=True) | |
| outpath = os.path.join(outdir, "bot_response.wav") | |
| if ELEVENLABS_API_KEY and _HAVE_ELEVEN: | |
| try: | |
| from elevenlabs import generate | |
| audio_bytes = generate(text=text, voice="alloy", model="eleven_monolingual_v1") | |
| with open(outpath, "wb") as f: f.write(audio_bytes) | |
| print("[TTS] Generado con ElevenLabs:", outpath) | |
| return outpath | |
| except Exception as e: print("[TTS] Error ElevenLabs:", e) | |
| try: | |
| from TTS.api import TTS | |
| tts = TTS("tts_models/es/css10/vits") | |
| tts.tts_to_file(text=text, file_path=outpath) | |
| print("[TTS] Generado con Coqui:", outpath) | |
| return outpath | |
| except Exception as e: print("[TTS] Error Coqui:", e) | |
| try: | |
| import pyttsx3 | |
| engine = pyttsx3.init() | |
| engine.save_to_file(text, outpath) | |
| engine.runAndWait() | |
| print("[TTS] Generado con pyttsx3:", outpath) | |
| return outpath | |
| except Exception as e: print("[TTS] Error pyttsx3:", e) | |
| print("[TTS] No se pudo generar audio.") | |
| return None | |
| # ---------------------------------------------------- | |
| # LLM | |
| # ---------------------------------------------------- | |
| llm = ChatOpenAI( | |
| openai_api_key=OPENROUTER_KEY or OPENAI_API_KEY, | |
| openai_api_base=OPENROUTER_BASE if OPENROUTER_KEY else "https://api.openai.com/v1", | |
| model_name="openai/gpt-4o-mini", temperature=0.2, max_tokens=400, | |
| model_kwargs={"extra_headers": {"Helicone-Auth": f"Bearer {HELICONE}"} if HELICONE else {}}, | |
| ) | |
| SYSTEM_PROMPT = ( | |
| "Eres un asistente de educaci贸n financiera y gu铆a de la web. " | |
| "Tu rol es estrictamente informativo y general. Nunca des asesoramiento financiero personalizado, " | |
| "opiniones sobre inversiones espec铆ficas, o uses datos privados. " | |
| "Si la consulta parece ser personal, compleja o requiere consejo, deriva al usuario a un asesor humano (Marta)." | |
| ) | |
| # ---------------------------------------------------- | |
| # L贸gica del Chat (con filtros integrados) | |
| # ---------------------------------------------------- | |
| def run_rag_answer(user_msg: str): | |
| docs_text = "" | |
| try: | |
| results = vectorstore.similarity_search(user_msg, k=3) if vectorstore else [] | |
| docs_text = "\n\n".join([d.page_content for d in results]) | |
| except: pass | |
| prompt = f"{SYSTEM_PROMPT}\n\nContexto:\n{docs_text}\n\nPregunta: {user_msg}\nRespuesta breve y general:" | |
| out = llm.invoke([{"role": "system","content": SYSTEM_PROMPT},{"role": "user","content": prompt}]) | |
| return out.content if hasattr(out, "content") else str(out) | |
| def respond(message, history, tier, tts_enabled): | |
| if not message.strip(): | |
| return "", history, None | |
| response_text = "" | |
| try: | |
| # 1. Clasificar intenci贸n y aplicar filtros de entrada | |
| intent_details = classify_intent(message) | |
| intent = intent_details.get("intent") | |
| feature = intent_details.get("feature") | |
| if intent == "escalate_marta": | |
| print(f"Filtro activado (Entrada): Raz贸n '{intent_details.get('reason')}'. Escalando a Marta.") | |
| response_text = escalate_to_marta_msg() | |
| # 2. Revisar si el plan permite la funci贸n | |
| elif feature and not is_allowed(feature, tier): | |
| required_tier = FEATURES[feature]["min_tier"] | |
| print(f"Filtro activado (Plan): Usuario '{tier}' intent贸 usar '{feature}' que requiere '{required_tier}'.") | |
| response_text = upsell_msg(required_tier, tier) | |
| # 3. Si pasa los filtros, generar respuesta con RAG/LLM | |
| else: | |
| response_text = run_rag_answer(message) | |
| # 4. FILTRO DE SEGURIDAD EN LA SALIDA: Revisar la respuesta del LLM | |
| response_lower = response_text.lower() | |
| if any(trig in response_lower for trig in PERSONALIZATION_TRIGGERS) or \ | |
| any(trig in response_lower for trig in COMPLEXITY_TRIGGERS): | |
| print("鈿狅笍 ADVERTENCIA: La respuesta del LLM activ贸 un filtro de seguridad. Se descarta y se escala.") | |
| response_text = escalate_to_marta_msg() | |
| # 5. Guardar historial | |
| if history is None: history = [] | |
| history.append({"role": "user", "content": message}) | |
| history.append({"role": "assistant", "content": response_text}) | |
| # 6. TTS si est谩 activado | |
| audio_out = None | |
| if tts_enabled and response_text: | |
| audio_path = tts_generate(response_text) | |
| if audio_path: | |
| audio_out = gr.update(value=audio_path, autoplay=True) | |
| return "", history, audio_out | |
| except Exception as e: | |
| print(f"Error en respond: {e}") | |
| return "", history, None | |
| # ---------------------------------------------------- | |
| # Funci贸n para transcribir el audio | |
| # ---------------------------------------------------- | |
| def transcribe_audio(audio): | |
| if not _HAVE_ASR or audio is None: | |
| return gr.update() | |
| sr, y = audio | |
| temp_filename = f"temp_audio_{uuid.uuid4()}.wav" | |
| print(f"Transcribiendo audio... (Duraci贸n: {len(y)/sr:.2f}s)") | |
| try: | |
| scipy.io.wavfile.write(temp_filename, sr, y.astype(np.int16)) | |
| generate_kwargs = { | |
| "language": "spanish", "task": "transcribe", | |
| "num_beams": 5, "no_repeat_ngram_size": 3 | |
| } | |
| result = transcriber(temp_filename, generate_kwargs=generate_kwargs) | |
| transcribed_text = result.get("text", "No se pudo transcribir.").strip() | |
| print(f"Texto transcrito: '{transcribed_text}'") | |
| except Exception as e: | |
| print(f"Error durante la transcripci贸n: {e}") | |
| transcribed_text = "Error al transcribir." | |
| finally: | |
| if os.path.exists(temp_filename): | |
| os.remove(temp_filename) | |
| return gr.update(value=transcribed_text, interactive=True) | |
| # ---------------------------------------------------- | |
| # UI (Gradio) | |
| # ---------------------------------------------------- | |
| custom_css = """ | |
| #hidden-audio { width: 1px !important; height: 1px !important; opacity: 0 !important; position: absolute; } | |
| """ | |
| initial_history = [{"role":"assistant","content":"隆Hola! 馃憢 Soy tu asistente virtual. 驴En qu茅 puedo ayudarte hoy?"}] | |
| with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo: | |
| chatbot_ui = gr.Chatbot(height=400, value=initial_history, type="messages", label="Chat") | |
| with gr.Row(): | |
| msg = gr.Textbox(placeholder="Escribe o graba un mensaje...", container=False, scale=8) | |
| send_btn = gr.Button("Enviar", scale=1) | |
| audio_in = gr.Audio(sources=["microphone"], type="numpy", show_label=False, elem_id="record-button", scale=0) | |
| with gr.Row(): | |
| tts_enabled = gr.Checkbox(label="馃攰 Respuesta por audio", value=True) | |
| tier = gr.Dropdown(["no_registrado", "basico", "intermedio", "gold"], value="no_registrado", label="Plan de usuario") | |
| audio_out = gr.Audio(type="filepath", autoplay=True, elem_id="hidden-audio") | |
| # Eventos | |
| send_btn.click( | |
| fn=respond, | |
| inputs=[msg, chatbot_ui, tier, tts_enabled], | |
| outputs=[msg, chatbot_ui, audio_out] | |
| ) | |
| msg.submit( | |
| fn=respond, | |
| inputs=[msg, chatbot_ui, tier, tts_enabled], | |
| outputs=[msg, chatbot_ui, audio_out] | |
| ) | |
| if _HAVE_ASR: | |
| audio_in.stop_recording(transcribe_audio, inputs=audio_in, outputs=msg) | |
| if __name__ == "__main__": | |
| demo.launch(show_error=True) |