Got it. Let’s design **the ASR engine** as a proper daemon with a stable gRPC surface, while keeping it compact and aligned with your “Go owns lifecycle + shared FS + sequential jobs + kill/restart daemon” constraints.

Below is the **technical layout plan** + how your two scripts become a reusable engine that supports:

* multiple model variants (Parakeet, Canary, etc.)
* job-specific parameters (VAD preset/tuning, timestamps mode, threads, language, etc.)
* consistent input/output coordination using filesystem paths
* streaming status updates to Go (gRPC server-stream)
* robust kill semantics (Go kills/restarts daemon)

---

## 1) ASR Engine responsibilities (strict and simple)

### Engine daemon (Python, gRPC over UDS)

Implements:

* `LoadModel(ModelSpec)` → loads VAD + ONNX model pipeline; keeps warm
* `UnloadModel(model_id)` → frees pipeline
* `StartJob(JobSpec + job_params)` → runs transcription, writes outputs under `output_dir`
* `StopJob(job_id)` → cooperative cancel (best effort)
* `GetJobStatus(job_id)` + `StreamJobStatus(job_id)` → updates to Go
* `ListLoadedModels()` + memory/resource snapshot

Constraints:

* exactly **one loaded model** at a time (v1)
* exactly **one running job** at a time (v1)
* if busy, `StartJob` returns `RESOURCE_EXHAUSTED`

**Kill** is *not* handled inside engine: Go kills the daemon process and restarts it. (Engine can expose a `KillJob` RPC for symmetry/logging, but Go doesn’t rely on it.)

---

## 2) How to coordinate audio input + results paths (your question)

### The rule

**Go provides:**

* `input_path`: absolute path inside container (e.g., `/data/in/foo.wav`)
* `output_dir`: absolute path inside container (e.g., `/data/out/<job_id>/`)
* `job_id`: generated by Go

**Engine writes:**

* transcript text file
* segments JSONL (real segment timestamps)
* optional word JSONL (heuristic word timestamps)
* a final `result.json` summary
* a `status.json` (optional but recommended for debugging)

**Engine returns** (in final JobStatus):

* a map of output file paths (strings), and basic stats

This is deterministic, debuggable, and requires no data transfer.

### Output naming convention (stable)

Inside `output_dir` the ASR engine writes:

* `transcript.txt`
* `segments.jsonl`  (segment timestamps from `seg.start/seg.end`)
* `words.jsonl`     (optional; heuristic)
* `result.json`     (single structured summary)
* `status.json`     (optional; updated periodically)

Go can depend on these names.

---

## 3) Convert your scripts into an engine: internal module design

Your scripts mix:

* model initialization (VAD + onnxruntime session options + `onnx_asr.load_model(...).with_vad(...)`)
* audio loading
* segment postprocessing (merge short segments)
* timestamp dumping

We turn that into three layers:

### A) `AsrBackend` (pure logic; testable)

* owns the loaded pipeline (vad + model)
* exposes `transcribe(audio_path, output_dir, params, cancel_token) -> ResultPaths + Stats`

### B) `ModelManager` (lifecycle + inventory)

* loads/unloads models and tracks:

  * loaded model_id
  * load timestamp
  * estimated sizes (disk size, rss snapshot deltas best-effort)
  * device/provider config

### C) gRPC server (thin, stable)

* translates proto messages into backend calls
* maintains job state and publishes status to stream subscribers

---

## 4) ASR engine folder layout (minimal, reusable)

```
python/asr_engine/
  pyproject.toml
  uv.lock
  scriberr_asr_engine/
    __init__.py
    server.py              # gRPC server over UDS
    model_manager.py
    backend.py             # AsrBackend
    audio_io.py            # librosa/soundfile wrapper
    postprocess.py         # merge short segments logic
    timestamps.py          # format_ts + word timestamp heuristic
    status_store.py        # in-memory job status + optional status.json writer
    metrics.py             # rss/gpu mem snapshot helpers (best-effort)
  proto/ (optional if you keep proto elsewhere)
```

---

## 5) Model support: Parakeet / Canary / variants

### Unify model selection

Represent the onnx-asr model selection as:

* **By registry name** (HF style): `model="nemo-parakeet-tdt-0.6b-v2"`
* **Or by local export path**: `path=/models/asr/parakeet-tdt-0.6b-v2-onnx`

So `ModelSpec` should carry:

* `model_name` (string) and optional `model_path`
* `variant` or `family` (optional): `"parakeet"`, `"canary"` (pure metadata)
* provider/device config
* session options (threads)

**Engine implementation:** build `load_kwargs` based on whether model_path exists.

This directly matches your second script’s `use_local_export`.

---

## 6) Job-specific parameters (how they map from your scripts)

You already have tunables:

* VAD preset or explicit vad params
* merge short segments heuristic
* include segment timestamps
* include heuristic word timestamps
* session threads
* language / other model params
* output formats

### Define ASR job params (typed on the engine side)

Even if proto uses `map<string,string>`, inside Python parse into a typed dataclass:

