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
26 changes: 23 additions & 3 deletions examples/transformers/transcribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,19 @@ def load_audio(path):
return prepare_audio(audio, sample_rate)


def main():
def looks_like_audio_path(keyword):
"""Return whether a keyword has a path separator or an audio suffix."""
suffixes = (
".wav", ".mp3", ".flac", ".ogg", ".m4a", ".opus", ".aac", ".wma",
)
return (
"/" in keyword
or "\\" in keyword
or keyword.lower().endswith(suffixes)
)


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("audio", nargs="*", type=Path, help="Local audio files; default: pinned official English sample")
parser.add_argument("--language", nargs="+", default=["en"], choices=["zh", "en", "ja"])
Expand All @@ -68,10 +80,18 @@ def main():
parser.add_argument("--max-new-tokens", type=int, default=256)
parser.add_argument("--device", choices=["cpu", "cuda"], default="cpu")
parser.add_argument("--dtype", choices=["float32", "bfloat16"], default="float32")
args = parser.parse_args()
args = parser.parse_args(argv)
if not 1 <= args.max_new_tokens <= 1024:
parser.error("--max-new-tokens must be between 1 and 1024")
if not args.audio and any(
looks_like_audio_path(word) for word in args.keywords or []
):
parser.error(
"--keywords consumed a possible audio path. "
"Put the file first or use -- before the filename."
)
languages = languages_for_batch(args.language, len(args.audio) or 1)
audio = [load_audio(path) for path in args.audio]
import torch

cuda_available = args.device == "cuda" and torch.cuda.is_available()
Expand All @@ -81,7 +101,7 @@ def main():
from huggingface_hub import hf_hub_download

args.audio = [Path(hf_hub_download(SAMPLE_MODEL, "example/en.mp3", revision=SAMPLE_REVISION, token=False))]
audio = [load_audio(path) for path in args.audio]
audio = [load_audio(args.audio[0])]
if sum(len(item) for item in audio) > MAX_SECONDS * SAMPLE_RATE:
raise ValueError("Keep total batch audio within 60 seconds for this example")

Expand Down
50 changes: 50 additions & 0 deletions tests/test_transformers_quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import json
from pathlib import Path
import re
import sys
import unittest
from unittest.mock import Mock

import numpy as np
import pytest
Expand Down Expand Up @@ -135,5 +137,53 @@ def test_model_download_entries_distinguish_native_and_toolkit(suffix, entry):
assert "Fun-ASR-Nano-2512-hf" not in mlt


@pytest.mark.parametrize("keywords", [["OpenAI", "recording.wav"], ["recording.wav"], ["dir/clip.wav"]])
def test_keywords_swallowing_audio_are_rejected(keywords, monkeypatch):
hub = Mock()
monkeypatch.setitem(sys.modules, "huggingface_hub", hub)
monkeypatch.setitem(sys.modules, "torch", None)
with pytest.raises(SystemExit) as error:
native.main(["--keywords", *keywords])
assert error.value.code == 2
hub.hf_hub_download.assert_not_called()


@pytest.mark.parametrize("argv", [
["recording.wav", "--keywords", "OpenAI"],
["recording.wav", "--keywords", "开放时间", "营业时间"],
["--keywords", "OpenAI", "--", "recording.wav"],
["--prompt", "test", "recording.wav"],
])
def test_cli_decodes_local_audio(argv, monkeypatch, tmp_path):
import soundfile as sf

monkeypatch.chdir(tmp_path)
sf.write("recording.wav", np.zeros(16000), 16000)
load_audio = native.load_audio

def check_audio(path):
assert path == Path("recording.wav")
assert load_audio(path).shape == (16000,)
raise StopIteration

monkeypatch.setattr(native, "load_audio", check_audio)
monkeypatch.setitem(sys.modules, "torch", None)
monkeypatch.setitem(sys.modules, "huggingface_hub", None)
with pytest.raises(StopIteration):
native.main(argv)


@pytest.mark.parametrize("argv", [[], ["--keywords", "OpenAI"]])
def test_cli_defaults_to_pinned_sample(argv, monkeypatch):
hub = Mock()
hub.hf_hub_download.side_effect = StopIteration
monkeypatch.setitem(sys.modules, "huggingface_hub", hub)
monkeypatch.setitem(sys.modules, "torch", Mock())
with pytest.raises(StopIteration):
native.main(argv)
hub.hf_hub_download.assert_called_once_with(
native.SAMPLE_MODEL, "example/en.mp3", revision=native.SAMPLE_REVISION, token=False)


if __name__ == "__main__":
unittest.main()
Loading