Files
sound-analyze/services/api/app/services/stats_service.py
Iwwww 1b864228d4 feat(api): add backend
routes and WebSockets
2025-12-26 19:26:06 +03:00

36 lines
1.1 KiB
Python

from datetime import datetime, timedelta
from app.repositories.audio_repository import AudioRepository
from app.schemas.stats import StatsSummary
_PERIODS = {
"10s": timedelta(seconds=10),
"1m": timedelta(minutes=1),
"1h": timedelta(hours=1),
"6h": timedelta(hours=6),
"24h": timedelta(hours=24),
"7d": timedelta(days=7),
"30d": timedelta(days=30),
}
class StatsService:
def __init__(self, repo: AudioRepository):
self.repo = repo
async def summary(self, period: str) -> StatsSummary:
if period not in _PERIODS:
raise ValueError(f"Unsupported period: {period}")
since = datetime.utcnow() - _PERIODS[period]
raw = await self.repo.summary_since(since)
total = raw["total_count"]
silence_percent = (raw["silence_count"] / total * 100.0) if total else 0.0
return StatsSummary(
avg_db=round(raw["avg_db"], 2),
max_db=round(raw["max_db"], 2),
dominant_freq=raw["dominant_freq"],
silence_percent=round(silence_percent, 2),
)