Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/compat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,12 @@ jobs:
--version-set "${{ matrix.version-set }}" \
--python-version "${{ matrix.python-version }}"
- name: Cache downloaded test models
if: matrix.integration == 'gguf'
if: matrix.integration == 'gguf' || matrix.integration == 'faster_whisper'
uses: actions/cache@v4
with:
path: tests/compat/.cache
path: |
tests/compat/.cache
~/.cache/huggingface/hub
key: compat-models-${{ matrix.integration }}-${{ hashFiles(format('tests/compat/test_{0}_compat.py', matrix.integration)) }}
- name: Run compatibility tests
run: python -m pytest "tests/compat/test_${{ matrix.integration }}_compat.py" -q -rxX
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ under Unreleased and move into a version section at release time.

## Unreleased

### Added

- `mlx_whisper` and `faster_whisper` integrations track local Whisper model
loads and transcriptions, including faster-whisper's
`BatchedInferencePipeline`. Transcriptions record duration, language, word
count and audio metadata. With `attachments_enabled=True` they also upload
the input audio and transcript. See docs/whisper.md.

### Fixed

- Process-wide integrations and hub patches now support sequential SDK client
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ for client lifecycle and the full contract.
| Integration | Example |
|---|---|
| `transformers` | [transformers_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/transformers_example.py) |
| `mlx_whisper` / `faster_whisper` | [whisper_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/whisper_example.py) |
| `mlx` | [mlx_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/mlx_example.py) |
| `timm` | [timm_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/timm_example.py) |
| `gguf` | [gguf_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/gguf_example.py) |
Expand Down
2 changes: 2 additions & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,5 @@ To run the full matrix locally: `python scripts/run_compat_local.py`.
| `ultralytics` | `min` | `ultralytics==8.0.200`, `numpy==1.26.4` | 3.10, 3.11, 3.12, 3.13 |
| `ultralytics` | `current` | `ultralytics==8.4.182`, `numpy==2.2.6` | 3.10, 3.11, 3.12, 3.13 |
| `mlx` | `current` | `mlx==0.32.4`, `mlx-lm==0.32.2` | 3.12, 3.13 |
| `faster_whisper` | `current` | `faster-whisper==1.2.1`, `ctranslate2==4.8.2`, `numpy==2.2.6` | 3.12, 3.13 |
| `mlx_whisper` | `current` | `mlx-whisper==0.4.3`, `mlx==0.32.3`, `numpy==2.2.6` | 3.12, 3.13 |
5 changes: 3 additions & 2 deletions docs/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ with client.chat.completions.create(model=model, messages=messages, stream=True)
Async streams support `async with`, `await stream.close()`, and
`await stream.aclose()`. A bare `break` without closing, or simply abandoning an
unconsumed stream, does not provide an observable end of the operation. There is
no garbage-collection finalizer. Keep stream consumption within the lifetime of
the SDK client and do not consume one iterator concurrently from multiple tasks.
no garbage-collection finalizer, except for faster-whisper segments (see
[whisper.md](whisper.md)). Keep stream consumption within the lifetime of the
SDK client and do not consume one iterator concurrently from multiple tasks.

## Audit findings outside these wrappers

Expand Down
105 changes: 105 additions & 0 deletions docs/whisper.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Local Whisper speech recognition

WildEdge tracks local Whisper transcription with two integrations:

