Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

COPE AI Assistant — offline, CPU-only Hinglish audio → Form-1 pipeline

A privacy-first, fully-offline, CPU-only pipeline that turns peer-support meeting audio into a structured wellbeing report ("Form 1: Peer Interaction Log"). Built for a headless Linux mini-server (Intel Xeon Gold 6338 @ 2.0 GHz, 4 logical CPUs, 31 GiB usable RAM, ~1 TB virtual disk, no GPU). Nothing leaves the box — after a one-time online bootstrap, the system runs with the network cable unplugged.

Testing build. Scope: live in-browser recording + file upload, batch transcription, PII redaction, Form-1 generation, reviewer edit/approve, single local Postgres + Redis + Ollama. Real-time streaming transcription, all five report forms, WhatsApp integration, analytics, and external alert delivery are out of scope for this build. The architecture does not preclude adding them later.


Quick start (for a teammate who just cloned this repo)

# 0. Install Docker Engine + Docker Compose v2 (one-time; needs sudo).
#    See the "Prerequisites" section below for the exact commands.
sudo apt-get update
sudo apt-get install -y docker.io docker-compose-plugin openssl

# 1. Copy .env.example to .env and set real secrets (placeholders are rejected).
cp .env.example .env
# Edit .env — at minimum set:
#   JWT_SECRET, POSTGRES_PASSWORD, REDACTION_ENVELOPE_KEY
#   (long random strings). Defaults already pick the box-tuned models.

# 2. ONE-TIME bootstrap. Needs the network. Downloads:
#       Ollama Qwen3-14B (~9.2 GiB) + faster-whisper/IndicWhisper + Silero VAD
#       + IndicNER. Optionally Qwen3-30B-A3B (~18.5 GiB) if you set
#       BOOTSTRAP_PULL_OPT_IN=true in .env.
make bootstrap

# 3. Verify offline readiness (cable can stay in — the internal Docker
#    network is the egress cutoff; this confirms it).
make verify-offline

# 4. Start everything (offline-safe).
make up

# 5. Run the smoke test (bundled silence WAV; replace with a real Hinglish
#    clip in backend/samples/hinglish_short.wav for content assertions).
make smoke

Open https://<mini-server-IP>/ — accept the self-signed cert warning (see "Trusting the self-signed cert" below). Default seeded logins (test build only — see bootstrap/seed.py):

  • reviewer / reviewer — records, edits and approves reports
  • admin / admin — also operates the headless box via the /admin portal

How the system is shaped

Two separated concerns (the spec mandate)

  • Ingestion (live recording + file upload) is concurrent, I/O-only, and unbounded on this hardware. Many people can record at once; the server only appends bytes to per-session files on the local volume. No model work.
  • Processing is a single Redis-backed Celery queue with WORKER_CONCURRENCY=1 (hard-capped to 1 on this 4-core box — see app/config.py). Jobs run FIFO; while one runs, the others wait. The admin portal surfaces queue position + ETA. Concurrency > 1 would thrash the 4 cores.
  • Jobs are persisted in Postgres; the queue survives a make down/up. Nothing is lost on a normal restart.

Pipeline stages (each idempotent, each writes job_events)

RECORDING ─ finalize ─▶ PENDING ─▶ PREPROCESSING ─▶ VAD ─▶ TRANSCRIBING
   ─▶ NORMALIZING ─▶ REDACTING ─▶ ENRICHING ─▶ GENERATING ─▶ DRAFTED
   ─▶ (reviewer edit/approve) ─▶ COMPLETED (audio deleted per retention)

Memory strategy (verified against this box)

On a 4-core box the bottleneck is CPU cores, not RAM — so we don't buy throughput with parallelism; instead we spend spare RAM on warmth + quality: the LLM and the ASR model stay resident forever. The default LLM is qwen3:14b-instruct-q4_k_m (~9.2 GiB resident) precisely because 30B-A3B (which does fit in 31 GiB) does not buy throughput on a 4-core CPU and leaves thin headroom during live jobs. The 30B-A3B model is opt-in via OLLAMA_MODEL=qwen3:30b-a3b-q4_k_m for non-interactive quality runs.

Approximate resident budget (14B default):

Component Resident
OS + containerd + cgroup overhead ~1.4 GiB
Postgres (tuned: shared_buffers 1GB, effective_cache 6GB reclaimable) ~1.4 GiB
Redis ~0.3 GiB
Ollama + Qwen3-14B Q4_K_M ~9.3 GiB
faster-whisper medium int8 ~1.9 GiB
Silero VAD + IndicNER ~0.7 GiB
api + worker Python ~1.4 GiB
tmpfs /scratch (RAM-backed) up to 2.0 GiB
One job's transient buffers (conc=1 ever) ~1.3 GiB
Peak ~18–19 GiB (headroom on 31 GiB)

