|
| 1 | +"""Local speech recognition with Qwen3-ASR (0.6B or 1.7B), via the ``qwen-asr`` package. |
| 2 | +
|
| 3 | +Runs on PyTorch: on a CUDA GPU when one is available, otherwise on the CPU in float32 |
| 4 | +(no NVIDIA hardware needed; the 0.6B model is the practical size on a CPU). Qwen3-ASR |
| 5 | +covers 30 languages plus Chinese dialects, and reports the language it heard. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +import numpy as np |
| 14 | + |
| 15 | +from polyglot.core import languages |
| 16 | +from polyglot.core.errors import ConfigError, TranscriptionFailed |
| 17 | +from polyglot.core.models import SAMPLE_RATE, Transcript |
| 18 | +from polyglot.core.ports import RawAudio |
| 19 | + |
| 20 | +log = logging.getLogger(__name__) |
| 21 | + |
| 22 | +DEFAULT_MODEL = "Qwen/Qwen3-ASR-0.6B" |
| 23 | +MODELS = ("Qwen/Qwen3-ASR-0.6B", "Qwen/Qwen3-ASR-1.7B") |
| 24 | + |
| 25 | +#: Language code -> the name Qwen3-ASR takes and reports. Its 30 languages. |
| 26 | +LANGUAGES: dict[str, str] = { |
| 27 | + "zh": "Chinese", "en": "English", "yue": "Cantonese", "ar": "Arabic", "de": "German", |
| 28 | + "fr": "French", "es": "Spanish", "pt": "Portuguese", "id": "Indonesian", |
| 29 | + "it": "Italian", "ko": "Korean", "ru": "Russian", "th": "Thai", "vi": "Vietnamese", |
| 30 | + "ja": "Japanese", "tr": "Turkish", "hi": "Hindi", "ms": "Malay", "nl": "Dutch", |
| 31 | + "sv": "Swedish", "da": "Danish", "fi": "Finnish", "pl": "Polish", "cs": "Czech", |
| 32 | + "tl": "Filipino", "fa": "Persian", "el": "Greek", "hu": "Hungarian", |
| 33 | + "mk": "Macedonian", "ro": "Romanian", |
| 34 | +} # fmt: skip |
| 35 | +_CODES = {name.lower(): code for code, name in LANGUAGES.items()} |
| 36 | +_CODES["fil"] = "tl" # Filipino's ISO 639-2 code, should the model report it |
| 37 | + |
| 38 | + |
| 39 | +def language_name(code: str | None) -> str | None: |
| 40 | + """The name to force ``code`` with, or None (auto-detect) if Qwen3-ASR lacks it.""" |
| 41 | + if not code: |
| 42 | + return None |
| 43 | + code = code.replace("_", "-").lower() |
| 44 | + if code in ("fil", "zh-yue", "zh-hk"): |
| 45 | + code = "tl" if code == "fil" else "yue" |
| 46 | + return LANGUAGES.get(code) or LANGUAGES.get(languages.primary(code) or "") |
| 47 | + |
| 48 | + |
| 49 | +def language_code(reported: str | None) -> str | None: |
| 50 | + """Qwen3-ASR's reported language ("French", sometimes "fr") as a code, or None.""" |
| 51 | + if not reported: |
| 52 | + return None |
| 53 | + key = reported.strip().lower() |
| 54 | + if key in LANGUAGES: |
| 55 | + return key |
| 56 | + return _CODES.get(key) |
| 57 | + |
| 58 | + |
| 59 | +class Qwen3Transcriber: |
| 60 | + def __init__( |
| 61 | + self, |
| 62 | + model: str = DEFAULT_MODEL, |
| 63 | + *, |
| 64 | + device: str = "auto", |
| 65 | + max_new_tokens: int = 256, |
| 66 | + ) -> None: |
| 67 | + self.model_name, self.device, self.max_new_tokens = model, device, max_new_tokens |
| 68 | + self._model: Any = None |
| 69 | + self.effective_device: str | None = None # "cpu" or "cuda:0", after load() |
| 70 | + |
| 71 | + def load(self) -> None: |
| 72 | + if self._model is not None: |
| 73 | + return |
| 74 | + try: |
| 75 | + import torch # lazy: optional dependency (uv sync --extra qwen3) |
| 76 | + from qwen_asr import Qwen3ASRModel |
| 77 | + except ImportError as exc: |
| 78 | + raise ConfigError( |
| 79 | + "Qwen3-ASR needs the qwen-asr package (uv sync --extra qwen3)" |
| 80 | + ) from exc |
| 81 | + has_cuda = bool(torch.cuda.is_available()) |
| 82 | + if self.device == "cuda" and not has_cuda: |
| 83 | + raise ConfigError("no CUDA GPU is available to PyTorch; choose Automatic or CPU") |
| 84 | + on_gpu = has_cuda and self.device != "cpu" |
| 85 | + device_map = "cuda:0" if on_gpu else "cpu" |
| 86 | + # bfloat16 halves GPU memory; on a CPU it is slow or unsupported, so use float32. |
| 87 | + dtype = torch.bfloat16 if on_gpu else torch.float32 |
| 88 | + log.info("loading Qwen3-ASR %s on %s", self.model_name, device_map) |
| 89 | + try: |
| 90 | + self._model = Qwen3ASRModel.from_pretrained( |
| 91 | + self.model_name, |
| 92 | + dtype=dtype, |
| 93 | + device_map=device_map, |
| 94 | + max_inference_batch_size=1, # one utterance at a time |
| 95 | + max_new_tokens=self.max_new_tokens, |
| 96 | + ) |
| 97 | + except Exception as exc: |
| 98 | + raise TranscriptionFailed( |
| 99 | + f"could not load Qwen3-ASR model {self.model_name!r}: {exc}" |
| 100 | + ) from exc |
| 101 | + self.effective_device = device_map |
| 102 | + log.info("Qwen3-ASR %s loaded on %s", self.model_name, device_map) |
| 103 | + |
| 104 | + def transcribe(self, audio: RawAudio, language: str | None) -> Transcript: |
| 105 | + if self._model is None: |
| 106 | + raise TranscriptionFailed("model not loaded") |
| 107 | + forced = language_name(language) |
| 108 | + try: |
| 109 | + results = self._model.transcribe( |
| 110 | + audio=(np.ascontiguousarray(audio, dtype=np.float32), SAMPLE_RATE), |
| 111 | + language=forced, |
| 112 | + ) |
| 113 | + result = results[0] if isinstance(results, (list, tuple)) else results |
| 114 | + except Exception as exc: |
| 115 | + raise TranscriptionFailed(f"transcription failed: {exc}") from exc |
| 116 | + text = str(getattr(result, "text", "") or "").strip() |
| 117 | + code = language_code(getattr(result, "language", None)) if text else None |
| 118 | + if forced and code is None: |
| 119 | + code = language # forced: the model did not need to say |
| 120 | + # Qwen3-ASR gives no confidence score. A reported language counts as confident; |
| 121 | + # the lock still waits for ``asr.lock_after`` utterances that agree. |
| 122 | + return Transcript(text=text, language=code, language_probability=1.0 if code else 0.0) |
0 commit comments