File size: 1,592 Bytes
ecef9b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from datetime import datetime
from motor.motor_asyncio import AsyncIOMotorClient
from dotenv import load_dotenv

load_dotenv()

MONGODB_URI = os.getenv("MONGODB_URI")
# Connect to MongoDB
client = AsyncIOMotorClient(MONGODB_URI)
db = client.get_database() # This will use 'users' from the URI

users_collection = db.users
generations_collection = db.generations

async def log_generation(username: str, gen_type: str, duration: float = 0.0):
    """Logs a successful audio generation to MongoDB."""
    try:
        await generations_collection.insert_one({
            "username": username,
            "type": gen_type,
            "duration": duration,
            "timestamp": datetime.utcnow()
        })
    except Exception as e:
        print(f"Failed to log generation: {e}")

async def get_dashboard_stats(username: str):
    """Fetches real stats for the dashboard."""
    try:
        total_gens = await generations_collection.count_documents({"username": username})
        # Mock calculation for compute saved: 2 minutes per generation
        compute_saved_minutes = total_gens * 2
        
        hours = compute_saved_minutes // 60
        mins = compute_saved_minutes % 60
        compute_str = f"{hours}h {mins}m" if hours > 0 else f"{mins}m"
        
        return {
            "total_generations": total_gens,
            "compute_saved": compute_str
        }
    except Exception as e:
        print(f"Failed to fetch stats: {e}")
        return {"total_generations": 0, "compute_saved": "0m"}

# For backward compatibility during migration
users_db = {}