30B-A3B peak ≈ 28 GiB (fits, tight). The /admin/system panel shows live RAM so the operator can watch peak-vs-budget at any moment. (Measured numbers get recorded into the README at the end of the testing phase.)

Locked stack

  • Backend: FastAPI + Uvicorn (Python 3.11), Celery workers, Redis broker, PostgreSQL 16 with JSONB columns.
  • LLM serving: Ollama — its OpenAI-compatible endpoint at ollama:11434 is only reachable on the internal Docker network.
  • ASR runtime: faster-whisper (CTranslate2 int8) inside the worker.
  • VAD: Silero VAD (segments speech, drops silence).
  • NER: AI4Bharat IndicNER (MuRIL-based) + deterministic regex rules.
  • Diarization: pyannote 3.1, gated, OFF by default (ENABLE_DIARIZATION).
  • LLM model: Qwen3-14B-Instruct Q4_K_M (primary) · 8B (speed) · 30B-A3B (opt-in) — all one-line swaps via OLLAMA_MODEL.
  • Frontend: minimal vanilla-JS SPA (no build chain) served by nginx.
  • Audio decode: ffmpeg. Object storage: a local Docker volume on the SSD (no S3 / MinIO in this build).
  • TLS termination: nginx with a self-signed cert generated at bootstrap.

Offline proof (acceptance: no inference call leaves the host)

The whole stack attaches to a Docker network with internal: true (see docker-compose.yml). Docker installs no outbound route to the host/internet for any service on that network — the services can still reach each other (Postgres, Redis, Ollama, api↔worker over the broker).

To prove it after bootstrap:

make verify-offline
# (and, belt-and-braces)
sudo iptables -P OUTPUT DROP && make up && make smoke && sudo iptables -P OUTPUT ACCEPT

bootstrap/verify_offline.sh also confirms the model/weight volumes are populated and the network is internal: true.


Trusting the self-signed cert (one-time, per browser)

