Spaces:
Runtime error
Runtime error
from app.core.logging_setup import logger | |
from app.core.db_setup import interaction_patterns_collection, user_memory_collection | |
from datetime import datetime, timezone | |
def get_interaction_trends(): | |
"""Analyze the user's interaction patterns (hourly and day-of-week).""" | |
try: | |
trends = list( | |
interaction_patterns_collection.find({}, {"_id": 0}).sort([ | |
("day_of_week", 1), | |
("hour", 1) | |
]) | |
) | |
return [ | |
(trend["hour"], trend["day_of_week"], trend["interaction_count"]) for trend in trends | |
] | |
except Exception as e: | |
logger.error(f"Unexpected error: {e}") | |
return [] | |
def get_time_of_day(): | |
"""Determine the current time of day.""" | |
logger.info("⏰ Detecting time of day...") | |
hour = datetime.now(timezone.utc).hour | |
if 6 <= hour < 12: | |
return "morning" | |
elif 12 <= hour < 18: | |
return "afternoon" | |
elif 18 <= hour < 24: | |
return "evening" | |
else: | |
return "night" | |
def analyze_usage_patterns(): | |
"""Analyze interaction trends and store the most active time of day.""" | |
trends = get_interaction_trends() | |
time_counts = {"morning": 0, "afternoon": 0, "evening": 0, "night": 0} | |
for hour, _, count in trends: | |
if 6 <= hour < 12: | |
time_counts["morning"] += count | |
elif 12 <= hour < 18: | |
time_counts["afternoon"] += count | |
elif 18 <= hour < 24: | |
time_counts["evening"] += count | |
else: | |
time_counts["night"] += count | |
most_active = max(time_counts, key=time_counts.get) | |
try: | |
user_memory_collection.update_one( | |
{"key": "most_active_time"}, | |
{"$set": {"value": most_active}}, | |
upsert=True | |
) | |
logger.info(f"Stored most active time: {most_active}") | |
except Exception as e: | |
logger.error(f"Unexpected error: {e}") | |
return most_active |