S2S / backend /database.py
Krishnakkp's picture
feat: initial deployment to HF spaces
ecef9b0
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 = {}