Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

tts_model.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from typing import Annotated, Literal
  17. from abc import ABC
  18. import httpx
  19. import ormsgpack
  20. from pydantic import BaseModel, conint
  21. from rag.utils import num_tokens_from_string
  22. import json
  23. import re
  24. import time
  25. class ServeReferenceAudio(BaseModel):
  26. audio: bytes
  27. text: str
  28. class ServeTTSRequest(BaseModel):
  29. text: str
  30. chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
  31. # Audio format
  32. format: Literal["wav", "pcm", "mp3"] = "mp3"
  33. mp3_bitrate: Literal[64, 128, 192] = 128
  34. # References audios for in-context learning
  35. references: list[ServeReferenceAudio] = []
  36. # Reference id
  37. # For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
  38. # Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
  39. reference_id: str | None = None
  40. # Normalize text for en & zh, this increase stability for numbers
  41. normalize: bool = True
  42. # Balance mode will reduce latency to 300ms, but may decrease stability
  43. latency: Literal["normal", "balanced"] = "normal"
  44. class Base(ABC):
  45. def __init__(self, key, model_name, base_url):
  46. pass
  47. def tts(self, audio):
  48. pass
  49. def normalize_text(self, text):
  50. return re.sub(r'(\*\*|##\d+\$\$|#)', '', text)
  51. class FishAudioTTS(Base):
  52. def __init__(self, key, model_name, base_url="https://api.fish.audio/v1/tts"):
  53. if not base_url:
  54. base_url = "https://api.fish.audio/v1/tts"
  55. key = json.loads(key)
  56. self.headers = {
  57. "api-key": key.get("fish_audio_ak"),
  58. "content-type": "application/msgpack",
  59. }
  60. self.ref_id = key.get("fish_audio_refid")
  61. self.base_url = base_url
  62. def tts(self, text):
  63. from http import HTTPStatus
  64. text = self.normalize_text(text)
  65. request = ServeTTSRequest(text=text, reference_id=self.ref_id)
  66. with httpx.Client() as client:
  67. try:
  68. with client.stream(
  69. method="POST",
  70. url=self.base_url,
  71. content=ormsgpack.packb(
  72. request, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
  73. ),
  74. headers=self.headers,
  75. timeout=None,
  76. ) as response:
  77. if response.status_code == HTTPStatus.OK:
  78. for chunk in response.iter_bytes():
  79. yield chunk
  80. else:
  81. response.raise_for_status()
  82. yield num_tokens_from_string(text)
  83. except httpx.HTTPStatusError as e:
  84. raise RuntimeError(f"**ERROR**: {e}")
  85. class QwenTTS(Base):
  86. def __init__(self, key, model_name, base_url=""):
  87. import dashscope
  88. self.model_name = model_name
  89. dashscope.api_key = key
  90. def tts(self, text):
  91. from dashscope.api_entities.dashscope_response import SpeechSynthesisResponse
  92. from dashscope.audio.tts import ResultCallback, SpeechSynthesizer, SpeechSynthesisResult
  93. from collections import deque
  94. class Callback(ResultCallback):
  95. def __init__(self) -> None:
  96. self.dque = deque()
  97. def _run(self):
  98. while True:
  99. if not self.dque:
  100. time.sleep(0)
  101. continue
  102. val = self.dque.popleft()
  103. if val:
  104. yield val
  105. else:
  106. break
  107. def on_open(self):
  108. pass
  109. def on_complete(self):
  110. self.dque.append(None)
  111. def on_error(self, response: SpeechSynthesisResponse):
  112. raise RuntimeError(str(response))
  113. def on_close(self):
  114. pass
  115. def on_event(self, result: SpeechSynthesisResult):
  116. if result.get_audio_frame() is not None:
  117. self.dque.append(result.get_audio_frame())
  118. text = self.normalize_text(text)
  119. callback = Callback()
  120. SpeechSynthesizer.call(model=self.model_name,
  121. text=text,
  122. callback=callback,
  123. format="mp3")
  124. try:
  125. for data in callback._run():
  126. yield data
  127. yield num_tokens_from_string(text)
  128. except Exception as e:
  129. raise RuntimeError(f"**ERROR**: {e}")