api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import base64
  2. import io
  3. import json
  4. import queue
  5. import random
  6. import traceback
  7. import wave
  8. from argparse import ArgumentParser
  9. from http import HTTPStatus
  10. from pathlib import Path
  11. from typing import Annotated, Literal, Optional
  12. import librosa
  13. import numpy as np
  14. import pyrootutils
  15. import soundfile as sf
  16. import torch
  17. from kui.asgi import (
  18. Body,
  19. HTTPException,
  20. HttpView,
  21. JSONResponse,
  22. Kui,
  23. OpenAPI,
  24. StreamResponse,
  25. )
  26. from kui.asgi.routing import MultimethodRoutes
  27. from loguru import logger
  28. from pydantic import BaseModel, Field
  29. pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
  30. # from fish_speech.models.vqgan.lit_module import VQGAN
  31. from fish_speech.models.vqgan.modules.firefly import FireflyArchitecture
  32. from tools.llama.generate import (
  33. GenerateRequest,
  34. GenerateResponse,
  35. WrappedGenerateResponse,
  36. launch_thread_safe_queue,
  37. )
  38. from tools.vqgan.inference import load_model as load_decoder_model
  39. def wav_chunk_header(sample_rate=44100, bit_depth=16, channels=1):
  40. buffer = io.BytesIO()
  41. with wave.open(buffer, "wb") as wav_file:
  42. wav_file.setnchannels(channels)
  43. wav_file.setsampwidth(bit_depth // 8)
  44. wav_file.setframerate(sample_rate)
  45. wav_header_bytes = buffer.getvalue()
  46. buffer.close()
  47. return wav_header_bytes
  48. # Define utils for web server
  49. async def http_execption_handler(exc: HTTPException):
  50. return JSONResponse(
  51. dict(
  52. statusCode=exc.status_code,
  53. message=exc.content,
  54. error=HTTPStatus(exc.status_code).phrase,
  55. ),
  56. exc.status_code,
  57. exc.headers,
  58. )
  59. async def other_exception_handler(exc: "Exception"):
  60. traceback.print_exc()
  61. status = HTTPStatus.INTERNAL_SERVER_ERROR
  62. return JSONResponse(
  63. dict(statusCode=status, message=str(exc), error=status.phrase),
  64. status,
  65. )
  66. def encode_reference(*, decoder_model, reference_audio, enable_reference_audio):
  67. if enable_reference_audio and reference_audio is not None:
  68. # Load audios, and prepare basic info here
  69. reference_audio_content, _ = librosa.load(
  70. reference_audio, sr=decoder_model.spec_transform.sample_rate, mono=True
  71. )
  72. audios = torch.from_numpy(reference_audio_content).to(decoder_model.device)[
  73. None, None, :
  74. ]
  75. audio_lengths = torch.tensor(
  76. [audios.shape[2]], device=decoder_model.device, dtype=torch.long
  77. )
  78. logger.info(
  79. f"Loaded audio with {audios.shape[2] / decoder_model.spec_transform.sample_rate:.2f} seconds"
  80. )
  81. # VQ Encoder
  82. if isinstance(decoder_model, FireflyArchitecture):
  83. prompt_tokens = decoder_model.encode(audios, audio_lengths)[0][0]
  84. logger.info(f"Encoded prompt: {prompt_tokens.shape}")
  85. else:
  86. prompt_tokens = None
  87. logger.info("No reference audio provided")
  88. return prompt_tokens
  89. def decode_vq_tokens(
  90. *,
  91. decoder_model,
  92. codes,
  93. ):
  94. feature_lengths = torch.tensor([codes.shape[1]], device=decoder_model.device)
  95. logger.info(f"VQ features: {codes.shape}")
  96. if isinstance(decoder_model, FireflyArchitecture):
  97. # VQGAN Inference
  98. return decoder_model.decode(
  99. indices=codes[None],
  100. feature_lengths=feature_lengths,
  101. ).squeeze()
  102. raise ValueError(f"Unknown model type: {type(decoder_model)}")
  103. routes = MultimethodRoutes(base_class=HttpView)
  104. def get_random_paths(base_path, data, speaker, emotion):
  105. if base_path and data and speaker and emotion and (Path(base_path).exists()):
  106. if speaker in data and emotion in data[speaker]:
  107. files = data[speaker][emotion]
  108. lab_files = [f for f in files if f.endswith(".lab")]
  109. wav_files = [f for f in files if f.endswith(".wav")]
  110. if lab_files and wav_files:
  111. selected_lab = random.choice(lab_files)
  112. selected_wav = random.choice(wav_files)
  113. lab_path = Path(base_path) / speaker / emotion / selected_lab
  114. wav_path = Path(base_path) / speaker / emotion / selected_wav
  115. if lab_path.exists() and wav_path.exists():
  116. return lab_path, wav_path
  117. return None, None
  118. def load_json(json_file):
  119. if not json_file:
  120. logger.info("Not using a json file")
  121. return None
  122. try:
  123. with open(json_file, "r", encoding="utf-8") as file:
  124. data = json.load(file)
  125. except FileNotFoundError:
  126. logger.warning(f"ref json not found: {json_file}")
  127. data = None
  128. except Exception as e:
  129. logger.warning(f"Loading json failed: {e}")
  130. data = None
  131. return data
  132. class InvokeRequest(BaseModel):
  133. text: str = "你说的对, 但是原神是一款由米哈游自主研发的开放世界手游."
  134. reference_text: Optional[str] = None
  135. reference_audio: Optional[str] = None
  136. max_new_tokens: int = 1024
  137. chunk_length: Annotated[int, Field(ge=0, le=500, strict=True)] = 100
  138. top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
  139. repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2
  140. temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
  141. emotion: Optional[str] = None
  142. format: Literal["wav", "mp3", "flac"] = "wav"
  143. streaming: bool = False
  144. ref_json: Optional[str] = "ref_data.json"
  145. ref_base: Optional[str] = "ref_data"
  146. speaker: Optional[str] = None
  147. def get_content_type(audio_format):
  148. if audio_format == "wav":
  149. return "audio/wav"
  150. elif audio_format == "flac":
  151. return "audio/flac"
  152. elif audio_format == "mp3":
  153. return "audio/mpeg"
  154. else:
  155. return "application/octet-stream"
  156. @torch.inference_mode()
  157. def inference(req: InvokeRequest):
  158. # Parse reference audio aka prompt
  159. prompt_tokens = None
  160. ref_data = load_json(req.ref_json)
  161. ref_base = req.ref_base
  162. lab_path, wav_path = get_random_paths(ref_base, ref_data, req.speaker, req.emotion)
  163. if lab_path and wav_path:
  164. with open(lab_path, "r", encoding="utf-8") as lab_file:
  165. ref_text = lab_file.read()
  166. req.reference_audio = wav_path
  167. req.reference_text = ref_text
  168. logger.info("ref_path: " + str(wav_path))
  169. logger.info("ref_text: " + ref_text)
  170. # Parse reference audio aka prompt
  171. prompt_tokens = encode_reference(
  172. decoder_model=decoder_model,
  173. reference_audio=req.reference_audio,
  174. enable_reference_audio=req.reference_audio is not None,
  175. )
  176. # LLAMA Inference
  177. request = dict(
  178. device=decoder_model.device,
  179. max_new_tokens=req.max_new_tokens,
  180. text=req.text,
  181. top_p=req.top_p,
  182. repetition_penalty=req.repetition_penalty,
  183. temperature=req.temperature,
  184. compile=args.compile,
  185. iterative_prompt=req.chunk_length > 0,
  186. chunk_length=req.chunk_length,
  187. max_length=2048,
  188. prompt_tokens=prompt_tokens,
  189. prompt_text=req.reference_text,
  190. )
  191. response_queue = queue.Queue()
  192. llama_queue.put(
  193. GenerateRequest(
  194. request=request,
  195. response_queue=response_queue,
  196. )
  197. )
  198. if req.streaming:
  199. yield wav_chunk_header()
  200. segments = []
  201. while True:
  202. result: WrappedGenerateResponse = response_queue.get()
  203. if result.status == "error":
  204. raise result.response
  205. break
  206. result: GenerateResponse = result.response
  207. if result.action == "next":
  208. break
  209. with torch.autocast(
  210. device_type=decoder_model.device.type, dtype=args.precision
  211. ):
  212. fake_audios = decode_vq_tokens(
  213. decoder_model=decoder_model,
  214. codes=result.codes,
  215. )
  216. fake_audios = fake_audios.float().cpu().numpy()
  217. if req.streaming:
  218. yield (fake_audios * 32768).astype(np.int16).tobytes()
  219. else:
  220. segments.append(fake_audios)
  221. if req.streaming:
  222. return
  223. if len(segments) == 0:
  224. raise HTTPException(
  225. HTTPStatus.INTERNAL_SERVER_ERROR,
  226. content="No audio generated, please check the input text.",
  227. )
  228. fake_audios = np.concatenate(segments, axis=0)
  229. yield fake_audios
  230. async def inference_async(req: InvokeRequest):
  231. for chunk in inference(req):
  232. yield chunk
  233. async def buffer_to_async_generator(buffer):
  234. yield buffer
  235. @routes.http.post("/v1/invoke")
  236. async def api_invoke_model(
  237. req: Annotated[InvokeRequest, Body(exclusive=True)],
  238. ):
  239. """
  240. Invoke model and generate audio
  241. """
  242. if args.max_text_length > 0 and len(req.text) > args.max_text_length:
  243. raise HTTPException(
  244. HTTPStatus.BAD_REQUEST,
  245. content=f"Text is too long, max length is {args.max_text_length}",
  246. )
  247. if req.streaming and req.format != "wav":
  248. raise HTTPException(
  249. HTTPStatus.BAD_REQUEST,
  250. content="Streaming only supports WAV format",
  251. )
  252. if req.streaming:
  253. return StreamResponse(
  254. iterable=inference_async(req),
  255. headers={
  256. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  257. },
  258. content_type=get_content_type(req.format),
  259. )
  260. else:
  261. fake_audios = next(inference(req))
  262. buffer = io.BytesIO()
  263. sf.write(
  264. buffer,
  265. fake_audios,
  266. decoder_model.spec_transform.sample_rate,
  267. format=req.format,
  268. )
  269. return StreamResponse(
  270. iterable=buffer_to_async_generator(buffer.getvalue()),
  271. headers={
  272. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  273. },
  274. content_type=get_content_type(req.format),
  275. )
  276. @routes.http.post("/v1/health")
  277. async def api_health():
  278. """
  279. Health check
  280. """
  281. return JSONResponse({"status": "ok"})
  282. def parse_args():
  283. parser = ArgumentParser()
  284. parser.add_argument(
  285. "--llama-checkpoint-path",
  286. type=str,
  287. default="checkpoints/fish-speech-1.2",
  288. )
  289. parser.add_argument(
  290. "--decoder-checkpoint-path",
  291. type=str,
  292. default="checkpoints/fish-speech-1.2/firefly-gan-vq-fsq-4x1024-42hz-generator.pth",
  293. )
  294. parser.add_argument("--decoder-config-name", type=str, default="firefly_gan_vq")
  295. parser.add_argument("--device", type=str, default="cuda")
  296. parser.add_argument("--half", action="store_true")
  297. parser.add_argument("--compile", action="store_true")
  298. parser.add_argument("--max-text-length", type=int, default=0)
  299. parser.add_argument("--listen", type=str, default="127.0.0.1:8000")
  300. parser.add_argument("--workers", type=int, default=1)
  301. return parser.parse_args()
  302. # Define Kui app
  303. openapi = OpenAPI(
  304. {
  305. "title": "Fish Speech API",
  306. },
  307. ).routes
  308. app = Kui(
  309. routes=routes + openapi[1:], # Remove the default route
  310. exception_handlers={
  311. HTTPException: http_execption_handler,
  312. Exception: other_exception_handler,
  313. },
  314. cors_config={},
  315. )
  316. if __name__ == "__main__":
  317. import threading
  318. import uvicorn
  319. args = parse_args()
  320. args.precision = torch.half if args.half else torch.bfloat16
  321. logger.info("Loading Llama model...")
  322. llama_queue = launch_thread_safe_queue(
  323. checkpoint_path=args.llama_checkpoint_path,
  324. device=args.device,
  325. precision=args.precision,
  326. compile=args.compile,
  327. )
  328. logger.info("Llama model loaded, loading VQ-GAN model...")
  329. decoder_model = load_decoder_model(
  330. config_name=args.decoder_config_name,
  331. checkpoint_path=args.decoder_checkpoint_path,
  332. device=args.device,
  333. )
  334. logger.info("VQ-GAN model loaded, warming up...")
  335. # Dry run to check if the model is loaded correctly and avoid the first-time latency
  336. list(
  337. inference(
  338. InvokeRequest(
  339. text="Hello world.",
  340. reference_text=None,
  341. reference_audio=None,
  342. max_new_tokens=0,
  343. top_p=0.7,
  344. repetition_penalty=1.2,
  345. temperature=0.7,
  346. emotion=None,
  347. format="wav",
  348. ref_base=None,
  349. ref_json=None,
  350. )
  351. )
  352. )
  353. logger.info(f"Warming up done, starting server at http://{args.listen}")
  354. host, port = args.listen.split(":")
  355. uvicorn.run(app, host=host, port=int(port), workers=args.workers, log_level="info")