File size: 5,822 Bytes
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e3b725
04684e6
 
 
 
 
 
 
 
 
1e3b725
04684e6
 
 
 
1e3b725
 
04684e6
 
 
 
 
 
 
 
1e3b725
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
1e3b725
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""
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.")