speech_provider.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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.llm 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 or 'https://api.piaoquantv.com/ad/file/upload'
  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, pitch: float, rate: float, filename: str, text: str, *, model: Optional[str] = None, format: Optional[str] = None) -> TextToSpeechResponse:
  22. # Resolve output path under app/audio and ensure directory exists
  23. app_dir = Path(__file__).resolve().parents[1] # .../app
  24. audio_dir = app_dir / "audio"
  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. text=text,
  46. pitch=pitch,
  47. rate=rate,
  48. format=audio_format,
  49. sample_rate=sample_rate,
  50. callback=callback,
  51. word_timestamp_enabled=True,
  52. phoneme_timestamp_enabled=True,
  53. )
  54. # After synthesis completes, upload the file to OSS
  55. try:
  56. url = _upload_file(UPLOAD_PATH, out_path)
  57. return TextToSpeechResponse(audio_url=url)
  58. except Exception as e:
  59. # If upload fails, fall back to local path to avoid breaking
  60. print(f"[warn] Upload failed: {e}")
  61. return TextToSpeechResponse(audio_url=str(out_path))
  62. class Callback(ResultCallback):
  63. def __init__(self, out_path: str, sample_rate: int = 16000, channels: int = 1, sampwidth: int = 2, audio_format: str = "mp3"):
  64. self.out_path = out_path
  65. self.sample_rate = sample_rate
  66. self.channels = channels
  67. self.sampwidth = sampwidth
  68. self.wav_file = None
  69. self._fh = None
  70. self.audio_format = audio_format
  71. def on_open(self):
  72. print('Speech synthesizer is opened.')
  73. # Ensure parent directory exists (in case not created earlier)
  74. Path(self.out_path).parent.mkdir(parents=True, exist_ok=True)
  75. if self.audio_format == "wav":
  76. self.wav_file = wave_open(self.out_path, 'wb')
  77. self.wav_file.setnchannels(self.channels)
  78. self.wav_file.setsampwidth(self.sampwidth)
  79. self.wav_file.setframerate(self.sample_rate)
  80. else:
  81. # For mp3 (and other compressed formats), write raw bytes
  82. self._fh = open(self.out_path, 'wb')
  83. def on_complete(self):
  84. print('Speech synthesizer is completed.')
  85. if self.wav_file:
  86. self.wav_file.close()
  87. self.wav_file = None
  88. if self._fh:
  89. self._fh.close()
  90. self._fh = None
  91. def on_error(self, response: SpeechSynthesisResponse):
  92. print('Speech synthesizer failed, response is %s' % (str(response)))
  93. def on_close(self):
  94. print('Speech synthesizer is closed.')
  95. def on_event(self, result: SpeechSynthesisResult):
  96. frame = result.get_audio_frame()
  97. if not frame:
  98. return
  99. if self.wav_file:
  100. self.wav_file.writeframes(frame)
  101. elif self._fh:
  102. self._fh.write(frame)
  103. def _extract_url_from_response(resp_json: dict) -> Optional[str]:
  104. # Try common shapes: {data: {url}}, {url}, {data: "http..."}
  105. try_keys = [
  106. ("data", "fileUrl"),
  107. ("data",),
  108. ("fileUrl",),
  109. ("result", "fileUrl"),
  110. ("payload", "fileUrl"),
  111. ]
  112. for path in try_keys:
  113. cur = resp_json
  114. ok = True
  115. for k in path:
  116. if isinstance(cur, dict) and k in cur:
  117. cur = cur[k]
  118. print(cur)
  119. else:
  120. ok = False
  121. break
  122. if ok and isinstance(cur, str) and cur.startswith("http"):
  123. return cur
  124. return None
  125. def _upload_file(upload_url: str, file_path: Path) -> str:
  126. if not upload_url:
  127. raise ValueError("upload_url is empty")
  128. if not Path(file_path).exists():
  129. raise FileNotFoundError(str(file_path))
  130. filename = Path(file_path).name
  131. # Guess content type
  132. content_type = "audio/mpeg" if filename.lower().endswith(".mp3") else "audio/wav"
  133. with open(file_path, "rb") as f:
  134. files = {
  135. "file": (filename, f, content_type),
  136. "fileType": (None, "VOICE")
  137. }
  138. resp = requests.post(upload_url, files=files, timeout=30)
  139. resp.raise_for_status()
  140. # Try to parse JSON for a URL; fallback to raw text if JSON invalid
  141. url: Optional[str] = None
  142. try:
  143. data = resp.json()
  144. url = _extract_url_from_response(data)
  145. except Exception:
  146. pass
  147. if not url:
  148. # As a last resort, if the response text looks like a URL, use it
  149. txt = (resp.text or "").strip()
  150. if txt.startswith("http"):
  151. url = txt
  152. if not url:
  153. raise RuntimeError("Upload succeeded but no URL found in response")
  154. return url