webui.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import gc
  2. import html
  3. import io
  4. import os
  5. import queue
  6. import wave
  7. from argparse import ArgumentParser
  8. from pathlib import Path
  9. import gradio as gr
  10. import librosa
  11. import numpy as np
  12. import pyrootutils
  13. import torch
  14. from loguru import logger
  15. from transformers import AutoTokenizer
  16. pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
  17. from fish_speech.i18n import i18n
  18. from tools.llama.generate import launch_thread_safe_queue
  19. from tools.vqgan.inference import load_model as load_vqgan_model
  20. # Make einx happy
  21. os.environ["EINX_FILTER_TRACEBACK"] = "false"
  22. HEADER_MD = f"""# Fish Speech
  23. {i18n("A text-to-speech model based on VQ-GAN and Llama developed by [Fish Audio](https://fish.audio).")}
  24. {i18n("You can find the source code [here](https://github.com/fishaudio/fish-speech) and models [here](https://huggingface.co/fishaudio/fish-speech-1).")}
  25. {i18n("Related code are released under BSD-3-Clause License, and weights are released under CC BY-NC-SA 4.0 License.")}
  26. {i18n("We are not responsible for any misuse of the model, please consider your local laws and regulations before using it.")}
  27. """
  28. TEXTBOX_PLACEHOLDER = i18n("Put your text here.")
  29. try:
  30. import spaces
  31. GPU_DECORATOR = spaces.GPU
  32. except ImportError:
  33. def GPU_DECORATOR(func):
  34. def wrapper(*args, **kwargs):
  35. return func(*args, **kwargs)
  36. return wrapper
  37. def build_html_error_message(error):
  38. return f"""
  39. <div style="color: red;
  40. font-weight: bold;">
  41. {html.escape(str(error))}
  42. </div>
  43. """
  44. @GPU_DECORATOR
  45. @torch.inference_mode()
  46. def inference(
  47. text,
  48. enable_reference_audio,
  49. reference_audio,
  50. reference_text,
  51. max_new_tokens,
  52. chunk_length,
  53. top_p,
  54. repetition_penalty,
  55. temperature,
  56. speaker,
  57. ):
  58. if args.max_gradio_length > 0 and len(text) > args.max_gradio_length:
  59. return (
  60. None,
  61. i18n("Text is too long, please keep it under {} characters.").format(
  62. args.max_gradio_length
  63. ),
  64. )
  65. # Parse reference audio aka prompt
  66. prompt_tokens = None
  67. if enable_reference_audio and reference_audio is not None:
  68. # reference_audio_sr, reference_audio_content = reference_audio
  69. reference_audio_content, _ = librosa.load(
  70. reference_audio, sr=vqgan_model.sampling_rate, mono=True
  71. )
  72. audios = torch.from_numpy(reference_audio_content).to(vqgan_model.device)[
  73. None, None, :
  74. ]
  75. logger.info(
  76. f"Loaded audio with {audios.shape[2] / vqgan_model.sampling_rate:.2f} seconds"
  77. )
  78. # VQ Encoder
  79. audio_lengths = torch.tensor(
  80. [audios.shape[2]], device=vqgan_model.device, dtype=torch.long
  81. )
  82. prompt_tokens = vqgan_model.encode(audios, audio_lengths)[0][0]
  83. # LLAMA Inference
  84. request = dict(
  85. tokenizer=llama_tokenizer,
  86. device=vqgan_model.device,
  87. max_new_tokens=max_new_tokens,
  88. text=text,
  89. top_p=top_p,
  90. repetition_penalty=repetition_penalty,
  91. temperature=temperature,
  92. compile=args.compile,
  93. iterative_prompt=chunk_length > 0,
  94. chunk_length=chunk_length,
  95. max_length=args.max_length,
  96. speaker=speaker if speaker else None,
  97. prompt_tokens=prompt_tokens if enable_reference_audio else None,
  98. prompt_text=reference_text if enable_reference_audio else None,
  99. )
  100. payload = dict(
  101. response_queue=queue.Queue(),
  102. request=request,
  103. )
  104. llama_queue.put(payload)
  105. codes = []
  106. while True:
  107. result = payload["response_queue"].get()
  108. if result == "next":
  109. # TODO: handle next sentence
  110. continue
  111. if result == "done":
  112. if payload["success"] is False:
  113. return None, build_html_error_message(payload["response"])
  114. break
  115. codes.append(result)
  116. codes = torch.cat(codes, dim=1)
  117. # VQGAN Inference
  118. feature_lengths = torch.tensor([codes.shape[1]], device=vqgan_model.device)
  119. fake_audios = vqgan_model.decode(
  120. indices=codes[None], feature_lengths=feature_lengths, return_audios=True
  121. )[0, 0]
  122. fake_audios = fake_audios.float().cpu().numpy()
  123. if torch.cuda.is_available():
  124. torch.cuda.empty_cache()
  125. gc.collect()
  126. return (vqgan_model.sampling_rate, fake_audios), None
  127. def wav_chunk_header(sample_rate=44100, bit_depth=16, channels=1):
  128. buffer = io.BytesIO()
  129. with wave.open(buffer, "wb") as wav_file:
  130. wav_file.setnchannels(channels)
  131. wav_file.setsampwidth(bit_depth // 8)
  132. wav_file.setframerate(sample_rate)
  133. wav_header_bytes = buffer.getvalue()
  134. buffer.close()
  135. return wav_header_bytes
  136. @torch.inference_mode
  137. def inference_stream(
  138. text,
  139. enable_reference_audio,
  140. reference_audio,
  141. reference_text,
  142. max_new_tokens,
  143. chunk_length,
  144. top_p,
  145. repetition_penalty,
  146. temperature,
  147. speaker,
  148. ):
  149. if args.max_gradio_length > 0 and len(text) > args.max_gradio_length:
  150. yield (
  151. None,
  152. i18n("Text is too long, please keep it under {} characters.").format(
  153. args.max_gradio_length
  154. ),
  155. )
  156. # Parse reference audio aka prompt
  157. prompt_tokens = None
  158. if enable_reference_audio and reference_audio is not None:
  159. # reference_audio_sr, reference_audio_content = reference_audio
  160. reference_audio_content, _ = librosa.load(
  161. reference_audio, sr=vqgan_model.sampling_rate, mono=True
  162. )
  163. audios = torch.from_numpy(reference_audio_content).to(vqgan_model.device)[
  164. None, None, :
  165. ]
  166. logger.info(
  167. f"Loaded audio with {audios.shape[2] / vqgan_model.sampling_rate:.2f} seconds"
  168. )
  169. # VQ Encoder
  170. audio_lengths = torch.tensor(
  171. [audios.shape[2]], device=vqgan_model.device, dtype=torch.long
  172. )
  173. prompt_tokens = vqgan_model.encode(audios, audio_lengths)[0][0]
  174. # LLAMA Inference
  175. request = dict(
  176. tokenizer=llama_tokenizer,
  177. device=vqgan_model.device,
  178. max_new_tokens=max_new_tokens,
  179. text=text,
  180. top_p=top_p,
  181. repetition_penalty=repetition_penalty,
  182. temperature=temperature,
  183. compile=args.compile,
  184. iterative_prompt=chunk_length > 0,
  185. chunk_length=chunk_length,
  186. max_length=args.max_length,
  187. speaker=speaker if speaker else None,
  188. prompt_tokens=prompt_tokens if enable_reference_audio else None,
  189. prompt_text=reference_text if enable_reference_audio else None,
  190. is_streaming=True,
  191. )
  192. payload = dict(
  193. response_queue=queue.Queue(),
  194. request=request,
  195. )
  196. llama_queue.put(payload)
  197. yield wav_chunk_header(), None
  198. while True:
  199. result = payload["response_queue"].get()
  200. if result == "next":
  201. # TODO: handle next sentence
  202. continue
  203. if result == "done":
  204. if payload["success"] is False:
  205. yield None, build_html_error_message(payload["response"])
  206. break
  207. # VQGAN Inference
  208. feature_lengths = torch.tensor([result.shape[1]], device=vqgan_model.device)
  209. fake_audios = vqgan_model.decode(
  210. indices=result[None], feature_lengths=feature_lengths, return_audios=True
  211. )[0, 0]
  212. fake_audios = fake_audios.float().cpu().numpy()
  213. yield (
  214. np.concatenate([fake_audios, np.zeros((11025,))], axis=0) * 32768
  215. ).astype(np.int16).tobytes(), None
  216. if torch.cuda.is_available():
  217. torch.cuda.empty_cache()
  218. gc.collect()
  219. pass
  220. def build_app():
  221. with gr.Blocks(theme=gr.themes.Base()) as app:
  222. gr.Markdown(HEADER_MD)
  223. # Use light theme by default
  224. app.load(
  225. None,
  226. None,
  227. js="() => {const params = new URLSearchParams(window.location.search);if (!params.has('__theme')) {params.set('__theme', 'light');window.location.search = params.toString();}}",
  228. )
  229. # Inference
  230. with gr.Row():
  231. with gr.Column(scale=3):
  232. text = gr.Textbox(
  233. label=i18n("Input Text"), placeholder=TEXTBOX_PLACEHOLDER, lines=15
  234. )
  235. with gr.Row():
  236. with gr.Tab(label=i18n("Advanced Config")):
  237. chunk_length = gr.Slider(
  238. label=i18n("Iterative Prompt Length, 0 means off"),
  239. minimum=0,
  240. maximum=500,
  241. value=30,
  242. step=8,
  243. )
  244. max_new_tokens = gr.Slider(
  245. label=i18n("Maximum tokens per batch, 0 means no limit"),
  246. minimum=0,
  247. maximum=args.max_length,
  248. value=0, # 0 means no limit
  249. step=8,
  250. )
  251. top_p = gr.Slider(
  252. label="Top-P", minimum=0, maximum=1, value=0.7, step=0.01
  253. )
  254. repetition_penalty = gr.Slider(
  255. label=i18n("Repetition Penalty"),
  256. minimum=0,
  257. maximum=2,
  258. value=1.5,
  259. step=0.01,
  260. )
  261. temperature = gr.Slider(
  262. label="Temperature",
  263. minimum=0,
  264. maximum=2,
  265. value=0.7,
  266. step=0.01,
  267. )
  268. speaker = gr.Textbox(
  269. label=i18n("Speaker"),
  270. placeholder=i18n("Type name of the speaker"),
  271. lines=1,
  272. )
  273. with gr.Tab(label=i18n("Reference Audio")):
  274. gr.Markdown(
  275. i18n(
  276. "5 to 10 seconds of reference audio, useful for specifying speaker."
  277. )
  278. )
  279. enable_reference_audio = gr.Checkbox(
  280. label=i18n("Enable Reference Audio"),
  281. )
  282. reference_audio = gr.Audio(
  283. label=i18n("Reference Audio"),
  284. type="filepath",
  285. )
  286. reference_text = gr.Textbox(
  287. label=i18n("Reference Text"),
  288. placeholder=i18n("Reference Text"),
  289. lines=1,
  290. value="在一无所知中,梦里的一天结束了,一个新的「轮回」便会开始。",
  291. )
  292. with gr.Column(scale=3):
  293. with gr.Row():
  294. error = gr.HTML(label=i18n("Error Message"))
  295. with gr.Row():
  296. audio = gr.Audio(label=i18n("Generated Audio"), type="numpy")
  297. with gr.Row():
  298. stream_audio = gr.Audio(
  299. label=i18n("Streaming Audio"),
  300. streaming=True,
  301. autoplay=True,
  302. interactive=False,
  303. )
  304. with gr.Row():
  305. with gr.Column(scale=3):
  306. generate = gr.Button(
  307. value="\U0001F3A7 " + i18n("Generate"), variant="primary"
  308. )
  309. generate_stream = gr.Button(
  310. value="\U0001F3A7 " + i18n("Streaming Generate"),
  311. variant="primary",
  312. )
  313. # # Submit
  314. generate.click(
  315. inference,
  316. [
  317. text,
  318. enable_reference_audio,
  319. reference_audio,
  320. reference_text,
  321. max_new_tokens,
  322. chunk_length,
  323. top_p,
  324. repetition_penalty,
  325. temperature,
  326. speaker,
  327. ],
  328. [audio, error],
  329. concurrency_limit=1,
  330. )
  331. generate_stream.click(
  332. inference_stream,
  333. [
  334. text,
  335. enable_reference_audio,
  336. reference_audio,
  337. reference_text,
  338. max_new_tokens,
  339. chunk_length,
  340. top_p,
  341. repetition_penalty,
  342. temperature,
  343. speaker,
  344. ],
  345. [stream_audio, error],
  346. concurrency_limit=10,
  347. )
  348. return app
  349. def parse_args():
  350. parser = ArgumentParser()
  351. parser.add_argument(
  352. "--llama-checkpoint-path",
  353. type=Path,
  354. default="checkpoints/text2semantic-sft-large-v1-4k.pth",
  355. )
  356. parser.add_argument(
  357. "--llama-config-name", type=str, default="dual_ar_2_codebook_large"
  358. )
  359. parser.add_argument(
  360. "--vqgan-checkpoint-path",
  361. type=Path,
  362. default="checkpoints/vq-gan-group-fsq-2x1024.pth",
  363. )
  364. parser.add_argument("--vqgan-config-name", type=str, default="vqgan_pretrain")
  365. parser.add_argument("--tokenizer", type=str, default="fishaudio/fish-speech-1")
  366. parser.add_argument("--device", type=str, default="cuda")
  367. parser.add_argument("--half", action="store_true")
  368. parser.add_argument("--max-length", type=int, default=2048)
  369. parser.add_argument("--compile", action="store_true")
  370. parser.add_argument("--max-gradio-length", type=int, default=0)
  371. return parser.parse_args()
  372. if __name__ == "__main__":
  373. args = parse_args()
  374. args.precision = torch.half if args.half else torch.bfloat16
  375. logger.info("Loading Llama model...")
  376. llama_queue = launch_thread_safe_queue(
  377. config_name=args.llama_config_name,
  378. checkpoint_path=args.llama_checkpoint_path,
  379. device=args.device,
  380. precision=args.precision,
  381. max_length=args.max_length,
  382. compile=args.compile,
  383. )
  384. llama_tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
  385. logger.info("Llama model loaded, loading VQ-GAN model...")
  386. vqgan_model = load_vqgan_model(
  387. config_name=args.vqgan_config_name,
  388. checkpoint_path=args.vqgan_checkpoint_path,
  389. device=args.device,
  390. )
  391. logger.info("VQ-GAN model loaded, warming up...")
  392. # Dry run to check if the model is loaded correctly and avoid the first-time latency
  393. inference(
  394. text="Hello, world!",
  395. enable_reference_audio=False,
  396. reference_audio=None,
  397. reference_text="",
  398. max_new_tokens=0,
  399. chunk_length=0,
  400. top_p=0.7,
  401. repetition_penalty=1.5,
  402. temperature=0.7,
  403. speaker=None,
  404. )
  405. logger.info("Warming up done, launching the web UI...")
  406. app = build_app()
  407. app.launch(show_api=False)