views.py 16 KB

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