views.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import io
  2. import os
  3. import re
  4. import shutil
  5. import tempfile
  6. import time
  7. from http import HTTPStatus
  8. from pathlib import Path
  9. import numpy as np
  10. import ormsgpack
  11. import soundfile as sf
  12. import torch
  13. from kui.asgi import (
  14. Body,
  15. HTTPException,
  16. HttpView,
  17. JSONResponse,
  18. Routes,
  19. StreamResponse,
  20. UploadFile,
  21. request,
  22. )
  23. from loguru import logger
  24. from typing_extensions import Annotated
  25. from fish_speech.utils.schema import (
  26. AddReferenceRequest,
  27. AddReferenceResponse,
  28. DeleteReferenceResponse,
  29. ListReferencesResponse,
  30. ServeTTSRequest,
  31. ServeVQGANDecodeRequest,
  32. ServeVQGANDecodeResponse,
  33. ServeVQGANEncodeRequest,
  34. ServeVQGANEncodeResponse,
  35. UpdateReferenceResponse,
  36. )
  37. from tools.server.api_utils import (
  38. buffer_to_async_generator,
  39. format_response,
  40. get_content_type,
  41. inference_async,
  42. )
  43. from tools.server.inference import inference_wrapper as inference
  44. from tools.server.model_manager import ModelManager
  45. from tools.server.model_utils import (
  46. batch_vqgan_decode,
  47. cached_vqgan_batch_encode,
  48. )
  49. MAX_NUM_SAMPLES = int(os.getenv("NUM_SAMPLES", 1))
  50. routes = Routes()
  51. @routes.http("/v1/health")
  52. class Health(HttpView):
  53. @classmethod
  54. async def get(cls):
  55. return JSONResponse({"status": "ok"})
  56. @classmethod
  57. async def post(cls):
  58. return JSONResponse({"status": "ok"})
  59. @routes.http.post("/v1/vqgan/encode")
  60. async def vqgan_encode(req: Annotated[ServeVQGANEncodeRequest, Body(exclusive=True)]):
  61. """
  62. Encode audio using VQGAN model.
  63. """
  64. try:
  65. # Get the model from the app
  66. model_manager: ModelManager = request.app.state.model_manager
  67. decoder_model = model_manager.decoder_model
  68. # Encode the audio
  69. start_time = time.time()
  70. tokens = cached_vqgan_batch_encode(decoder_model, req.audios)
  71. logger.info(
  72. f"[EXEC] VQGAN encode time: {(time.time() - start_time) * 1000:.2f}ms"
  73. )
  74. # Return the response
  75. return ormsgpack.packb(
  76. ServeVQGANEncodeResponse(tokens=[i.tolist() for i in tokens]),
  77. option=ormsgpack.OPT_SERIALIZE_PYDANTIC,
  78. )
  79. except Exception as e:
  80. logger.error(f"Error in VQGAN encode: {e}", exc_info=True)
  81. raise HTTPException(
  82. HTTPStatus.INTERNAL_SERVER_ERROR, content="Failed to encode audio"
  83. )
  84. @routes.http.post("/v1/vqgan/decode")
  85. async def vqgan_decode(req: Annotated[ServeVQGANDecodeRequest, Body(exclusive=True)]):
  86. """
  87. Decode tokens to audio using VQGAN model.
  88. """
  89. try:
  90. # Get the model from the app
  91. model_manager: ModelManager = request.app.state.model_manager
  92. decoder_model = model_manager.decoder_model
  93. # Decode the audio
  94. tokens = [torch.tensor(token, dtype=torch.int) for token in req.tokens]
  95. start_time = time.time()
  96. audios = batch_vqgan_decode(decoder_model, tokens)
  97. logger.info(
  98. f"[EXEC] VQGAN decode time: {(time.time() - start_time) * 1000:.2f}ms"
  99. )
  100. audios = [audio.astype(np.float16).tobytes() for audio in audios]
  101. # Return the response
  102. return ormsgpack.packb(
  103. ServeVQGANDecodeResponse(audios=audios),
  104. option=ormsgpack.OPT_SERIALIZE_PYDANTIC,
  105. )
  106. except Exception as e:
  107. logger.error(f"Error in VQGAN decode: {e}", exc_info=True)
  108. raise HTTPException(
  109. HTTPStatus.INTERNAL_SERVER_ERROR, content="Failed to decode tokens to audio"
  110. )
  111. @routes.http.post("/v1/tts")
  112. async def tts(req: Annotated[ServeTTSRequest, Body(exclusive=True)]):
  113. """
  114. Generate speech from text using TTS model.
  115. """
  116. try:
  117. # Get the model from the app
  118. app_state = request.app.state
  119. model_manager: ModelManager = app_state.model_manager
  120. engine = model_manager.tts_inference_engine
  121. sample_rate = engine.decoder_model.sample_rate
  122. # Check if the text is too long
  123. if app_state.max_text_length > 0 and len(req.text) > app_state.max_text_length:
  124. raise HTTPException(
  125. HTTPStatus.BAD_REQUEST,
  126. content=f"Text is too long, max length is {app_state.max_text_length}",
  127. )
  128. # Check if streaming is enabled
  129. if req.streaming and req.format != "wav":
  130. raise HTTPException(
  131. HTTPStatus.BAD_REQUEST,
  132. content="Streaming only supports WAV format",
  133. )
  134. # Perform TTS
  135. if req.streaming:
  136. return StreamResponse(
  137. iterable=inference_async(req, engine),
  138. headers={
  139. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  140. },
  141. content_type=get_content_type(req.format),
  142. )
  143. else:
  144. fake_audios = next(inference(req, engine))
  145. buffer = io.BytesIO()
  146. sf.write(
  147. buffer,
  148. fake_audios,
  149. sample_rate,
  150. format=req.format,
  151. )
  152. return StreamResponse(
  153. iterable=buffer_to_async_generator(buffer.getvalue()),
  154. headers={
  155. "Content-Disposition": f"attachment; filename=audio.{req.format}",
  156. },
  157. content_type=get_content_type(req.format),
  158. )
  159. except HTTPException:
  160. # Re-raise HTTP exceptions as they are already properly formatted
  161. raise
  162. except Exception as e:
  163. logger.error(f"Error in TTS generation: {e}", exc_info=True)
  164. raise HTTPException(
  165. HTTPStatus.INTERNAL_SERVER_ERROR, content="Failed to generate speech"
  166. )
  167. @routes.http.post("/v1/references/add")
  168. async def add_reference(
  169. id: str = Body(...), audio: UploadFile = Body(...), text: str = Body(...)
  170. ):
  171. """
  172. Add a new reference voice with audio file and text.
  173. """
  174. temp_file_path = None
  175. try:
  176. # Validate input parameters
  177. if not id or not id.strip():
  178. raise ValueError("Reference ID cannot be empty")
  179. if not text or not text.strip():
  180. raise ValueError("Reference text cannot be empty")
  181. # Get the model manager to access the reference loader
  182. app_state = request.app.state
  183. model_manager: ModelManager = app_state.model_manager
  184. engine = model_manager.tts_inference_engine
  185. # Read the uploaded audio file
  186. audio_content = audio.read()
  187. if not audio_content:
  188. raise ValueError("Audio file is empty or could not be read")
  189. # Create a temporary file for the audio data
  190. with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
  191. temp_file.write(audio_content)
  192. temp_file_path = temp_file.name
  193. # Add the reference using the engine's reference loader
  194. engine.add_reference(id, temp_file_path, text)
  195. response = AddReferenceResponse(
  196. success=True,
  197. message=f"Reference voice '{id}' added successfully",
  198. reference_id=id,
  199. )
  200. return format_response(response)
  201. except FileExistsError as e:
  202. logger.warning(f"Reference ID '{id}' already exists: {e}")
  203. response = AddReferenceResponse(
  204. success=False,
  205. message=f"Reference ID '{id}' already exists",
  206. reference_id=id,
  207. )
  208. return format_response(response, status_code=409) # Conflict
  209. except ValueError as e:
  210. logger.warning(f"Invalid input for reference '{id}': {e}")
  211. response = AddReferenceResponse(success=False, message=str(e), reference_id=id)
  212. return format_response(response, status_code=400)
  213. except (FileNotFoundError, OSError) as e:
  214. logger.error(f"File system error for reference '{id}': {e}")
  215. response = AddReferenceResponse(
  216. success=False, message="File system error occurred", reference_id=id
  217. )
  218. return format_response(response, status_code=500)
  219. except Exception as e:
  220. logger.error(f"Unexpected error adding reference '{id}': {e}", exc_info=True)
  221. response = AddReferenceResponse(
  222. success=False, message="Internal server error occurred", reference_id=id
  223. )
  224. return format_response(response, status_code=500)
  225. finally:
  226. # Clean up temporary file
  227. if temp_file_path and os.path.exists(temp_file_path):
  228. try:
  229. os.unlink(temp_file_path)
  230. except OSError as e:
  231. logger.warning(
  232. f"Failed to clean up temporary file {temp_file_path}: {e}"
  233. )
  234. @routes.http.get("/v1/references/list")
  235. async def list_references():
  236. """
  237. Get a list of all available reference voice IDs.
  238. """
  239. try:
  240. # Get the model manager to access the reference loader
  241. app_state = request.app.state
  242. model_manager: ModelManager = app_state.model_manager
  243. engine = model_manager.tts_inference_engine
  244. # Get the list of reference IDs
  245. reference_ids = engine.list_reference_ids()
  246. response = ListReferencesResponse(
  247. success=True,
  248. reference_ids=reference_ids,
  249. message=f"Found {len(reference_ids)} reference voices",
  250. )
  251. return format_response(response)
  252. except Exception as e:
  253. logger.error(f"Unexpected error listing references: {e}", exc_info=True)
  254. response = ListReferencesResponse(
  255. success=False, reference_ids=[], message="Internal server error occurred"
  256. )
  257. return format_response(response, status_code=500)
  258. @routes.http.delete("/v1/references/delete")
  259. async def delete_reference(reference_id: str = Body(...)):
  260. """
  261. Delete a reference voice by ID.
  262. """
  263. try:
  264. # Validate input parameters
  265. if not reference_id or not reference_id.strip():
  266. raise ValueError("Reference ID cannot be empty")
  267. # Get the model manager to access the reference loader
  268. app_state = request.app.state
  269. model_manager: ModelManager = app_state.model_manager
  270. engine = model_manager.tts_inference_engine
  271. # Delete the reference using the engine's reference loader
  272. engine.delete_reference(reference_id)
  273. response = DeleteReferenceResponse(
  274. success=True,
  275. message=f"Reference voice '{reference_id}' deleted successfully",
  276. reference_id=reference_id,
  277. )
  278. return format_response(response)
  279. except FileNotFoundError as e:
  280. logger.warning(f"Reference ID '{reference_id}' not found: {e}")
  281. response = DeleteReferenceResponse(
  282. success=False,
  283. message=f"Reference ID '{reference_id}' not found",
  284. reference_id=reference_id,
  285. )
  286. return format_response(response, status_code=404) # Not Found
  287. except ValueError as e:
  288. logger.warning(f"Invalid input for reference '{reference_id}': {e}")
  289. response = DeleteReferenceResponse(
  290. success=False, message=str(e), reference_id=reference_id
  291. )
  292. return format_response(response, status_code=400)
  293. except OSError as e:
  294. logger.error(f"File system error deleting reference '{reference_id}': {e}")
  295. response = DeleteReferenceResponse(
  296. success=False,
  297. message="File system error occurred",
  298. reference_id=reference_id,
  299. )
  300. return format_response(response, status_code=500)
  301. except Exception as e:
  302. logger.error(
  303. f"Unexpected error deleting reference '{reference_id}': {e}", exc_info=True
  304. )
  305. response = DeleteReferenceResponse(
  306. success=False,
  307. message="Internal server error occurred",
  308. reference_id=reference_id,
  309. )
  310. return format_response(response, status_code=500)
  311. @routes.http.post("/v1/references/update")
  312. async def update_reference(
  313. old_reference_id: str = Body(...), new_reference_id: str = Body(...)
  314. ):
  315. """
  316. Rename a reference voice directory from old_reference_id to new_reference_id.
  317. """
  318. try:
  319. # Validate input parameters
  320. if not old_reference_id or not old_reference_id.strip():
  321. raise ValueError("Old reference ID cannot be empty")
  322. if not new_reference_id or not new_reference_id.strip():
  323. raise ValueError("New reference ID cannot be empty")
  324. if old_reference_id == new_reference_id:
  325. raise ValueError("New reference ID must be different from old reference ID")
  326. # Validate ID format per ReferenceLoader rules
  327. id_pattern = r"^[a-zA-Z0-9\-_ ]+$"
  328. if not re.match(id_pattern, new_reference_id) or len(new_reference_id) > 255:
  329. raise ValueError(
  330. "New reference ID contains invalid characters or is too long"
  331. )
  332. # Access engine to update caches after renaming
  333. app_state = request.app.state
  334. model_manager: ModelManager = app_state.model_manager
  335. engine = model_manager.tts_inference_engine
  336. refs_base = Path("references")
  337. old_dir = refs_base / old_reference_id
  338. new_dir = refs_base / new_reference_id
  339. # Existence checks
  340. if not old_dir.exists() or not old_dir.is_dir():
  341. raise FileNotFoundError(f"Reference ID '{old_reference_id}' not found")
  342. if new_dir.exists():
  343. # Conflict: destination already exists
  344. response = UpdateReferenceResponse(
  345. success=False,
  346. message=f"Reference ID '{new_reference_id}' already exists",
  347. old_reference_id=old_reference_id,
  348. new_reference_id=new_reference_id,
  349. )
  350. return format_response(response, status_code=409)
  351. # Perform rename
  352. old_dir.rename(new_dir)
  353. # Update in-memory cache key if present
  354. if old_reference_id in engine.ref_by_id:
  355. engine.ref_by_id[new_reference_id] = engine.ref_by_id.pop(old_reference_id)
  356. response = UpdateReferenceResponse(
  357. success=True,
  358. message=(
  359. f"Reference voice renamed from '{old_reference_id}' to '{new_reference_id}' successfully"
  360. ),
  361. old_reference_id=old_reference_id,
  362. new_reference_id=new_reference_id,
  363. )
  364. return format_response(response)
  365. except FileNotFoundError as e:
  366. logger.warning(str(e))
  367. response = UpdateReferenceResponse(
  368. success=False,
  369. message=str(e),
  370. old_reference_id=old_reference_id,
  371. new_reference_id=new_reference_id,
  372. )
  373. return format_response(response, status_code=404)
  374. except ValueError as e:
  375. logger.warning(f"Invalid input for update reference: {e}")
  376. response = UpdateReferenceResponse(
  377. success=False,
  378. message=str(e),
  379. old_reference_id=old_reference_id if "old_reference_id" in locals() else "",
  380. new_reference_id=new_reference_id if "new_reference_id" in locals() else "",
  381. )
  382. return format_response(response, status_code=400)
  383. except OSError as e:
  384. logger.error(f"File system error renaming reference: {e}")
  385. response = UpdateReferenceResponse(
  386. success=False,
  387. message="File system error occurred",
  388. old_reference_id=old_reference_id,
  389. new_reference_id=new_reference_id,
  390. )
  391. return format_response(response, status_code=500)
  392. except Exception as e:
  393. logger.error(f"Unexpected error updating reference: {e}", exc_info=True)
  394. response = UpdateReferenceResponse(
  395. success=False,
  396. message="Internal server error occurred",
  397. old_reference_id=old_reference_id if "old_reference_id" in locals() else "",
  398. new_reference_id=new_reference_id if "new_reference_id" in locals() else "",
  399. )
  400. return format_response(response, status_code=500)