```python
@dataclass
class AsrJobParams:
    vad_preset: str = "balanced"
    vad_speech_pad_ms: int | None = None
    vad_min_silence_ms: int | None = None
    vad_min_speech_ms: int | None = None
    vad_max_speech_s: int | None = None

    include_segments: bool = True
    include_words: bool = False
    merge_short_segments: bool = True
    merge_attach_threshold_s: float = 0.25
    merge_attach_max_words: int = 2

    sample_rate: int = 16000
```

Resolution logic:

* if explicit vad values are provided, override preset
* otherwise use preset defaults (your `get_vad_params`)

This lets Go pass a job-specific “aggressive” preset, or explicit numbers.

---

## 7) Timestamp requirements (segment + word)

### Segment timestamps (real)

Your `onnx_asr` segments already have `start/end` (as in script 2). So engine should always be able to write `segments.jsonl` if requested.

### Word timestamps (heuristic)

Keep your heuristic function as-is and make it optional via `include_words`.

**Important:** do *not* pretend it’s forced alignment. Label it `mode: "heuristic"` in `result.json`.

---

## 8) gRPC surface for ASR (concrete subset)

You already decided on gRPC/UDS. For ASR engine v1, you can keep the proto small. You do **not** need to finalize diarization proto yet.

Minimum ASR messages:

* `LoadModel(model_id, model_name, model_path, device/provider, threads, vad_backend)`
* `UnloadModel(model_id)`
* `StartJob(job_id, input_path, output_dir, model_id, params map)`
* `StopJob(job_id)`
* `GetJobStatus(job_id)`
* `StreamJobStatus(job_id)` (server stream)
* `ListLoadedModels()`
* `GetEngineInfo()` (rss bytes, busy, active_job_id)

**JobStatus** should include:

* `state`
* `progress_pct` (you can fake coarse progress early; or emit `message` only)
* outputs map on completion

---

## 9) How the ASR job runner works (step-by-step)

### StartJob(job)

1. Validate:

   * `input_path` exists and is readable
   * `output_dir` exists or can be created
   * model loaded and matches `model_id`
   * engine not busy

2. Create output files:

   * write a `meta.json` with job + params (good for debugging)
   * optionally init `status.json`

3. Load audio:

   * `librosa.load(..., sr=16000, mono=True)` (works, but slower)
   * **Recommendation for production:** use `soundfile` or `ffmpeg` pipeline for speed/format coverage; but you can keep librosa initially.

4. Run recognition:

   * `results = asr.recognize(audio, sample_rate=...)`
   * iterate segments
   * apply merge heuristic if enabled
   * collect segments with start/end/text

5. Write outputs:

   * transcript.txt = joined text
   * segments.jsonl = each segment record (like your script)
   * words.jsonl = optional heuristic
   * result.json = summary (model_id, timings, counts, outputs)

6. Emit streaming status updates:

   * `RUNNING` at start
   * `JOB_PROGRESS` periodically (every N segments or every X seconds)
   * terminal status with outputs map

### Progress %

You can compute a coarse progress even without true audio duration by using:

* if segments provide `end` timestamps, then progress ≈ `last_end / audio_duration`
* audio_duration = `len(audio)/sr`

That’s surprisingly effective.

---

## 10) What happens on Stop and on Kill

### StopJob(job_id)

* set a cancellation flag
* engine loop checks flag between segments (or between batches)
* if set, stop early:

  * write partial outputs if you want (optional)
  * mark job `CANCELLED`
  * emit final JobStatus

### Kill

* Go kills daemon, so:

  * gRPC stream breaks
  * Go marks job cancelled/failed
  * Go restarts daemon
  * Go reloads model if desired

Engine doesn’t need complex recovery.

---

## 11) uv + Docker: how the ASR engine is built and run

### Build-time

* In Docker build, create venv for ASR engine using uv:

  * `/opt/venvs/asr`
* Install ASR engine package and deps into that venv.

### Runtime

Go starts ASR engine daemon:

* `/opt/venvs/asr/bin/python -m scriberr_asr_engine.server --socket /run/scriberr/engines/asr.sock`

Go connects via gRPC/UDS.

---

## 12) Mapping your existing code into the backend (directly)

### Pipeline init from your script

This logic moves into `ModelManager.load_model()`:

* create `rt.SessionOptions()`, set threads from ModelSpec
* `vad = onnx_asr.load_vad("silero")` (or configured)
* `asr = onnx_asr.load_model(model=..., path=..., providers=..., sess_options=opts)`
* apply `.with_vad(vad, **vad_params)`
* store `self.pipeline = asr`

### Segment merge logic from script 1

Move into `postprocess.merge_short_segments(segments, params)` where each segment has `text`, `start`, `end`, `duration` (duration can be `end-start`).

### Timestamp writers from script 2

Move into `timestamps.write_segments_jsonl(...)` and `timestamps.write_words_jsonl(...)`.

---

# Answering your last question explicitly: “How do we coordinate results and audio input path etc??”

**Go controls:**

* `job_id`
* `input_path`
* `output_dir`
* job params

**ASR engine guarantees:**

* it reads `input_path`
* it writes outputs to `output_dir` using fixed filenames
* it returns those output paths in `JobStatus.outputs`

So Go can always find:

* `/data/out/<job_id>/transcript.txt`
* `/data/out/<job_id>/segments.jsonl`
* etc.

No ambiguity, no passing blobs.

