forked from thezak48/comps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_metrics.py
More file actions
120 lines (105 loc) · 3.99 KB
/
Copy pathdatabase_metrics.py
File metadata and controls
120 lines (105 loc) · 3.99 KB
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
118
119
120
from db import query, query_one
from storage import is_s3_enabled
def get_metrics():
import os
from datetime import datetime, timedelta
metrics = {}
# Total users
row = query_one("SELECT COUNT(*) FROM users")
metrics["total_users"] = row[0] if row else 0
# Total comparisons
row = query_one("SELECT COUNT(*) FROM comparisons")
metrics["total_comparisons"] = row[0] if row else 0
# Total images
row = query_one("SELECT COUNT(*) FROM image_positions")
metrics["total_images"] = row[0] if row else 0
# Active users (last 7 days)
week_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
row = query_one(
"SELECT COUNT(DISTINCT user_id) FROM comparisons WHERE created_at >= ?",
(week_ago,),
)
metrics["active_users_7d"] = row[0] if row else 0
# Comparisons created in last 7 days
row = query_one(
"SELECT COUNT(*) FROM comparisons WHERE created_at >= ?",
(week_ago,),
)
metrics["comparisons_7d"] = row[0] if row else 0
# --- Date-based metrics for last 14 days ---
days = 14
today = datetime.now().date()
date_labels = [(today - timedelta(days=i)).strftime("%Y-%m-%d") for i in reversed(range(days))]
# Users registered per day
user_rows = query(
"""
SELECT DATE(created_at), COUNT(*) FROM users
WHERE created_at >= ?
GROUP BY DATE(created_at)
""",
((today - timedelta(days=days - 1)).strftime("%Y-%m-%d"),),
)
user_counts = dict(user_rows)
metrics["users_per_day"] = [user_counts.get(date, 0) for date in date_labels]
# Comparisons created per day
comp_rows = query(
"""
SELECT DATE(created_at), COUNT(*) FROM comparisons
WHERE created_at >= ?
GROUP BY DATE(created_at)
""",
((today - timedelta(days=days - 1)).strftime("%Y-%m-%d"),),
)
comp_counts = dict(comp_rows)
metrics["comparisons_per_day"] = [comp_counts.get(date, 0) for date in date_labels]
# Images uploaded per day (by image_positions join comparisons for date)
img_rows = query(
"""
SELECT DATE(c.created_at), COUNT(ip.filename)
FROM image_positions ip
JOIN comparisons c ON ip.comparison_id = c.id
WHERE c.created_at >= ?
GROUP BY DATE(c.created_at)
""",
((today - timedelta(days=days - 1)).strftime("%Y-%m-%d"),),
)
img_counts = dict(img_rows)
metrics["images_per_day"] = [img_counts.get(date, 0) for date in date_labels]
metrics["date_labels"] = date_labels
total_size = 0
if is_s3_enabled():
# For S3-backed storage, sum uploaded image sizes from metadata.
rows = query("SELECT image_size FROM image_metadata WHERE image_size IS NOT NULL")
total_size = sum(_parse_image_size_bytes(row[0]) for row in rows if row and row[0])
else:
# Total image size on disk (sum of all files in uploads/)
uploads_dir = os.getenv("UPLOADS_PATH", "uploads")
for dirpath, dirnames, filenames in os.walk(uploads_dir):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.isfile(fp):
total_size += os.path.getsize(fp)
metrics["total_images_size_bytes"] = total_size
metrics["total_images_humansize"] = format_bytes(total_size)
return metrics
def format_bytes(bytes):
if bytes < 1024:
return f"{bytes} B"
elif bytes < 1024 * 1024:
return f"{(bytes / 1024):.2f} KB"
elif bytes < 1024 * 1024 * 1024:
return f"{(bytes / (1024 * 1024)):.2f} MB"
else:
return f"{(bytes / (1024 * 1024 * 1024)):.2f} GB"
def _parse_image_size_bytes(image_size: str) -> int:
value = image_size.strip().lower()
if value.endswith("bytes"):
value = value[:-5].strip()
elif value.endswith("byte"):
value = value[:-4].strip()
elif value.endswith("b"):
value = value[:-1].strip()
try:
return int(value)
except ValueError:
return 0