Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .agents/context/DATABASE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,30 @@ Index: `(event_id, joined_at)`, `user_id`.

---

### `usage_records`

What each event used, per UTC hour (#1166). Written in batches by `portal/usage.py`
(`UsageMeter.flush`, every 60 s, soon after a transcription worker stops, and at shutdown), never on the
live path: each flush adds to the row for its hour. `usage_metrics` (API key events) is unchanged.

| Column | Type | Notes |
|---|---|---|
| `id` | Integer PK | — |
| `event_id` | FK → events.id CASCADE | Resolved from the event id or slug the counter was recorded with |
| `room_id` | Integer nullable | Plain value, no FK, so usage outlives a removed room |
| `service` | String(20) | `transcription`, `translation`, `speech` (AI voice), `listening`, `listeners` |
| `provider` | String(32) | Engine provider; for listening, `webrtc` (WHEP audio) or `ai_translation` (`/ws/tts`) |
| `model` | String(100) | Model, or the voice for `speech`; empty for listening |
| `language_code` | String(10) | Booth language or `floor` (transcription), target language (translation, speech), channel (listening) |
| `unit` | String(16) | `seconds`, `characters` or `connections` |
| `quantity` | Float | Amount in `unit`; adds up across rows |
| `period_start` | DateTime(tz) | Start of the UTC hour |
| `updated_at` | DateTime(tz) | Last flush that added to the row |

Unique index `uq_usage_records_bucket` on `(event_id, period_start, room_id, service, provider, model, language_code)`.

---

### `booth_live_state`

What a live booth needs to survive a portal restart (TD-03). One row per booth with
Expand Down Expand Up @@ -317,6 +341,7 @@ Tracks which languages the translation worker should generate for a given room o
| 051 | `051_keep_transcripts_on_booth_delete.py` | `transcript_segments.booth_id` FK becomes `ON DELETE SET NULL`, so removing a booth keeps its transcript (#1364) |
| 052 | `052_youtube_captions_language.py` | `rooms.youtube_captions_language` — the room's YouTube CC track language (#1087, plan 006) |
| 053 | `053_add_booth_caption_seq.py` | `booths.caption_seq` durable interpreter-booth caption sequence (#1365) |
| 054 | `054_add_usage_records.py` | `usage_records` table: hourly usage per event, room, service, provider, model and language (#1166) |

Run migrations: `uv run alembic upgrade head`

Expand Down
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ jobs:
node --test tests/test_demo_modal.js
node tests/test_listener_event.js
node tests/test_whep_listener.js
node tests/test_mission_control_monitor.js
node --test tests/test_whep_lifecycle.js
node tests/test_subtitle_overlay.js
node --test tests/test_overlay_connection.js
Expand Down
3 changes: 2 additions & 1 deletion agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ VoxBento is a production-grade **browser-first interpretation booth console** fo
| `portal/outage_log.py` | `OutageLog` — reconcile loops log a repeating failure once per outage, not per tick |
| `portal/booth_recovery.py` | Saves each booth's Go Live switch and active interpreter to `booth_live_state` and restores them at startup (TD-03) |
| `portal/attendance.py` | `AttendanceTracker` — interpreter visits and interpreting time from booth state, batched writes to `interpreter_attendance` (#1215) |
| `portal/usage.py` | `UsageMeter` — transcription seconds, translated characters, AI voice seconds and listening per event, counted in memory and added to `usage_records` in batches (#1166); `ListeningSampler` reads WHEP listeners from the MediaMTX Control API and AI voice sockets |
| `portal/live_demo.py` | Home-page live demo (`/ws/demo/live`): local Whisper → NLLB → Supertonic pipeline, site + visitor glossary, admission limits, and the admin-edited `live_demo_settings` row (`/admin/live-demo/`) |
| `portal/live_demo_ai.py` | Independent live demo speech, translation and voice settings and encrypted keys; no event or room dependency |
| `portal/user_admin.py` | Administrative access rules, user flags (`can_host`, `is_admin`, `is_active`, `email_verified`) |
Expand All @@ -99,7 +100,7 @@ VoxBento is a production-grade **browser-first interpretation booth console** fo
| `portal/static/js/admin.js` | Admin panel JS helpers |
| `mediamtx.yml` | MediaMTX config — WHIP/WHEP paths, RTSP, Control API, `overridePublisher` |
| `docker-compose.yml` | portal + mediamtx + jitsi-web/prosody/jicofo/jvb |
| `alembic/versions/` | 53 migrations (001–053); run `uv run alembic upgrade head` |
| `alembic/versions/` | 54 migrations (001–054); run `uv run alembic upgrade head` |

---

Expand Down
47 changes: 47 additions & 0 deletions alembic/versions/054_add_usage_records.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""add usage records
Hourly totals of what each event used (#1166): seconds of audio transcribed, characters
translated, seconds of AI voice made, and listening time and connections per channel.
Revision ID: 054
Revises: 053
"""

from __future__ import annotations

import sqlalchemy as sa

from alembic import op

revision = "054"
down_revision = "053"
branch_labels = None
depends_on = None


def upgrade() -> None:
op.create_table(
"usage_records",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("event_id", sa.Integer(), sa.ForeignKey("events.id", ondelete="CASCADE"), nullable=False),
sa.Column("room_id", sa.Integer(), nullable=True),
sa.Column("service", sa.String(length=20), nullable=False),
sa.Column("provider", sa.String(length=32), nullable=False),
sa.Column("model", sa.String(length=100), nullable=False),
sa.Column("language_code", sa.String(length=10), nullable=False),
sa.Column("unit", sa.String(length=16), nullable=False),
sa.Column("quantity", sa.Float(), nullable=False),
sa.Column("period_start", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
)
op.create_index(
"uq_usage_records_bucket",
"usage_records",
["event_id", "period_start", "room_id", "service", "provider", "model", "language_code"],
Comment on lines +38 to +40

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

room_id is nullable, and a standard unique index treats NULL != NULL in both PostgreSQL and SQLite, so overlapping flushes for roomless usage can insert duplicate rows.

unique=True,
Comment thread
shashank03-dev marked this conversation as resolved.
Resolved
)


def downgrade() -> None:
op.drop_index("uq_usage_records_bucket", table_name="usage_records")
op.drop_table("usage_records")
15 changes: 13 additions & 2 deletions fastapi_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from starlette.middleware.base import BaseHTTPMiddleware
from unilimit.integrations.fastapi import RateLimitExceeded, setup

from portal import meeting_source, program_ingest, youtube_caption_sync
from portal import meeting_source, program_ingest, usage, youtube_caption_sync
from portal.auth import (
ADMIN_CSRF_COOKIE,
generate_admin_csrf_token,
Expand Down Expand Up @@ -113,6 +113,8 @@ async def _gen():
ingest_task = asyncio.create_task(program_ingest.reconcile_loop()) if settings.program_ingest_enabled else None
meeting_task = asyncio.create_task(meeting_source.reconcile_loop())
attendance_task = asyncio.create_task(booths.attendance.run())
usage_task = asyncio.create_task(usage.meter.run())
listening_task = asyncio.create_task(usage.ListeningSampler(usage.meter).run())
# Restores saved YouTube caption choices after a restart and keeps them in step (#1087, plan 006).
captions_task = (
asyncio.create_task(youtube_caption_sync.reconcile_loop()) if settings.youtube_connect_enabled else None
Expand All @@ -135,7 +137,16 @@ async def _gen():
logging.getLogger("uvicorn.access").addFilter(_HealthCheckFilter())
yield

tasks_to_cancel = [reaper_task, webhook_task, notification_task, rate_limit_cleanup_task, meeting_task, attendance_task]
tasks_to_cancel = [
reaper_task,
webhook_task,
notification_task,
rate_limit_cleanup_task,
meeting_task,
attendance_task,
usage_task,
Comment thread
shashank03-dev marked this conversation as resolved.
Resolved
Comment thread
shashank03-dev marked this conversation as resolved.
Resolved
listening_task,
]
if ingest_task:
tasks_to_cancel.append(ingest_task)
if recovery_task:
Expand Down
41 changes: 41 additions & 0 deletions portal/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,47 @@ def __repr__(self) -> str:
return f"<UsageMetric event={self.event_id} metric={self.metric_name!r} value={self.value}>"


class UsageRecord(Base):
"""How much of one service an event used in one hour (#1166).

Written in batches by ``portal.usage`` (never on the live path): each save adds to the
row for its hour, room, service, provider, model and language. ``quantity`` is in
``unit`` (seconds, characters or connections), so rows of one service add up.
"""

__tablename__ = "usage_records"
__table_args__ = (
Index(
"uq_usage_records_bucket",
"event_id",
"period_start",
"room_id",
"service",
"provider",
"model",
"language_code",
unique=True,
),
)

id: Mapped[int] = mapped_column(primary_key=True)
event_id: Mapped[int] = mapped_column(ForeignKey("events.id", ondelete="CASCADE"))
# A plain value, not a foreign key: usage stays after a room is removed.
room_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
service: Mapped[str] = mapped_column(String(20))
provider: Mapped[str] = mapped_column(String(32), default="")
model: Mapped[str] = mapped_column(String(100), default="")
language_code: Mapped[str] = mapped_column(String(10), default="")
unit: Mapped[str] = mapped_column(String(16))
quantity: Mapped[float] = mapped_column(sa.Float, default=0.0)
# Start of the UTC hour the usage happened in.
period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now)

def __repr__(self) -> str:
return f"<UsageRecord event={self.event_id} service={self.service!r} quantity={self.quantity}>"


# ---------------------------------------------------------------------------
# Interpreter attendance (#1215)
# ---------------------------------------------------------------------------
Expand Down
8 changes: 5 additions & 3 deletions portal/routers/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from portal.program_relay import RTMPS_MODES
from portal.roles import INTERPRETER, ROLE_RANK, can_go_live, can_set_active, highest_role, role_label
from portal.room_setup import AUDIO_DESK, AUDIO_ENCODER, AUDIO_MEETING, floor_feed_choice
from portal.usage import MONITOR_QUERY
from portal.user_menu import resolve_user_menu, user_menu_context
from portal.utils import _ensure_mediamtx_path, _make_jitsi_url, safe_redirect

Expand Down Expand Up @@ -208,7 +209,8 @@ async def interpreter_booth_by_identity(
display_language = language or language_code.upper()
await _ensure_mediamtx_path(channel_id)
whip_url = f"{settings.mediamtx_whip_base}/{mediamtx_path}/whip"
whep_url = f"{settings.mediamtx_whip_base}/{mediamtx_path}/whep"
# Staff players are marked so listening time leaves them out (#1166).
whep_url = f"{settings.mediamtx_whip_base}/{mediamtx_path}/whep?{MONITOR_QUERY}"
floor_path = make_mediamtx_path(event_slug, room_id, "floor")
floor_hls_url = None
offer_floor = False
Expand Down Expand Up @@ -251,7 +253,7 @@ async def interpreter_booth_by_identity(
relay_b = await get_booth_by_id(session, db_booth.room.relay_booth_id)
if relay_b:
relay_channel = make_mediamtx_path(event_slug, relay_b.room_id, relay_b.language_code)
relay_whep_url = f"{settings.mediamtx_whip_base}/{relay_channel}/whep"
relay_whep_url = f"{settings.mediamtx_whip_base}/{relay_channel}/whep?{MONITOR_QUERY}"
relay_language_name = relay_b.language_name
default_jitsi_url = _make_jitsi_url(settings.effective_jitsi_base_url, settings.default_jitsi_room)
final_jitsi_url = room_jitsi_url or default_jitsi_url
Expand All @@ -276,7 +278,7 @@ async def interpreter_booth_by_identity(
"whep_url": whep_url,
"floor_label": floor_label,
"floor_hls_url": floor_hls_url,
"floor_whep_url": f"{settings.mediamtx_whip_base}/{floor_path}/whep",
"floor_whep_url": f"{settings.mediamtx_whip_base}/{floor_path}/whep?{MONITOR_QUERY}",
"offer_floor": offer_floor,
"offer_meeting": meeting_monitor_enabled and bool(final_jitsi_url),
"relay_whep_url": relay_whep_url,
Expand Down
3 changes: 2 additions & 1 deletion portal/static/js/mission-control.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,8 @@ function handleVolumeChange(boothId, volume) {
const vol = parseInt(volume, 10);

if (vol > 0 && !entry.whep) {
const whepUrl = `${config.whipBase}/${entry.state.mediamtx_path}/whep`;
// Marked as staff monitoring so the event's listening time leaves it out (#1166).
const whepUrl = `${config.whipBase}/${entry.state.mediamtx_path}/whep?monitor=1`;
const whep = window.createWhepClient();
whep.start({ whepUrl, audioEl: entry.audioElement });
entry.whep = whep;
Expand Down
15 changes: 15 additions & 0 deletions portal/transcription/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Dict

import portal.webhooks.worker as _wh_worker
from portal import usage
from portal.config import settings
from portal.transcription.process import FfmpegProcess
from portal.transcription.providers.atlascloud import AtlasCloudProvider
Expand Down Expand Up @@ -112,6 +113,18 @@ async def wait_until_stopped(self):
except Exception as e:
logger.error(f"[{self.booth_id}][{self.session_id}] Task ended with exception: {e}")

def _count_audio(self, seconds: float) -> None:
usage.record(
usage.TRANSCRIPTION,
seconds,
event_slug=self.event_slug,
room_id=self.room_id,
# The provider that actually runs: an unknown name falls back to local Whisper.
provider=self.provider_name if self.provider_name in PROVIDERS else "local",
model=self.model_size,
language_code=self.language_code,
)

async def _run_loop(self):
"""Run provider retries, audio capture, and webhook/model cleanup on exit."""
self.loop_entered = True
Expand All @@ -131,6 +144,7 @@ async def _run_loop(self):
# The context manager entirely encapsulates ffmpeg process lifecycle and cleanup.
async with FfmpegProcess(self.rtsp_url, self.sample_rate, self.booth_id) as process:
self.ready.set()
process = usage.MeteredProcess(process, self.provider.sample_rate, self._count_audio)
try:
actual_language = self.transcription_language or self.language_code
if actual_language == "floor":
Expand Down Expand Up @@ -204,6 +218,7 @@ async def notify_gap(start: float, end: float):
from portal.transcription.providers.local import decrement_model_ref

decrement_model_ref(self.model_size)
usage.meter.request_flush()
logger.info(f"[{self.booth_id}][{self.session_id}] Transcription worker exited and cleaned up cleanly.")


Expand Down
Loading