File size: 2,506 Bytes
8b8fa39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)
        }