webui.py 13 KB

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