Spaces:
Running
Running
Update usage_tracker.py
Browse files- usage_tracker.py +33 -10
usage_tracker.py
CHANGED
|
@@ -21,6 +21,13 @@ class UsageTracker:
|
|
| 21 |
data.setdefault('models', {})
|
| 22 |
data.setdefault('api_endpoints', {})
|
| 23 |
data.setdefault('recent_daily_usage', {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
return data
|
| 25 |
except json.JSONDecodeError:
|
| 26 |
print(f"Warning: Could not decode JSON from {self.data_file}. Starting with empty data.")
|
|
@@ -33,15 +40,27 @@ class UsageTracker:
|
|
| 33 |
'total_requests': 0,
|
| 34 |
'models': {},
|
| 35 |
'api_endpoints': {},
|
| 36 |
-
'recent_daily_usage': {}
|
| 37 |
}
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def save_data(self):
|
| 40 |
"""Saves current usage data to the JSON file."""
|
| 41 |
with self.lock:
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
with open(self.data_file, 'w') as f:
|
| 44 |
-
json.dump(
|
| 45 |
except IOError as e:
|
| 46 |
print(f"Error saving usage data to {self.data_file}: {e}")
|
| 47 |
|
|
@@ -76,15 +95,18 @@ class UsageTracker:
|
|
| 76 |
self.data['api_endpoints'][endpoint]['last_used'] = current_time
|
| 77 |
|
| 78 |
# Update daily usage
|
|
|
|
| 79 |
if current_date not in self.data['recent_daily_usage']:
|
| 80 |
self.data['recent_daily_usage'][current_date] = defaultdict(int)
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
self.data['recent_daily_usage'][current_date][model] += 1
|
| 84 |
self.data['recent_daily_usage'][current_date][endpoint] += 1
|
| 85 |
-
|
| 86 |
-
#
|
| 87 |
-
|
| 88 |
|
| 89 |
|
| 90 |
def get_usage_summary(self, days: int = 7):
|
|
@@ -97,12 +119,13 @@ class UsageTracker:
|
|
| 97 |
'recent_daily_usage': {}
|
| 98 |
}
|
| 99 |
|
| 100 |
-
# Filter daily usage for the last 'days'
|
| 101 |
today = datetime.date.today()
|
| 102 |
for i in range(days):
|
| 103 |
date = (today - datetime.timedelta(days=i)).strftime("%Y-%m-%d")
|
| 104 |
if date in self.data['recent_daily_usage']:
|
| 105 |
-
|
| 106 |
-
|
|
|
|
| 107 |
return summary
|
| 108 |
|
|
|
|
| 21 |
data.setdefault('models', {})
|
| 22 |
data.setdefault('api_endpoints', {})
|
| 23 |
data.setdefault('recent_daily_usage', {})
|
| 24 |
+
|
| 25 |
+
# Convert loaded daily usage dictionaries back to defaultdicts for internal use
|
| 26 |
+
loaded_daily_usage = {}
|
| 27 |
+
for date, entities in data['recent_daily_usage'].items():
|
| 28 |
+
loaded_daily_usage[date] = defaultdict(int, entities)
|
| 29 |
+
data['recent_daily_usage'] = loaded_daily_usage
|
| 30 |
+
|
| 31 |
return data
|
| 32 |
except json.JSONDecodeError:
|
| 33 |
print(f"Warning: Could not decode JSON from {self.data_file}. Starting with empty data.")
|
|
|
|
| 40 |
'total_requests': 0,
|
| 41 |
'models': {},
|
| 42 |
'api_endpoints': {},
|
| 43 |
+
'recent_daily_usage': {} # This will hold defaultdicts for each date
|
| 44 |
}
|
| 45 |
|
| 46 |
+
def _convert_defaultdicts_to_dicts(self, obj):
|
| 47 |
+
"""Recursively converts defaultdicts to dicts for JSON serialization."""
|
| 48 |
+
if isinstance(obj, defaultdict):
|
| 49 |
+
return {k: self._convert_defaultdicts_to_dicts(v) for k, v in obj.items()}
|
| 50 |
+
elif isinstance(obj, dict):
|
| 51 |
+
return {k: self._convert_defaultdicts_to_dicts(v) for k, v in obj.items()}
|
| 52 |
+
elif isinstance(obj, list):
|
| 53 |
+
return [self._convert_defaultdicts_to_dicts(elem) for elem in obj]
|
| 54 |
+
return obj
|
| 55 |
+
|
| 56 |
def save_data(self):
|
| 57 |
"""Saves current usage data to the JSON file."""
|
| 58 |
with self.lock:
|
| 59 |
+
# Convert defaultdicts to regular dicts before saving
|
| 60 |
+
data_to_save = self._convert_defaultdicts_to_dicts(self.data)
|
| 61 |
try:
|
| 62 |
with open(self.data_file, 'w') as f:
|
| 63 |
+
json.dump(data_to_save, f, indent=4)
|
| 64 |
except IOError as e:
|
| 65 |
print(f"Error saving usage data to {self.data_file}: {e}")
|
| 66 |
|
|
|
|
| 95 |
self.data['api_endpoints'][endpoint]['last_used'] = current_time
|
| 96 |
|
| 97 |
# Update daily usage
|
| 98 |
+
# Ensure the inner dictionary for the current_date is a defaultdict
|
| 99 |
if current_date not in self.data['recent_daily_usage']:
|
| 100 |
self.data['recent_daily_usage'][current_date] = defaultdict(int)
|
| 101 |
+
elif not isinstance(self.data['recent_daily_usage'][current_date], defaultdict):
|
| 102 |
+
# This handles cases where data was loaded as a plain dict
|
| 103 |
+
self.data['recent_daily_usage'][current_date] = defaultdict(int, self.data['recent_daily_usage'][current_date])
|
| 104 |
+
|
| 105 |
self.data['recent_daily_usage'][current_date][model] += 1
|
| 106 |
self.data['recent_daily_usage'][current_date][endpoint] += 1
|
| 107 |
+
|
| 108 |
+
# Removed the line that converts defaultdict back to dict here.
|
| 109 |
+
# Conversion will now happen only during save_data.
|
| 110 |
|
| 111 |
|
| 112 |
def get_usage_summary(self, days: int = 7):
|
|
|
|
| 119 |
'recent_daily_usage': {}
|
| 120 |
}
|
| 121 |
|
| 122 |
+
# Filter daily usage for the last 'days' and ensure it's a plain dict for the summary
|
| 123 |
today = datetime.date.today()
|
| 124 |
for i in range(days):
|
| 125 |
date = (today - datetime.timedelta(days=i)).strftime("%Y-%m-%d")
|
| 126 |
if date in self.data['recent_daily_usage']:
|
| 127 |
+
# Convert the defaultdict for this date to a plain dict for the summary
|
| 128 |
+
summary['recent_daily_usage'][date] = dict(self.data['recent_daily_usage'][date])
|
| 129 |
+
|
| 130 |
return summary
|
| 131 |
|