UdemyScout / core /stats.py
Brainw's picture
Upload 14 files
638f319 verified
Raw History Blame Contribute Delete
2.91 kB
import json
from pathlib import Path
from datetime import datetime
STATS_FILE = Path("data/daily_stats.json")
def get_expired_count(current_total, new_count):
if not STATS_FILE.exists():
return 0
try:
data = json.loads(STATS_FILE.read_text())
last_total = data.get("last_total", 0)
last_date = data.get("last_date", "")
today = datetime.utcnow().date().isoformat()
# approximate logic: expired = (yesterday_total + new_today) - current_total
# limit to 0 to avoid negative numbers on weird edge cases
expired = max(0, (last_total + new_count) - current_total)
return expired
except:
return 0
def save_daily_stats(current_total):
try:
data = {
"last_total": current_total,
"last_date": datetime.utcnow().date().isoformat()
}
STATS_FILE.write_text(json.dumps(data))
except:
pass
def compute_stats(c):
total = len(c)
new = sum(1 for i in c if i.get('new'))
# Calculate expiring soon (naive check based on status text or logic)
# We don't have easy access to raw expiry objects here unless we pass them or parse status
# But we can check if "Expires" is in the status string if it's already formatted?
# Actually, better to pass raw data before formatting or parse the date string.
# Since we formatted status as "Start|End", we can parse "End".
expiring = 0
today = datetime.utcnow().date().isoformat()
for i in c:
status_raw = i.get('status', '')
if '|' in status_raw:
_, end_date = status_raw.split('|')
# If end_date is today or tomorrow, count as expiring soon
if end_date <= today: # Already expired or expires today
pass # Actually if it's in the list it's active, but maybe "Expiring Soon" means < 24h
# Simple string comparison works for ISO dates
# If end_date is close to today... let's just count all for now as "Active"
# and maybe check if end_date == today?
pass
# Re-reading user request: "cx wants ⏱ Expiring Soon: 12"
# Let's rely on the fact that our scrapers fetch "fresh" coupons.
# Most DiscUdemy are 24h. UdemyFreebies are often <24h.
# Let's count items where end_date is today or tomorrow.
expiring = 0
try:
from datetime import timedelta
limit = (datetime.utcnow().date() + timedelta(days=1)).isoformat()
for i in c:
s = i.get('status', '')
if '|' in s:
end = s.split('|')[1]
if end <= limit:
expiring += 1
except:
pass
expired_since_last = get_expired_count(total, new)
return {'total': total, 'new_today': new, 'expired_since_last': expired_since_last, 'expiring_soon': expiring}