""" Nexari Context Engine (UPDATED) Author: Piyush Improvements: - Robust emotion pipeline usage & error handling - Safer fallback when model not available - Returns compact psychological profile instruction """ from transformers import pipeline print(">>> Context: Loading Emotion Analysis Model...") # load with top_k=1 by default try: emotion_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", top_k=1) except Exception as e: print(f"Context: Failed to load emotion model: {e}") emotion_classifier = None def _safe_emotion_analysis(text): if not emotion_classifier: return ("neutral", 0.0) try: # pipeline may return list of dicts or list-of-lists depending on version res = emotion_classifier(text) if isinstance(res, list) and len(res) > 0: # res could be [{'label':..., 'score':...}] or [['label',score],...] first = res[0] if isinstance(first, dict): return (first.get('label', 'neutral'), float(first.get('score', 0.0))) elif isinstance(first, list) and len(first) > 0 and isinstance(first[0], dict): return (first[0].get('label', 'neutral'), float(first[0].get('score', 0.0))) return ("neutral", 0.0) except Exception as e: print(f"Emotion analysis error: {e}") return ("neutral", 0.0) def get_smart_context(user_text): """ Analyzes the user's 'Vibe' and returns a short persona instruction. """ try: label, confidence = _safe_emotion_analysis(user_text) top_emotion = label.lower() confidence = float(confidence) word_count = len(user_text.split()) if user_text else 0 if word_count < 4: conversation_mode = "Ping-Pong Mode (Fast)" elif word_count < 20: conversation_mode = "Standard Chat Mode (Balanced)" else: conversation_mode = "Deep Dive Mode (Detailed)" if top_emotion == "joy": emotional_context = "User: Positive/Energetic. Vibe: Celebrate — be upbeat but concise." elif top_emotion == "sadness": emotional_context = "User: Low Energy. Vibe: Supportive — patient and gentle." elif top_emotion == "anger": emotional_context = "User: Frustrated. Vibe: De-escalate — calm, solution-first." elif top_emotion == "fear": emotional_context = "User: Anxious. Vibe: Reassure and clarify." elif top_emotion == "surprise": emotional_context = "User: Curious/Alert. Vibe: Engage and explain." else: emotional_context = "User: Neutral/Professional. Vibe: Helpful and efficient." return ( f"\n[PSYCHOLOGICAL PROFILE]\n" f"1. Interaction Mode: {conversation_mode}\n" f"2. {emotional_context}\n" f"3. Directive: Mirror user's energy; keep follow-ups short and on-topic.\n" ) except Exception as e: print(f"Context Error: {e}") return ""