# Speech API (Scribe Live on this Mac)

Appy can serve speech-to-text over a WebSocket that speaks the protocol of
[Zoom Scribe's Live mode](https://developers.zoom.us/docs/ai-services/scribe/live-mode/). A client written for
`wss://api.zoom.us/v2/aiservices/scribe/live` works with Appy by changing the address and the token. The audio never
leaves the Mac: it is turned into text by the speech model chosen in Settings › Voice.

Turn it on in **Settings › Voice › Speech API**. That page shows the address and the token.

```
ws://127.0.0.1:8723/v2/aiservices/scribe/live      subprotocol: live-asr
Authorization: Bearer <token>
```

- The server is bound to loopback, so only this Mac can connect, unless devices on the network are allowed (below).
  Appy must be running.
- A browser cannot set headers on a WebSocket, so the token may also go in the query: `?access_token=<token>`.
- **New Token** in Settings replaces the token, and the old one stops working at once.
- The port (8723 by default) can be changed in Settings.

## Devices on this network

Turn on **Allow devices on this network** (off by default) on the same page, and the server listens on every
interface, IPv4 and IPv6, instead of loopback only. Settings then also shows the address other devices use, made from
the Mac's Bonjour host name:

```
ws://Studio.local:8723/v2/aiservices/scribe/live      subprotocol: live-asr
```

The token is still required on every connection, exactly as on this Mac: anyone on the network can reach the port,
but only a client with the token gets a session. Bonjour does not carry the token; copy it from Settings.

While it is on, Appy advertises the server over Bonjour so apps (Chime Mobile, for one) can find it:

| | |
| --- | --- |
| Service type | `_scribe-live._tcp` |
| Name | The Mac's computer name (System Settings › General › Sharing) |
| Port | The Speech API port |
| TXT `path` | `/v2/aiservices/scribe/live` |
| TXT `protocol` | `live-asr` |
| TXT `app` | `appy` |
| TXT `v` | `1`, the version of these keys |

`dns-sd -B _scribe-live._tcp` lists the Macs that offer it, and `dns-sd -L "<name>" _scribe-live._tcp` gives the host,
port and TXT keys. An iOS app that browses for it needs `_scribe-live._tcp` in its `NSBonjourServices` and an
`NSLocalNetworkUsageDescription`. Turning the option off, or the Speech API off, withdraws the advertisement.

## A session

1. Connect. Appy sends `session.created` with a `session_id`.
2. Send `session.update` (optional). Appy answers `session.updated` with the settings in effect.
3. Stream audio as binary frames: signed 16-bit little-endian PCM, 16 kHz, mono, about 100 ms (3,200 bytes) a frame,
   with no WAV header. To tag a frame, send `{"type":"input_audio_buffer.append","timestamp":…,"metadata":…}` just before it.
4. For each utterance Appy sends:
   - `input_audio_buffer.speech_started` (`item_id`, `audio_start_ms`)
   - `transcription.delta` (`item_id`, `delta`), about once a second while the person speaks, only with
     `interim_results`. Each delta is the whole guess so far: replace the last one, don't append.
   - `input_audio_buffer.speech_stopped` (`item_id`, `audio_end_ms`), after 0.7 s of quiet, or after 25 s of
     continuous speech, when the utterance is cut so its text does not wait.
   - `transcription.completed`: `item_id`, `transcript`, `audio_start_ms`, `audio_end_ms`, `transcription_latency_ms`,
     `language`, and `metadata`, which is the most recent metadata sent at or before the utterance began. With polishing
     it also carries `outputs.text_polishing.text`.
5. Send `session.close`. Appy finishes any utterance under way, sends what is still to come, then `session.closed`
   with `reason`.

Times are milliseconds from the first audio of the session.

```json
{"type":"session.update",
 "config":{"language":"en-US","interim_results":true},
 "audio":{"format":"pcm16"},
 "outputs":{"text_polishing":{"enabled":true,"include_transcript":true}},
 "reference_id":"call-42"}
```

## How it differs from Zoom

| | Zoom Scribe Live | Appy |
| --- | --- | --- |
| Audio | pcm16 or opus | pcm16 only. Asking for `opus` gets a fatal `unsupported_audio_format`. |
| `model` | Zoom's models | Ignored. The speech model chosen in Settings › Voice is used and named in `session.updated`. |
| `language` | used | Passed to models that take one (Whisper, Apple Speech). Parakeet and SenseVoice work it out themselves. |
| `diarization`, `profanity_filter`, `vocabulary` | supported | Not offered. `session.updated` reports `diarization_enabled: false` and `profanity_filter_enabled: false`, and completed items have no `speaker`. |
| Text polishing | Zoom's | Gemini, with the key from Settings › AI, using the voice clean-up prompt. Without a key, a non-fatal `text_polishing_unavailable` error is sent and transcripts still come. |
| Limits | 120 min a session, 30 s idle | The same: `session.closed` with `max_duration_reached` or `idle_timeout`. |

Errors are `{"type":"error","error":{"code","message","fatal"}}`. A fatal one is followed by `session.closed`. Codes:
`unsupported_audio_format`, `invalid_frame`, `invalid_message`, `unknown_message`, `no_speech_model`,
`transcription_failed`, `text_polishing_unavailable`.

## Example (Python, `pip install websockets`)

```python
import asyncio, json, websockets

async def main(pcm: bytes, token: str):
    async with websockets.connect("ws://127.0.0.1:8723/v2/aiservices/scribe/live", subprotocols=["live-asr"],
                                  additional_headers={"Authorization": "Bearer " + token}) as ws:
        await ws.send(json.dumps({"type": "session.update", "config": {"interim_results": True}}))
        async def send():
            for i in range(0, len(pcm), 3200):
                await ws.send(pcm[i:i + 3200])
                await asyncio.sleep(0.1)
            await ws.send(json.dumps({"type": "session.close"}))
        asyncio.create_task(send())
        async for message in ws:
            event = json.loads(message)
            if event["type"] == "transcription.completed":
                print(event["transcript"])
```

Implementation: `Sources/AppyCore/Scribe.swift` (protocol, WebSocket frames, utterance detection; tested in
`ScribeTests`) and `Sources/Appy/ScribeServer.swift` (listener and sessions).
