qwen_engine.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import numpy as np
  2. from typing import Optional
  3. class QwenASREngine:
  4. def __init__(
  5. self,
  6. model_id: str = "Qwen/Qwen3-ASR-0.6B",
  7. device: str = "auto",
  8. language: Optional[str] = None,
  9. ):
  10. import torch
  11. from qwen_asr import Qwen3ASRModel
  12. self.model_id = model_id
  13. self.language = language
  14. self.sample_rate = 16000
  15. if device == "auto":
  16. device = "cuda" if torch.cuda.is_available() else "cpu"
  17. self.device = device
  18. dtype = torch.float16 if device == "cuda" else torch.float32
  19. print(f"Loading Qwen3-ASR: {model_id} on {device}")
  20. self.model = Qwen3ASRModel.from_pretrained(
  21. model_id, dtype=dtype, device_map=device,
  22. )
  23. print("ASR model ready")
  24. def transcribe_array(self, audio_array: np.ndarray, sample_rate: int = 16000) -> dict:
  25. if sample_rate != self.sample_rate:
  26. audio_array = self._resample(audio_array, sample_rate, self.sample_rate)
  27. result = self.model.transcribe(
  28. audio=(audio_array, self.sample_rate),
  29. language=self.language,
  30. )
  31. return {"text": result[0].text, "language": result[0].language}
  32. def _resample(self, audio: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
  33. if orig_sr == target_sr:
  34. return audio
  35. duration = len(audio) / orig_sr
  36. new_length = int(duration * target_sr)
  37. indices = np.linspace(0, len(audio) - 1, new_length)
  38. return np.interp(indices, np.arange(len(audio)), audio)
  39. def get_model_info(self) -> dict:
  40. return {"model_id": self.model_id, "device": self.device}