- `mlx_whisper` for [mlx-whisper](https://github.com/ml-explore/mlx-examples/tree/main/whisper) on Apple Silicon
- `faster_whisper` for [faster-whisper](https://github.com/SYSTRAN/faster-whisper) (CTranslate2)

Initialize the SDK before loading a model or importing `transcribe` by name:

```python
import wildedge

client = wildedge.init(integrations=["mlx_whisper"])
import mlx_whisper

result = mlx_whisper.transcribe("speech.wav", path_or_hf_repo="/models/whisper")
```

faster-whisper decodes lazily, so the transcription is recorded once you have
read all of its segments:

```python
client = wildedge.init(integrations=["faster_whisper"])
from faster_whisper import WhisperModel

model = WhisperModel("/models/whisper", device="cpu", compute_type="int8")
segments, info = model.transcribe("speech.wav")
text = "".join(segment.text for segment in segments)
```

`BatchedInferencePipeline(model).transcribe(...)` is tracked the same way.

## What's recorded

**Model loads**

- Load time, format (`mlx` or `ctranslate2`), family (`whisper`), accelerator
and compute type or quantization.
- The model ID is the backend plus the model name, for example
`faster_whisper:Systran/faster-whisper-tiny`. A Hugging Face repo keeps its
repo name, also when loaded from a cache path. A local folder is named after
the folder.
- Every load is recorded, including a second `WhisperModel` for the same model.
- mlx-whisper caches one model at a time and reloads when you switch models.
Each reload is recorded. A model that was already cached before the SDK
started is recorded once, with zero load time and `model_cache_hit=true`.

**Transcriptions**

- Wall-clock duration and `language`.
- `language_confidence` (faster-whisper only; mlx-whisper doesn't report it).
- `transcript_word_count`, except for languages written without spaces between
words, such as Chinese, Japanese and Thai.
- `time_to_first_segment_ms` (faster-whisper only).
- Audio metadata:
- WAV files: duration, sample rate, channels and bit depth.
- 1-D arrays: treated as 16 kHz mono, as both libraries expect.
- Other formats: duration only, when faster-whisper reports it. The SDK
doesn't decode the audio a second time.

Token counts aren't reported; neither library exposes them.

## faster-whisper segment lifecycle

Timing runs from `transcribe()` until the last segment is read, including time
your code spends between segments. Read the segments inside the trace or span
that should own the transcription.

| How the segments end | Recorded as |
| --- | --- |
| All segments read | One successful transcription |
| `segments.close()` | One unsuccessful transcription, `STREAM_CLOSED` |
| Loop exits early without `close()` | One unsuccessful transcription, `STREAM_ABANDONED`, sent when the iterator is garbage collected and timed up to the last segment read |
| Never iterated (for example, only `info.language` was used) | Nothing |
| Decoder error | One error event; the exception reaches your code unchanged |

A `WhisperModel` stays with the SDK client that was active when it was created.
After you replace the client, create the model again; until then, it isn't
tracked and the SDK warns once.

## Capturing audio and transcripts

Capture is off by default. With `attachments_enabled=True`, each transcription
uploads:

- the input audio: the original file for a path, or a 16-bit WAV for an array
- the transcript as `transcript.txt`

Keep in mind:

- Each attachment is capped at 10 MiB, and the client's own attachment limits
also apply. A transcript over the cap isn't uploaded at all.
- Audio passed as a file-like object isn't captured.
- An audio file must still exist when the transcription finishes.
- To upload transcripts but not audio, pass an `attachment_filter` that keeps
only output attachments:
`attachment_filter=lambda items: [a for a in items if a.role == "output"]`.
- Transcript text is never added to event attributes.

## Examples and tests

See [the runnable example](../examples/whisper_example.py). Compatibility CI
decodes real audio with a random-weight MLX Whisper model and the pinned public
faster-whisper tiny model. To run the faster-whisper tests offline, set
`WILDEDGE_FASTER_WHISPER_MODEL=/path/to/model`.
48 changes: 48 additions & 0 deletions examples/whisper_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Transcribe a WAV using a local Whisper model with automatic instrumentation.

Install mlx-whisper (Apple Silicon) or faster-whisper, set WILDEDGE_DSN, then:
python examples/whisper_example.py mlx_whisper /path/to/model /path/to/audio.wav
python examples/whisper_example.py faster_whisper /path/to/model /path/to/audio.wav

See docs/whisper.md for lifecycle and opt-in attachment capture behavior.
"""

import argparse

import wildedge


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("backend", choices=["mlx_whisper", "faster_whisper"])
parser.add_argument("model")
parser.add_argument("audio")
parser.add_argument(
"--capture", action="store_true", help="Attach audio and transcript"
)
args = parser.parse_args()
client = wildedge.init(
integrations=[args.backend], attachments_enabled=args.capture
)
try:
with client.trace(), client.span(name="transcribe"):
if args.backend == "mlx_whisper":
import mlx_whisper # noqa: PLC0415 -- optional runtime

result = mlx_whisper.transcribe(args.audio, path_or_hf_repo=args.model)
print(result["text"])
else:
from faster_whisper import ( # noqa: PLC0415 -- optional runtime
WhisperModel,
)

model = WhisperModel(args.model, device="cpu", compute_type="int8")
segments, _info = model.transcribe(args.audio)
print("".join(segment.text for segment in segments))
client.flush()
finally:
client.close()


if __name__ == "__main__":
main()
7 changes: 7 additions & 0 deletions scripts/compat_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
"mlx": {
"current": ["mlx==0.32.4", "mlx-lm==0.32.2"],
},
"faster_whisper": {
"current": ["faster-whisper==1.2.1", "ctranslate2==4.8.2", "numpy==2.2.6"]
},
"mlx_whisper": {"current": ["mlx-whisper==0.4.3", "mlx==0.32.3", "numpy==2.2.6"]},
}

SUPPORTED_PYTHON = {
Expand All @@ -71,6 +75,8 @@
"transformers": ["3.10", "3.11", "3.12", "3.13"],
"ultralytics": ["3.10", "3.11", "3.12", "3.13"],
"mlx": ["3.12", "3.13"],
"faster_whisper": ["3.12", "3.13"],
"mlx_whisper": ["3.12", "3.13"],
}

# Integrations without a row of their own, and the row that exercises them.
Expand All @@ -81,6 +87,7 @@
# Integrations that need a specific runner; everything else runs on Linux.
RUNNER = {
"mlx": "macos-14",
"mlx_whisper": "macos-14",
}

# Python versions run as non-blocking canaries, and only with current pins.
Expand Down
53 changes: 53 additions & 0 deletions tests/compat/test_faster_whisper_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Real CTranslate2 model load and lazy transcription using Whisper tiny."""

import os
from pathlib import Path

import faster_whisper
import numpy as np
import pytest
from huggingface_hub import snapshot_download


@pytest.fixture(scope="module")
def model_path():
# A local model can be supplied for offline development. CI caches HF downloads.
path = os.environ.get("WILDEDGE_FASTER_WHISPER_MODEL") or snapshot_download(
"Systran/faster-whisper-tiny",
revision="d90ca5fe260221311c53c58e660288d3deb8d356",
allow_patterns=["config.json", "model.bin", "tokenizer.json", "vocabulary.*"],
)
assert Path(path).is_dir()
return path


def test_load_and_lazy_transcribe(compat_client, model_path):
compat_client.instrument("faster_whisper")
model = faster_whisper.WhisperModel(model_path, device="cpu", compute_type="int8")
load = compat_client.one("model_load")
if "WILDEDGE_FASTER_WHISPER_MODEL" not in os.environ:
# Named after the hub repo, not the snapshot hash in the cache path.
assert load["model_id"] == "faster_whisper:Systran/faster-whisper-tiny"
segments, info = model.transcribe(
np.zeros(16000, dtype=np.float32), language="en", beam_size=1
)
assert not compat_client.of_type("inference")
text = " ".join(segment.text for segment in segments)
event = compat_client.one("inference")
assert event["model_id"] == load["model_id"]
assert event["attributes"]["transcript_word_count"] == len(text.split())
assert event["attributes"]["language_confidence"] == info.language_probability
assert event["inference"]["input_meta"]["duration_ms"] == 1000


def test_batched_pipeline(compat_client, model_path):
compat_client.instrument("faster_whisper")
model = faster_whisper.WhisperModel(model_path, device="cpu", compute_type="int8")
load = compat_client.one("model_load")
pipeline = faster_whisper.BatchedInferencePipeline(model)
segments, _info = pipeline.transcribe(
np.zeros(16000, dtype=np.float32), language="en", batch_size=2
)
list(segments)
event = compat_client.one("inference")
assert event["model_id"] == load["model_id"]
49 changes: 49 additions & 0 deletions tests/compat/test_mlx_whisper_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Real MLX Whisper loader and decoding, with locally built random weights."""

import importlib
import json
from dataclasses import asdict

import mlx.core as mx
import mlx_whisper
import numpy as np
from mlx.utils import tree_flatten
from mlx_whisper.whisper import ModelDimensions, Whisper


def test_load_and_transcribe(compat_client, tmp_path):
dimensions = ModelDimensions(
n_mels=80,
n_audio_ctx=1500,
n_audio_state=8,
n_audio_head=2,
n_audio_layer=1,
n_vocab=51865,
n_text_ctx=448,
n_text_state=8,
n_text_head=2,
n_text_layer=1,
)
mx.random.seed(0)
model = Whisper(dimensions, mx.float32)
(tmp_path / "config.json").write_text(json.dumps(asdict(dimensions)))
mx.save_safetensors(
str(tmp_path / "weights.safetensors"), dict(tree_flatten(model.parameters()))
)
importlib.import_module("mlx_whisper.transcribe").ModelHolder.model = None
compat_client.instrument("mlx_whisper")
result = mlx_whisper.transcribe(
np.zeros(16000, dtype=np.float32),
path_or_hf_repo=str(tmp_path),
language="en",
fp16=False,
sample_len=2,
temperature=0,
condition_on_previous_text=False,
)
load = compat_client.one("model_load")
event = compat_client.one("inference")
assert event["model_id"] == load["model_id"]
assert event["attributes"]["transcript_word_count"] == len(result["text"].split())
assert event["inference"]["input_meta"]["duration_ms"] == 1000
assert event["inference"]["input_meta"]["sample_rate"] == 16000
Loading
Loading