# Romanian speech recognition

Source: https://docs.surogate.ai/engine/inference/speech/

For speech generation with named voices on CPU, see [Romanian text-to-speech](/engine/inference/tts/).

Surogate transcribes Romanian speech on a GPU or a CPU. Pick the model that fits your audio:

| Model | Use |
|---|---|
| [`surogate/surogate-ro-110m-tdt-ctc`](https://huggingface.co/surogate/surogate-ro-110m-tdt-ctc) | Transcribe complete audio files |
| [`surogate/surogate-ro-110m-streaming`](https://huggingface.co/surogate/surogate-ro-110m-streaming) | File transcription or live audio with partial and final transcripts |

Start the non-streaming model:

```bash
surogate serve --stt surogate/surogate-ro-110m-tdt-ctc --device 0 --port 8080
```

It reads the whole recording before it returns any text, and it uses the
repository's Romanian language model automatically. A live-audio request gets an
error telling you to use file transcription instead.

For live audio, install the streaming dependency and start the streaming model:

```bash
pip install 'silero-vad==6.2.1'
surogate serve --stt surogate/surogate-ro-110m-streaming --device 0 --port 8080
```

Use `--device cpu` to run without a GPU; CPU-only PyTorch works. Installed wheels
include the speech server. From a source checkout, build with `make serve-build`, or
use `make serve-stt-build` to build only the speech server, with no CUDA toolkit.
That target needs a C++ compiler, the FFmpeg development libraries and PyTorch in the
active environment; set `STT_PYTHON=/path/to/python` to choose the environment. A
source build configured with `-DSINFER_ENABLE_FFMPEG=OFF` (for a host without the
FFmpeg development libraries) or `-DSUROGATE_BUILD_SPEECH=OFF` builds everything
except the speech server. For a private Hugging Face repository, authenticate with
`hf auth login` or set `HF_TOKEN`.

### CPU compute options

`--threads N` sets the number of CPU compute threads (default 4, range 1–256). It
also applies inside the HTTP inference workers, and it doesn't depend on how many
HTTP connections or streaming sessions are open.

```bash
surogate serve --stt surogate/surogate-ro-110m-tdt-ctc --device cpu --threads 4
```

With an MKL-enabled LibTorch build, `--cpu-kernels auto` (the default) turns on the
optimized FP32 path on CPU. It fuses the attention projections, caches bounded
position projections, drops a padding copy in relative attention, and reuses packed
feed-forward weights for shapes it has seen before. It also caches language-model
backoff scores within each request. While clip lengths keep changing, it uses
ordinary GEMM until a shape comes back, so it doesn't pay the packing cost each time.

`--cpu-kernels reference` selects the original implementation, for comparisons.
`--cpu-kernels optimized` fails without CPU and MKL support, where `auto` falls back
to the reference path. Either way LibTorch is still the runtime dependency, and model
precision, decoding rules and scores stay the same.

This path replaces an earlier experimental oneDNN rewrite of the linear layers. It
matched the reference exactly in encoder/CTC tensor comparisons and passed both
decoder transcript checks on all 903 Romanian control recordings, plus streaming and
boundary cases. [STT CPU kernel measurements](/engine/inference/stt-cpu-kernels/) has the latency,
cache behavior and validation scope.

The first start downloads the acoustic checkpoint you chose and its Romanian
language model, then prepares reusable files under `~/.cache/surogate/serve`. Allow
about 5 GB of disk space for both. Later starts reuse them. Set `SUROGATE_SERVE_CACHE`
to move the cache.

To use local files:

```bash
surogate serve --stt /models/Ib_final.nemo \
  --lm /models/ro_4gram.arpa --device cpu

surogate serve --stt /models/Is_ctc_final_20260915.nemo \
  --lm /models/ro_4gram.nemo --device 0
```

The matching language model can be a NeMo `.nemo` archive or a token-ID `.arpa`
file. Preparation happens automatically and is cached. The non-streaming model
doesn't need `silero-vad`.

The served model ID is the model argument you started the server with, and
`/v1/models` reports it. `--served-model-name` sets an alias for your deployment.
`--api-key` turns on bearer-token authentication for every endpoint.
`--api-key-file PATH` reads the key from a file, which keeps it out of the process's
command line.

## Transcribe a file

```bash
curl http://localhost:8080/v1/audio/transcriptions \
  -F file=@recording.wav
```

The response is `{"text":"…","usage":{"type":"duration","seconds":2.63}}`. You can
send WAV, FLAC, MP3, Ogg, M4A, AAC or WebM; stereo and other sample rates are
converted automatically. Uploads are limited to 64 MiB and ten minutes. The
non-streaming model processes the whole file at once, so longer files need more
memory. The streaming model splits recordings at pauses into segments of at most
60 seconds.

Optional form fields:

| Field | Values |
|---|---|
| `model` | The served model ID; omit to use the running model |
| `language` | `ro` |
| `response_format` | `json` (default), `text`, or `verbose_json` |
| `decoding` | `beam` (default): CTC with the language model; `greedy`: the TDT decoder alone |

`greedy` writes down what was said, without the language model pulling it towards
likely text. A text-to-speech worker uses it to check the codes it dictated (see
[pocket-tts packages](/engine/inference/tts/#pocket-tts-packages)).

`verbose_json` also returns the duration and language. Translation, word
alignment, subtitle formats and prompting are not available, and unsupported fields
return an error.

Every successful transcription reports the audio length it is billed for, in
seconds, in every format:

- the `X-Audio-Duration-Seconds` response header, on every format;
- `usage`, OpenAI's object for audio billed by duration
  (`{"type": "duration", "seconds": …}`), in `json` and `verbose_json`.

Both carry the same number, and so does `verbose_json`'s `duration`, so a gateway
can meter a transcription without decoding the file or reading the body. A failed
transcription carries neither. The value is the length of the decoded audio,
counted in 16 kHz samples (62.5 µs each):

- WAV, FLAC and other lossless files are billed for exactly their length.
- MP3 is billed for its audio, without the encoder's padding, when the file has
  a gapless (Xing/LAME) header, as encoders write by default.
- AAC and M4A can include up to one AAC frame of encoder padding at the end:
  1024 samples at the file's own rate, which is 23 ms at 44.1 kHz and 64 ms at
  16 kHz.

The header is a decimal number of seconds that parses back to exactly the same
value, for example `2.63` or `1.0`. Audio shorter than a millisecond is written in
exponent form (`6.25e-05` for one sample), so parse the header as a float.

## Stream microphone audio

This endpoint needs the streaming model. First, create a stream:

```bash
curl -X POST http://localhost:8080/v1/audio/streams
```

The response includes an `id`. Send **mono, 16 kHz, signed 16-bit little-endian
PCM**, without a WAV header, to that stream:

```bash
curl -X POST "http://localhost:8080/v1/audio/streams/STREAM_ID" \
  -H 'Content-Type: application/octet-stream' --data-binary @chunk.pcm
```

Each response contains an `events` array. A `partial` event updates the current
utterance. A `final` event replaces the partial text, which it may change, and
completes the segment. About 640 ms of silence ends an utterance, and the model also
needs about one second of audio lookahead.

Send chunks in order, and wait for each response before you send the stream's next
chunk. Keep recording and buffer new audio while you wait. A chunk can hold any whole
number of samples, up to ten seconds; 32–160 ms chunks work well for live capture.
Keep sending the silence you capture too, or the server can't detect pauses.

Drain the last audio and close the stream:

```bash
curl -X POST "http://localhost:8080/v1/audio/streams/STREAM_ID?finish=true"
```

The finishing request can carry PCM as well. To cancel a stream and discard its
unfinished audio, send `DELETE /v1/audio/streams/STREAM_ID`. A stream expires after
two minutes without a request. `--max-num-seqs` sets how many streams can be live at
once (default 8), and each keeps its own audio and transcript state. Inference
requests share one model and run one at a time.

### Stream over a WebSocket

Over the internet, a POST per chunk costs a network round trip per chunk. A WebSocket carries
the same stream over one connection: open `GET /v1/audio/streams` as a WebSocket, send audio as
binary messages without waiting for replies, and read the events as they arrive.

- The first message from the server is `{"type": "ready", "sample_rate": 16000, "channels": 1,
  "encoding": "pcm_s16le"}`.
- Each binary message is a chunk of mono, 16 kHz, 16-bit little-endian PCM, at most ten seconds.
- Each event that the HTTP interface returns for a chunk comes back as one JSON text message,
  in the same order and with the same content (`partial`, `final`).
- The text message `{"type": "finish"}` drains the audio. The server then sends the last events
  and `{"type": "done"}`, and closes the connection.
- Closing the WebSocket without `finish` discards the stream, as `DELETE` does.
- On an error the server sends `{"type": "error", "error": {"message": …}}` and closes with a
  status code: 1003 for a text message other than `finish`, 1007 for half a sample or invalid
  UTF-8, 1009 for a message over ten seconds of audio, 1002 for any other protocol error, and
  1011 when transcription fails.

A WebSocket stream counts against `--max-num-seqs` like an HTTP one, and when all are in use
the opening handshake is refused with HTTP 429. The stream lives exactly as long as its
connection: it has no two-minute expiry, and the HTTP endpoints can't reach it. A connection that
sends nothing, not even a ping, for 60 seconds is closed with status 1001 and its stream
discarded, so a client that pauses its audio should send pings to stay connected.

The connection needs the same `Authorization` header as the other endpoints. Browsers can't set
that header on a WebSocket, so connect from a server-side client or through a gateway that adds
it. The server offers no subprotocols (`Sec-WebSocket-Protocol`) and no compression; a client that
insists on a subprotocol fails to connect. A client speaking another WebSocket version gets
HTTP 426 with `Sec-WebSocket-Version: 13`. Keep your side of the TCP connection open until the
server closes it: after a half-close (shutting down only the sending side), the client receives
nothing more.

```python
from websockets.sync.client import connect

with connect("ws://localhost:8080/v1/audio/streams") as ws:
    print(ws.recv())                 # ready
    for chunk in chunks:             # bytes of PCM16
        ws.send(chunk)
    ws.send('{"type": "finish"}')
    for message in ws:
        print(message)               # partial and final events, then done
```

## Metrics

`GET /metrics` reports the server in Prometheus text format, like the LLM server:

- `surogate_up`;
- `surogate_requests{state="running"}`: every request except a GET, counted from arrival until its
  response has been written or its client has gone. This includes requests that are uploading,
  waiting for the model, or sending stream audio.
- `surogate_streams_open`: live streams, counted from creation until they are finished, deleted or
  expired;
- `surogate_requests_total{endpoint,outcome}`: finished transcriptions and stream creations;
- `surogate_audio_seconds_total`: seconds of audio transcribed.

To drain a server before you restart it, wait for both gauges to reach 0. A `/metrics` request
can wait behind a request that holds a worker thread, so treat a timeout as busy, never as idle.
With an API key set, `/metrics` needs the key like every other endpoint.

Speech serving runs in its own server mode. It doesn't add audio inputs to chat
completion requests, and it has no OpenAI Realtime WebSocket endpoint.

See also: [Romanian text-to-speech](/engine/inference/tts/) to turn text back into Romanian speech, and the
[OpenAI-compatible API](/engine/inference/api/) for the chat endpoints of the LLM server.
