"""Container start-up: prepare the database, create the first admin, then serve. A deployed instance has no shell for an operator to run ``manage.py init`` in, so the first admin has to come from the environment. That makes the password the single most dangerous value in the deployment, and this file spends most of its length on it: * a literal ``changeme`` (or anything under 12 characters) is refused outright -- the app reaches real patient audio, and a guessable admin account on a public URL is not a "testing shortcut", it is an open door; * with no password supplied at all, one is generated and printed once. That is safe to leave unattended: nobody can log in without reading the logs. Everything else is environment plumbing: PORT / ANNOTATOR_PORT listen port (7860 suits Hugging Face Spaces) ANNOTATOR_DB database file; defaults under ANNOTATOR_DATA ANNOTATOR_DATA writable directory for the db and the chunk cache ANNOTATOR_SECRET session signing key -- required, see app.main ANNOTATOR_ADMIN admin username (default "admin") ANNOTATOR_ADMIN_PASSWORD admin password; generated if absent ANNOTATOR_DEMO seed the bundled sample corpus into an empty database """ from __future__ import annotations import os import secrets import string import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) MIN_PASSWORD = 12 WEAK = {"changeme", "password", "admin", "admin123", "aimscribe", "12345678"} def pick_data_dir() -> Path: """First writable candidate wins. Hugging Face Spaces mount persistent storage at /data when it is enabled; without it the directory is absent or read-only and the app falls back to the image, where the database lives only as long as the container does. """ for candidate in (os.getenv("ANNOTATOR_DATA"), "/data", str(ROOT / "annotator" / "data")): if not candidate: continue p = Path(candidate) try: p.mkdir(parents=True, exist_ok=True) probe = p / ".write-test" probe.write_text("ok", encoding="utf-8") probe.unlink() return p except Exception: continue raise RuntimeError("no writable data directory found") def resolve_admin_password() -> tuple[str, bool]: """(password, was_generated). Refuses anything guessable.""" given = os.getenv("ANNOTATOR_ADMIN_PASSWORD", "").strip() if not given: alphabet = string.ascii_letters + string.digits return "".join(secrets.choice(alphabet) for _ in range(20)), True if given.lower() in WEAK or len(given) < MIN_PASSWORD: raise SystemExit( f"\n REFUSING TO START: ANNOTATOR_ADMIN_PASSWORD is weak.\n" f" It must be at least {MIN_PASSWORD} characters and not a common word.\n" f" This account can read every patient recording in the corpus.\n" f" Leave it unset and one will be generated for you.\n") return given, False def bootstrap_demo(db_path: str) -> None: """Fill an empty deployment with the bundled sample so it has something to show. A Space that boots to an empty queue demonstrates nothing: no audio, no tasks, a dashboard of dashes. This imports the two short recordings shipped in ``demo_assets`` into both tracks and simulates a few days of work by annotators with deliberately different habits, so every screen is populated the moment the URL opens. Runs only when ``ANNOTATOR_DEMO`` is set and the database holds no recordings, so it can never overwrite real annotation work. """ from annotator.app.db import Recording, Task, get_session session = get_session() if session.query(Recording).count(): session.close() return session.close() assets = ROOT / "annotator" / "demo_assets" if not (assets / "audio").is_dir(): print(" ANNOTATOR_DEMO set but annotator/demo_assets is missing", flush=True) return from annotator.app.importer import import_folder from annotator.seed_demo import seed print(" seeding demo data (ANNOTATOR_DEMO=1)", flush=True) stats = import_folder(assets / "audio", [assets / "v1"], [assets / "v1"], chunk_s=150.0, gold_fraction=0.45, double_fraction=0.3, calibration=4, mode="diarization") # The same chunks again for the transcription track: the two workforces work the same # audio, and cloning here avoids re-cutting it. session = get_session() for t in session.query(Task).filter(Task.mode == "diarization").all(): session.add(Task(recording_id=t.recording_id, index=t.index, start_s=t.start_s, end_s=t.end_s, kind=t.kind, wanted=t.wanted, mode="transcription", prediction=t.prediction, gold=t.gold)) session.commit() session.close() work = seed(reset=False, db_path=db_path) print(f" demo ready: {stats['recordings']} recordings, {stats['tasks'] * 2} tasks, " f"{work['submissions']} submissions", flush=True) print(" SYNTHETIC DATA -- the Bengali is a scripted consultation, not a real patient.", flush=True) def main() -> int: data = pick_data_dir() os.environ.setdefault("ANNOTATOR_DATA", str(data)) os.environ.setdefault("ANNOTATOR_CACHE", str(data / "chunks")) os.environ["ANNOTATOR_DEPLOYED"] = "1" db_path = os.getenv("ANNOTATOR_DB") or str(data / "annotator.db") port = int(os.getenv("PORT") or os.getenv("ANNOTATOR_PORT") or 7860) host = os.getenv("ANNOTATOR_HOST", "0.0.0.0") from annotator.app.db import User, get_session, init_db init_db(db_path) if os.getenv("ANNOTATOR_DEMO"): bootstrap_demo(db_path) session = get_session() existing = session.query(User).filter_by(role="admin").first() if existing is None: from annotator.app.main import hash_password username = os.getenv("ANNOTATOR_ADMIN", "admin").strip() or "admin" password, generated = resolve_admin_password() session.add(User(username=username, full_name="Administrator", password_hash=hash_password(password), role="admin", track="both", qualified=True)) session.commit() print("\n" + "=" * 64) print(f" created admin account: {username}") if generated: print(f" generated password: {password}") print(" This is printed once. Copy it now, then change it in the app.") else: print(" password: from ANNOTATOR_ADMIN_PASSWORD") print("=" * 64 + "\n") else: print(f" admin account present: {existing.username}") session.close() persistent = str(data) != str(ROOT / "annotator" / "data") print(f" data {data}" + ("" if persistent else " (EPHEMERAL - lost on rebuild)")) print(f" database {db_path}") print(f" listening http://{host}:{port}") if not persistent: print(" NOTE: this instance has no persistent volume. Annotations survive restarts\n" " of the process but not a rebuild of the container. Fine for a trial;\n" " attach a volume before real annotation work begins.") import uvicorn from annotator.app.main import create_app create_app(db_path) uvicorn.run("annotator.app.main:app", host=host, port=port, proxy_headers=True, forwarded_allow_ips="*") return 0 if __name__ == "__main__": raise SystemExit(main())