Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

tts_model.py 3.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. class ServeReferenceAudio(BaseModel):
  25. audio: bytes
  26. text: str
  27. class ServeTTSRequest(BaseModel):
  28. text: str
  29. chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
  30. # Audio format
  31. format: Literal["wav", "pcm", "mp3"] = "mp3"
  32. mp3_bitrate: Literal[64, 128, 192] = 128
  33. # References audios for in-context learning
  34. references: list[ServeReferenceAudio] = []
  35. # Reference id
  36. # For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
  37. # Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
  38. reference_id: str | None = None
  39. # Normalize text for en & zh, this increase stability for numbers
  40. normalize: bool = True
  41. # Balance mode will reduce latency to 300ms, but may decrease stability
  42. latency: Literal["normal", "balanced"] = "normal"
  43. class Base(ABC):
  44. def __init__(self, key, model_name, base_url):
  45. pass
  46. def tts(self, audio):
  47. pass
  48. def normalize_text(self, text):
  49. return re.sub(r'(\*\*|##\d+\$\$|#)', '', text)
  50. class FishAudioTTS(Base):
  51. def __init__(self, key, model_name, base_url="https://api.fish.audio/v1/tts"):
  52. if not base_url:
  53. base_url = "https://api.fish.audio/v1/tts"
  54. key = json.loads(key)
  55. self.headers = {
  56. "api-key": key.get("fish_audio_ak"),
  57. "content-type": "application/msgpack",
  58. }
  59. self.ref_id = key.get("fish_audio_refid")
  60. self.base_url = base_url
  61. def tts(self, text):
  62. from http import HTTPStatus
  63. text = self.normalize_text(text)
  64. request = ServeTTSRequest(text=text, reference_id=self.ref_id)
  65. with httpx.Client() as client:
  66. try:
  67. with client.stream(
  68. method="POST",
  69. url=self.base_url,
  70. content=ormsgpack.packb(
  71. request, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
  72. ),
  73. headers=self.headers,
  74. timeout=None,
  75. ) as response:
  76. if response.status_code == HTTPStatus.OK:
  77. for chunk in response.iter_bytes():
  78. yield chunk
  79. else:
  80. response.raise_for_status()
  81. yield num_tokens_from_string(text)
  82. except httpx.HTTPStatusError as e:
  83. raise RuntimeError(f"**ERROR**: {e}")