""" ============================================================ ANALYTICS - USER & CHAT ANALYTICS ============================================================ Basic analytics track karta hai: - Daily active users - Popular topics - Response quality metrics - Usage patterns ============================================================ """ import time import logging from collections import Counter, defaultdict from datetime import datetime, timedelta from typing import Dict, List, Optional logger = logging.getLogger('RuhiAnalytics') class ChatAnalytics: """ Chat analytics tracker. Privacy-friendly - koi personal data store nahi karta. Sirf aggregate metrics track karta hai. """ def __init__(self): self.daily_users = defaultdict(set) self.hourly_messages = defaultdict(int) self.topic_counter = Counter() self.response_lengths = [] self.session_durations = {} self.total_messages = 0 self.total_sessions = 0 self.popular_questions = Counter() self.language_distribution = Counter() self.emoji_usage = Counter() self.start_time = time.time() # Topic keywords for classification self.topic_keywords = { 'greeting': [ 'hi', 'hello', 'hey', 'kaise', 'namaste', 'kya hal', 'sup', 'howdy', ], 'personal': [ 'naam', 'name', 'kaun', 'who', 'umar', 'age', 'kahan', 'where', ], 'emotion': [ 'sad', 'happy', 'khush', 'dukhi', 'mood', 'feel', 'pyar', 'love', 'angry', 'gussa', 'lonely', 'akela', 'bore', ], 'knowledge': [ 'kya hai', 'what is', 'batao', 'explain', 'samjhao', 'meaning', 'matlab', 'define', ], 'story': [ 'kahani', 'story', 'sunao', 'tell me', 'joke', 'funny', 'mazak', ], 'advice': [ 'advice', 'salaah', 'help', 'madad', 'kya karu', 'suggest', 'recommend', ], 'creative': [ 'poem', 'shayari', 'song', 'gana', 'write', 'likh', 'create', 'banao', ], 'tech': [ 'code', 'programming', 'python', 'javascript', 'computer', 'phone', 'app', 'website', ], 'study': [ 'padhai', 'exam', 'school', 'college', 'homework', 'study', 'learn', 'sikho', ], 'casual': [ 'kya kar', 'doing', 'bored', 'timepass', 'chat', 'baat', 'talk', 'chal', ], } def track_message( self, user_id: str, message: str, response: str, session_id: str, response_time: float = 0, ): """ Ek message interaction track karta hai. Args: user_id: Anonymized user ID message: User ka message response: AI ka response session_id: Current session response_time: Response generation time """ try: now = datetime.utcnow() date_key = now.strftime("%Y-%m-%d") hour_key = now.strftime("%Y-%m-%d-%H") # Daily active users (anonymized) user_hash = hash(user_id) % 1000000 self.daily_users[date_key].add(user_hash) # Hourly message count self.hourly_messages[hour_key] += 1 # Total count self.total_messages += 1 # Topic detection topic = self._detect_topic(message) self.topic_counter[topic] += 1 # Response length tracking self.response_lengths.append(len(response)) # Popular questions (normalized) normalized_q = self._normalize_question(message) if len(normalized_q) > 5: self.popular_questions[normalized_q] += 1 # Language detection (basic) lang = self._detect_language(message) self.language_distribution[lang] += 1 # Emoji counting emojis = self._extract_emojis(message) for emoji in emojis: self.emoji_usage[emoji] += 1 # Session tracking if session_id not in self.session_durations: self.session_durations[session_id] = { 'start': time.time(), 'message_count': 0, } self.session_durations[session_id]['message_count'] += 1 self.session_durations[session_id]['last_active'] = time.time() except Exception as e: logger.error(f"Analytics tracking error: {e}") def _detect_topic(self, message: str) -> str: """Message ka topic detect karta hai""" message_lower = message.lower() for topic, keywords in self.topic_keywords.items(): if any(kw in message_lower for kw in keywords): return topic return 'other' def _normalize_question(self, message: str) -> str: """Question ko normalize karta hai for counting""" normalized = message.lower().strip() normalized = ' '.join(normalized.split()) if len(normalized) > 50: normalized = normalized[:50] return normalized def _detect_language(self, text: str) -> str: """Basic language detection""" hindi_chars = sum( 1 for c in text if '\u0900' <= c <= '\u097F' ) english_chars = sum( 1 for c in text if c.isascii() and c.isalpha() ) total = hindi_chars + english_chars if total == 0: return 'other' hindi_ratio = hindi_chars / total if hindi_ratio > 0.7: return 'hindi' elif hindi_ratio > 0.2: return 'hinglish' else: return 'english' def _extract_emojis(self, text: str) -> list: """Emojis extract karta hai""" import re emoji_pattern = re.compile( "[" "\U0001F600-\U0001F64F" "\U0001F300-\U0001F5FF" "\U0001F680-\U0001F6FF" "\U0001F1E0-\U0001F1FF" "\U00002702-\U000027B0" "\U000024C2-\U0001F251" "\U0001f926-\U0001f937" "\U00010000-\U0010ffff" "\u2640-\u2642" "\u2600-\u2B55" "\u200d" "\u23cf" "\u23e9" "\u231a" "\ufe0f" "\u3030" "]+", flags=re.UNICODE ) return emoji_pattern.findall(text) def get_dashboard_data(self) -> dict: """ Analytics dashboard ke liye data return karta hai. Koi personal info nahi - sirf aggregate metrics. """ now = datetime.utcnow() today = now.strftime("%Y-%m-%d") uptime_seconds = int(time.time() - self.start_time) # Calculate averages avg_response_length = 0 if self.response_lengths: avg_response_length = int( sum(self.response_lengths) / len(self.response_lengths) ) # Active sessions active_sessions = sum( 1 for s in self.session_durations.values() if time.time() - s.get('last_active', 0) < 300 ) # Average session duration avg_session_duration = 0 completed_sessions = [ s for s in self.session_durations.values() if s.get('last_active') and s.get('start') ] if completed_sessions: durations = [ s['last_active'] - s['start'] for s in completed_sessions ] avg_session_duration = int(sum(durations) / len(durations)) # Messages per hour (last 24 hours) messages_last_24h = sum( count for key, count in self.hourly_messages.items() if key >= (now - timedelta(hours=24)).strftime("%Y-%m-%d-%H") ) return { "overview": { "total_messages": self.total_messages, "total_sessions": len(self.session_durations), "active_sessions": active_sessions, "today_users": len(self.daily_users.get(today, set())), "messages_last_24h": messages_last_24h, "uptime_seconds": uptime_seconds, }, "engagement": { "avg_response_length_chars": avg_response_length, "avg_session_duration_seconds": avg_session_duration, "avg_messages_per_session": round( self.total_messages / max( len(self.session_durations), 1 ), 1 ), }, "topics": { topic: count for topic, count in self.topic_counter.most_common(10) }, "popular_questions": { q: count for q, count in self.popular_questions.most_common(10) }, "languages": dict(self.language_distribution), "top_emojis": { emoji: count for emoji, count in self.emoji_usage.most_common(10) }, } def cleanup_old_data(self, days_to_keep: int = 7): """Purana data delete karta hai""" cutoff = ( datetime.utcnow() - timedelta(days=days_to_keep) ).strftime("%Y-%m-%d") # Clean daily users old_dates = [ d for d in self.daily_users if d < cutoff ] for d in old_dates: del self.daily_users[d] # Clean hourly messages cutoff_hour = ( datetime.utcnow() - timedelta(days=days_to_keep) ).strftime("%Y-%m-%d-%H") old_hours = [ h for h in self.hourly_messages if h < cutoff_hour ] for h in old_hours: del self.hourly_messages[h] # Keep only recent response lengths if len(self.response_lengths) > 10000: self.response_lengths = self.response_lengths[-5000:] # Clean old sessions old_sessions = [ sid for sid, data in self.session_durations.items() if time.time() - data.get('last_active', 0) > 86400 * days_to_keep ] for sid in old_sessions: del self.session_durations[sid] logger.info(f"Analytics cleanup: removed {len(old_dates)} days of data") # Global instance chat_analytics = ChatAnalytics()