NarratifAI / app.py
NarratifAI deploy
Deploy asr_system 21d00fa
0ecbbcf
Raw History Blame Contribute Delete
125 kB
""" Main application entry point for Hugging Face Space Author: Maaldeens License: MIT """ import asyncio import hashlib import hmac import io import json import os import threading import time import uuid import argparse import logging import warnings from concurrent.futures import ThreadPoolExecutor from typing import Optional import uvicorn from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException from fastapi.responses import JSONResponse, Response from fastapi.middleware.cors import CORSMiddleware # pyannote.audio calls torchaudio.set_audio_backend() which is a no-op in # torchaudio 2.x (dispatcher always enabled). Suppress the UserWarning it emits. warnings.filterwarnings( "ignore", message="torchaudio._backend.set_audio_backend has been deprecated", category=UserWarning, ) try: import requests as _requests _requests_available = True except ImportError: _requests_available = False # ZeroGPU support β€” only activate on ZeroGPU Spaces. # SPACES_ZERO_GPU=1 is set exclusively by HF's ZeroGPU infrastructure. # SPACE_ID is present on ALL HF Spaces (including T4/A10G paid tiers) and # is therefore NOT a reliable gate; use SPACES_ZERO_GPU instead. try: import spaces as _spaces _HF_ZERO_GPU = os.getenv("SPACES_ZERO_GPU") == "1" except ImportError: _spaces = None _HF_ZERO_GPU = False _executor = ThreadPoolExecutor(max_workers=2) # All compute and job routes require a verified Firebase user. Integrations # must obtain their own service account's Firebase ID token; shared keys do # not grant user impersonation or bypass billing. _MAX_AUDIO_SECONDS = 2 * 60 * 60 _MAX_UPLOAD_BYTES = 256 * 1024 * 1024 _WORK_SLOTS = threading.BoundedSemaphore(8) # ── Supabase persistent job storage ────────────────────────────────────────── _SUPABASE_URL = os.getenv("SUPABASE_URL", "") _SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "") def _sb_headers() -> dict: return { "apikey": _SUPABASE_KEY, "Authorization": f"Bearer {_SUPABASE_KEY}", "Content-Type": "application/json", "Prefer": "return=representation", } def _supabase_request(method: str, path: str, payload=None, params=None) -> Optional[dict]: """Make a request to Supabase REST API using requests library.""" if not _requests_available: return None if not _SUPABASE_URL or not _SUPABASE_KEY: return None url = f"{_SUPABASE_URL}{path}" headers = _sb_headers() if method in ("POST", "PUT", "PATCH") and payload is not None: headers["Prefer"] = "return=representation,resolution=merge-duplicates" try: resp = _requests.request( method, url, params=params, json=payload, headers=headers, timeout=10, ) if resp.status_code >= 400: logger.warning(f"Supabase {method} {path} HTTP {resp.status_code}") return None return resp.json() if resp.text else {} except Exception as e: logger.warning(f"Supabase {method} {path} failed: {type(e).__name__}") return None def _upsert_job( job_id: str, status: str, result: Optional[dict] = None, progress: Optional[dict] = None, detail: Optional[str] = None, submitted_at: Optional[float] = None, firebase_uid: Optional[str] = None, ): """Update an existing owner-bound job. Storage failures are explicit.""" payload = { "job_id": job_id, "status": status, } if result is not None: payload["result"] = result if progress is not None: payload["progress"] = progress if detail is not None: payload["detail"] = detail if submitted_at is not None: payload["submitted_at"] = submitted_at if firebase_uid: payload["firebase_uid"] = firebase_uid if not _SUPABASE_URL or not _SUPABASE_KEY: raise RuntimeError("Job storage is not configured") # Creation happens insert-only in reserve_processing; progress cannot # accidentally create jobs or replace their owners. payload.pop("job_id", None) resp = _supabase_request("PATCH", "/rest/v1/transcription_jobs", payload=payload, params={"job_id": f"eq.{job_id}"}) if not resp: raise RuntimeError("Job storage unavailable") def _get_job(job_id: str) -> Optional[dict]: """Read authoritative job state and ownership from Supabase.""" rows = _supabase_request( "GET", "/rest/v1/transcription_jobs", params={"job_id": f"eq.{job_id}", "limit": "1"}, ) if rows is None: raise HTTPException(status_code=503, detail="Job storage unavailable") if rows and isinstance(rows, list) and len(rows) > 0: row = rows[0] return row return None def _delete_job(job_id: str): """Remove job from local cache and Supabase.""" _supabase_request( "DELETE", "/rest/v1/transcription_jobs", params={"job_id": f"eq.{job_id}"}, ) try: import anthropic as _anthropic _anthropic_available = True except ImportError: _anthropic_available = False # Languages where smaller Whisper models perform poorly. # medium has almost no Yoruba/Igbo/Hausa training data β€” large-v3 is # the minimum model where these languages plus English code-switching # produce usable results. _UPGRADE_LANGUAGES = {"yo", "ig", "ha"} _UPGRADE_TARGET = "whisper-large-v3" # Short generic language hints for code-switching audio. # We deliberately avoid full sentences β€” Whisper can hallucinate them # when uncertain, causing cascading repetition loops across chunks. _LANGUAGE_PROMPTS = { "yo": "Yoruba and English, proper tone marks.", "ig": "Igbo and English, proper diacritics.", "ha": "Hausa and English, proper tone marks.", } from src.transcription.engine import TranscriptionEngine, NATIVE_MODELS, native_asr_enabled from src.output.formatter import OutputFormatter from src import ai_cost as _ai_cost # Setup logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # Initialize FastAPI app app = FastAPI( title="Modular ASR System", description="Upgradable speech-to-text transcription system", version="1.0.0" ) from src.security import RequestAdmission app.add_middleware(RequestAdmission, authorize=lambda request: _require_uid(request), max_upload_bytes=_MAX_UPLOAD_BYTES) # Add CORS middleware β€” origins configurable via env var # Default allows all origins WITHOUT credentials (browser-safe default). # For production, set CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com _cors_origins = [o.strip() for o in os.getenv("CORS_ORIGINS", "*").split(",")] _allow_credentials = os.getenv("CORS_ALLOW_CREDENTIALS", "false").lower() == "true" app.add_middleware( CORSMiddleware, allow_origins=_cors_origins, allow_credentials=_allow_credentials, allow_methods=["*"], allow_headers=["*"], ) # Initialize transcription engine engine = None @app.on_event("startup") async def startup_event(): global engine config_path = os.getenv("CONFIG_PATH", "config/settings.yaml") engine = TranscriptionEngine(config_path) logger.info(f"Transcription engine initialized with model: {engine.current_model_key}") # Google Play refunds take their credits back (every 6 hours; idempotent). asyncio.create_task(_google_voided_loop()) asyncio.create_task(_reap_orphans_after_restart()) # Nari voice (only where its secret is set, i.e. staging): load the voice # model now so the first spoken question doesn't wait for it. if os.getenv("NARI_VOICE_SECRET"): async def _preload_voice(): try: from src import voice as _voice await asyncio.to_thread(_voice.fast_pipeline) logger.info(f"Nari voice model ready: {_voice.FAST_MODEL}") except Exception as e: logger.warning(f"Nari voice model not preloaded: {e}") asyncio.create_task(_preload_voice()) # Diarization availability diagnostic β€” visible in HF Space logs hf_token_set = bool(os.getenv("HF_TOKEN")) if engine.diarization.is_available(): logger.info("Speaker diarization: AVAILABLE (pyannote importable + HF_TOKEN set)") # Pre-load the pyannote pipeline in the background so the first # transcription request doesn't stall waiting for the ~1 GB model download. async def _preload_pyannote(): try: logger.info("Pre-loading pyannote diarization pipeline in background…") await asyncio.to_thread(engine.diarization._load_pipeline) logger.info("Pyannote diarization pipeline pre-loaded successfully.") except Exception as exc: logger.warning(f"Pyannote pipeline pre-load failed (will retry on first use): {type(exc).__name__}") asyncio.create_task(_preload_pyannote()) else: try: from src.diarization.engine import _PYANNOTE_AVAILABLE as _pyannote_ok except Exception: _pyannote_ok = False logger.warning( "Speaker diarization: UNAVAILABLE β€” " f"pyannote_importable={_pyannote_ok}, hf_token_set={hf_token_set}. " "Set HF_TOKEN in Space secrets and ensure pyannote/speaker-diarization-3.1 " "is accessible on HuggingFace." ) # Verify Supabase connectivity on startup if _SUPABASE_URL and _SUPABASE_KEY: test_resp = _supabase_request( "GET", "/rest/v1/transcription_jobs", params={"limit": "1"} ) if test_resp is not None: logger.info(f"Supabase connection OK: {_SUPABASE_URL}") else: logger.warning(f"Supabase connection FAILED: {_SUPABASE_URL}") else: logger.warning("Supabase not configured β€” job results will NOT persist across restarts") @app.get("/") async def root(): return { "name": "Modular ASR System", "version": "1.0.0", "owner": "Maaldeens", "license": "MIT", "status": "operational", "available_models": list(engine.get_available_models().keys()) if engine else [], "current_model": engine.current_model_key if engine else None } @app.get("/models") async def list_models(): if not engine: raise HTTPException(status_code=503, detail="Engine not initialized") return { "available_models": engine.get_available_models(), "current_model": engine.current_model_key } @app.get("/diarization-status") async def diarization_status_endpoint(): """Diagnostic endpoint β€” shows why diarization is or isn't available.""" # Run the import directly to capture the real exception (not a cached flag) pyannote_importable = False pyannote_error = "" try: import pyannote.audio as _pa # noqa: F401 pyannote_importable = True except Exception as e: pyannote_error = f"{type(e).__name__}: {e}" hf_token_set = bool(os.getenv("HF_TOKEN")) available = engine.diarization.is_available() if engine else False reason = None if not available: if not pyannote_importable: reason = pyannote_error or "pyannote.audio failed to import" elif not hf_token_set: reason = "HF_TOKEN is not set β€” add it to HuggingFace Space secrets" else: reason = "unknown" return { "available": available, "pyannote_importable": pyannote_importable, "hf_token_set": hf_token_set, "reason": reason, } # ── Cancellation ────────────────────────────────────────────────────────────── # A user can cancel a job from the app. The flag lives in Supabase (status # "cancelled") because on Modal the cancel request can land on a different # container than the one running the job; _CANCELLED is the same-container # fast path. The running job checks between 5-minute blocks. _CANCELLED: set = set() # Job rows hold finished transcripts so the app can collect them; they are # not kept beyond JOB_RETENTION_DAYS (stated in the privacy policy). JOB_RETENTION_DAYS = 7 _last_purge = 0.0 def _purge_old_jobs() -> None: global _last_purge now = time.time() if now - _last_purge < 3600: return _last_purge = now cutoff = now - JOB_RETENTION_DAYS * 86400 def run(): if _SUPABASE_URL and _SUPABASE_KEY and _requests_available: try: for when in (f"lt.{cutoff}", "is.null"): # null: rows from before timestamps were stored response = _requests.delete(f"{_SUPABASE_URL}/rest/v1/transcription_jobs", params={"submitted_at": when}, headers=_sb_headers(), timeout=15) response.raise_for_status() except Exception as e: logger.warning(f"Job purge failed: {type(e).__name__}") threading.Thread(target=run, daemon=True).start() class _JobCancelled(Exception): pass def _is_cancelled(job_id: str) -> bool: if job_id in _CANCELLED: return True # Cancellation is shared by all workers/containers through Supabase. rows = _supabase_request( "GET", "/rest/v1/transcription_jobs", params={"job_id": f"eq.{job_id}", "select": "status", "limit": "1"}, ) if rows and isinstance(rows, list) and rows and rows[0].get("status") == "cancelled": _CANCELLED.add(job_id) return True return False _HALLUCINATION_PATTERNS = [ "thank you for watching", "thanks for watching", "see you in the next video", "don't forget to subscribe", "like and subscribe", "see you next time", "thanks for listening", "please subscribe", ] def _is_likely_hallucination(text: str) -> bool: lower = text.lower() return any(p in lower for p in _HALLUCINATION_PATTERNS) def _is_repetition_loop(text: str) -> bool: t = text.strip() if len(t) < 20: return False # 1) Single-character dominance (e.g. "GGGGG" or "-------") most_common_count = max(t.count(c) for c in set(t)) if most_common_count / len(t) > 0.70: return True # 2) Short-phrase repetition (e.g. "thanks for watching" repeated) probe = t[:15] if t.count(probe) > max(5, len(t) // 50): return True # 3) Alternating short-token repetition (e.g. "G-G-G-G" or "I'm I'm I'm") tokens = t.split() if len(tokens) >= 8: for window in (2, 3, 4): pattern = tuple(tokens[:window]) repeats = 0 for i in range(0, len(tokens) - window + 1, window): if tuple(tokens[i:i + window]) == pattern: repeats += window if repeats / len(tokens) > 0.60: return True # 4) Sentence-level repetition β€” Whisper often hallucinates the same # stock sentences (e.g. Yoruba/English phrases, "thanks for watching") # repeatedly on music or noisy audio. import re sentences = [s.strip() for s in re.split(r"[.!?]+", t) if len(s.strip()) > 8] if len(sentences) >= 6: from collections import Counter counts = Counter(sentences) most_common_count = counts.most_common(1)[0][1] if most_common_count >= 4: return True unique_ratio = len(counts) / len(sentences) if unique_ratio < 0.35: return True # 5) Single-character stutter with separators: "Z, Z, Z, Z" or "G-G-G-G" # Extract alphabetic chars and check for dominance of one letter. alpha_only = re.sub(r"[^a-zA-Z]", "", t) if len(alpha_only) > 20: from collections import Counter c = Counter(alpha_only.lower()) if c.most_common(1)[0][1] / len(alpha_only) > 0.60: return True return False _BATCH_SIZE = 30 def _generate_minutes_with_claude( segments: list, speaker_names: dict, session_name: str ) -> dict: """Summarise a transcript into structured meeting minutes using Claude.""" api_key = os.getenv("ANTHROPIC_API_KEY") if not api_key or not _anthropic_available: return {"summary": "", "topics": [], "decisions": [], "action_items": []} lines = [] for seg in segments: spk = seg.get("speaker") name = speaker_names.get(spk, spk) if spk else "Speaker" text = seg.get("text", "").strip() if text: lines.append(f"{name}: {text}") transcript_text = "\n".join(lines) if not transcript_text: return {"summary": "", "topics": [], "decisions": [], "action_items": []} client = _ai_cost.metered(_anthropic.Anthropic(api_key=api_key)) system = ( "You are a professional meeting minutes writer. " "Given a meeting transcript, return ONLY valid JSON with exactly these keys:\n" "summary (string, 2-3 sentence overview), " "topics (array of strings, key discussion points, max 8), " "decisions (array of strings, decisions made, empty if none), " "action_items (array of strings, format 'Owner: task' where owner is known, empty if none). " "Be concise and factual. Only include what was explicitly discussed. No markdown fences." ) try: msg = client.messages.create( model=MINUTES_MODEL, max_tokens=1024, system=system, messages=[{ "role": "user", "content": f"Meeting: {session_name}\n\nTranscript:\n{transcript_text[:40000]}", }], ) response_text = msg.content[0].text.strip() # Strip markdown fences if model adds them despite instructions if response_text.startswith("```"): parts = response_text.split("```") response_text = parts[1].lstrip("json").strip() if len(parts) > 1 else response_text parsed = json.loads(response_text) return { "summary": parsed.get("summary", ""), "topics": parsed.get("topics", []), "decisions": parsed.get("decisions", []), "action_items": parsed.get("action_items", []), } except Exception as e: logger.warning(f"Minutes generation failed: {type(e).__name__}") return {"summary": "", "topics": [], "decisions": [], "action_items": []} def _get_speaker_sentiments(segments: list, speaker_names: dict) -> dict: """Return per-speaker tone label using one Claude call.""" api_key = os.getenv("ANTHROPIC_API_KEY") if not api_key or not _anthropic_available: return {} speaker_texts: dict[str, list[str]] = {} for seg in segments: spk = seg.get("speaker") if not spk: continue text = seg.get("text", "").strip() if text: speaker_texts.setdefault(spk, []).append(text) if not speaker_texts: return {} client = _ai_cost.metered(_anthropic.Anthropic(api_key=api_key)) summaries = [] for spk_id, texts in speaker_texts.items(): name = speaker_names.get(spk_id, spk_id) combined = " ".join(texts[:60])[:2000] summaries.append(f"{spk_id} ({name}): {combined}") system = ( "Analyse the overall tone of each speaker in this meeting excerpt. " "For each speaker ID return exactly one label from: calm, neutral, tense, enthusiastic, concerned. " "Return ONLY valid JSON: {\"SPEAKER_00\": \"calm\", ...}. No markdown fences." ) try: msg = client.messages.create( model="claude-haiku-4-5-20251001", max_tokens=256, system=system, messages=[{"role": "user", "content": "\n\n".join(summaries)}], ) response_text = msg.content[0].text.strip() if response_text.startswith("```"): parts = response_text.split("```") response_text = parts[1].lstrip("json").strip() if len(parts) > 1 else response_text return json.loads(response_text) except Exception as e: logger.warning(f"Sentiment analysis failed: {type(e).__name__}") return {} def _adds_words(original: str, corrected: str) -> bool: """True when a correction is clearly longer than the line it corrects.""" before, after = len(original.split()), len(corrected.split()) return after > before + max(3, before // 4) def _enhance_segments_with_claude(segments: list, language: str) -> list: segments = [s for s in segments if not _is_likely_hallucination(s.get("text", ""))] api_key = os.getenv("ANTHROPIC_API_KEY") if not api_key or not _anthropic_available: return segments client = _ai_cost.metered(_anthropic.Anthropic(api_key=api_key)) lang_desc = { "yo": "Yoruba-English code-switching", "ig": "Igbo-English code-switching", "ha": "Hausa-English code-switching", }.get(language, language or "en") if language and "," in language: # A meeting that switches language: each segment stays in its own. lang_desc = ("a meeting that switches between " + ", ".join(language.split(",")) + "; keep every segment in the language it was spoken in") # Only changed segments come back: echoing every unchanged line made # output tokens (5x the price of input on Haiku) the largest per-minute # cost of a transcription. Segments left out keep their original text. system = ( "You are a transcription corrector. Given numbered segments, fix ASR " "errors (misheard words, wrong names, broken punctuation). " "Mark a segment HALLUCINATED (exactly) only if it is a stock phrase Whisper " "invents on silence or noise: video outros and subtitle credits such as " "'Thank you for watching', 'See you in the next video', 'Don't forget to " "subscribe', 'Subtitles by ...'. Never mark a segment HALLUCINATED because " "it is unusual, off-topic, technical, full of unfamiliar names, or in a " "different language from the rest: meetings switch topic and language. " "Never translate. Never add new sentences. Each segment is its own stretch " "of time: never move words from one segment into another, even to finish a " "sentence that continues on the next line. Preserve code-switching exactly. " "Output ONLY the segments you changed or marked, one per line, format: " "[N] corrected text (or [N] HALLUCINATED). If nothing needs changing, " "output exactly: NONE" ) def _process(batch: list) -> list: out: list = [] numbered = "\n".join( f"[{i}] {seg.get('text', '').strip()}" for i, seg in enumerate(batch) if seg.get("text", "").strip() ) if not numbered: return out try: msg = client.messages.create( model="claude-haiku-4-5-20251001", max_tokens=4096, system=system, messages=[{ "role": "user", "content": ( f"Language: {lang_desc}\n\n" f"Segments:\n{numbered}" ), }], ) try: logger.info(f"Claude cleanup batch: {len(batch)} segments, " f"in={msg.usage.input_tokens} out={msg.usage.output_tokens}") except Exception: pass response_text = msg.content[0].text.strip() result_map: dict[int, str] = {} for line in response_text.splitlines(): line = line.strip() if not line: continue if line.startswith("[") and "]" in line: try: idx_str, rest = line[1:].split("]", 1) result_map[int(idx_str.strip())] = rest.strip() except ValueError: pass for i, seg in enumerate(batch): corrected = result_map.get(i) if corrected is None: out.append(seg) elif corrected == "HALLUCINATED": text = seg.get("text", "") # Only drop what looks like Whisper filler. A long, real # sentence is kept even if the model thought it out of place. if len(text.split()) <= 12 or _is_likely_hallucination(text) or _is_repetition_loop(text): logger.info("Stripped hallucinated segment (Claude)") else: logger.info("Kept segment flagged by Claude") out.append(seg) elif _adds_words(seg.get("text", ""), corrected): # A "correction" that grows the line has pulled in words from # its neighbours, which then appear twice in the transcript. logger.info("Kept original: correction added words") out.append(seg) else: out.append({**seg, "text": corrected}) except Exception as e: logger.warning(f"Claude batch enhancement failed: {type(e).__name__} β€” keeping originals") out.extend(batch) return out # Batches are independent, so send them concurrently: an hour-long # meeting is ~30 batches, which took several minutes one after another. from concurrent.futures import ThreadPoolExecutor as _Pool batches = [segments[i:i + _BATCH_SIZE] for i in range(0, len(segments), _BATCH_SIZE)] with _Pool(max_workers=min(6, max(1, len(batches)))) as pool: results = list(pool.map(lambda f: f(), _ai_cost.run_in_context(_process, batches))) return [seg for part in results for seg in part] def _base_letters(text: str) -> str: """Text without tone marks, accents, case or punctuation.""" import unicodedata plain = "".join(ch for ch in unicodedata.normalize("NFD", text) if unicodedata.category(ch) != "Mn") return " ".join("".join(ch.lower() if ch.isalnum() else " " for ch in plain).split()) def _is_same_text_with_marks(original: str, corrected: str, min_ratio: float = 0.8) -> bool: """Adding tone marks keeps the letters; anything else (a refusal, an explanation, a translation) changes them, so it is rejected.""" import difflib a, b = _base_letters(original), _base_letters(corrected) if not a or not b: return False return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() >= min_ratio def _add_diacritics_with_claude(text: str, language: str) -> str: """Post-process transcription to add proper tone marks/diacritics.""" if not text or not text.strip(): return text if language not in ("yo", "ig", "ha"): return text api_key = os.getenv("ANTHROPIC_API_KEY") if not api_key or not _anthropic_available: return text client = _ai_cost.metered(_anthropic.Anthropic(api_key=api_key)) lang_name = {"yo": "Yoruba", "ig": "Igbo", "ha": "Hausa"}.get(language, language) # Build language-specific system prompt if language == "yo": from src.yoruba_knowledge import build_yoruba_prompt_context system = build_yoruba_prompt_context() else: system = ( f"You are a {lang_name} language expert. Your ONLY job is to add the " f"correct tone marks and diacritics to {lang_name} words. " "Do NOT change English words. Do NOT translate. Do NOT add or remove " "words. Do NOT change the meaning. Only add missing tone marks. " "Return ONLY the corrected text, nothing else." ) try: msg = client.messages.create( model="claude-haiku-4-5-20251001", max_tokens=4096, system=system, messages=[{ "role": "user", "content": f"Add proper {lang_name} tone marks to this text:\n\n{text}", }], ) corrected = msg.content[0].text.strip() # Claude sometimes adds explanations despite instructions. # Strip parenthetical notes, markdown, and "(No Yoruba words...)" lines. import re # Remove lines that look like explanations lines = corrected.splitlines() cleaned_lines = [] for line in lines: stripped = line.strip() if stripped.startswith("(") and stripped.endswith(")"): continue if stripped.startswith("[") and stripped.endswith("]"): continue if "No Yoruba" in stripped or "no Yoruba" in stripped: continue if "entirely in English" in stripped: continue cleaned_lines.append(line) corrected = "\n".join(cleaned_lines).strip() if corrected and _is_same_text_with_marks(text, corrected): logger.info(f"Added {lang_name} diacritics via Claude") return corrected logger.info(f"Claude {lang_name} diacritics rejected: the letters changed, keeping original") except Exception as e: logger.warning(f"Claude diacritics failed: {type(e).__name__} β€” keeping original") return text def _require_uid(request: Request) -> str: cached = getattr(request.state, "verified_uid", None) if cached: return cached uid = _verified_uid(request) if not uid: raise HTTPException(status_code=401, detail="Sign in to continue.") profile = _billing_profile(uid) if profile is None: raise HTTPException(status_code=403, detail="Account profile required.") if profile.get("disabled_at"): raise HTTPException(status_code=403, detail="Account suspended.") return uid def _owned_job(job_id: str, request: Request) -> dict: uid = _require_uid(request) try: uuid.UUID(job_id) except ValueError: raise HTTPException(status_code=404, detail="Job not found") row = _get_job(job_id) if not row or row.get("firebase_uid") != uid: raise HTTPException(status_code=404, detail="Job not found") return _reap_if_orphaned(job_id, row) # A job left "processing" by a server that restarted never finishes. On the # HF Space (one process; SPACE_ID is set by Hugging Face) a processing job this # process didn't start was orphaned by a restart. Anywhere, nothing runs for # 3 hours. Either way fail it and refund the reserved credits so the app stops # polling and the user can retry. _ORPHAN_MAX_AGE = 3 * 3600 def _reap_if_orphaned(job_id: str, row: dict) -> dict: if row.get("status") != "processing": return row try: age = time.time() - float(row.get("submitted_at") or 0) except (TypeError, ValueError): age = 0 single_process = bool(os.getenv("SPACE_ID")) lost = single_process and job_id not in _JOB_SUBMIT_TIMES and age > 30 if not (lost or (row.get("submitted_at") and age > _ORPHAN_MAX_AGE)): return row logger.warning(f"Job {job_id} orphaned (age {age:.0f}s); failing and refunding") _upsert_job(job_id, status="error", detail="The server restarted. Please try again.") try: _finish_work(job_id, False) except Exception: logger.error("Orphaned job refund needs reconciliation: %s", job_id) return dict(row, status="error") def _reap_orphans_sync() -> int: """Fail and refund every job a crash or restart left "processing", so credits come back even if nobody opens the app to check on the job.""" if not os.getenv("SPACE_ID"): return 0 # several processes elsewhere: rely on the 3-hour rule rows = _supabase_request("GET", "/rest/v1/transcription_jobs", None, {"status": "eq.processing", "select": "job_id,status,submitted_at", "limit": "500"}) or [] reaped = 0 for row in rows: job_id = row.get("job_id") if job_id and _reap_if_orphaned(job_id, row).get("status") == "error": reaped += 1 return reaped async def _reap_orphans_after_restart(): await asyncio.sleep(45) # past the 30 s grace for jobs submitted at start-up try: n = await asyncio.to_thread(_reap_orphans_sync) if n: logger.info(f"Restart clean-up: {n} interrupted job(s) failed and refunded") except Exception as exc: logger.warning(f"Restart clean-up failed: {type(exc).__name__}") @app.get("/progress/{job_id}") async def get_progress(job_id: str, request: Request): row = await asyncio.to_thread(_owned_job, job_id, request) p = row.get("progress") or {} total, current = p.get("total", 0), p.get("current", 0) return {"current": current, "total": total, "percent": round(current / total * 100) if total > 0 else 0} _JOB_SUBMIT_TIMES: dict = {} @app.post("/cancel/{job_id}") async def cancel_job(job_id: str, request: Request): row = await asyncio.to_thread(_owned_job, job_id, request) if row.get("status") == "processing": await asyncio.to_thread(_upsert_job, job_id, status="cancelled", detail="Cancelled by user") return {"status": "cancelled" if row.get("status") == "processing" else row.get("status")} @app.get("/status/{job_id}") async def get_status(job_id: str, request: Request): row = await asyncio.to_thread(_owned_job, job_id, request) return {"status": row.get("status", "processing")} @app.get("/result/{job_id}") async def get_result(job_id: str, request: Request): row = await asyncio.to_thread(_owned_job, job_id, request) status = row.get("status") if status == "processing": return JSONResponse(status_code=202, content={"status": "processing"}) if status == "cancelled": raise HTTPException(status_code=410, detail="Transcription cancelled.") if status == "error": raise HTTPException(status_code=422, detail=_user_detail(row.get("detail")) or "Transcription failed. Please try again.") if status == "done" and row.get("result"): # GET never consumes a result. Retention cleanup removes expired jobs. return JSONResponse(content=row["result"]) raise HTTPException(status_code=503, detail="Result temporarily unavailable") def _generate_docx_bytes( ai_minutes: dict, session_name: str, segments: list, speaker_names: dict, prepared_by: str = "", ) -> bytes: """Build a Word document from AI minutes + full transcript.""" try: from docx import Document from docx.shared import Pt, RGBColor, Inches from docx.oxml import OxmlElement from docx.oxml.ns import qn from docx.enum.text import WD_ALIGN_PARAGRAPH except ImportError: raise RuntimeError("python-docx not installed") import datetime doc = Document() # ── Styles ────────────────────────────────────────────────────────────── style = doc.styles["Normal"] style.font.name = "Inter" style.font.size = Pt(11) style.font.color.rgb = RGBColor.from_string("111111") style.paragraph_format.line_spacing = 1.35 style.paragraph_format.space_after = Pt(8) section = doc.sections[0] section.top_margin = section.bottom_margin = Inches(0.65) section.left_margin = section.right_margin = Inches(0.72) for name, size in (("Title", 28), ("Heading 1", 16), ("Heading 2", 11)): heading = doc.styles[name] heading.font.name = "Inter" heading.font.size = Pt(size) heading.font.color.rgb = RGBColor.from_string("111111") heading.paragraph_format.space_before = Pt(20) heading.paragraph_format.space_after = Pt(8) heading.paragraph_format.keep_with_next = True borders = OxmlElement("w:pBdr") bottom = OxmlElement("w:bottom") bottom.set(qn("w:val"), "nil") borders.append(bottom) heading.element.get_or_add_pPr().append(borders) brand = doc.add_paragraph() brand.paragraph_format.space_after = Pt(20) from pathlib import Path logo_path = Path(__file__).resolve().parent / "src" / "output" / "assets" / "narratifai-logo.png" brand.add_run().add_picture(str(logo_path), width=Inches(0.42)) brand_run = brand.add_run(" NarratifAI") brand_run.bold = True brand_run.font.size = Pt(14) footer = section.footer.paragraphs[0] footer.alignment = WD_ALIGN_PARAGRAPH.RIGHT footer_run = footer.add_run("NarratifAI / Meeting report Β· ") footer_run.font.size = Pt(8) footer_run.font.color.rgb = RGBColor.from_string("5F5F5F") field = OxmlElement("w:fldSimple") field.set(qn("w:instr"), "PAGE") footer._p.append(field) # ── Cover ──────────────────────────────────────────────────────────────── title_para = doc.add_heading("", level=0) run = title_para.add_run(session_name) run.font.size = Pt(28) run.font.color.rgb = RGBColor.from_string("111111") title_para.alignment = WD_ALIGN_PARAGRAPH.LEFT sub = doc.add_paragraph("Minutes of meeting") sub.alignment = WD_ALIGN_PARAGRAPH.LEFT sub.runs[0].font.size = Pt(13) sub.runs[0].font.bold = True date_str = datetime.datetime.now().strftime("%-d %B %Y") meta = doc.add_paragraph(f"Date: {date_str}") meta.alignment = WD_ALIGN_PARAGRAPH.LEFT meta.runs[0].font.size = Pt(11) meta.runs[0].font.color.rgb = RGBColor.from_string("5F5F5F") if prepared_by: prep = doc.add_paragraph(f"Prepared by: {prepared_by}") prep.alignment = WD_ALIGN_PARAGRAPH.LEFT prep.runs[0].font.size = Pt(11) doc.add_paragraph("") # ── AI Summary ─────────────────────────────────────────────────────────── summary = ai_minutes.get("summary", "") topics = ai_minutes.get("topics") or [] decisions = ai_minutes.get("decisions") or [] action_items = ai_minutes.get("action_items") or [] if summary or topics or decisions or action_items: h = doc.add_heading("AI Summary", level=1) h.runs[0].font.color.rgb = RGBColor.from_string("111111") if summary: p = doc.add_paragraph(summary) p.paragraph_format.space_after = Pt(14) if topics: doc.add_heading("Key Topics", level=2) for t in topics: doc.add_paragraph(t, style="List Bullet") if decisions: doc.add_heading("Decisions Made", level=2) for d in decisions: doc.add_paragraph(d, style="List Bullet") if action_items: doc.add_heading("Action Items", level=2) for a in action_items: doc.add_paragraph(a, style="List Bullet") doc.add_paragraph("") # ── Full Transcript ────────────────────────────────────────────────────── h2 = doc.add_heading("Full Transcript", level=1) h2.runs[0].font.color.rgb = RGBColor.from_string("111111") def _ts(s: float) -> str: h = int(s // 3600) m = int((s % 3600) // 60) sec = int(s % 60) return f"{h:02}:{m:02}:{sec:02}" for seg in segments: spk_id = seg.get("speaker") name = speaker_names.get(spk_id, spk_id) if spk_id else None text = seg.get("text", "").strip() start = seg.get("start", 0) if not text: continue p = doc.add_paragraph() ts_run = p.add_run(f"[{_ts(start)}] ") ts_run.font.size = Pt(9) ts_run.font.color.rgb = RGBColor.from_string("5F5F5F") if name: spk_run = p.add_run(f"{name}: ") spk_run.font.bold = True spk_run.font.size = Pt(11) p.add_run(text).font.size = Pt(11) buf = io.BytesIO() doc.save(buf) return buf.getvalue() async def _generate_minutes(request: Request, docx: bool = False): uid = await asyncio.to_thread(_require_uid, request) try: body = await request.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON body") _minutes_input(request, body) if not _WORK_SLOTS.acquire(blocking=False): raise HTTPException(status_code=429, detail="Server busy. Try again later.") reference = str(uuid.uuid4()) reserved = False settled = False try: canonical = {"segments": body["segments"], "speakers": body.get("speaker_names", {}), "session": body.get("session_name", "Meeting")[:200]} cache_key = hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode()).hexdigest() rate = await asyncio.to_thread(_ai_cost.credit_rate, _supabase_request) chars = min(sum(len(s.get("text", "")) for s in body["segments"]), 40000) + 1500 hold = _ai_cost.floor_credits(MINUTES_DOC_CREDITS, _ai_cost.worst_case_usd(MINUTES_MODEL, chars, 1024), rate) reservation = await asyncio.to_thread(_reserve_work, uid, reference, hold, "minutes", cache_key) result = reservation.get("cached") reserved = result is None meter = _ai_cost.start() # asyncio.to_thread carries this context into the call if reserved: result = await asyncio.to_thread(_generate_minutes_with_claude, body["segments"], body.get("speaker_names", {}), body.get("session_name", "Meeting")[:200]) if not isinstance(result, dict) or not any(result.get(k) for k in ("summary", "topics", "decisions", "action_items")): raise HTTPException(status_code=503, detail="Minutes generation temporarily unavailable") if docx: payload = await asyncio.to_thread(_generate_docx_bytes, result, body.get("session_name", "Meeting")[:200], body["segments"], body.get("speaker_names", {}), str(body.get("prepared_by", ""))[:200]) if reserved: cost = _ai_cost.floor_credits(MINUTES_DOC_CREDITS, meter.usd, rate) completed = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/rpc/complete_minutes_priced", {"p_reference": reference, "p_result": result, "p_cost": cost}) if not isinstance(completed, dict) or completed.get("error"): raise HTTPException(status_code=503, detail="Could not save minutes. Please retry.") settled = True if docx: return Response(content=payload, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", headers={"Content-Disposition": 'attachment; filename="meeting-minutes.docx"'}) return JSONResponse(content=result) finally: if reserved and not settled: try: await asyncio.to_thread(_finish_work, reference, False) except Exception: logger.error("Minutes reservation needs reconciliation: %s", reference) _WORK_SLOTS.release() @app.post("/translate") async def translate_transcript_endpoint(request: Request): from src.translation import validate_translation, translate_texts, translation_credits, translation_hold_usd uid = await asyncio.to_thread(_require_uid, request) try: target, texts = validate_translation(await request.json()) except (ValueError, TypeError): raise HTTPException(status_code=400, detail="Choose a supported language and a transcript of up to 500 segments and 50,000 characters.") if not _WORK_SLOTS.acquire(blocking=False): raise HTTPException(status_code=429, detail="Server busy. Try again later.") reference = str(uuid.uuid4()) reserved = settled = False try: # Translation shares the existing five-credit AI document reservation # and owner-bound cache. Namespace prevents collisions with minutes. canonical = {"task": "translation-v1", "target": target, "texts": texts} cache_key = hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode()).hexdigest() rate = await asyncio.to_thread(_ai_cost.credit_rate, _supabase_request) fixed = translation_credits(texts) hold = _ai_cost.floor_credits(fixed, translation_hold_usd(texts), rate) reservation = await asyncio.to_thread(_reserve_work, uid, reference, hold, "minutes", cache_key) result = reservation.get("cached") reserved = result is None meter = _ai_cost.start() if reserved: key = os.getenv("ANTHROPIC_API_KEY") if not key or not _anthropic_available: raise RuntimeError("Translation service unavailable") def generate(): with _ai_cost.metered(_anthropic.Anthropic(api_key=key, max_retries=0)) as client: return translate_texts(client, target, texts) translated = await asyncio.to_thread(generate) result = {"target_language": target, "texts": translated} cost = _ai_cost.floor_credits(fixed, meter.usd, rate) completed = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/rpc/complete_minutes_priced", {"p_reference": reference, "p_result": result, "p_cost": cost}) if not isinstance(completed, dict) or completed.get("error") or completed.get("state") != "settled": raise RuntimeError("Could not save translation") if not isinstance(result, dict) or result.get("target_language") != target or not isinstance(result.get("texts"), list) or len(result["texts"]) != len(texts): raise RuntimeError("Invalid cached translation") settled = True return {**result, "credits_charged": (completed.get("charged", reservation.get("reserved", 0)) if isinstance(completed, dict) else reservation.get("reserved", 0)) if reserved else 0} except HTTPException: raise except Exception: logger.error("Translation failed for reservation %s", reference) raise HTTPException(status_code=503, detail="Translation unavailable. Please try again.") finally: if reserved and not settled: try: await asyncio.to_thread(_finish_work, reference, False) except Exception: logger.error("Translation reservation needs reconciliation: %s", reference) _WORK_SLOTS.release() @app.post("/minutes") async def generate_minutes_endpoint(request: Request): return await _generate_minutes(request) @app.post("/minutes/docx") async def generate_minutes_docx_endpoint(request: Request): return await _generate_minutes(request, docx=True) # ── Credits (pay-as-you-go) ─────────────────────────────────────────────────── # Server-side source of truth for packs and prices; the apps only display # what /credits/packs returns. 1 credit = 1 audio minute (2 on the largest # model); speaker identification is included; an AI minutes document is 5. # Balances change only through the apply_credits() SQL function, which is # idempotent per (kind, reference) so retries never double-count. CREDIT_PACKS = [ {"id": "starter", "name": "Starter", "credits": 100, "price_ngn": 1500}, {"id": "standard", "name": "Standard", "credits": 350, "price_ngn": 4500}, {"id": "pro", "name": "Pro", "credits": 1000, "price_ngn": 12000}, {"id": "business", "name": "Business", "credits": 3000, "price_ngn": 33000}, ] CREDITS_PER_MINUTE = { "whisper-tiny": 1, "whisper-small": 1, "whisper-medium": 1, "whisper-large-v3": 2, } MINUTES_DOC_CREDITS = 5 MINUTES_MODEL = "claude-haiku-4-5-20251001" _FIREBASE_PROJECT = os.getenv("FIREBASE_PROJECT_ID", "clarifai-11cb7") _JOB_BILLING: dict = {} def _credits_for_minutes(minutes: float, model_key: str) -> int: import math rate = CREDITS_PER_MINUTE.get(model_key, 1) return max(1, math.ceil(max(minutes, 0.0) - 1e-9)) * rate # ConsulMeet's live notetaker has no Firebase user. With the shared secret it # acts as this service account, which needs a complimentary user_profiles row # (created by the VAPT migration) so it is never charged. _NOTETAKER_SHARED_SECRET = os.getenv("NOTETAKER_SHARED_SECRET", "") NOTETAKER_UID = "consulmeet-notetaker" def _verified_uid(request: Request) -> Optional[str]: """Firebase uid from a verified 'Authorization: Bearer <ID token>', or None. Missing tokens are rejected by _require_uid. Body user IDs never establish identity. """ key = request.headers.get("x-notetaker-key", "") if _NOTETAKER_SHARED_SECRET and key and hmac.compare_digest(key, _NOTETAKER_SHARED_SECRET): return NOTETAKER_UID auth = request.headers.get("authorization", "") if not auth.lower().startswith("bearer "): return None token = auth.split(" ", 1)[1].strip() try: from google.oauth2 import id_token as _gid from google.auth.transport import requests as _gareq claims = _gid.verify_firebase_token(token, _gareq.Request(), audience=_FIREBASE_PROJECT) return (claims or {}).get("user_id") or (claims or {}).get("sub") except Exception as e: logger.warning(f"Firebase token rejected: {type(e).__name__}") raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.") def _billing_profile(uid: str) -> Optional[dict]: rows = _supabase_request( "GET", "/rest/v1/user_profiles", params={"firebase_uid": f"eq.{uid}", "select": "credits,plan,plan_expires_at,disabled_at", "limit": "1"}, ) if rows is None: raise HTTPException(status_code=503, detail="Billing temporarily unavailable") return rows[0] if rows and isinstance(rows, list) else None def _is_unlimited(profile: Optional[dict]) -> bool: """Complimentary accounts, and anyone still inside a paid subscription period from before credits launched, are never charged.""" if not profile: return False plan = (profile.get("plan") or "free").lower() expires = profile.get("plan_expires_at") if plan == "complimentary" and not expires: return True if plan in ("complimentary", "pro", "team") and expires: from datetime import datetime, timezone try: return datetime.fromisoformat(expires.replace("Z", "+00:00")) > datetime.now(timezone.utc) except ValueError: return False return False def _apply_credits(uid: str, delta: int, kind: str, reference: Optional[str], note: str = "") -> Optional[int]: res = _supabase_request( "POST", "/rest/v1/rpc/apply_credits", payload={"p_uid": uid, "p_delta": int(delta), "p_kind": kind, "p_reference": reference, "p_note": note or None}, ) if res is None: logger.error(f"Credit {kind} of {delta} for {uid} ({reference}) FAILED") return None return res if isinstance(res, int) else None def _probe_duration_sec(content: bytes, filename: str) -> Optional[float]: """Audio length via ffprobe, to check the balance before starting.""" import re, subprocess, tempfile suffix = os.path.splitext(filename or "")[1] or ".bin" try: with tempfile.NamedTemporaryFile(suffix=suffix) as f: f.write(content) f.flush() out = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", f.name], capture_output=True, text=True, timeout=30, ) try: return float(out.stdout.strip()) except ValueError: pass # Browser recordings (MediaRecorder WebM) carry no duration in the # header, so ffprobe says "N/A". Decode the audio and read the time # ffmpeg reached instead. out = subprocess.run( ["ffmpeg", "-hide_banner", "-nostdin", "-i", f.name, "-map", "0:a:0", "-f", "null", "-"], capture_output=True, text=True, timeout=120, ) times = re.findall(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", out.stderr) if not times: return None h, m, s = times[-1] return int(h) * 3600 + int(m) * 60 + float(s) except Exception as e: logger.warning("Could not probe audio duration") return None def _not_enough_credits(needed: int, balance: int) -> HTTPException: return HTTPException( status_code=402, detail={ "code": "insufficient_credits", "message": f"This needs about {needed} credits and you have {balance}. Buy more credits to continue.", "needed": needed, "balance": balance, }, ) # Custom amounts: the buyer types any naira amount. The smallest pack's rate # applies, and each bigger pack's rate kicks in once the amount reaches that # pack's size, so a custom amount is never worse than the packs (and buying # exactly a pack's price gives exactly that pack's credits). CUSTOM_MIN_NGN = 500 CUSTOM_MAX_NGN = 500_000 # iPhone can't take a free amount (Apple sells fixed-price products only), so # it gets these presets; the four pack prices are the existing pack products. APPLE_PRESET_NGN = [1000, 1500, 2500, 4500, 7500, 12000, 20000, 33000] def credits_for_naira(naira: int) -> int: tiers = sorted(CREDIT_PACKS, key=lambda p: p["credits"]) best = (naira * tiers[0]["credits"]) // tiers[0]["price_ngn"] for t in tiers[1:]: c = (naira * t["credits"]) // t["price_ngn"] if c >= t["credits"]: best = max(best, c) return best @app.get("/credits/packs") async def credit_packs(): return { "packs": CREDIT_PACKS, "credits_per_minute": CREDITS_PER_MINUTE, "minutes_doc_credits": MINUTES_DOC_CREDITS, "currency": "NGN", "custom": { "min_ngn": CUSTOM_MIN_NGN, "max_ngn": CUSTOM_MAX_NGN, "tiers": [{"credits": p["credits"], "price_ngn": p["price_ngn"]} for p in sorted(CREDIT_PACKS, key=lambda p: p["credits"])], "apple_presets": [{"price_ngn": n, "credits": credits_for_naira(n), "product_id": f"com.consulaw.narratifai.credits.{_apple_preset_suffix(n)}"} for n in APPLE_PRESET_NGN], }, } def _apple_preset_suffix(naira: int) -> str: """Pack prices reuse the original pack products; other presets are ngn<amount>.""" pack = next((p for p in CREDIT_PACKS if p["price_ngn"] == naira), None) return pack["id"] if pack else f"ngn{naira}" @app.get("/credits/quote") async def credit_quote(amount_ngn: int): if amount_ngn < CUSTOM_MIN_NGN or amount_ngn > CUSTOM_MAX_NGN: raise HTTPException(status_code=400, detail=f"Choose an amount between NGN {CUSTOM_MIN_NGN:,} and NGN {CUSTOM_MAX_NGN:,}.") return {"amount_ngn": amount_ngn, "credits": credits_for_naira(amount_ngn)} _SETTINGS_CACHE: dict = {"at": 0.0, "values": {}} def _platform_setting(key: str, default=True): """A system_settings value (switches set in the admin portal), cached 30 s. If Supabase can't be read, the default wins so an outage never blocks users.""" if time.time() - _SETTINGS_CACHE["at"] > 30: rows = _supabase_request("GET", "/rest/v1/system_settings", params={"select": "key,value"}) if isinstance(rows, list): _SETTINGS_CACHE["values"] = {r.get("key"): r.get("value") for r in rows} _SETTINGS_CACHE["at"] = time.time() value = _SETTINGS_CACHE["values"].get(key, default) if isinstance(value, str) and value.lower() in ("true", "false"): return value.lower() == "true" return value def _paused(key: str, what: str) -> Optional[HTTPException]: if _platform_setting(key, True) is False: note = _platform_setting("maintenance_message", "") or "" return HTTPException(status_code=503, detail=(note.strip() or f"{what} is paused for maintenance. Please try again soon.")) return None def _require_staff(request: Request, permission: str) -> str: """Email of an active admin_staff member, from a verified Firebase token.""" auth = request.headers.get("authorization", "") if not auth.lower().startswith("bearer "): raise HTTPException(status_code=401, detail="Sign in as staff.") try: from google.oauth2 import id_token as _gid from google.auth.transport import requests as _gareq claims = _gid.verify_firebase_token(auth.split(" ", 1)[1].strip(), _gareq.Request(), audience=_FIREBASE_PROJECT) or {} except Exception: raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.") email = (claims.get("email") or "").lower() rows = _supabase_request("GET", "/rest/v1/admin_staff", params={"email": f"eq.{email}", "select": "role,active", "limit": "1"}) if email else None if not rows or rows[0].get("active") is False: raise HTTPException(status_code=403, detail="Staff only.") allowed = {"super_admin": {"credits:write", "payments:read"}, "ops_admin": {"credits:write", "payments:read"}} if permission not in allowed.get(rows[0].get("role"), set()): raise HTTPException(status_code=403, detail="Permission denied") # The portal's 2FA session (issued by the admin-2fa function after a # server-checked TOTP code). Only its SHA-256 is stored. session = request.headers.get("x-admin-session", "") sessions = _supabase_request("GET", "/rest/v1/admin_sessions", params={ "token_hash": f"eq.{hashlib.sha256(session.encode()).hexdigest()}", "select": "email,expires_at", "limit": "1", }) if session else None if not sessions or (sessions[0].get("email") or "").lower() != email: raise HTTPException(status_code=401, detail="Confirm your 2FA code again.") from datetime import datetime, timezone try: expires = datetime.fromisoformat(str(sessions[0]["expires_at"]).replace("Z", "+00:00")) except Exception: expires = None if not expires or expires < datetime.now(timezone.utc): raise HTTPException(status_code=401, detail="Confirm your 2FA code again.") return email @app.post("/credits/admin-grant") async def credits_admin_grant(request: Request): """Staff adjust a user's balance (support refunds, testers, promotions). A negative amount removes credits (never below zero).""" staff = await asyncio.to_thread(_require_staff, request, "credits:write") body = await request.json() target = (body.get("firebase_uid") or "").strip() try: amount = int(body.get("amount")) except (TypeError, ValueError): raise HTTPException(status_code=400, detail="amount must be a whole number") if not target or amount == 0 or abs(amount) > 100000: raise HTTPException(status_code=400, detail="firebase_uid and a non-zero amount (max 100,000) are required") note = (body.get("note") or "").strip()[:200] payload = {"p_email": staff, "p_uid": target, "p_delta": amount, "p_note": note, "p_reference": f"admin:{uuid.uuid4()}"} def call(): # Not _supabase_request: the database's reason is needed to tell staff # what went wrong (it only says "failed"). r = _requests.post(f"{_SUPABASE_URL}/rest/v1/rpc/admin_adjust_credits", json=payload, headers=_sb_headers(), timeout=15) try: data = r.json() if r.text else {} except ValueError: data = {} return r.status_code, data try: status, result = await asyncio.to_thread(call) except Exception as e: logger.warning(f"Admin credit change failed: {type(e).__name__}") raise HTTPException(status_code=503, detail="The database could not be reached. Try again in a minute.") if status >= 400 or not isinstance(result, dict) or "balance" not in result: reason = (result.get("message") or result.get("hint") or "") if isinstance(result, dict) else "" logger.warning(f"Admin credit change for {target} refused: HTTP {status} {reason[:120]}") known = { "permission_denied": "Your staff role can't change credits (super admin or ops admin only).", "profile_not_found": "This user has no NarratifAI profile yet. Ask them to open the app once, then try again.", "invalid_delta": "Use a whole number between -100,000 and 100,000.", "reference_owner_mismatch": "This change clashed with another one. Try again.", "account_deleted": "This account is being deleted, so its balance can't change.", } detail = next((v for k, v in known.items() if k in reason), None) if not detail and "deleted" in reason.lower(): detail = known["account_deleted"] raise HTTPException(status_code=409 if detail else 503, detail=detail or f"Could not update the balance ({reason[:120] or f'HTTP {status}'}).") balance = result["balance"] logger.info(f"Staff {staff} changed {target} by {amount} credits (balance {balance})") return {"balance": balance} @app.get("/credits/admin-ledger/{firebase_uid}") async def credits_admin_ledger(firebase_uid: str, request: Request): """Staff view of a user's last 50 credit movements.""" await asyncio.to_thread(_require_staff, request, "payments:read") rows = await asyncio.to_thread( _supabase_request, "GET", "/rest/v1/credit_ledger", None, {"firebase_uid": f"eq.{firebase_uid}", "order": "created_at.desc", "limit": "50", "select": "delta,balance_after,kind,note,created_at"}, ) return {"entries": rows or []} _WORK_LABEL = {"transcription": "Transcription", "minutes": "Meeting minutes", "translation": "Translation"} def _credit_history(uid: str) -> list: rows = _supabase_request( "GET", "/rest/v1/credit_ledger", None, {"firebase_uid": f"eq.{uid}", "order": "created_at.desc", "limit": "100", "select": "delta,balance_after,kind,note,reference,created_at"}, ) or [] refs = sorted({(r.get("reference") or "").removeprefix("settlement:") for r in rows if r.get("kind") in ("charge", "refund") and r.get("reference")}) kinds = {} for i in range(0, len(refs), 40): chunk = [x for x in refs[i:i + 40] if x and all(c.isalnum() or c in "-_:." for c in x)] if not chunk: continue found = _supabase_request("GET", "/rest/v1/processing_reservations", None, {"reference": f"in.({','.join(chunk)})", "select": "reference,kind"}) or [] kinds.update({f["reference"]: f.get("kind") for f in found}) out = [] for r in rows: kind, note, ref, delta = r.get("kind"), r.get("note") or "", r.get("reference") or "", r.get("delta") or 0 settlement = ref.startswith("settlement:") work = _WORK_LABEL.get(kinds.get(ref.removeprefix("settlement:")) or "", "") detail = "" if kind == "signup_bonus": label = "Welcome credits" elif kind == "purchase": label = "Credits bought" elif kind == "admin_grant": label = "Added by NarratifAI" if delta > 0 else "Adjusted by NarratifAI" detail = note elif kind == "refund" and (ref.startswith("apple-refund:") or ref.startswith("google-refund:")): label = "Store refund" elif kind == "refund": label = "Returned" detail = f"{work or 'Processing'} failed or came out shorter" if settlement else note elif note in ("Transfer to team wallet", "Closed team wallet returned to owner"): label = "Team wallet" detail = note else: label = work or "Used" detail = "Adjusted to the final length" if settlement else "" out.append({"label": label, "detail": detail, "delta": delta, "balance_after": r.get("balance_after"), "created_at": r.get("created_at")}) return out @app.get("/credits/history") async def credits_history(request: Request): """The signed-in user's last 100 credit movements, in plain words.""" uid = await asyncio.to_thread(_require_uid, request) return {"entries": await asyncio.to_thread(_credit_history, uid)} def _reserve_work(uid: str, reference: str, cost: int, kind: str, cache_key: Optional[str] = None, companion_id: Optional[str] = None) -> dict: if companion_id: result = _supabase_request("POST", "/rest/v1/rpc/reserve_companion_processing", payload={ "p_uid": uid, "p_id": companion_id, "p_cost": cost}) elif cache_key: payload = {"p_uid": uid, "p_reference": reference, "p_cache_key": cache_key} if cost != 5: # minutes keep the SQL default; translation is priced by length payload["p_cost"] = cost result = _supabase_request("POST", "/rest/v1/rpc/reserve_minutes", payload=payload) else: result = _supabase_request("POST", "/rest/v1/rpc/reserve_processing", payload={ "p_uid": uid, "p_reference": reference, "p_cost": cost, "p_kind": kind}) if not isinstance(result, dict): raise HTTPException(status_code=503, detail="Billing temporarily unavailable") if result.get("error") == "insufficient_credits": raise _not_enough_credits(cost, result.get("balance", 0)) if result.get("error") == "rate_limited": raise HTTPException(status_code=429, detail="Too many jobs. Try again later.") if result.get("error"): raise HTTPException(status_code=403, detail="Account is unavailable for processing") return result def _finish_work(reference: str, success: bool, cost: int = 0): result = _supabase_request("POST", "/rest/v1/rpc/finish_processing", payload={ "p_reference": reference, "p_success": success, "p_cost": cost}) if not isinstance(result, dict) or result.get("error"): raise RuntimeError("Could not settle processing reservation") return result def _minutes_input(request: Request, body: dict): uid = _require_uid(request) if not isinstance(body, dict) or not isinstance(body.get("segments"), list): raise HTTPException(status_code=400, detail="Transcript segments required") segments = body["segments"] if not segments or len(segments) > 5000 or any(not isinstance(s, dict) or not isinstance(s.get("text"), str) for s in segments): raise HTTPException(status_code=400, detail="Invalid transcript segments") if sum(len(s["text"]) for s in segments) > 100000: raise HTTPException(status_code=413, detail="Transcript is too long") if not isinstance(body.get("speaker_names", {}), dict) or not isinstance(body.get("session_name", "Meeting"), str): raise HTTPException(status_code=400, detail="Invalid meeting metadata") return uid # ── Paystack / Supabase helpers ─────────────────────────────────────────────── def _supabase_update_plan(firebase_uid: str, plan: str, expires_iso: Optional[str], data: dict): """Write plan change to Supabase using the service-role key (bypasses RLS).""" url = os.getenv("SUPABASE_URL", "") key = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "") if not url or not key or not _requests_available: logger.warning("Supabase service-role key or URL not set β€” skipping plan update") return headers = { "apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json", "Prefer": "return=minimal", } payload = {"plan": plan, "plan_expires_at": expires_iso} sub_code = data.get("subscription_code") or data.get("subscription", {}).get("subscription_code") if sub_code: payload["paystack_subscription_code"] = sub_code customer = data.get("customer", {}) customer_code = customer.get("customer_code") if isinstance(customer, dict) else None if customer_code: payload["paystack_customer_code"] = customer_code _requests.patch( f"{url}/rest/v1/user_profiles?firebase_uid=eq.{firebase_uid}", json=payload, headers=headers, timeout=10, ) def _supabase_increment_audio_minutes(firebase_uid: str, audio_duration_sec: float): """Increment audio_minutes_used for a user atomically after a successful transcription.""" url = os.getenv("SUPABASE_URL", "") key = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "") if not url or not key or not _requests_available or not firebase_uid: return minutes_used = max(1, round(audio_duration_sec / 60)) headers = { "apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json", "Prefer": "return=minimal", } # Atomic increment via Postgres RPC function try: _requests.post( f"{url}/rest/v1/rpc/increment_audio_minutes", json={"p_firebase_uid": firebase_uid, "p_minutes": minutes_used}, headers=headers, timeout=10, ) except Exception as exc: logger.warning(f"Could not increment audio_minutes_used: {type(exc).__name__}") def _paystack_plan_expires(data: dict) -> Optional[str]: """Extract subscription end date from a Paystack charge.success/subscription.create payload.""" # subscription object may be nested sub = data.get("subscription") or data next_date = sub.get("next_payment_date") or sub.get("paid_at") if not next_date: return None # Add 31 days as a safe buffer when exact next-billing isn't present from datetime import datetime, timezone, timedelta try: dt = datetime.fromisoformat(next_date.replace("Z", "+00:00")) except ValueError: return None return (dt + timedelta(days=31)).isoformat() @app.post("/account/delete") async def delete_account(request: Request): """Delegate identity + database deletion to the durable verified Edge workflow.""" uid = _verified_uid(request) if not uid: raise HTTPException(status_code=401, detail="Sign in again to delete your account.") if not _SUPABASE_URL or not _SUPABASE_KEY: raise HTTPException(status_code=503, detail="Account service unavailable") token = request.headers.get("authorization", "").split(" ", 1)[-1] try: resp = await asyncio.to_thread(_requests.post, f"{_SUPABASE_URL}/functions/v1/account-delete", headers={"apikey": _SUPABASE_KEY, "x-firebase-token": token}, json={"confirm": "DELETE"}, timeout=60) data = resp.json() except Exception: raise HTTPException(status_code=503, detail="Deletion service unavailable. Please retry.") if resp.status_code not in (200, 202): raise HTTPException(status_code=resp.status_code, detail=data.get("error", "Could not delete account")) return JSONResponse(data, status_code=resp.status_code) @app.post("/paystack/init") async def paystack_init(request: Request): uid = await asyncio.to_thread(_require_uid, request) paused = _paused("allow_payments", "Buying credits") if paused: raise paused secret = os.getenv("PAYSTACK_SECRET_KEY", "") if not secret or not _requests_available: raise HTTPException(status_code=503, detail="Payments temporarily unavailable") try: body = await request.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON") if not isinstance(body, dict): raise HTTPException(status_code=400, detail="Invalid payment request") profiles = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/user_profiles", None, {"firebase_uid": f"eq.{uid}", "select": "email", "limit": "1"}) email = profiles[0].get("email") if profiles else None if not email: raise HTTPException(status_code=503, detail="Billing email unavailable") pack = next((p for p in CREDIT_PACKS if p["id"] == body.get("pack_id")), None) if pack: naira, credits = pack["price_ngn"], pack["credits"] else: naira = body.get("amount_ngn") if isinstance(naira, bool) or not isinstance(naira, int) or not CUSTOM_MIN_NGN <= naira <= CUSTOM_MAX_NGN: raise HTTPException(status_code=400, detail="Choose a valid credit pack or whole-naira amount") credits = credits_for_naira(naira) callback = body.get("callback_url") or "narratifai://paystack-callback" if callback not in ("narratifai://paystack-callback", "https://narratifai.com/pricing?paid=1", "https://www.narratifai.com/pricing?paid=1"): raise HTTPException(status_code=400, detail="Invalid payment callback") reference = "narratifai-" + uuid.uuid4().hex order = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/payment_orders", { "reference": reference, "firebase_uid": uid, "email": email, "amount": naira * 100, "currency": "NGN", "credits": credits, }) if not order: raise HTTPException(status_code=503, detail="Could not create payment order") # One checkout per tap: the same request arriving twice (some browsers and # data-saving proxies resend it) shares the first checkout instead of # opening a second Paystack payment. shared = await _same_checkout(uid, naira * 100, reference, order) if shared: return shared try: response = await asyncio.to_thread(_requests.post, "https://api.paystack.co/transaction/initialize", json={"email": email, "amount": naira * 100, "currency": "NGN", "reference": reference, "callback_url": callback, "metadata": {"firebase_uid": uid}}, headers={"Authorization": f"Bearer {secret}"}, timeout=20) data = response.json().get("data", {}) if response.status_code != 200 or data.get("reference") != reference or not data.get("authorization_url"): raise ValueError("Payment initialization failed") except Exception: raise HTTPException(status_code=502, detail="Could not start payment. Please try again.") # Kept so a duplicate of this request can be sent to the same checkout. await asyncio.to_thread(_supabase_request, "PATCH", "/rest/v1/payment_orders", {"authorization_url": data["authorization_url"]}, {"reference": f"eq.{reference}"}) return {"authorization_url": data["authorization_url"], "reference": reference, "credits": credits} CHECKOUT_DEDUPE_SECONDS = 15 def _created_at(row) -> str: row = row[0] if isinstance(row, list) and row else row return str((row or {}).get("created_at") or "") if isinstance(row, dict) else "" async def _same_checkout(uid: str, amount_kobo: int, reference: str, order) -> Optional[dict]: """If an identical checkout (same account, same amount) started just before this one, drop this order and return that checkout instead. The first of two simultaneous requests always proceeds, so exactly one payment opens.""" from datetime import datetime, timedelta, timezone mine = _created_at(order) if not mine: return None since = (datetime.now(timezone.utc) - timedelta(seconds=CHECKOUT_DEDUPE_SECONDS)).isoformat() rows = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None, { "firebase_uid": f"eq.{uid}", "amount": f"eq.{amount_kobo}", "fulfilled_at": "is.null", "created_at": f"gte.{since}", "select": "reference,created_at,credits", "order": "created_at.asc,reference.asc", "limit": "5", }) or [] earlier = [r for r in rows if isinstance(r, dict) and r.get("reference") != reference and (str(r.get("created_at")), str(r.get("reference"))) < (mine, reference)] if not earlier: return None first = earlier[0] await asyncio.to_thread(_supabase_request, "DELETE", "/rest/v1/payment_orders", None, {"reference": f"eq.{reference}", "fulfilled_at": "is.null"}) # The first request is usually still talking to Paystack: wait for its page. for _ in range(20): got = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None, { "reference": f"eq.{first['reference']}", "select": "authorization_url", "limit": "1"}) url = got[0].get("authorization_url") if isinstance(got, list) and got else None if url: logger.info(f"Duplicate checkout {reference} for {uid} joined {first['reference']}") return {"authorization_url": url, "reference": first["reference"], "credits": first.get("credits")} await asyncio.sleep(0.5) raise HTTPException(status_code=409, detail="Your payment is already opening. Please wait a moment.") # ── Apple in-app purchase (iOS) ─────────────────────────────────────────────── # Credit packs are consumable IAPs with product ids <bundle id>.credits.<pack id>. # The app sends the StoreKit 2 signed transaction here; it is verified against # Apple's certificate chain (src/apple_iap.py), so no App Store API key is needed. # # Two store apps sell credits (regional split, 2026-11): # - com.consulaw.narratifai (Consulaw Tech Services Ltd, Africa/Middle East/Asia): # the four packs plus ngn<amount> top-ups, priced in naira. # - com.consulawtechnologies.narratifai (Consulaw Technologies Ltd, UK region): # the four packs only, priced in pounds (UK_PACK_GBP). # A product id must belong to the app that sold it. APPLE_BUNDLE_ID = "com.consulaw.narratifai" UK_BUNDLE_ID = "com.consulawtechnologies.narratifai" STORE_BUNDLE_IDS = (APPLE_BUNDLE_ID, UK_BUNDLE_ID) UK_PRODUCT_PREFIX = UK_BUNDLE_ID + ".credits." # Google Play caps product IDs at 40 characters, so the UK app's Play packs # are uk.credits.<pack> (its App Store packs keep the bundle prefix). UK_PLAY_PRODUCT_PREFIX = "uk.credits." # UK store prices (base territory GBR, approved 2026-11-24). Other countries' # prices are Apple/Google conversions; the ledger records the GBP list price. UK_PACK_GBP = {"starter": "2.99", "standard": "9.99", "pro": "24.99", "business": "59.99"} # Sandbox purchases (TestFlight, App Review) are free, so they only fund # accounts we choose: the App Review demo account plus any Firebase uids in # APPLE_SANDBOX_UIDS (comma separated). Everyone else is refused. APPLE_SANDBOX_UIDS = {"IcN3wZSLoaac1wXAKoCsLKzKsX02"} | { u.strip() for u in os.environ.get("APPLE_SANDBOX_UIDS", "").split(",") if u.strip()} APPLE_PRODUCT_PREFIX = "com.consulaw.narratifai.credits." def _apple_pack(product_id: str) -> Optional[dict]: """The pack (or preset amount) a store product id stands for, with the app that sells it ("bundle") and its list price ("price": currency, amount).""" from decimal import Decimal uk_prefix = next((p for p in (UK_PRODUCT_PREFIX, UK_PLAY_PRODUCT_PREFIX) if product_id.startswith(p)), None) if uk_prefix: suffix = product_id[len(uk_prefix):] pack = next((p for p in CREDIT_PACKS if p["id"] == suffix), None) if not pack or suffix not in UK_PACK_GBP: return None return {**pack, "bundle": UK_BUNDLE_ID, "price": ("GBP", Decimal(UK_PACK_GBP[suffix]))} if not product_id.startswith(APPLE_PRODUCT_PREFIX): return None suffix = product_id[len(APPLE_PRODUCT_PREFIX):] pack = next((p for p in CREDIT_PACKS if p["id"] == suffix), None) if pack: return {**pack, "bundle": APPLE_BUNDLE_ID, "price": ("NGN", pack["price_ngn"])} if suffix.startswith("ngn") and suffix[3:].isdigit() and int(suffix[3:]) in APPLE_PRESET_NGN: naira = int(suffix[3:]) return {"id": suffix, "name": "Custom amount", "credits": credits_for_naira(naira), "price_ngn": naira, "bundle": APPLE_BUNDLE_ID, "price": ("NGN", naira)} return None def _purchase_note(pack: dict, qty: int, source: str, test: bool = False) -> str: """Ledger note for a store purchase, e.g. "Starter pack, NGN 1,500 (Apple)" or "Starter pack, GBP 2.99 (Google Play, GB)". The admin reads the currency and amount from it, so keep this shape.""" currency, unit = pack["price"] label = "Custom amount" if pack["id"].startswith("ngn") else f"{pack['name']} pack" if test: return f"{label}, {currency} 0 ({source})" total = unit * qty amount = f"{total:,}" if currency == "NGN" else f"{total:,.2f}" return f"{label}, {currency} {amount} ({source})" @app.post("/credits/apple") async def credits_apple(request: Request): """Credit a verified App Store purchase. Safe to call more than once for the same transaction: it is only ever credited once.""" from src.apple_iap import verify_jws, AppleJWSError, account_token uid = await asyncio.to_thread(_require_uid, request) body = await request.json() try: tx = verify_jws(str(body.get("signed_transaction") or "")) except AppleJWSError as e: logger.warning(f"Apple purchase rejected for {uid}: {type(e).__name__}") raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Apple.") pack = _apple_pack(tx.get("productId") or "") if not pack or tx.get("bundleId") != pack["bundle"] or tx.get("type") not in (None, "Consumable"): raise HTTPException(status_code=400, detail="This purchase isn't a NarratifAI credit pack.") if tx.get("revocationDate"): raise HTTPException(status_code=400, detail="Apple has refunded this purchase.") env = tx.get("environment") if env != "Production" and not (env == "Sandbox" and uid in APPLE_SANDBOX_UIDS): raise HTTPException(status_code=403, detail="Test purchases cannot fund production credits.") token = tx.get("appAccountToken") if token != account_token(uid): logger.warning(f"Apple transaction {tx.get('transactionId')} belongs to another account (caller {uid})") raise HTTPException(status_code=403, detail="This purchase was made from a different NarratifAI account.") tx_id = str(tx.get("transactionId") or "") if not tx_id: raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Apple.") reference = f"apple:{tx_id}" prior = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger", None, {"kind": "eq.purchase", "reference": f"eq.{reference}", "select": "firebase_uid", "limit": "1"}) if prior: if prior[0].get("firebase_uid") != uid: raise HTTPException(status_code=403, detail="This purchase was already added to a different account.") profile = await asyncio.to_thread(_billing_profile, uid) return {"balance": int((profile or {}).get("credits") or 0), "credits_added": 0, "already_credited": True} qty = max(1, int(tx.get("quantity") or 1)) credits = pack["credits"] * qty sandbox = tx.get("environment") == "Sandbox" # Sandbox purchases (TestFlight, App Review) cost nothing: record NGN 0 so # they never show up as revenue. note = (_purchase_note(pack, qty, "Apple sandbox test", test=True) if sandbox else _purchase_note(pack, qty, "Apple")) balance = await asyncio.to_thread(_apply_credits, uid, credits, "purchase", reference, note) if balance is None: raise HTTPException(status_code=500, detail="Your payment went through but the credits didn't save. Reopen the app to retry.") logger.info(f"Apple purchase {tx_id}: +{credits} credits for {uid} ({'sandbox' if sandbox else 'production'})") return {"balance": balance, "credits_added": credits, "already_credited": False} @app.post("/apple/notifications") async def apple_notifications(request: Request): """App Store Server Notifications V2. A refunded or revoked credit pack takes its credits back (never below zero).""" from src.apple_iap import verify_jws, AppleJWSError body = await request.json() try: note = verify_jws(str(body.get("signedPayload") or "")) except AppleJWSError as e: logger.warning(f"Apple notification rejected: {type(e).__name__}") raise HTTPException(status_code=400, detail="invalid signature") kind = note.get("notificationType") data = note.get("data") or {} if data.get("bundleId") not in STORE_BUNDLE_IDS or kind not in ("REFUND", "REVOKE"): return {"ok": True} try: tx = verify_jws(str(data.get("signedTransactionInfo") or "")) except AppleJWSError: return {"ok": True} if tx.get("environment") != "Production" or tx.get("bundleId") != data.get("bundleId"): return {"ok": True} tx_id = str(tx.get("transactionId") or "") rows = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger", None, {"kind": "eq.purchase", "reference": f"eq.apple:{tx_id}", "select": "firebase_uid,delta", "limit": "1"}) if not rows: logger.warning(f"Apple {kind} for unknown transaction {tx_id}") return {"ok": True} uid, delta = rows[0]["firebase_uid"], int(rows[0]["delta"]) await asyncio.to_thread(_apply_credits, uid, -delta, "refund", f"apple-refund:{tx_id}", f"Apple {kind.lower()}: purchase {tx_id} reversed") logger.info(f"Apple {kind} {tx_id}: -{delta} credits for {uid}") return {"ok": True} # ── Google Play Billing (Android) ──────────────────────────────────────────── # Same product ids and packs as the App Store. The app sends the purchase # token; src/google_play.py asks Google what it really is, then the pack is # credited once (reference google:<orderId>) and consumed so it can be bought # again. Test purchases by license testers cost nothing, so like Apple sandbox # they only fund the accounts in APPLE_SANDBOX_UIDS. @app.post("/credits/google") async def credits_google(request: Request): """Credit a verified Google Play purchase. Safe to call more than once for the same purchase: it is only ever credited once.""" from src import google_play from src.apple_iap import account_token uid = await asyncio.to_thread(_require_uid, request) body = await request.json() product_id = str(body.get("product_id") or "") purchase_token = str(body.get("purchase_token") or "") pack = _apple_pack(product_id) if not pack or not purchase_token: raise HTTPException(status_code=400, detail="This purchase isn't a NarratifAI credit pack.") try: purchase = await asyncio.to_thread(google_play.get_purchase, product_id, purchase_token, pack["bundle"]) except google_play.GooglePlayError as e: logger.warning(f"Google Play purchase check failed for {uid}: {e}") raise HTTPException(status_code=503 if e.retryable else 400, detail="We couldn't verify this purchase with Google Play." if not e.retryable else "Google Play is not reachable right now. Your purchase is safe and will be added shortly.") state = purchase.get("purchaseState") if state == 2: raise HTTPException(status_code=409, detail="Google Play is still processing this payment.") if state != 0: raise HTTPException(status_code=400, detail="This purchase was cancelled or refunded.") if purchase.get("obfuscatedExternalAccountId") != account_token(uid): logger.warning(f"Google purchase {purchase.get('orderId')} belongs to another account (caller {uid})") raise HTTPException(status_code=403, detail="This purchase was made from a different NarratifAI account.") test = purchase.get("purchaseType") == 0 if test and uid not in APPLE_SANDBOX_UIDS: raise HTTPException(status_code=403, detail="Test purchases cannot fund production credits.") order_id = str(purchase.get("orderId") or "") if not order_id: raise HTTPException(status_code=400, detail="We couldn't verify this purchase with Google Play.") reference = f"google:{order_id}" prior = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/credit_ledger", None, {"kind": "eq.purchase", "reference": f"eq.{reference}", "select": "firebase_uid", "limit": "1"}) if prior: if prior[0].get("firebase_uid") != uid: raise HTTPException(status_code=403, detail="This purchase was already added to a different account.") if purchase.get("consumptionState") != 1: await asyncio.to_thread(google_play.consume, product_id, purchase_token, pack["bundle"]) profile = await asyncio.to_thread(_billing_profile, uid) return {"balance": int((profile or {}).get("credits") or 0), "credits_added": 0, "already_credited": True} qty = max(1, int(purchase.get("quantity") or 1)) credits = pack["credits"] * qty note = (_purchase_note(pack, qty, "Google Play test", test=True) if test else _purchase_note(pack, qty, f"Google Play, {purchase.get('regionCode') or 'unknown region'}")) balance = await asyncio.to_thread(_apply_credits, uid, credits, "purchase", reference, note) if balance is None: raise HTTPException(status_code=500, detail="Your payment went through but the credits didn't save. Reopen the app to retry.") if not await asyncio.to_thread(google_play.consume, product_id, purchase_token, pack["bundle"]): logger.warning(f"Google purchase {order_id} credited but not consumed yet; the next check retries") logger.info(f"Google purchase {order_id}: +{credits} credits for {uid} ({'test' if test else 'production'})") return {"balance": balance, "credits_added": credits, "already_credited": False} def _google_voided_sync() -> int: """Take back credits for Google Play purchases refunded or charged back in the last 30 days. Each reversal is recorded once (google-refund:<orderId>).""" from src import google_play since = int((time.time() - 30 * 86400) * 1000) voided = [] for package in STORE_BUNDLE_IDS: if google_play.configured(package): voided += google_play.voided_purchases(since, package) reversed_count = 0 seen = set() for v in voided: order_id = str(v.get("orderId") or "") if not order_id or order_id in seen: continue seen.add(order_id) rows = _supabase_request("GET", "/rest/v1/credit_ledger", None, {"kind": "eq.purchase", "reference": f"eq.google:{order_id}", "select": "firebase_uid,delta", "limit": "1"}) if not rows: continue uid, delta = rows[0]["firebase_uid"], int(rows[0]["delta"]) if _apply_credits(uid, -delta, "refund", f"google-refund:{order_id}", f"Google Play refund: order {order_id} reversed") is not None: reversed_count += 1 return reversed_count async def _google_voided_loop(): while True: try: n = await asyncio.to_thread(_google_voided_sync) if n: logger.info(f"Google Play refunds checked: {n} purchase(s) reversed or already reversed") except Exception as exc: # GooglePlayError messages are our own wording (no tokens), so say why. from src import google_play why = str(exc) if isinstance(exc, google_play.GooglePlayError) else type(exc).__name__ logger.warning(f"Google Play refund check failed: {why}") await asyncio.sleep(6 * 3600) def _fulfill_paystack_charge(data): from src.payments import charge_payload, fulfillment_succeeded try: payload = charge_payload(data) except ValueError: raise HTTPException(status_code=400, detail="Invalid payment event") result = _supabase_request("POST", "/rest/v1/rpc/fulfill_payment_order", payload) if not fulfillment_succeeded(result): logger.error("Paystack fulfillment not completed for reference %s", payload["p_reference"]) raise HTTPException(status_code=503, detail="Payment not credited yet; retry required") return result @app.post("/paystack/verify") async def paystack_verify(request: Request): uid = await asyncio.to_thread(_require_uid, request) try: body = await request.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON") reference = body.get("reference") if isinstance(body, dict) else None if not isinstance(reference, str) or not reference or len(reference) > 200: raise HTTPException(status_code=400, detail="Payment reference required") orders = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None, {"reference": f"eq.{reference}", "firebase_uid": f"eq.{uid}", "select": "reference,credits,fulfilled_at", "limit": "1"}) if orders is None: raise HTTPException(status_code=503, detail="Payment status unavailable") if not orders: raise HTTPException(status_code=404, detail="Payment order not found") order = orders[0] if order.get("fulfilled_at"): return {"credited": True, "credits": order["credits"], "reference": reference} secret = os.getenv("PAYSTACK_SECRET_KEY", "") if not secret: raise HTTPException(status_code=503, detail="Payment verification unavailable") from src.payments import verified_charge try: data = await asyncio.to_thread(verified_charge, reference, secret) except Exception: raise HTTPException(status_code=503, detail="Could not verify payment; retry shortly") if data.get("domain") != "live" or data.get("status") != "success": return {"credited": False, "status": data.get("status", "pending"), "reference": reference} await asyncio.to_thread(_fulfill_paystack_charge, data) return {"credited": True, "credits": order["credits"], "reference": reference} @app.post("/paystack/webhook") async def paystack_webhook(request: Request): """Receive and verify Paystack webhook events; update Supabase on subscription changes.""" secret = os.getenv("PAYSTACK_SECRET_KEY", "") body = await request.body() sig = request.headers.get("x-paystack-signature", "") if not secret: # Without the secret the signature can't be checked; never trust an # unsigned "payment succeeded". logger.error("Paystack webhook received but PAYSTACK_SECRET_KEY is not set") raise HTTPException(status_code=503, detail="Payments not configured") expected = hmac.new(secret.encode(), body, hashlib.sha512).hexdigest() if not hmac.compare_digest(sig, expected): raise HTTPException(status_code=403, detail="Invalid signature") try: event = json.loads(body) except Exception: raise HTTPException(status_code=400, detail="Invalid JSON") if not isinstance(event, dict) or event.get("event") != "charge.success": return {"ok": True} data = event.get("data") if not isinstance(data, dict): raise HTTPException(status_code=400, detail="Invalid payment event") if data.get("domain") != "live" or data.get("status") != "success": return {"ok": True} await asyncio.to_thread(_fulfill_paystack_charge, data) return {"ok": True} # --------------------------------------------------------------------------- # GPU-aware transcription shim # On HuggingFace Spaces with ZeroGPU this acquires a shared A100 for the # duration of the call then releases it back to the pool. Everywhere else # (Modal, local) it is a plain function call. # --------------------------------------------------------------------------- if _HF_ZERO_GPU: @_spaces.GPU(duration=300) def _transcribe_with_engine(content: bytes, filename: str, **kwargs): return engine.transcribe_bytes(content, filename=filename, **kwargs) else: def _transcribe_with_engine(content: bytes, filename: str, **kwargs): return engine.transcribe_bytes(content, filename=filename, **kwargs) # The engine holds one "current model" shared by every job. Switching it at # submit time (as this used to) let a second upload swap the model out from # under a job that was still running. Each job now selects its own model and # runs inside this lock, so concurrent uploads queue instead of colliding. _ENGINE_LOCK = threading.Lock() # ── Keep-alive while jobs run ───────────────────────────────────────────────── # Both hosts sleep/scale down after a period with no *incoming requests*, # regardless of work in progress. That used to force long idle windows # (HF 1 h, Modal 1 h) so a job didn't die when the phone stopped polling, # and the idle GPU became the biggest serving cost. Instead, while any job # is running the server requests its own public URL every few minutes, # which counts as traffic on both hosts, so the idle window can be short. _ACTIVE_JOBS = 0 _ACTIVE_LOCK = threading.Lock() def _self_url() -> str: explicit = os.getenv("SELF_URL", "").rstrip("/") if explicit: return explicit host = os.getenv("SPACE_HOST", "") # set by Hugging Face Spaces return f"https://{host}" if host else "" def _keepalive_loop() -> None: while True: time.sleep(240) url = _self_url() if _ACTIVE_JOBS > 0 and url and _requests_available: try: _requests.get(f"{url}/health", timeout=15) except Exception as e: logger.warning(f"Keep-alive ping failed: {type(e).__name__}") threading.Thread(target=_keepalive_loop, name="keepalive", daemon=True).start() def _job_started() -> None: global _ACTIVE_JOBS with _ACTIVE_LOCK: _ACTIVE_JOBS += 1 def _job_finished() -> None: global _ACTIVE_JOBS with _ACTIVE_LOCK: _ACTIVE_JOBS = max(0, _ACTIVE_JOBS - 1) def _default_model_key() -> str: return engine.config.get("models", {}).get("default") or engine.current_model_key def _drop_repetition_segments(segments: list) -> list: """Remove hallucinated loops segment by segment instead of failing the job. Long meetings legitimately repeat phrases ("all in favour", the agenda title), so judging the whole transcript at once rejected real 30-60 min recordings after all the work was done. Here only segments that are themselves loops, or the 4th+ consecutive copy of the same text, go. """ cleaned = [] run_text, run_len = None, 0 for seg in segments: text = (seg.get("text") or "").strip() if not text: continue key = text.lower() run_len = run_len + 1 if key == run_text else 1 run_text = key if run_len > 3 or _is_repetition_loop(text): logger.info("Dropped repeated/looping segment") continue cleaned.append(seg) return cleaned _SENTENCE_SPLIT = __import__("re").compile(r"(?<=[.!?])\s+") def _collapse_repeated_sentences(segments: list) -> list: """Drop a sentence that exactly repeats one of the 3 sentences before it. Whisper sometimes loops inside a 30 s window ("X. Y. X. X.") without the whole segment looking like a loop. A person repeating a full 5+ word sentence verbatim within a few sentences is rare, so the copy is removed; short replies ("Yes. Yes.") are left alone. """ import re norm = lambda t: " ".join(re.sub(r"[^a-z0-9' ]", " ", t.lower()).split()) recent: list = [] out = [] for seg in segments: kept = [] for sentence in _SENTENCE_SPLIT.split((seg.get("text") or "").strip()): key = norm(sentence) if key and key in recent and len(key.split()) >= 5: continue if key: recent = (recent + [key])[-3:] kept.append(sentence) text = " ".join(kept).strip() if text: out.append({**seg, "text": text}) return out LONG_RECORDING_SEC = 600 # recordings this long also get an email when ready # A failed job's detail is what the user is told, then, after this marker, # what staff need to diagnose it. /result only ever returns the first part. _STAFF_DETAIL = " | staff: " _UNREADABLE_AUDIO = ("invalid data", "could not decode", "ffmpeg", "libsndfile", "soundfile", "unsupported format", "audio file could not be read", "no audio stream") def _failure_detail(e: BaseException) -> str: """Plain reason for the user plus the technical one for staff.""" name, text = type(e).__name__, str(e) low = f"{name} {text}".lower() if "out of memory" in low or name == "OutOfMemoryError": user = "The transcription server was too busy for this recording. Please try again in a few minutes." elif any(k in low for k in _UNREADABLE_AUDIO): user = "We couldn't read this audio file. Try exporting it as MP3, M4A or WAV and uploading it again." elif "timeout" in low or "timed out" in low: user = "This recording took too long to process. Please try again, or split it into shorter parts." else: user = "Something went wrong on our side while transcribing. Please try again." return f"{user}{_STAFF_DETAIL}{name}: {text[:300]}" def _user_detail(detail: Optional[str]) -> str: return (detail or "").split(_STAFF_DETAIL)[0].strip() def _worth_retrying(e: BaseException) -> bool: """A second attempt helps with server-side hiccups, not with a bad file.""" low = f"{type(e).__name__} {e}".lower() return not any(k in low for k in _UNREADABLE_AUDIO) def _notify(uid: str, kind: str, title: str, body: str, data: dict) -> None: """In-app notification; the database hands it on for email and push (notify-dispatch). Never fails the job.""" if not uid or uid == NOTETAKER_UID: return try: _supabase_request("POST", "/rest/v1/notifications", payload={ "firebase_uid": uid, "kind": kind, "title": title[:120], "body": body[:400], "data": data}) except Exception as e: logger.warning(f"Notification not saved: {type(e).__name__}") def _run_transcription_sync( jid: str, content: bytes, filename: str, model_key: Optional[str], **kwargs, ): """Sync worker running in ThreadPoolExecutor β€” returns immediately so 202 is sent.""" _job_started() meter = _ai_cost.start() settled = False try: if _is_cancelled(jid): raise _JobCancelled() with _ENGINE_LOCK: target_model = model_key or _default_model_key() if target_model != engine.current_model_key: engine.set_model(target_model) # One automatic retry for unexpected server errors, so a passing # problem (a model that failed to load, a GPU hiccup) never # reaches the user. Nothing is charged until the job settles. for attempt in (1, 2): try: result = _transcribe_with_engine(content, filename, **kwargs) break except _JobCancelled: raise except Exception as e: if attempt == 2 or not _worth_retrying(e) or _is_cancelled(jid): raise logger.warning(f"Job {jid} attempt 1 failed ({type(e).__name__}: {e}); retrying once", exc_info=True) if result.segments: result.segments = _collapse_repeated_sentences( _drop_repetition_segments(result.segments) ) result.text = " ".join((seg.get("text") or "").strip() for seg in result.segments) loop_only = not result.segments and _is_repetition_loop(result.text or "") if loop_only or not (result.text or "").strip(): logger.warning("No usable speech after loop cleanup") _upsert_job( jid, status="error", detail=( "Transcription failed: no clear speech was recognised. " "Try selecting the correct language manually or a larger model." ), ) return if result.segments: result.segments = _enhance_segments_with_claude( result.segments, ",".join(result.languages) if getattr(result, "languages", None) else (result.language or "en"), ) # Add tone marks / diacritics for Nigerian languages. A meeting that # switched language only gets them on the Yoruba/Igbo/Hausa parts. lang_for_diacritics = kwargs.get("language") or result.language if getattr(result, "languages", None): touched = False for seg in result.segments or []: seg_lang = seg.get("language") if seg_lang in ("yo", "ig", "ha") and seg.get("text"): seg["text"] = _add_diacritics_with_claude(seg["text"], seg_lang) touched = True if touched: result.text = " ".join(s.get("text", "") for s in result.segments if s.get("text")).strip() elif lang_for_diacritics in ("yo", "ig", "ha") and result.text: result.text = _add_diacritics_with_claude(result.text, lang_for_diacritics) for seg in result.segments or []: original = seg.get("text", "") if original: seg["text"] = _add_diacritics_with_claude(original, lang_for_diacritics) formatted_output = OutputFormatter.format(result.to_dict(), "json") payload = json.loads(formatted_output) speakers = None diarization_status = "skipped" diarize = kwargs.get("diarization", False) if result.segments: found = sorted({ seg.get("speaker") for seg in result.segments if seg.get("speaker") }) speakers = found if found else None if diarize: if not engine.diarization.is_available(): diarization_status = "unavailable" elif speakers: diarization_status = "success" else: diarization_status = "failed" speaker_sentiment = _get_speaker_sentiments(result.segments or [], {}) if _is_cancelled(jid): raise _JobCancelled() billing = _JOB_BILLING[jid] fixed = _credits_for_minutes(result.audio_duration / 60, billing["model"]) # Never below cost + markup: GPU time plus every Claude call this job made # (clean-up, tone marks, speaker mood), at the lowest price a credit sells for. rate = _ai_cost.credit_rate(_supabase_request) job_usd = meter.usd + _ai_cost.gpu_usd(float(getattr(result, "processing_time", 0) or 0), rate) floor = _ai_cost.floor_credits(fixed, job_usd, rate) # Transcription shows its price before it starts, so the floor only # charges more once PRICE_FLOOR_TRANSCRIPTION=enforce; until then it is # logged to show how often it would apply. cost = floor if os.getenv("PRICE_FLOOR_TRANSCRIPTION", "log") == "enforce" else fixed if floor > fixed: logger.info(f"Job {jid}: cost floor {'applied' if cost > fixed else 'would apply'} ({fixed} -> {floor} credits, ${job_usd:.4f})") result_payload = { "success": True, "filename": filename, "model_used": result.model_used, "processing_time": result.processing_time, "audio_duration": result.audio_duration, "language": result.language, "output_format": "json", "speakers": speakers, "diarization_status": diarization_status, "speaker_sentiment": speaker_sentiment, "result": payload, } completion = _supabase_request("POST", "/rest/v1/rpc/complete_transcription", payload={ "p_reference": jid, "p_cost": cost, "p_result": result_payload}) if cost > fixed and isinstance(completion, dict) and completion.get("error") == "insufficient_credits": # Not enough for the extra: deliver the transcript at the normal price. completion = _supabase_request("POST", "/rest/v1/rpc/complete_transcription", payload={ "p_reference": jid, "p_cost": fixed, "p_result": result_payload}) if not isinstance(completion, dict) or completion.get("error"): raise RuntimeError("Could not publish and settle transcription") if completion.get("cancelled"): raise _JobCancelled() settled = True logger.info(f"Job {jid} completed successfully.") name = os.path.splitext(os.path.basename(filename or ""))[0][:80] or "Your recording" _notify(kwargs.get("firebase_uid") or "", "transcript_ready", "Transcript ready", f"{name} has been transcribed. Tap to read it.", {"route": "/history", "job_id": jid, "long": bool(result.audio_duration and result.audio_duration >= LONG_RECORDING_SEC)}) # Track usage: increment audio_minutes_used in Supabase firebase_uid = kwargs.get("firebase_uid") or "" if firebase_uid and result.audio_duration: try: _supabase_increment_audio_minutes(firebase_uid, result.audio_duration) except Exception: pass except _JobCancelled: logger.info(f"Job {jid} cancelled β€” stopped and discarded.") _upsert_job(jid, status="cancelled", detail="Cancelled by user") _CANCELLED.discard(jid) except Exception as e: logger.error(f"Background transcription job {jid} failed: {type(e).__name__}: {e}", exc_info=True) _upsert_job(jid, status="error", detail=_failure_detail(e)) name = os.path.splitext(os.path.basename(filename or ""))[0][:80] or "Your recording" _notify(kwargs.get("firebase_uid") or "", "transcript_failed", "Transcription failed", f"We couldn't transcribe {name}. Any credits it used have been returned. Please try again.", {"route": "/history", "job_id": jid}) finally: _job_finished() _CANCELLED.discard(jid) _JOB_BILLING.pop(jid, None) _JOB_SUBMIT_TIMES.pop(jid, None) if not settled: try: _finish_work(jid, False) except Exception: logger.error("Reservation needs reconciliation: %s", jid) _WORK_SLOTS.release() @app.post("/companion/transcribe") async def transcribe_companion(request: Request): from src.companion import load_upload, assemble_upload import io uid = await asyncio.to_thread(_require_uid, request) body = await request.json() if not isinstance(body, dict): raise HTTPException(400, "Invalid request") upload = await asyncio.to_thread(load_upload, uid, body.get("id"), _supabase_request) if upload.get("job_id"): return JSONResponse(status_code=202, content={"job_id": upload["job_id"], "duplicate": True}) # Bound simultaneous assembly independently of GPU admission. if not _COMPANION_SLOTS.acquire(blocking=False): raise HTTPException(429, "Another upload is being prepared. Retry shortly.") try: content = await asyncio.to_thread(assemble_upload, upload, _supabase_request) request.state.companion_upload_id = upload["id"] suffix = ".mp4" if upload["mime_type"] == "audio/mp4" else ".ogg" if "ogg" in upload["mime_type"] else ".webm" return await transcribe(request, UploadFile(filename="meeting" + suffix, file=io.BytesIO(content)), language=None, task="transcribe", return_timestamps=True, output_format="json", model="whisper-small", diarization=True, num_speakers=None, job_id=None, firebase_uid=uid) finally: _COMPANION_SLOTS.release() _COMPANION_SLOTS = threading.BoundedSemaphore(1) @app.post("/voice/transcribe") async def voice_transcribe(request: Request, file: UploadFile = File(...), language: Optional[str] = Form(None)): """A short spoken question for Nari, turned into text synchronously. Called only by Nari's backend (shared secret NARI_VOICE_SECRET), which signs the user in and handles limits and billing.""" from src import voice as _voice if not _voice.authorized(request.headers.get("x-nari-voice-key"), os.getenv("NARI_VOICE_SECRET")): raise HTTPException(status_code=403, detail="Forbidden") if not engine: raise HTTPException(status_code=503, detail="Engine not initialized") content = await file.read(_voice.MAX_VOICE_BYTES + 1) if not content: raise HTTPException(status_code=400, detail="No audio") if len(content) > _voice.MAX_VOICE_BYTES: raise HTTPException(status_code=413, detail="Voice clips can be up to a minute long") langs = _voice.languages(language) started = time.time() if not _voice.wants_engine(langs): # Fast path: the dedicated voice model (no engine lock, no model swap). suffix = os.path.splitext(file.filename or "")[1] or ".webm" try: out = await asyncio.to_thread(_voice.transcribe_fast, content, suffix, langs) except ValueError: raise HTTPException(status_code=400, detail="That recording couldn't be read") if out.get("too_long"): raise HTTPException(status_code=413, detail="Voice clips can be up to a minute long") return {**out, "processing_seconds": round(time.time() - started, 2), "path": "fast"} def run(): # Share the engine with transcription jobs, but don't wait behind a # long job: a voice question that can't start soon is refused. if not _ENGINE_LOCK.acquire(timeout=20): return None try: return _transcribe_with_engine(content, file.filename or "voice.webm", language=langs[0] if langs else None, languages=langs, respect_pick=bool(langs)) finally: _ENGINE_LOCK.release() result = await asyncio.to_thread(run) if result is None: raise HTTPException(status_code=503, detail="Busy. Try again in a moment.") seconds = float(getattr(result, "audio_duration", 0) or 0) if seconds > _voice.MAX_VOICE_SECONDS: raise HTTPException(status_code=413, detail="Voice clips can be up to a minute long") return { "text": _voice.clean_text(getattr(result, "text", "")), "language": getattr(result, "language", None), "seconds": round(seconds, 2), "processing_seconds": round(time.time() - started, 2), "path": "engine", } @app.post("/transcribe") async def transcribe( request: Request, file: UploadFile = File(...), language: Optional[str] = Form(None), task: str = Form("transcribe"), return_timestamps: bool = Form(True), output_format: str = Form("json"), model: Optional[str] = Form(None), diarization: bool = Form(False), num_speakers: Optional[int] = Form(None), job_id: Optional[str] = Form(None), firebase_uid: Optional[str] = Form(None), ): """ Submit an audio file for transcription. Returns 202 immediately with a job_id. Poll GET /result/{job_id} for the completed transcript. Poll GET /progress/{job_id} for chunk-level progress. """ uid = await asyncio.to_thread(_require_uid, request) if not engine: raise HTTPException(status_code=503, detail="Engine not initialized") if not file.filename: raise HTTPException(status_code=400, detail="No file provided") content = await file.read(_MAX_UPLOAD_BYTES + 1) if len(content) > _MAX_UPLOAD_BYTES: raise HTTPException(status_code=413, detail="Audio upload is too large") # Support comma-separated multi-language hints: "yo,en" or "ig,en" lang_list = [l.strip().lower() for l in (language or "").split(",") if l.strip() and l.strip() != "auto"] primary_lang = lang_list[0] if lang_list else None # Upgrade model if ANY requested language is a Nigerian language needs_upgrade = any(l in _UPGRADE_LANGUAGES for l in lang_list) effective_model = model if needs_upgrade: # Only upgrade to large-v3 when GPU is available. On CPU, large-v3 # is impractically slow and may OOM on resource-constrained hosts. try: import torch has_gpu = torch.cuda.is_available() except Exception: has_gpu = False if has_gpu: if not effective_model or effective_model != _UPGRADE_TARGET: logger.info(f"Languages {lang_list} β€” GPU detected, auto-upgrading model to {_UPGRADE_TARGET}") effective_model = _UPGRADE_TARGET else: logger.info(f"Languages {lang_list} β€” CPU-only, staying with default model for speed") effective_model = effective_model or _default_model_key() # One Nigerian language, alone or with English: use its dedicated model # (falls back to large-v3 inside the engine if it can't load), at the # same price either way. natives = [l for l in lang_list if l in NATIVE_MODELS] if len(natives) == 1 and all(l in NATIVE_MODELS or l == "en" for l in lang_list) and native_asr_enabled() \ and NATIVE_MODELS[natives[0]] in engine.registry.list_available_models(): effective_model = NATIVE_MODELS[natives[0]] logger.info(f"Languages {lang_list}: using {effective_model}") # Validate only; the worker switches models under _ENGINE_LOCK. if effective_model and effective_model not in engine.registry.list_available_models(): raise HTTPException( status_code=400, detail=f"Model '{effective_model}' not available. Options: {list(engine.registry.list_available_models().keys())}", ) paused = _paused("allow_transcription_api", "Transcription") if paused: raise paused seconds = await asyncio.to_thread(_probe_duration_sec, content, file.filename) import math if seconds is None or not math.isfinite(seconds) or seconds <= 0: raise HTTPException(status_code=400, detail="Could not determine audio duration") if seconds > _MAX_AUDIO_SECONDS: raise HTTPException(status_code=413, detail="Audio must be at most two hours") if not _WORK_SLOTS.acquire(blocking=False): raise HTTPException(status_code=429, detail="Server busy. Try again later.") # Ignore legacy client IDs; they never select a persistent job key. jid = str(uuid.uuid4()) billing_model = effective_model or _default_model_key() # A model chosen for the user (Nigerian languages need a bigger one) never # costs more than the option they picked. chosen = model or _default_model_key() if CREDITS_PER_MINUTE.get(chosen, 1) < CREDITS_PER_MINUTE.get(billing_model, 1): billing_model = chosen cost = _credits_for_minutes(seconds / 60, billing_model) reserved = False try: reservation = await asyncio.to_thread(_reserve_work, uid, jid, cost, "transcription", companion_id=getattr(request.state, "companion_upload_id", None)) if reservation.get("duplicate"): _WORK_SLOTS.release() return JSONResponse(status_code=202, content={"job_id": reservation["job_id"], "status": "processing", "duplicate": True}) jid = reservation.get("job_id", jid) reserved = True _JOB_BILLING[jid] = {"uid": uid, "model": billing_model, "reserved": cost} now = time.time() _JOB_SUBMIT_TIMES[jid] = now # SQL creates the owner-bound job insert-only in the reservation transaction. _purge_old_jobs() except Exception: if reserved: await asyncio.to_thread(_finish_work, jid, False) _JOB_BILLING.pop(jid, None) _WORK_SLOTS.release() raise # For Nigerian languages we pass the primary language code explicitly # (e.g. "yo") so Whisper uses its Yoruba decoder and produces proper # tone marks. When multiple languages are requested, we still pass the # primary one β€” Whisper handles occasional English words within a # predominantly Yoruba stream better than pure auto-detection. effective_lang = primary_lang def _progress_cb(current: int, total: int) -> None: if _is_cancelled(jid): raise _JobCancelled() percent = round(current / total * 100) if total > 0 else 0 progress = {"current": current, "total": total, "percent": percent} _upsert_job(jid, status="processing", progress=progress) # We deliberately do NOT pass a static initial_prompt for Nigerian # languages. Whisper's HuggingFace implementation treats the prompt as # prefix text and regurgitates it when uncertain, causing cascading # hallucinations across chunks. Rely on whisper-large-v3's training # data for Yoruba/Igbo/Hausa diacritics instead. transcription_kwargs = { "language": effective_lang, # Every requested language: a meeting may switch between them (or # into English); the engine finds where each one is spoken. "languages": lang_list, "task": task, "return_timestamps": return_timestamps, "diarization": diarization, "num_speakers": num_speakers, "progress_callback": _progress_cb, "firebase_uid": uid, } try: _executor.submit( _run_transcription_sync, jid, content, file.filename or "audio", effective_model, **transcription_kwargs, ) except Exception: try: await asyncio.to_thread(_finish_work, jid, False) await asyncio.to_thread(_upsert_job, jid, status="error", detail="Queue unavailable") finally: _JOB_BILLING.pop(jid, None) _WORK_SLOTS.release() raise HTTPException(status_code=503, detail="Queue unavailable. Try again later.") logger.info(f"Job {jid} accepted β€” transcription running in background.") return JSONResponse( status_code=202, content={"job_id": jid, "status": "processing"}, ) @app.get("/health") async def health_check(): return { "status": "healthy", "engine_initialized": engine is not None } def main(): parser = argparse.ArgumentParser(description="Modular ASR Transcription System") parser.add_argument("--api", action="store_true", help="Run as API server") parser.add_argument("--host", default="0.0.0.0", help="API host") parser.add_argument("--port", type=int, default=7860, help="API port") parser.add_argument("--config", "-c", help="Config file path") args = parser.parse_args() if args.config: os.environ["CONFIG_PATH"] = args.config if args.api: uvicorn.run(app, host=args.host, port=args.port) return if __name__ == "__main__": main()
"""
Main application entry point for Hugging Face Space
Author: Maaldeens
License: MIT
"""
import asyncio
import hashlib
import hmac
import io
import json
import os
import threading
import time
import uuid
import argparse
import logging
import warnings
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
import uvicorn
from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
# pyannote.audio calls torchaudio.set_audio_backend() which is a no-op in
# torchaudio 2.x (dispatcher always enabled). Suppress the UserWarning it emits.
warnings.filterwarnings(
"ignore",
message="torchaudio._backend.set_audio_backend has been deprecated",
category=UserWarning,
)
try:
import requests as _requests
_requests_available = True
except ImportError:
_requests_available = False
# ZeroGPU support β€” only activate on ZeroGPU Spaces.
# SPACES_ZERO_GPU=1 is set exclusively by HF's ZeroGPU infrastructure.
# SPACE_ID is present on ALL HF Spaces (including T4/A10G paid tiers) and
# is therefore NOT a reliable gate; use SPACES_ZERO_GPU instead.
try:
import spaces as _spaces
_HF_ZERO_GPU = os.getenv("SPACES_ZERO_GPU") == "1"
except ImportError:
_spaces = None
_HF_ZERO_GPU = False
_executor = ThreadPoolExecutor(max_workers=2)
# All compute and job routes require a verified Firebase user. Integrations
# must obtain their own service account's Firebase ID token; shared keys do
# not grant user impersonation or bypass billing.
_MAX_AUDIO_SECONDS = 2 * 60 * 60
_MAX_UPLOAD_BYTES = 256 * 1024 * 1024
_WORK_SLOTS = threading.BoundedSemaphore(8)
# ── Supabase persistent job storage ──────────────────────────────────────────
_SUPABASE_URL = os.getenv("SUPABASE_URL", "")
_SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
def _sb_headers() -> dict:
return {
"apikey": _SUPABASE_KEY,
"Authorization": f"Bearer {_SUPABASE_KEY}",
"Content-Type": "application/json",
"Prefer": "return=representation",
}
def _supabase_request(method: str, path: str, payload=None, params=None) -> Optional[dict]:
"""Make a request to Supabase REST API using requests library."""
if not _requests_available:
return None
if not _SUPABASE_URL or not _SUPABASE_KEY:
return None
url = f"{_SUPABASE_URL}{path}"
headers = _sb_headers()
if method in ("POST", "PUT", "PATCH") and payload is not None:
headers["Prefer"] = "return=representation,resolution=merge-duplicates"
try:
resp = _requests.request(
method,
url,
params=params,
json=payload,
headers=headers,
timeout=10,
)
if resp.status_code >= 400:
logger.warning(f"Supabase {method} {path} HTTP {resp.status_code}")
return None
return resp.json() if resp.text else {}
except Exception as e:
logger.warning(f"Supabase {method} {path} failed: {type(e).__name__}")