webui.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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
  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 fish_speech.text.chn_text_norm.text import Text as ChnNormedText
  20. from fish_speech.utils import autocast_exclude_mps, set_seed
  21. from tools.api import decode_vq_tokens, encode_reference
  22. from tools.file import AUDIO_EXTENSIONS, audio_to_bytes, list_files, read_ref_text
  23. from tools.llama.generate import (
  24. GenerateRequest,
  25. GenerateResponse,
  26. WrappedGenerateResponse,
  27. launch_thread_safe_queue,
  28. )
  29. from tools.schema import (
  30. GLOBAL_NUM_SAMPLES,
  31. ASRPackRequest,
  32. ServeASRRequest,
  33. ServeASRResponse,
  34. ServeASRSegment,
  35. ServeAudioPart,
  36. ServeForwardMessage,
  37. ServeMessage,
  38. ServeReferenceAudio,
  39. ServeRequest,
  40. ServeResponse,
  41. ServeStreamDelta,
  42. ServeStreamResponse,
  43. ServeTextPart,
  44. ServeTimedASRResponse,
  45. ServeTTSRequest,
  46. ServeVQGANDecodeRequest,
  47. ServeVQGANDecodeResponse,
  48. ServeVQGANEncodeRequest,
  49. ServeVQGANEncodeResponse,
  50. ServeVQPart,
  51. )
  52. from tools.vqgan.inference import load_model as load_decoder_model
  53. # Make einx happy
  54. os.environ["EINX_FILTER_TRACEBACK"] = "false"
  55. HEADER_MD = f"""# Fish Speech
  56. {i18n("A text-to-speech model based on VQ-GAN and Llama developed by [Fish Audio](https://fish.audio).")}
  57. {i18n("You can find the source code [here](https://github.com/fishaudio/fish-speech) and models [here](https://huggingface.co/fishaudio/fish-speech-1.5).")}
  58. {i18n("Related code and weights are released under CC BY-NC-SA 4.0 License.")}
  59. {i18n("We are not responsible for any misuse of the model, please consider your local laws and regulations before using it.")}
  60. """
  61. TEXTBOX_PLACEHOLDER = i18n("Put your text here.")
  62. SPACE_IMPORTED = False
  63. def build_html_error_message(error):
  64. return f"""
  65. <div style="color: red;
  66. font-weight: bold;">
  67. {html.escape(str(error))}
  68. </div>
  69. """
  70. @torch.inference_mode()
  71. def inference(req: ServeTTSRequest):
  72. idstr: str | None = req.reference_id
  73. prompt_tokens, prompt_texts = [], []
  74. if idstr is not None:
  75. ref_folder = Path("references") / idstr
  76. ref_folder.mkdir(parents=True, exist_ok=True)
  77. ref_audios = list_files(
  78. ref_folder, AUDIO_EXTENSIONS, recursive=True, sort=False
  79. )
  80. if req.use_memory_cache == "never" or (
  81. req.use_memory_cache == "on-demand" and len(prompt_tokens) == 0
  82. ):
  83. prompt_tokens = [
  84. encode_reference(
  85. decoder_model=decoder_model,
  86. reference_audio=audio_to_bytes(str(ref_audio)),
  87. enable_reference_audio=True,
  88. )
  89. for ref_audio in ref_audios
  90. ]
  91. prompt_texts = [
  92. read_ref_text(str(ref_audio.with_suffix(".lab")))
  93. for ref_audio in ref_audios
  94. ]
  95. else:
  96. logger.info("Use same references")
  97. else:
  98. # Parse reference audio aka prompt
  99. refs = req.references
  100. if req.use_memory_cache == "never" or (
  101. req.use_memory_cache == "on-demand" and len(prompt_tokens) == 0
  102. ):
  103. prompt_tokens = [
  104. encode_reference(
  105. decoder_model=decoder_model,
  106. reference_audio=ref.audio,
  107. enable_reference_audio=True,
  108. )
  109. for ref in refs
  110. ]
  111. prompt_texts = [ref.text for ref in refs]
  112. else:
  113. logger.info("Use same references")
  114. if req.seed is not None:
  115. set_seed(req.seed)
  116. logger.warning(f"set seed: {req.seed}")
  117. # LLAMA Inference
  118. request = dict(
  119. device=decoder_model.device,
  120. max_new_tokens=req.max_new_tokens,
  121. text=(
  122. req.text
  123. if not req.normalize
  124. else ChnNormedText(raw_text=req.text).normalize()
  125. ),
  126. top_p=req.top_p,
  127. repetition_penalty=req.repetition_penalty,
  128. temperature=req.temperature,
  129. compile=args.compile,
  130. iterative_prompt=req.chunk_length > 0,
  131. chunk_length=req.chunk_length,
  132. max_length=4096,
  133. prompt_tokens=prompt_tokens,
  134. prompt_text=prompt_texts,
  135. )
  136. response_queue = queue.Queue()
  137. llama_queue.put(
  138. GenerateRequest(
  139. request=request,
  140. response_queue=response_queue,
  141. )
  142. )
  143. segments = []
  144. while True:
  145. result: WrappedGenerateResponse = response_queue.get()
  146. if result.status == "error":
  147. yield None, None, build_html_error_message(result.response)
  148. break
  149. result: GenerateResponse = result.response
  150. if result.action == "next":
  151. break
  152. with autocast_exclude_mps(
  153. device_type=decoder_model.device.type, dtype=args.precision
  154. ):
  155. fake_audios = decode_vq_tokens(
  156. decoder_model=decoder_model,
  157. codes=result.codes,
  158. )
  159. fake_audios = fake_audios.float().cpu().numpy()
  160. segments.append(fake_audios)
  161. if len(segments) == 0:
  162. return (
  163. None,
  164. None,
  165. build_html_error_message(
  166. i18n("No audio generated, please check the input text.")
  167. ),
  168. )
  169. # No matter streaming or not, we need to return the final audio
  170. audio = np.concatenate(segments, axis=0)
  171. yield None, (decoder_model.spec_transform.sample_rate, audio), None
  172. if torch.cuda.is_available():
  173. torch.cuda.empty_cache()
  174. gc.collect()
  175. n_audios = 4
  176. global_audio_list = []
  177. global_error_list = []
  178. def inference_wrapper(
  179. text,
  180. enable_reference_audio,
  181. reference_audio,
  182. reference_text,
  183. max_new_tokens,
  184. chunk_length,
  185. top_p,
  186. repetition_penalty,
  187. temperature,
  188. seed,
  189. batch_infer_num,
  190. ):
  191. audios = []
  192. errors = []
  193. for _ in range(batch_infer_num):
  194. result = inference(
  195. text,
  196. enable_reference_audio,
  197. reference_audio,
  198. reference_text,
  199. max_new_tokens,
  200. chunk_length,
  201. top_p,
  202. repetition_penalty,
  203. temperature,
  204. seed,
  205. )
  206. _, audio_data, error_message = next(result)
  207. audios.append(
  208. gr.Audio(value=audio_data if audio_data else None, visible=True),
  209. )
  210. errors.append(
  211. gr.HTML(value=error_message if error_message else None, visible=True),
  212. )
  213. for _ in range(batch_infer_num, n_audios):
  214. audios.append(
  215. gr.Audio(value=None, visible=False),
  216. )
  217. errors.append(
  218. gr.HTML(value=None, visible=False),
  219. )
  220. return None, *audios, *errors
  221. def wav_chunk_header(sample_rate=44100, bit_depth=16, channels=1):
  222. buffer = io.BytesIO()
  223. with wave.open(buffer, "wb") as wav_file:
  224. wav_file.setnchannels(channels)
  225. wav_file.setsampwidth(bit_depth // 8)
  226. wav_file.setframerate(sample_rate)
  227. wav_header_bytes = buffer.getvalue()
  228. buffer.close()
  229. return wav_header_bytes
  230. def normalize_text(user_input, use_normalization):
  231. if use_normalization:
  232. return ChnNormedText(raw_text=user_input).normalize()
  233. else:
  234. return user_input
  235. def update_examples():
  236. examples_dir = Path("references")
  237. examples_dir.mkdir(parents=True, exist_ok=True)
  238. example_audios = list_files(examples_dir, AUDIO_EXTENSIONS, recursive=True)
  239. return gr.Dropdown(choices=example_audios + [""])
  240. def build_app():
  241. with gr.Blocks(theme=gr.themes.Base()) as app:
  242. gr.Markdown(HEADER_MD)
  243. # Use light theme by default
  244. app.load(
  245. None,
  246. None,
  247. js="() => {const params = new URLSearchParams(window.location.search);if (!params.has('__theme')) {params.set('__theme', '%s');window.location.search = params.toString();}}"
  248. % args.theme,
  249. )
  250. # Inference
  251. with gr.Row():
  252. with gr.Column(scale=3):
  253. text = gr.Textbox(
  254. label=i18n("Input Text"), placeholder=TEXTBOX_PLACEHOLDER, lines=10
  255. )
  256. refined_text = gr.Textbox(
  257. label=i18n("Realtime Transform Text"),
  258. placeholder=i18n(
  259. "Normalization Result Preview (Currently Only Chinese)"
  260. ),
  261. lines=5,
  262. interactive=False,
  263. )
  264. with gr.Row():
  265. normalize = gr.Checkbox(
  266. label=i18n("Text Normalization"),
  267. value=False,
  268. )
  269. with gr.Row():
  270. with gr.Column():
  271. with gr.Tab(label=i18n("Advanced Config")):
  272. with gr.Row():
  273. chunk_length = gr.Slider(
  274. label=i18n("Iterative Prompt Length, 0 means off"),
  275. minimum=0,
  276. maximum=300,
  277. value=200,
  278. step=8,
  279. )
  280. max_new_tokens = gr.Slider(
  281. label=i18n(
  282. "Maximum tokens per batch, 0 means no limit"
  283. ),
  284. minimum=0,
  285. maximum=2048,
  286. value=0,
  287. step=8,
  288. )
  289. with gr.Row():
  290. top_p = gr.Slider(
  291. label="Top-P",
  292. minimum=0.6,
  293. maximum=0.9,
  294. value=0.7,
  295. step=0.01,
  296. )
  297. repetition_penalty = gr.Slider(
  298. label=i18n("Repetition Penalty"),
  299. minimum=1,
  300. maximum=1.5,
  301. value=1.2,
  302. step=0.01,
  303. )
  304. with gr.Row():
  305. temperature = gr.Slider(
  306. label="Temperature",
  307. minimum=0.6,
  308. maximum=0.9,
  309. value=0.7,
  310. step=0.01,
  311. )
  312. seed = gr.Number(
  313. label="Seed",
  314. info="0 means randomized inference, otherwise deterministic",
  315. value=0,
  316. )
  317. with gr.Tab(label=i18n("Reference Audio")):
  318. with gr.Row():
  319. gr.Markdown(
  320. i18n(
  321. "5 to 10 seconds of reference audio, useful for specifying speaker."
  322. )
  323. )
  324. with gr.Row():
  325. reference_id = gr.Textbox(
  326. label=i18n("Reference ID"),
  327. placeholder="Leave empty to use uploaded references",
  328. )
  329. with gr.Row():
  330. use_memory_cache = gr.Radio(
  331. label=i18n("Use Memory Cache"),
  332. choices=["never", "on-demand", "always"],
  333. value="on-demand",
  334. )
  335. with gr.Row():
  336. reference_audio = gr.Audio(
  337. label=i18n("Reference Audio"),
  338. type="filepath",
  339. )
  340. with gr.Row():
  341. reference_text = gr.Textbox(
  342. label=i18n("Reference Text"),
  343. lines=1,
  344. placeholder="在一无所知中,梦里的一天结束了,一个新的「轮回」便会开始。",
  345. value="",
  346. )
  347. with gr.Column(scale=3):
  348. with gr.Row():
  349. error = gr.HTML(
  350. label=i18n("Error Message"),
  351. visible=True,
  352. )
  353. with gr.Row():
  354. audio = gr.Audio(
  355. label=i18n("Generated Audio"),
  356. type="numpy",
  357. interactive=False,
  358. visible=True,
  359. )
  360. with gr.Row():
  361. with gr.Column(scale=3):
  362. generate = gr.Button(
  363. value="\U0001F3A7 " + i18n("Generate"), variant="primary"
  364. )
  365. text.input(fn=normalize_text, inputs=[text, normalize], outputs=[refined_text])
  366. def inference_wrapper(
  367. text,
  368. normalize,
  369. reference_id,
  370. reference_audio,
  371. reference_text,
  372. max_new_tokens,
  373. chunk_length,
  374. top_p,
  375. repetition_penalty,
  376. temperature,
  377. seed,
  378. use_memory_cache,
  379. ):
  380. references = []
  381. if reference_audio:
  382. # 将文件路径转换为字节
  383. with open(reference_audio, "rb") as audio_file:
  384. audio_bytes = audio_file.read()
  385. references = [
  386. ServeReferenceAudio(audio=audio_bytes, text=reference_text)
  387. ]
  388. req = ServeTTSRequest(
  389. text=text,
  390. normalize=normalize,
  391. reference_id=reference_id if reference_id else None,
  392. references=references,
  393. max_new_tokens=max_new_tokens,
  394. chunk_length=chunk_length,
  395. top_p=top_p,
  396. repetition_penalty=repetition_penalty,
  397. temperature=temperature,
  398. seed=int(seed) if seed else None,
  399. use_memory_cache=use_memory_cache,
  400. )
  401. for result in inference(req):
  402. if result[2]: # Error message
  403. return None, result[2]
  404. elif result[1]: # Audio data
  405. return result[1], None
  406. return None, i18n("No audio generated")
  407. # Submit
  408. generate.click(
  409. inference_wrapper,
  410. [
  411. refined_text,
  412. normalize,
  413. reference_id,
  414. reference_audio,
  415. reference_text,
  416. max_new_tokens,
  417. chunk_length,
  418. top_p,
  419. repetition_penalty,
  420. temperature,
  421. seed,
  422. use_memory_cache,
  423. ],
  424. [audio, error],
  425. concurrency_limit=1,
  426. )
  427. return app
  428. def parse_args():
  429. parser = ArgumentParser()
  430. parser.add_argument(
  431. "--llama-checkpoint-path",
  432. type=Path,
  433. default="checkpoints/fish-speech-1.5",
  434. )
  435. parser.add_argument(
  436. "--decoder-checkpoint-path",
  437. type=Path,
  438. default="checkpoints/fish-speech-1.5/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
  439. )
  440. parser.add_argument("--decoder-config-name", type=str, default="firefly_gan_vq")
  441. parser.add_argument("--device", type=str, default="cuda")
  442. parser.add_argument("--half", action="store_true")
  443. parser.add_argument("--compile", action="store_true")
  444. parser.add_argument("--max-gradio-length", type=int, default=0)
  445. parser.add_argument("--theme", type=str, default="light")
  446. return parser.parse_args()
  447. if __name__ == "__main__":
  448. args = parse_args()
  449. args.precision = torch.half if args.half else torch.bfloat16
  450. # Check if CUDA is available
  451. if not torch.cuda.is_available():
  452. logger.info("CUDA is not available, running on CPU.")
  453. args.device = "cpu"
  454. logger.info("Loading Llama model...")
  455. llama_queue = launch_thread_safe_queue(
  456. checkpoint_path=args.llama_checkpoint_path,
  457. device=args.device,
  458. precision=args.precision,
  459. compile=args.compile,
  460. )
  461. logger.info("Llama model loaded, loading VQ-GAN model...")
  462. decoder_model = load_decoder_model(
  463. config_name=args.decoder_config_name,
  464. checkpoint_path=args.decoder_checkpoint_path,
  465. device=args.device,
  466. )
  467. logger.info("Decoder model loaded, warming up...")
  468. # Dry run to check if the model is loaded correctly and avoid the first-time latency
  469. list(
  470. inference(
  471. ServeTTSRequest(
  472. text="Hello world.",
  473. references=[],
  474. reference_id=None,
  475. max_new_tokens=0,
  476. chunk_length=200,
  477. top_p=0.7,
  478. repetition_penalty=1.5,
  479. temperature=0.7,
  480. emotion=None,
  481. format="wav",
  482. )
  483. )
  484. )
  485. logger.info("Warming up done, launching the web UI...")
  486. app = build_app()
  487. app.launch(show_api=True)