The recorder uses getUserMedia/MediaRecorder, which require a secure context (HTTPS or localhost). The mini-server is on a LAN IP, so we serve over HTTPS with a self-signed cert (see bootstrap/gen-cert.sh — it bakes the host's IP 10.1.46.52 + localhost into the SAN).

  • Browsers will warn on first visit. Click "Advanced → Proceed" to trust per-session, or
  • Import compose/nginx/certs/selfsigned.crt into your OS/browser trust store for a permanent fix (per-device). On Chrome/Edge: Settings → Privacy and security → Security → Manage certificates → Authorities → Import.

Configuration

All configuration is via .env (see .env.example). Defaults are tuned to the measured target box. Highlights:

Var Default Purpose
OLLAMA_MODEL qwen3:14b-instruct-q4_k_m Primary LLM. 30B-A3B is opt-in.
OLLAMA_MODEL_OPT_IN qwen3:30b-a3b-q4_k_m Available but RAM-tight on this box.
OLLAMA_MODEL_SPEED qwen3:8b Speed tier.
OLLAMA_KEEP_ALIVE -1 Never unload — models stay warm-resident.
OLLAMA_NUM_THREAD 2 ≤4 cores; leave room for ASR pass.
WORKER_CONCURRENCY 1 Capped to 1 by config on a 4-core box.
STT_PROVIDER faster_whisper_indic Alt: faster_whisper_large_v3, whisper_cpp.
STT_CPU_THREADS 2 Shares cores with Ollama.
VAD_* tuned See .env.example.
MAX_AUDIO_SECONDS 7200 (2 h) Backpressure cap.
MAX_UPLOAD_MB 600 Upload cap.
MAX_QUEUE_DEPTH 20 Past this, intake returns 429.
AUDIO_RETENTION_HOURS 0 0 = delete at COMPLETED.
ENABLE_DIARIZATION false true also requires PYANNOTE_TOKEN.

The config validator forces: WORKER_CONCURRENCY=1, no placeholder secrets, PYANNOTE_TOKEN when diarization is on, RAM/caps not exceeding the box.

How to swap models (zero code change)

Edit .env:

OLLAMA_MODEL=qwen3:30b-a3b-q4_k_m   # opt-in

Then:

make down && make up
docker compose exec ollama ollama pull <model>   # if not already pulled at bootstrap

If you did not pull the model at bootstrap, set BOOTSTRAP_PULL_OPT_IN=true before re-running make bootstrap, or just docker compose exec ollama ollama pull <model> while the network is up.

You can also swap at runtime from the admin portal (/admin/config/model), which writes app_state.active_model; the worker picks up the change at the next job and an Ollama reload (briefly frees + re-loads RAM) happens.


Retention & privacy (privacy by construction)

  • Unredacted normalized transcript is encrypted (AES-GCM with REDACTION_ENVELOPE_KEY) into the transcripts.normalized_text bytea column only transiently, and is purged at finalization along with the audio. Raise PURGE_UNREDACTED_AT_FINALIZE=false at your peril (validator forbids it; the JSONB redacted_text is the durable record).
  • Audio is deleted per AUDIO_RETENTION_HOURS (default 0 = at COMPLETED).
  • The redactions.redaction_map stores only content hashes of original spans — never the original spans; reversing is impossible from the map alone.
  • PII is scrubbed from logs (app/logging.py has a per-handler filter hitting email/phone/roll-no/hostel patterns). Turn on LOG_LEVEL=DEBUG and verify: log output contains [EMAIL], [PHONE], etc.
  • The internal Docker network is the primary egress cutoff; running iptables -P OUTPUT DROP adds a second layer.

Operator: the /admin portal

The box is headless; /admin is the operator's only window. Login as admin. It shows:

  • Live service health (/healthz per service).
  • Live RAM/CPU/SSS via psutil, against the 32 GiB budget.
  • The live queue (depth, the current job's stage + ETA, waiting jobs).
  • Recent jobs (duration, peak MiB, status, crisis flag) and a failures view.
  • Active models + warmth status, diarization toggle.
  • Audio retention status.

Operator controls (every action writes audit_log; destructive actions require a confirm step in the UI):

  • Retry a failed job — re-runs from the last incomplete stage (idempotent).
  • Cancel a stuck job — sets CANCELLED; the worker honors it at the next stage boundary.
  • Pause / resume the queue (queued jobs stay put; the worker just stops pulling).
  • Toggle diarization (ENABLE_DIARIZATION at runtime via app_state).
  • Swap the active LLM model (OLLAMA_MODEL view).

Auto-refreshes over /ws/admin (1 s push) + REST polling of job/failure tables (5 s).


Trouble / diagnostics

make logs            # docker compose logs -f
make psql            # interactive psql inside the postgres container
make shell-worker    # bash inside the worker (psutil, ffmpeg, ct2 all here)
make shell-api

(If make logs doesn't exist yet — it's added in the next pass; meanwhile use docker compose logs -f directly.)


Acceptance tests (mapped to criteria)

# Test Source
A1 Offline run after make bootstrap with internal-only network bootstrap/verify_offline.sh
A2 No-egress proof (tcpdump / iptables test) documented in docs/egress-test.md
A3 E2E smoke produces Form-1 draft, editable, approvable make smoke → smoke_test.py
A4 Peak RAM ≤ 32 GB (measured via /admin/system) manual run
A5 Stage idempotency + retry test_stage_idempotency.py
A6 Consent gating refuses processing test_consent_required.py
A7 Live capture concurrency + FIFO test_queue_fifo.py + manual multi-client
A8 Backpressure (201+min, 601+MiB, 21st queue) manual
A9 FIFO + position + ETA test_queue_fifo.py
A10 Crisis flag UI banner manual
A11 Admin controls + audit manual; audit_log rows queryable via psql
A12 Redaction regex + map test_redaction_rules.py
A13 Schema validation + repair loop test_form1_schema.py
A14 PII scrubbed from logs manual
A15 Reproducibility (clone → bootstrap → up → smoke) this README

Prerequisites (one-time, host-level)

Docker and Docker Compose v2 are required; the box ships without them. As a sudo-enabled user (outside opencode):

sudo apt-get update
sudo apt-get install -y docker.io docker-compose-plugin openssl
sudo usermod -aG docker $USER
# Log out and back in for the docker group to take effect, then:
docker --version && docker compose version

Optional (recommended for a single-VM test server): enlarge swap from the default 2 GiB to 8 GiB so a transient spike never OOMs the box. As sudo:

sudo swapoff /swapfile 2>/dev/null
sudo fallocate -l 8G /swapfile && sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Project layout

See docs/DESIGN.md for the full file tree and Phase-1 design rationale. This README is the operator/teammate view; the design doc is the architect view.

  • compose/ — Docker Compose topology + Dockerfiles + nginx TLS config.
  • bootstrap/ — one-time-online scripts: model pulls, ASR conversion, cert generation, seed, offline verification.
  • backend/app/ — FastAPI app + pipeline + providers + worker entrypoint.
  • backend/migrations/ — Alembic init DDL.
  • backend/tests/ — unit + integration tests.
  • backend/smoke_test.py — end-to-end driver.
  • backend/samples/ — bundled silence WAV; replace with a real Hinglish clip for content-meaningful smoke runs.
  • packages/portal-ui/dist/ — the SPA. No build step; served statically.
  • docs/ — DESIGN.md, egress-test.md.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages