qwen_engine.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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-1.7B",
  7. model_id: str="Qwen/Qwen3-ASR-0.6B",
  8. device: str = "auto",
  9. language: Optional[str] = None
  10. ):
  11. import torch
  12. from qwen_asr import Qwen3ASRModel
  13. self.model_id = model_id
  14. self.language = language
  15. self.sample_rate = 16000
  16. if device == "auto":
  17. device = "cuda" if torch.cuda.is_available() else "cpu"
  18. self.device = device
  19. dtype = torch.float16 if device == "cuda" else torch.float32
  20. print(f"Loading Qwen3-ASR model: {model_id} on {device}")
  21. self.model = Qwen3ASRModel.from_pretrained(
  22. model_id,
  23. dtype=dtype,
  24. device_map=device
  25. )
  26. print("Model loaded successfully")
  27. def transcribe_audio(
  28. self,
  29. audio_data: bytes,
  30. sample_rate: int = 16000
  31. ) -> dict:
  32. audio_array = self._bytes_to_array(audio_data)
  33. return self.transcribe_array(audio_array, sample_rate)
  34. def transcribe_array(
  35. self,
  36. audio_array: np.ndarray,
  37. sample_rate: int = 16000
  38. ) -> dict:
  39. if sample_rate != self.sample_rate:
  40. audio_array = self._resample(audio_array, sample_rate, self.sample_rate)
  41. result = self.model.transcribe(
  42. audio=(audio_array, self.sample_rate),
  43. language=self.language
  44. )
  45. return {
  46. 'text': result[0].text,
  47. 'segments': [{'text': result[0].text}],
  48. 'language': result[0].language
  49. }
  50. def _bytes_to_array(self, audio_bytes: bytes) -> np.ndarray:
  51. int16_array = np.frombuffer(audio_bytes, dtype=np.int16)
  52. return int16_array.astype(np.float32) / 32768.0
  53. def _resample(self, audio: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
  54. if orig_sr == target_sr:
  55. return audio
  56. duration = len(audio) / orig_sr
  57. new_length = int(duration * target_sr)
  58. indices = np.linspace(0, len(audio) - 1, new_length)
  59. return np.interp(indices, np.arange(len(audio)), audio)
  60. def get_model_info(self) -> dict:
  61. return {
  62. 'model_id': self.model_id,
  63. 'device': self.device,
  64. 'language': self.language
  65. }