File size: 4,924 Bytes
e441606
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import time
import re
from typing import Dict, Any, List, Optional
from datetime import datetime
from utils.config import config

class SmartContextDetector:
    """Intelligently detects when context is relevant to user queries"""
    
    def __init__(self):
        # Keywords that suggest time/weather relevance
        self.time_indicators = [
            'time', 'date', 'today', 'now', 'current', 'moment', 
            'morning', 'afternoon', 'evening', 'night', 'weekend',
            'what time', 'what day', 'what year', 'what month'
        ]
        
        self.weather_indicators = [
            'weather', 'temperature', 'rain', 'snow', 'sunny', 'cloudy',
            'forecast', 'climate', 'season', 'hot', 'cold', 'warm', 'cool',
            'umbrella', 'jacket', 'outdoor', 'outside'
        ]
        
        self.location_indicators = [
            'in', 'at', 'near', 'around', 'local', 'here', 'there'
        ]
    
    def should_include_time_context(self, user_query: str, 
                                  conversation_history: List[Dict] = None) -> bool:
        """Determine if time context is relevant to the query"""
        query_lower = user_query.lower()
        
        # Direct time references
        if any(indicator in query_lower for indicator in self.time_indicators):
            return True
        
        # Check conversation context for time-related discussions
        if conversation_history:
            recent_messages = conversation_history[-3:]  # Last 3 messages
            context_text = " ".join([msg.get('content', '') for msg in recent_messages]).lower()
            if any(word in context_text for word in self.time_indicators):
                return True
        
        return False
    
    def should_include_weather_context(self, user_query: str,
                                     conversation_history: List[Dict] = None) -> bool:
        """Determine if weather context is relevant to the query"""
        query_lower = user_query.lower()
        
        # Direct weather references
        if any(indicator in query_lower for indicator in self.weather_indicators):
            return True
        
        # Location + activity combinations that often involve weather
        location_mentioned = any(loc.lower() in query_lower for loc in 
                               ['new york', 'london', 'tokyo', 'paris', 'los angeles', 'sydney', 'singapore', 'mumbai'])
        activity_mentioned = any(activity in query_lower for activity in 
                               ['outdoor', 'outside', 'walk', 'run', 'travel', 'trip', 'plans', 'going'])
        
        if location_mentioned and activity_mentioned:
            return True
        
        # Check conversation context
        if conversation_history:
            recent_messages = conversation_history[-3:]
            context_text = " ".join([msg.get('content', '') for msg in recent_messages]).lower()
            if any(word in context_text for word in self.weather_indicators):
                return True
        
        return False
    
    def extract_location_if_relevant(self, user_query: str) -> Optional[str]:
        """Extract location if query suggests location-specific context"""
        # Common locations
        locations = {
            'new york': ['new york', 'ny', 'nyc'],
            'london': ['london', 'uk', 'england'],
            'tokyo': ['tokyo', 'japan', 'jp'],
            'paris': ['paris', 'france', 'fr'],
            'los angeles': ['los angeles', 'la', 'california'],
            'sydney': ['sydney', 'australia', 'au'],
            'singapore': ['singapore', 'sg'],
            'mumbai': ['mumbai', 'india', 'in']
        }
        
        query_lower = user_query.lower()
        for location, aliases in locations.items():
            if any(alias in query_lower for alias in aliases):
                return location
        
        return None
    
    def get_relevant_context(self, user_query: str, 
                           conversation_history: List[Dict] = None) -> Dict[str, Any]:
        """Get only the context that's actually relevant"""
        context = {
            'include_time': self.should_include_time_context(user_query, conversation_history),
            'include_weather': self.should_include_weather_context(user_query, conversation_history),
            'detected_location': self.extract_location_if_relevant(user_query),
            'timestamp': time.time()
        }
        
        # Add actual context data only if needed
        if context['include_time']:
            now = datetime.now()
            context['time_data'] = {
                'current_time': now.strftime("%A, %B %d, %Y at %I:%M %p"),
                'day_of_week': now.strftime("%A"),
                'is_business_hours': 9 <= now.hour <= 17
            }
        
        return context

# Global instance
smart_context = SmartContextDetector()