views.py 17 KB

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