api.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import base64
  2. import io
  3. import queue
  4. import threading
  5. import traceback
  6. import wave
  7. from argparse import ArgumentParser
  8. from http import HTTPStatus
  9. from typing import Annotated, Literal, Optional
  10. import librosa
  11. import numpy as np
  12. import pyrootutils
  13. import soundfile as sf
  14. import torch
  15. from kui.wsgi import (
  16. Body,
  17. HTTPException,
  18. HttpView,
  19. JSONResponse,
  20. Kui,
  21. OpenAPI,
  22. StreamResponse,
  23. )
  24. from kui.wsgi.routing import MultimethodRoutes
  25. from loguru import logger
  26. from pydantic import BaseModel, Field
  27. from transformers import AutoTokenizer
  28. pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
  29. from tools.llama.generate import launch_thread_safe_queue
  30. from tools.vqgan.inference import load_model as load_vqgan_model
  31. from tools.webui import inference
  32. def wav_chunk_header(sample_rate=44100, bit_depth=16, channels=1):
  33. buffer = io.BytesIO()
  34. with wave.open(buffer, "wb") as wav_file:
  35. wav_file.setnchannels(channels)
  36. wav_file.setsampwidth(bit_depth // 8)
  37. wav_file.setframerate(sample_rate)
  38. wav_header_bytes = buffer.getvalue()
  39. buffer.close()
  40. return wav_header_bytes
  41. # Define utils for web server
  42. def http_execption_handler(exc: HTTPException):
  43. return JSONResponse(
  44. dict(
  45. statusCode=exc.status_code,
  46. message=exc.content,
  47. error=HTTPStatus(exc.status_code).phrase,
  48. ),
  49. exc.status_code,
  50. exc.headers,
  51. )
  52. def other_exception_handler(exc: "Exception"):
  53. traceback.print_exc()
  54. status = HTTPStatus.INTERNAL_SERVER_ERROR
  55. return JSONResponse(
  56. dict(statusCode=status, message=str(exc), error=status.phrase),
  57. status,
  58. )
  59. routes = MultimethodRoutes(base_class=HttpView)
  60. class InvokeRequest(BaseModel):
  61. text: str = "你说的对, 但是原神是一款由米哈游自主研发的开放世界手游."
  62. reference_text: Optional[str] = None
  63. reference_audio: Optional[str] = None
  64. max_new_tokens: int = 0
  65. chunk_length: Annotated[int, Field(ge=0, le=200, strict=True)] = 30
  66. top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
  67. repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.5
  68. temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
  69. speaker: Optional[str] = None
  70. format: Literal["wav", "mp3", "flac"] = "wav"
  71. streaming: bool = False
  72. @torch.inference_mode()
  73. def inference(req: InvokeRequest):
  74. # Parse reference audio aka prompt
  75. prompt_tokens = None
  76. if req.reference_audio is not None:
  77. buffer = io.BytesIO(base64.b64decode(req.reference_audio))
  78. reference_audio_content, _ = librosa.load(
  79. buffer, sr=vqgan_model.sampling_rate, mono=True
  80. )
  81. audios = torch.from_numpy(reference_audio_content).to(vqgan_model.device)[
  82. None, None, :
  83. ]
  84. logger.info(
  85. f"Loaded audio with {audios.shape[2] / vqgan_model.sampling_rate:.2f} seconds"
  86. )
  87. # VQ Encoder
  88. audio_lengths = torch.tensor(
  89. [audios.shape[2]], device=vqgan_model.device, dtype=torch.long
  90. )
  91. prompt_tokens = vqgan_model.encode(audios, audio_lengths)[0][0]
  92. # LLAMA Inference
  93. request = dict(
  94. tokenizer=llama_tokenizer,
  95. device=vqgan_model.device,
  96. max_new_tokens=req.max_new_tokens,
  97. text=req.text,
  98. top_p=req.top_p,
  99. repetition_penalty=req.repetition_penalty,
  100. temperature=req.temperature,
  101. compile=args.compile,
  102. iterative_prompt=req.chunk_length > 0,
  103. chunk_length=req.chunk_length,
  104. max_length=args.max_length,
  105. speaker=req.speaker,
  106. prompt_tokens=prompt_tokens,
  107. prompt_text=req.reference_text,
  108. is_streaming=True,
  109. )
  110. payload = dict(
  111. response_queue=queue.Queue(),
  112. request=request,
  113. )
  114. llama_queue.put(payload)
  115. if req.streaming:
  116. yield wav_chunk_header()
  117. segments = []
  118. while True:
  119. result = payload["response_queue"].get()
  120. if result == "next":
  121. # TODO: handle next sentence
  122. continue
  123. if result == "done":
  124. if payload["success"] is False:
  125. raise payload["response"]
  126. break
  127. # VQGAN Inference
  128. feature_lengths = torch.tensor([result.shape[1]], device=vqgan_model.device)
  129. fake_audios = vqgan_model.decode(
  130. indices=result[None], feature_lengths=feature_lengths, return_audios=True
  131. )[0, 0]
  132. fake_audios = fake_audios.float().cpu().numpy()
  133. if req.streaming:
  134. yield (fake_audios * 32768).astype(np.int16).tobytes()
  135. else:
  136. segments.append(fake_audios)
  137. if req.streaming is False:
  138. fake_audios = np.concatenate(segments, axis=0)
  139. yield fake_audios
  140. @routes.http.post("/v1/invoke")
  141. def api_invoke_model(
  142. req: Annotated[InvokeRequest, Body(exclusive=True)],
  143. ):
  144. """
  145. Invoke model and generate audio
  146. """
  147. if args.max_text_length > 0 and len(req.text) > args.max_text_length:
  148. raise HTTPException(
  149. HTTPStatus.BAD_REQUEST,
  150. content=f"Text is too long, max length is {args.max_text_length}",
  151. )
  152. if req.streaming and req.format != "wav":
  153. raise HTTPException(
  154. HTTPStatus.BAD_REQUEST,
  155. content="Streaming only supports WAV format",
  156. )
  157. generator = inference(req)
  158. if req.streaming:
  159. return StreamResponse(
  160. iterable=generator,
  161. headers={
  162. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  163. },
  164. content_type="application/octet-stream",
  165. )
  166. else:
  167. fake_audios = next(generator)
  168. buffer = io.BytesIO()
  169. sf.write(buffer, fake_audios, vqgan_model.sampling_rate, format=req.format)
  170. return StreamResponse(
  171. iterable=[buffer.getvalue()],
  172. headers={
  173. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  174. },
  175. content_type="application/octet-stream",
  176. )
  177. @routes.http.post("/v1/health")
  178. def api_health():
  179. """
  180. Health check
  181. """
  182. return JSONResponse({"status": "ok"})
  183. def parse_args():
  184. parser = ArgumentParser()
  185. parser.add_argument(
  186. "--llama-checkpoint-path",
  187. type=str,
  188. default="checkpoints/text2semantic-sft-medium-v1-4k.pth",
  189. )
  190. parser.add_argument(
  191. "--llama-config-name", type=str, default="dual_ar_2_codebook_medium"
  192. )
  193. parser.add_argument(
  194. "--vqgan-checkpoint-path",
  195. type=str,
  196. default="checkpoints/vq-gan-group-fsq-2x1024.pth",
  197. )
  198. parser.add_argument("--vqgan-config-name", type=str, default="vqgan_pretrain")
  199. parser.add_argument("--tokenizer", type=str, default="fishaudio/fish-speech-1")
  200. parser.add_argument("--device", type=str, default="cuda")
  201. parser.add_argument("--half", action="store_true")
  202. parser.add_argument("--max-length", type=int, default=2048)
  203. parser.add_argument("--compile", action="store_true")
  204. parser.add_argument("--max-text-length", type=int, default=0)
  205. parser.add_argument("--listen", type=str, default="127.0.0.1:8000")
  206. return parser.parse_args()
  207. # Define Kui app
  208. openapi = OpenAPI(
  209. {
  210. "title": "Fish Speech API",
  211. },
  212. ).routes
  213. app = Kui(
  214. routes=routes + openapi[1:], # Remove the default route
  215. exception_handlers={
  216. HTTPException: http_execption_handler,
  217. Exception: other_exception_handler,
  218. },
  219. cors_config={},
  220. )
  221. if __name__ == "__main__":
  222. import threading
  223. from zibai import create_bind_socket, serve
  224. args = parse_args()
  225. args.precision = torch.half if args.half else torch.bfloat16
  226. logger.info("Loading Llama model...")
  227. llama_queue = launch_thread_safe_queue(
  228. config_name=args.llama_config_name,
  229. checkpoint_path=args.llama_checkpoint_path,
  230. device=args.device,
  231. precision=args.precision,
  232. max_length=args.max_length,
  233. compile=args.compile,
  234. )
  235. llama_tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
  236. logger.info("Llama model loaded, loading VQ-GAN model...")
  237. vqgan_model = load_vqgan_model(
  238. config_name=args.vqgan_config_name,
  239. checkpoint_path=args.vqgan_checkpoint_path,
  240. device=args.device,
  241. )
  242. logger.info("VQ-GAN model loaded, warming up...")
  243. # Dry run to check if the model is loaded correctly and avoid the first-time latency
  244. list(
  245. inference(
  246. InvokeRequest(
  247. text="A warm-up sentence.",
  248. reference_text=None,
  249. reference_audio=None,
  250. max_new_tokens=0,
  251. chunk_length=30,
  252. top_p=0.7,
  253. repetition_penalty=1.5,
  254. temperature=0.7,
  255. speaker=None,
  256. format="wav",
  257. )
  258. )
  259. )
  260. logger.info(f"Warming up done, starting server at http://{args.listen}")
  261. sock = create_bind_socket(args.listen)
  262. sock.listen()
  263. # Start server
  264. serve(
  265. app=app,
  266. bind_sockets=[sock],
  267. max_workers=10,
  268. graceful_exit=threading.Event(),
  269. )