speech_provider.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. from wave import open as wave_open
  2. from pathlib import Path
  3. import re
  4. import os
  5. import json
  6. from typing import Optional
  7. import dashscope
  8. from dashscope.api_entities.dashscope_response import SpeechSynthesisResponse
  9. from dashscope.audio.tts import ResultCallback, SpeechSynthesizer, SpeechSynthesisResult
  10. import requests
  11. from ..schemas.speech import TextToSpeechResponse
  12. from ..core.config import get_settings
  13. settings = get_settings()
  14. # Configure DashScope API key from env/.env
  15. dashscope.api_key = settings.dashscope_api_key or ""
  16. UPLOAD_PATH = settings.upload_path
  17. def _safe_filename(name: str) -> str:
  18. # Keep alphanum, dash, underscore, Chinese; replace others with '_'
  19. return re.sub(r"[^\w\-\u4e00-\u9fff]+", "_", name).strip("_") or "output"
  20. class SpeechProvider:
  21. def text_to_speech(self, volume: int, pitch: float, rate: float, filename: str, text: str, *, model: Optional[str] = None, format: Optional[str] = None) -> TextToSpeechResponse:
  22. # Resolve output path under project-root/temp and ensure directory exists
  23. project_root = Path(__file__).resolve().parents[2] # repo root
  24. audio_dir = project_root / "temp"
  25. audio_dir.mkdir(parents=True, exist_ok=True)
  26. # determine desired output format (default mp3 for smaller size)
  27. audio_format = (format or 'mp3').lower()
  28. if audio_format not in {"wav", "mp3"}:
  29. audio_format = "mp3"
  30. # choose extension and sample rate
  31. ext = "wav" if audio_format == "wav" else "mp3"
  32. sample_rate = 48000 if audio_format == "wav" else 24000
  33. filename = f"{_safe_filename(filename)}.{ext}"
  34. out_path = audio_dir / filename
  35. # Prepare callback with audio params
  36. callback = Callback(
  37. out_path=str(out_path),
  38. sample_rate=sample_rate,
  39. channels=1,
  40. sampwidth=2,
  41. audio_format=audio_format,
  42. )
  43. SpeechSynthesizer.call(
  44. model=(model or 'sambert-zhifei-v1'),
  45. volume=volume,
  46. text=text,
  47. pitch=pitch,
  48. rate=rate,
  49. format=audio_format,
  50. sample_rate=sample_rate,
  51. callback=callback,
  52. word_timestamp_enabled=True,
  53. phoneme_timestamp_enabled=True,
  54. )
  55. # After synthesis completes, upload the file to OSS
  56. try:
  57. url = _upload_file(UPLOAD_PATH, out_path)
  58. # Upload succeeded; remove local audio file to save space
  59. try:
  60. Path(out_path).unlink(missing_ok=True)
  61. except Exception as del_err:
  62. print(f"[warn] Failed to delete local audio {out_path}: {del_err}")
  63. return TextToSpeechResponse(audio_url=url)
  64. except Exception as e:
  65. # If upload fails, fall back to local path to avoid breaking
  66. print(f"[warn] Upload failed: {e}")
  67. return TextToSpeechResponse(audio_url=str(out_path))
  68. class Callback(ResultCallback):
  69. def __init__(self, out_path: str, sample_rate: int = 16000, channels: int = 1, sampwidth: int = 2, audio_format: str = "mp3"):
  70. self.out_path = out_path
  71. self.sample_rate = sample_rate
  72. self.channels = channels
  73. self.sampwidth = sampwidth
  74. self.wav_file = None
  75. self._fh = None
  76. self.audio_format = audio_format
  77. def on_open(self):
  78. print('Speech synthesizer is opened.')
  79. # Ensure parent directory exists (in case not created earlier)
  80. Path(self.out_path).parent.mkdir(parents=True, exist_ok=True)
  81. if self.audio_format == "wav":
  82. self.wav_file = wave_open(self.out_path, 'wb')
  83. self.wav_file.setnchannels(self.channels)
  84. self.wav_file.setsampwidth(self.sampwidth)
  85. self.wav_file.setframerate(self.sample_rate)
  86. else:
  87. # For mp3 (and other compressed formats), write raw bytes
  88. self._fh = open(self.out_path, 'wb')
  89. def on_complete(self):
  90. print('Speech synthesizer is completed.')
  91. if self.wav_file:
  92. self.wav_file.close()
  93. self.wav_file = None
  94. if self._fh:
  95. self._fh.close()
  96. self._fh = None
  97. def on_error(self, response: SpeechSynthesisResponse):
  98. print('Speech synthesizer failed, response is %s' % (str(response)))
  99. def on_close(self):
  100. print('Speech synthesizer is closed.')
  101. def on_event(self, result: SpeechSynthesisResult):
  102. frame = result.get_audio_frame()
  103. if not frame:
  104. return
  105. if self.wav_file:
  106. self.wav_file.writeframes(frame)
  107. elif self._fh:
  108. self._fh.write(frame)
  109. def _extract_url_from_response(resp_json: dict) -> Optional[str]:
  110. # Try common shapes: {data: {url}}, {url}, {data: "http..."}
  111. try_keys = [
  112. ("data", "fileUrl"),
  113. ("data",),
  114. ("fileUrl",),
  115. ("result", "fileUrl"),
  116. ("payload", "fileUrl"),
  117. ]
  118. for path in try_keys:
  119. cur = resp_json
  120. ok = True
  121. for k in path:
  122. if isinstance(cur, dict) and k in cur:
  123. cur = cur[k]
  124. print(cur)
  125. else:
  126. ok = False
  127. break
  128. if ok and isinstance(cur, str) and cur.startswith("http"):
  129. return cur
  130. return None
  131. def _upload_file(upload_url: str, file_path: Path) -> str:
  132. if not upload_url:
  133. raise ValueError("upload_url is empty")
  134. if not Path(file_path).exists():
  135. raise FileNotFoundError(str(file_path))
  136. filename = Path(file_path).name
  137. # Guess content type
  138. content_type = "audio/mpeg" if filename.lower().endswith(".mp3") else "audio/wav"
  139. with open(file_path, "rb") as f:
  140. files = {
  141. "file": (filename, f, content_type),
  142. "fileType": (None, "VOICE")
  143. }
  144. resp = requests.post(upload_url, files=files, timeout=30)
  145. resp.raise_for_status()
  146. # Try to parse JSON for a URL; fallback to raw text if JSON invalid
  147. url: Optional[str] = None
  148. try:
  149. data = resp.json()
  150. url = _extract_url_from_response(data)
  151. except Exception:
  152. pass
  153. if not url:
  154. # As a last resort, if the response text looks like a URL, use it
  155. txt = (resp.text or "").strip()
  156. if txt.startswith("http"):
  157. url = txt
  158. if not url:
  159. raise RuntimeError("Upload succeeded but no URL found in response")
  160. return url