import json import os from datetime import datetime class UsageTracker: def __init__(self, data_file="usage_data.json"): self.data_file = data_file self.daily_limit = 1500 # Gemini 1.5 Flash free tier limit self._load_data() def _load_data(self): """Load usage data from file or initialize if not exists/new day""" today = datetime.now().strftime("%Y-%m-%d") if os.path.exists(self.data_file): try: with open(self.data_file, 'r') as f: data = json.load(f) # Reset if it's a new day if data.get("date") != today: self.usage_count = 0 self.date = today self._save_data() else: self.usage_count = data.get("count", 0) self.date = data.get("date", today) except Exception: # If file is corrupted, reset self.usage_count = 0 self.date = today self._save_data() else: self.usage_count = 0 self.date = today self._save_data() def _save_data(self): """Save current usage data to file""" data = { "date": self.date, "count": self.usage_count } with open(self.data_file, 'w') as f: json.dump(data, f) def increment(self): """Increment usage counter""" # Reload data to ensure we have the latest count from other instances self._load_data() # Ensure we're on the correct day before incrementing today = datetime.now().strftime("%Y-%m-%d") if self.date != today: self.usage_count = 0 self.date = today self.usage_count += 1 self._save_data() return self.usage_count def get_usage(self): """Get current usage stats""" # Reload data to ensure we have the latest count self._load_data() # Check date again just in case today = datetime.now().strftime("%Y-%m-%d") if self.date != today: self.usage_count = 0 self.date = today self._save_data() return { "count": self.usage_count, "limit": self.daily_limit, "remaining": max(0, self.daily_limit - self.usage_count) }