""" Modal deployment for NarratifAI ASR backend. Deploy: modal deploy modal_app.py Pre-warm model cache (run once after first deploy): modal run modal_app.py::download_models """ import modal # ── App ──────────────────────────────────────────────────────────────────────── app = modal.App("narratifai-asr") # ── Container image ──────────────────────────────────────────────────────────── # Use CUDA 12.1 base so pyannote.audio and speechbrain can find system CUDA libs # (debian_slim lacks libcudart.so.* which pyannote links against at runtime). # torch + torchaudio are installed first from the PyTorch CUDA 12.1 wheel index # so they include GPU kernels; requirements.txt is installed on top (pip skips # packages already satisfied). image = ( modal.Image.from_registry( "nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04", add_python="3.11", ) .apt_install(["ffmpeg", "libsndfile1", "build-essential", "git"]) .pip_install( ["torch==2.5.1", "torchaudio==2.5.1"], extra_index_url="https://download.pytorch.org/whl/cu121", ) .pip_install_from_requirements("requirements.txt") .add_local_dir("src", "/app/src", copy=True) .add_local_dir("config", "/app/config", copy=True) .add_local_file("app.py", "/app/app.py", copy=True) .env( { "MPLBACKEND": "Agg", "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", "HF_HOME": "/cache/huggingface", "GRADIO_ANALYTICS_ENABLED": "false", "CONFIG_PATH": "/app/config/settings.yaml", "PYTHONPATH": "/app", # Public URL used by the keep-alive ping in app.py. "SELF_URL": "https://consulawtech--narratifai-asr-web-app.modal.run", } ) ) # ── Persistent volume — model weights survive container restarts ─────────────── model_cache = modal.Volume.from_name("narratifai-model-cache", create_if_missing=True) # ── Secrets — set via: modal secret create narratifai-secrets HF_TOKEN=... ────── # consulmeet-notetaker-secret is a separate secret (not folded into # narratifai-secrets) so rotating/managing it never risks touching the # existing HF_TOKEN/ANTHROPIC_API_KEY/Supabase keys already stored there. secrets = [ modal.Secret.from_name("narratifai-secrets"), # Paystack secret key, kept separate so it can be rotated without # touching the other keys (scripts/set_paystack_key.sh creates it). modal.Secret.from_name("narratifai-paystack"), # Google Play Developer API access (OAuth refresh token) for Android credit # purchases; ~/NarratifAI/scripts/setup_ops_and_play.sh fills it in. modal.Secret.from_name("narratifai-google-play"), modal.Secret.from_name("consulmeet-notetaker-secret"), ] # ── Web endpoint (FastAPI ASGI) ──────────────────────────────────────────────── @app.function( image=image, gpu="A10G", # ~$1.10/hr billed per-second, scales to 0 when idle secrets=secrets, volumes={"/cache/huggingface": model_cache}, timeout=3600, # 60 min — accommodates long meetings + diarization + Claude # Was 3600 so a job didn't die when the phone stopped polling. app.py now # pings itself while jobs run, so the container only needs to stay warm # briefly between back-to-back jobs (idle GPU time is the main cost). scaledown_window=900, # Was 1 (single container) when usage was occasional/manual. Raised for # ConsulMeet's automated notetaker, which can have multiple concurrent # meetings transcribing at once. Safe across containers because # _upsert_job/_get_job already fall back to Supabase when a poll for # progress/result lands on a different container than the one running # the job — not relying on the in-memory cache being shared. max_containers=5, ) @modal.asgi_app() def web_app(): import os os.chdir("/app") from app import app as fastapi_app # noqa: PLC0415 return fastapi_app # ── Pre-warm utility — run once to cache models into the volume ─────────────── @app.function( image=image, gpu="A10G", secrets=secrets, volumes={"/cache/huggingface": model_cache}, timeout=1800, ) def download_models(): """Download Whisper models and pyannote into the persistent volume.""" import os os.environ["HF_HOME"] = "/cache/huggingface" from transformers import pipeline as hf_pipeline models_to_cache = [ "openai/whisper-tiny", "openai/whisper-small", "openai/whisper-medium", "openai/whisper-large-v3", ] for model_id in models_to_cache: print(f"Caching {model_id}...") hf_pipeline("automatic-speech-recognition", model=model_id) print(f" ✓ {model_id}") # Cache pyannote diarization model (requires HF_TOKEN with accepted terms) hf_token = os.getenv("HF_TOKEN") if hf_token: try: from pyannote.audio import Pipeline as PyannotePipeline PyannotePipeline.from_pretrained( "pyannote/speaker-diarization-3.1", use_auth_token=hf_token, ) print(" ✓ pyannote/speaker-diarization-3.1") except Exception as e: print(f" ✗ pyannote cache failed (check HF token terms): {e}") model_cache.commit() print("\nAll models cached into volume.")