manage.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. from __future__ import annotations
  2. import os
  3. os.environ["USE_LIBUV"] = "0"
  4. import datetime
  5. import html
  6. import json
  7. import platform
  8. import shutil
  9. import signal
  10. import subprocess
  11. import sys
  12. from pathlib import Path
  13. import gradio as gr
  14. import psutil
  15. import yaml
  16. from loguru import logger
  17. from tqdm import tqdm
  18. PYTHON = os.path.join(os.environ.get("PYTHON_FOLDERPATH", ""), "python")
  19. sys.path.insert(0, "")
  20. print(sys.path)
  21. cur_work_dir = Path(os.getcwd()).resolve()
  22. print("You are in ", str(cur_work_dir))
  23. from fish_speech.i18n import i18n
  24. from fish_speech.webui.launch_utils import Seafoam, is_module_installed, versions_html
  25. config_path = cur_work_dir / "fish_speech" / "configs"
  26. vqgan_yml_path = config_path / "firefly_gan_vq.yaml"
  27. llama_yml_path = config_path / "text2semantic_finetune.yaml"
  28. env = os.environ.copy()
  29. env["no_proxy"] = "127.0.0.1, localhost, 0.0.0.0"
  30. seafoam = Seafoam()
  31. def build_html_error_message(error):
  32. return f"""
  33. <div style="color: red; font-weight: bold;">
  34. {html.escape(error)}
  35. </div>
  36. """
  37. def build_html_ok_message(msg):
  38. return f"""
  39. <div style="color: green; font-weight: bold;">
  40. {html.escape(msg)}
  41. </div>
  42. """
  43. def build_html_href(link, desc, msg):
  44. return f"""
  45. <span style="color: green; font-weight: bold; display: inline-block">
  46. {html.escape(msg)}
  47. <a href="{link}">{desc}</a>
  48. </span>
  49. """
  50. def load_data_in_raw(path):
  51. with open(path, "r", encoding="utf-8") as file:
  52. data = file.read()
  53. return str(data)
  54. def kill_proc_tree(pid, including_parent=True):
  55. try:
  56. parent = psutil.Process(pid)
  57. except psutil.NoSuchProcess:
  58. # Process already terminated
  59. return
  60. children = parent.children(recursive=True)
  61. for child in children:
  62. try:
  63. os.kill(child.pid, signal.SIGTERM) # or signal.SIGKILL
  64. except OSError:
  65. pass
  66. if including_parent:
  67. try:
  68. os.kill(parent.pid, signal.SIGTERM) # or signal.SIGKILL
  69. except OSError:
  70. pass
  71. system = platform.system()
  72. p_label = None
  73. p_infer = None
  74. p_tensorboard = None
  75. def kill_process(pid):
  76. if system == "Windows":
  77. cmd = "taskkill /t /f /pid %s" % pid
  78. # os.system(cmd)
  79. subprocess.run(cmd)
  80. else:
  81. kill_proc_tree(pid)
  82. def change_label(if_label):
  83. global p_label
  84. if if_label == True and p_label is None:
  85. url = "http://localhost:3000"
  86. remote_url = "https://text-labeler.pages.dev/"
  87. try:
  88. p_label = subprocess.Popen(
  89. [
  90. (
  91. "asr-label-linux-x64"
  92. if sys.platform == "linux"
  93. else "asr-label-win-x64.exe"
  94. )
  95. ]
  96. )
  97. except FileNotFoundError:
  98. logger.warning("asr-label execution not found!")
  99. yield build_html_href(
  100. link=remote_url,
  101. desc=i18n("Optional online ver"),
  102. msg=i18n("Opened labeler in browser"),
  103. )
  104. elif if_label == False and p_label is not None:
  105. kill_process(p_label.pid)
  106. p_label = None
  107. yield build_html_ok_message("Nothing")
  108. def clean_infer_cache():
  109. import tempfile
  110. temp_dir = Path(tempfile.gettempdir())
  111. gradio_dir = str(temp_dir / "gradio")
  112. try:
  113. shutil.rmtree(gradio_dir)
  114. logger.info(f"Deleted cached audios: {gradio_dir}")
  115. except PermissionError:
  116. logger.info(f"Permission denied: Unable to delete {gradio_dir}")
  117. except FileNotFoundError:
  118. logger.info(f"{gradio_dir} was not found")
  119. except Exception as e:
  120. logger.info(f"An error occurred: {e}")
  121. def change_infer(
  122. if_infer,
  123. host,
  124. port,
  125. infer_decoder_model,
  126. infer_decoder_config,
  127. infer_llama_model,
  128. infer_compile,
  129. ):
  130. global p_infer
  131. if if_infer == True and p_infer == None:
  132. env = os.environ.copy()
  133. env["GRADIO_SERVER_NAME"] = host
  134. env["GRADIO_SERVER_PORT"] = port
  135. # 启动第二个进程
  136. url = f"http://{host}:{port}"
  137. yield build_html_ok_message(
  138. i18n("Inferring interface is launched at {}").format(url)
  139. )
  140. clean_infer_cache()
  141. p_infer = subprocess.Popen(
  142. [
  143. PYTHON,
  144. "tools/webui.py",
  145. "--decoder-checkpoint-path",
  146. infer_decoder_model,
  147. "--decoder-config-name",
  148. infer_decoder_config,
  149. "--llama-checkpoint-path",
  150. infer_llama_model,
  151. ]
  152. + (["--compile"] if infer_compile == "Yes" else []),
  153. env=env,
  154. )
  155. elif if_infer == False and p_infer is not None:
  156. kill_process(p_infer.pid)
  157. p_infer = None
  158. yield build_html_error_message(i18n("Infer interface is closed"))
  159. js = load_data_in_raw("fish_speech/webui/js/animate.js")
  160. css = load_data_in_raw("fish_speech/webui/css/style.css")
  161. data_pre_output = (cur_work_dir / "data").resolve()
  162. default_model_output = (cur_work_dir / "results").resolve()
  163. default_filelist = data_pre_output / "detect.list"
  164. data_pre_output.mkdir(parents=True, exist_ok=True)
  165. items = []
  166. dict_items = {}
  167. def load_yaml_data_in_fact(yml_path):
  168. with open(yml_path, "r", encoding="utf-8") as file:
  169. yml = yaml.safe_load(file)
  170. return yml
  171. def write_yaml_data_in_fact(yml, yml_path):
  172. with open(yml_path, "w", encoding="utf-8") as file:
  173. yaml.safe_dump(yml, file, allow_unicode=True)
  174. return yml
  175. def generate_tree(directory, depth=0, max_depth=None, prefix=""):
  176. if max_depth is not None and depth > max_depth:
  177. return ""
  178. tree_str = ""
  179. files = []
  180. directories = []
  181. for item in os.listdir(directory):
  182. if os.path.isdir(os.path.join(directory, item)):
  183. directories.append(item)
  184. else:
  185. files.append(item)
  186. entries = directories + files
  187. for i, entry in enumerate(entries):
  188. connector = "├── " if i < len(entries) - 1 else "└── "
  189. tree_str += f"{prefix}{connector}{entry}<br />"
  190. if i < len(directories):
  191. extension = "│ " if i < len(entries) - 1 else " "
  192. tree_str += generate_tree(
  193. os.path.join(directory, entry),
  194. depth + 1,
  195. max_depth,
  196. prefix=prefix + extension,
  197. )
  198. return tree_str
  199. def new_explorer(data_path, max_depth):
  200. return gr.Markdown(
  201. elem_classes=["scrollable-component"],
  202. value=generate_tree(data_path, max_depth=max_depth),
  203. )
  204. def add_item(
  205. folder: str,
  206. method: str,
  207. label_lang: str,
  208. if_initial_prompt: bool,
  209. initial_prompt: str | None,
  210. ):
  211. folder = folder.strip(" ").strip('"')
  212. folder_path = Path(folder)
  213. if folder and folder not in items and data_pre_output not in folder_path.parents:
  214. if folder_path.is_dir():
  215. items.append(folder)
  216. dict_items[folder] = dict(
  217. type="folder",
  218. method=method,
  219. label_lang=label_lang,
  220. initial_prompt=initial_prompt if if_initial_prompt else None,
  221. )
  222. elif folder:
  223. err = folder
  224. return gr.Checkboxgroup(choices=items), build_html_error_message(
  225. i18n("Invalid path: {}").format(err)
  226. )
  227. formatted_data = json.dumps(dict_items, ensure_ascii=False, indent=4)
  228. logger.info("After Adding: " + formatted_data)
  229. gr.Info(formatted_data)
  230. return gr.Checkboxgroup(choices=items), build_html_ok_message(
  231. i18n("Added path successfully!")
  232. )
  233. def remove_items(selected_items):
  234. global items, dict_items
  235. to_remove = [item for item in items if item in selected_items]
  236. for item in to_remove:
  237. del dict_items[item]
  238. items = [item for item in items if item in dict_items.keys()]
  239. formatted_data = json.dumps(dict_items, ensure_ascii=False, indent=4)
  240. logger.info(formatted_data)
  241. gr.Warning("After Removing: " + formatted_data)
  242. return gr.Checkboxgroup(choices=items, value=[]), build_html_ok_message(
  243. i18n("Removed path successfully!")
  244. )
  245. def show_selected(options):
  246. selected_options = ", ".join(options)
  247. if options:
  248. return i18n("Selected: {}").format(selected_options)
  249. else:
  250. return i18n("No selected options")
  251. from pydub import AudioSegment
  252. def convert_to_mono_in_place(audio_path: Path):
  253. audio = AudioSegment.from_file(audio_path)
  254. if audio.channels > 1:
  255. mono_audio = audio.set_channels(1)
  256. mono_audio.export(audio_path, format=audio_path.suffix[1:])
  257. logger.info(f"Convert {audio_path} successfully")
  258. def list_copy(list_file_path, method):
  259. wav_root = data_pre_output
  260. lst = []
  261. with list_file_path.open("r", encoding="utf-8") as file:
  262. for line in tqdm(file, desc="Processing audio/transcript"):
  263. wav_path, speaker_name, language, text = line.strip().split("|")
  264. original_wav_path = Path(wav_path)
  265. target_wav_path = (
  266. wav_root / original_wav_path.parent.name / original_wav_path.name
  267. )
  268. lst.append(f"{target_wav_path}|{speaker_name}|{language}|{text}")
  269. if target_wav_path.is_file():
  270. continue
  271. target_wav_path.parent.mkdir(parents=True, exist_ok=True)
  272. if method == i18n("Copy"):
  273. shutil.copy(original_wav_path, target_wav_path)
  274. else:
  275. shutil.move(original_wav_path, target_wav_path.parent)
  276. convert_to_mono_in_place(target_wav_path)
  277. original_lab_path = original_wav_path.with_suffix(".lab")
  278. target_lab_path = (
  279. wav_root
  280. / original_wav_path.parent.name
  281. / original_wav_path.with_suffix(".lab").name
  282. )
  283. if target_lab_path.is_file():
  284. continue
  285. if method == i18n("Copy"):
  286. shutil.copy(original_lab_path, target_lab_path)
  287. else:
  288. shutil.move(original_lab_path, target_lab_path.parent)
  289. if method == i18n("Move"):
  290. with list_file_path.open("w", encoding="utf-8") as file:
  291. file.writelines("\n".join(lst))
  292. del lst
  293. return build_html_ok_message(i18n("Use filelist"))
  294. def check_files(data_path: str, max_depth: int, label_model: str, label_device: str):
  295. global dict_items
  296. data_path = Path(data_path)
  297. gr.Warning("Pre-processing begins...")
  298. for item, content in dict_items.items():
  299. item_path = Path(item)
  300. tar_path = data_path / item_path.name
  301. if content["type"] == "folder" and item_path.is_dir():
  302. if content["method"] == i18n("Copy"):
  303. os.makedirs(tar_path, exist_ok=True)
  304. shutil.copytree(
  305. src=str(item_path), dst=str(tar_path), dirs_exist_ok=True
  306. )
  307. elif not tar_path.is_dir():
  308. shutil.move(src=str(item_path), dst=str(tar_path))
  309. for suf in ["wav", "flac", "mp3"]:
  310. for audio_path in tar_path.glob(f"**/*.{suf}"):
  311. convert_to_mono_in_place(audio_path)
  312. cur_lang = content["label_lang"]
  313. initial_prompt = content["initial_prompt"]
  314. transcribe_cmd = [
  315. PYTHON,
  316. "tools/whisper_asr.py",
  317. "--model-size",
  318. label_model,
  319. "--device",
  320. label_device,
  321. "--audio-dir",
  322. tar_path,
  323. "--save-dir",
  324. tar_path,
  325. "--language",
  326. cur_lang,
  327. ]
  328. if initial_prompt is not None:
  329. transcribe_cmd += ["--initial-prompt", initial_prompt]
  330. if cur_lang != "IGNORE":
  331. try:
  332. gr.Warning("Begin To Transcribe")
  333. subprocess.run(
  334. transcribe_cmd,
  335. env=env,
  336. )
  337. except Exception:
  338. print("Transcription error occurred")
  339. elif content["type"] == "file" and item_path.is_file():
  340. list_copy(item_path, content["method"])
  341. return build_html_ok_message(i18n("Move files successfully")), new_explorer(
  342. data_path, max_depth=max_depth
  343. )
  344. def generate_folder_name():
  345. now = datetime.datetime.now()
  346. folder_name = now.strftime("%Y%m%d_%H%M%S")
  347. return folder_name
  348. def train_process(
  349. data_path: str,
  350. option: str,
  351. # llama config
  352. llama_ckpt,
  353. llama_base_config,
  354. llama_lr,
  355. llama_maxsteps,
  356. llama_data_num_workers,
  357. llama_data_batch_size,
  358. llama_data_max_length,
  359. llama_precision,
  360. llama_check_interval,
  361. llama_grad_batches,
  362. llama_use_speaker,
  363. llama_use_lora,
  364. ):
  365. backend = "nccl" if sys.platform == "linux" else "gloo"
  366. new_project = generate_folder_name()
  367. print("New Project Name: ", new_project)
  368. if option == "VQGAN":
  369. msg = "Skipped VQGAN Training."
  370. gr.Warning(msg)
  371. logger.info(msg)
  372. if option == "LLAMA":
  373. msg = "LLAMA Training begins..."
  374. gr.Warning(msg)
  375. logger.info(msg)
  376. subprocess.run(
  377. [
  378. PYTHON,
  379. "tools/vqgan/extract_vq.py",
  380. str(data_pre_output),
  381. "--num-workers",
  382. "1",
  383. "--batch-size",
  384. "16",
  385. "--config-name",
  386. "firefly_gan_vq",
  387. "--checkpoint-path",
  388. "checkpoints/fish-speech-1.4/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
  389. ]
  390. )
  391. subprocess.run(
  392. [
  393. PYTHON,
  394. "tools/llama/build_dataset.py",
  395. "--input",
  396. str(data_pre_output),
  397. "--text-extension",
  398. ".lab",
  399. "--num-workers",
  400. "16",
  401. ]
  402. )
  403. ckpt_path = "checkpoints/fish-speech-1.4/model.pth"
  404. lora_prefix = "lora_" if llama_use_lora else ""
  405. llama_name = lora_prefix + "text2semantic_" + new_project
  406. latest = next(
  407. iter(
  408. sorted(
  409. [
  410. str(p.relative_to("results"))
  411. for p in Path("results").glob(lora_prefix + "text2sem*/")
  412. ],
  413. reverse=True,
  414. )
  415. ),
  416. llama_name,
  417. )
  418. project = (
  419. llama_name
  420. if llama_ckpt == i18n("new")
  421. else (
  422. latest
  423. if llama_ckpt == i18n("latest")
  424. else Path(llama_ckpt).relative_to("results")
  425. )
  426. )
  427. logger.info(project)
  428. if llama_check_interval > llama_maxsteps:
  429. llama_check_interval = llama_maxsteps
  430. train_cmd = [
  431. PYTHON,
  432. "fish_speech/train.py",
  433. "--config-name",
  434. "text2semantic_finetune",
  435. f"project={project}",
  436. f"trainer.strategy.process_group_backend={backend}",
  437. f"train_dataset.proto_files={str(['data/quantized-dataset-ft'])}",
  438. f"val_dataset.proto_files={str(['data/quantized-dataset-ft'])}",
  439. f"model.optimizer.lr={llama_lr}",
  440. f"trainer.max_steps={llama_maxsteps}",
  441. f"data.num_workers={llama_data_num_workers}",
  442. f"data.batch_size={llama_data_batch_size}",
  443. f"max_length={llama_data_max_length}",
  444. f"trainer.precision={llama_precision}",
  445. f"trainer.val_check_interval={llama_check_interval}",
  446. f"trainer.accumulate_grad_batches={llama_grad_batches}",
  447. f"train_dataset.interactive_prob={llama_use_speaker}",
  448. ] + ([f"+lora@model.model.lora_config=r_8_alpha_16"] if llama_use_lora else [])
  449. logger.info(train_cmd)
  450. subprocess.run(train_cmd)
  451. return build_html_ok_message(i18n("Training stopped"))
  452. def tensorboard_process(
  453. if_tensorboard: bool,
  454. tensorboard_dir: str,
  455. host: str,
  456. port: str,
  457. ):
  458. global p_tensorboard
  459. if if_tensorboard == True and p_tensorboard == None:
  460. url = f"http://{host}:{port}"
  461. yield build_html_ok_message(
  462. i18n("Tensorboard interface is launched at {}").format(url)
  463. )
  464. prefix = ["tensorboard"]
  465. if Path("fishenv").exists():
  466. prefix = ["fishenv/env/python.exe", "fishenv/env/Scripts/tensorboard.exe"]
  467. p_tensorboard = subprocess.Popen(
  468. prefix
  469. + [
  470. "--logdir",
  471. tensorboard_dir,
  472. "--host",
  473. host,
  474. "--port",
  475. port,
  476. "--reload_interval",
  477. "120",
  478. ]
  479. )
  480. elif if_tensorboard == False and p_tensorboard != None:
  481. kill_process(p_tensorboard.pid)
  482. p_tensorboard = None
  483. yield build_html_error_message(i18n("Tensorboard interface is closed"))
  484. def fresh_tb_dir():
  485. return gr.Dropdown(
  486. choices=[str(p) for p in Path("results").glob("**/tensorboard/")]
  487. )
  488. def list_decoder_models():
  489. paths = [str(p) for p in Path("checkpoints").glob("fish*/firefly*.pth")]
  490. if not paths:
  491. logger.warning("No decoder model found")
  492. return paths
  493. def list_llama_models():
  494. choices = [str(p.parent) for p in Path("checkpoints").glob("merged*/*model*.pth")]
  495. choices += [str(p.parent) for p in Path("checkpoints").glob("fish*/*model*.pth")]
  496. choices += [str(p.parent) for p in Path("checkpoints").glob("fs*/*model*.pth")]
  497. choices = sorted(choices, reverse=True)
  498. if not choices:
  499. logger.warning("No LLaMA model found")
  500. return choices
  501. def list_lora_llama_models():
  502. choices = sorted(
  503. [str(p) for p in Path("results").glob("lora*/**/*.ckpt")], reverse=True
  504. )
  505. if not choices:
  506. logger.warning("No LoRA LLaMA model found")
  507. return choices
  508. def fresh_decoder_model():
  509. return gr.Dropdown(choices=list_decoder_models())
  510. def fresh_llama_ckpt(llama_use_lora):
  511. return gr.Dropdown(
  512. choices=[i18n("latest"), i18n("new")]
  513. + (
  514. [str(p) for p in Path("results").glob("text2sem*/")]
  515. if not llama_use_lora
  516. else [str(p) for p in Path("results").glob("lora_*/")]
  517. )
  518. )
  519. def fresh_llama_model():
  520. return gr.Dropdown(choices=list_llama_models())
  521. def llama_lora_merge(llama_weight, lora_llama_config, lora_weight, llama_lora_output):
  522. if (
  523. lora_weight is None
  524. or not Path(lora_weight).exists()
  525. or not Path(llama_weight).exists()
  526. ):
  527. return build_html_error_message(
  528. i18n(
  529. "Path error, please check the model file exists in the corresponding path"
  530. )
  531. )
  532. gr.Warning("Merging begins...")
  533. merge_cmd = [
  534. PYTHON,
  535. "tools/llama/merge_lora.py",
  536. "--lora-config",
  537. "r_8_alpha_16",
  538. "--lora-weight",
  539. lora_weight,
  540. "--output",
  541. llama_lora_output + "_" + generate_folder_name(),
  542. ]
  543. logger.info(merge_cmd)
  544. subprocess.run(merge_cmd)
  545. return build_html_ok_message(i18n("Merge successfully"))
  546. def llama_quantify(llama_weight, quantify_mode):
  547. if llama_weight is None or not Path(llama_weight).exists():
  548. return build_html_error_message(
  549. i18n(
  550. "Path error, please check the model file exists in the corresponding path"
  551. )
  552. )
  553. gr.Warning("Quantifying begins...")
  554. now = generate_folder_name()
  555. quantify_cmd = [
  556. PYTHON,
  557. "tools/llama/quantize.py",
  558. "--checkpoint-path",
  559. llama_weight,
  560. "--mode",
  561. quantify_mode,
  562. "--timestamp",
  563. now,
  564. ]
  565. logger.info(quantify_cmd)
  566. subprocess.run(quantify_cmd)
  567. if quantify_mode == "int8":
  568. quantize_path = str(
  569. Path(os.getcwd()) / "checkpoints" / f"fs-1.2-{quantify_mode}-{now}"
  570. )
  571. else:
  572. quantize_path = str(
  573. Path(os.getcwd()) / "checkpoints" / f"fs-1.2-{quantify_mode}-g128-{now}"
  574. )
  575. return build_html_ok_message(
  576. i18n("Quantify successfully") + f"Path: {quantize_path}"
  577. )
  578. init_vqgan_yml = load_yaml_data_in_fact(vqgan_yml_path)
  579. init_llama_yml = load_yaml_data_in_fact(llama_yml_path)
  580. with gr.Blocks(
  581. head="<style>\n" + css + "\n</style>",
  582. js=js,
  583. theme=seafoam,
  584. analytics_enabled=False,
  585. title="Fish Speech",
  586. ) as demo:
  587. with gr.Row():
  588. with gr.Column():
  589. with gr.Tab("\U0001F4D6 " + i18n("Data Preprocessing")):
  590. with gr.Row():
  591. textbox = gr.Textbox(
  592. label="\U0000270F "
  593. + i18n("Input Audio & Source Path for Transcription"),
  594. info=i18n("Speaker is identified by the folder name"),
  595. interactive=True,
  596. )
  597. with gr.Row(equal_height=False):
  598. with gr.Column():
  599. output_radio = gr.Radio(
  600. label="\U0001F4C1 "
  601. + i18n("Select source file processing method"),
  602. choices=[i18n("Copy"), i18n("Move")],
  603. value=i18n("Copy"),
  604. interactive=True,
  605. )
  606. with gr.Column():
  607. error = gr.HTML(label=i18n("Error Message"))
  608. if_label = gr.Checkbox(
  609. label=i18n("Open Labeler WebUI"), scale=0, show_label=True
  610. )
  611. with gr.Row():
  612. label_device = gr.Dropdown(
  613. label=i18n("Labeling Device"),
  614. info=i18n(
  615. "It is recommended to use CUDA, if you have low configuration, use CPU"
  616. ),
  617. choices=["cpu", "cuda"],
  618. value="cuda",
  619. interactive=True,
  620. )
  621. label_model = gr.Dropdown(
  622. label=i18n("Whisper Model"),
  623. info=i18n("Faster Whisper, Up to 5g GPU memory usage"),
  624. choices=["large-v3", "medium"],
  625. value="large-v3",
  626. interactive=True,
  627. )
  628. label_radio = gr.Dropdown(
  629. label=i18n("Optional Label Language"),
  630. info=i18n(
  631. "If there is no corresponding text for the audio, apply ASR for assistance, support .txt or .lab format"
  632. ),
  633. choices=[
  634. (i18n("Chinese"), "zh"),
  635. (i18n("English"), "en"),
  636. (i18n("Japanese"), "ja"),
  637. (i18n("Disabled"), "IGNORE"),
  638. (i18n("auto"), "auto"),
  639. ],
  640. value="IGNORE",
  641. interactive=True,
  642. )
  643. with gr.Row():
  644. if_initial_prompt = gr.Checkbox(
  645. value=False,
  646. label=i18n("Enable Initial Prompt"),
  647. min_width=120,
  648. scale=0,
  649. )
  650. initial_prompt = gr.Textbox(
  651. label=i18n("Initial Prompt"),
  652. info=i18n(
  653. "Initial prompt can provide contextual or vocabulary-specific guidance to the model."
  654. ),
  655. placeholder="This audio introduces the basic concepts and applications of artificial intelligence and machine learning.",
  656. interactive=False,
  657. )
  658. with gr.Row():
  659. add_button = gr.Button(
  660. "\U000027A1 " + i18n("Add to Processing Area"),
  661. variant="primary",
  662. )
  663. remove_button = gr.Button(
  664. "\U000026D4 " + i18n("Remove Selected Data")
  665. )
  666. with gr.Tab("\U0001F6E0 " + i18n("Training Configuration")):
  667. with gr.Row():
  668. model_type_radio = gr.Radio(
  669. label=i18n(
  670. "Select the model to be trained (Depending on the Tab page you are on)"
  671. ),
  672. interactive=False,
  673. choices=["VQGAN", "LLAMA"],
  674. value="VQGAN",
  675. )
  676. with gr.Row():
  677. with gr.Tabs():
  678. with gr.Tab(label=i18n("VQGAN Configuration")) as vqgan_page:
  679. gr.HTML("You don't need to train this model!")
  680. with gr.Tab(label=i18n("LLAMA Configuration")) as llama_page:
  681. with gr.Row(equal_height=False):
  682. llama_use_lora = gr.Checkbox(
  683. label=i18n("Use LoRA"),
  684. info=i18n(
  685. "Use LoRA can save GPU memory, but may reduce the quality of the model"
  686. ),
  687. value=True,
  688. interactive=True,
  689. )
  690. llama_ckpt = gr.Dropdown(
  691. label=i18n("Select LLAMA ckpt"),
  692. choices=[i18n("latest"), i18n("new")]
  693. + [
  694. str(p)
  695. for p in Path("results").glob("text2sem*/")
  696. ]
  697. + [str(p) for p in Path("results").glob("lora*/")],
  698. value=i18n("latest"),
  699. interactive=True,
  700. )
  701. with gr.Row(equal_height=False):
  702. llama_lr_slider = gr.Slider(
  703. label=i18n("Initial Learning Rate"),
  704. info=i18n(
  705. "lr smaller -> usually train slower but more stable"
  706. ),
  707. interactive=True,
  708. minimum=1e-5,
  709. maximum=1e-4,
  710. step=1e-5,
  711. value=5e-5,
  712. )
  713. llama_maxsteps_slider = gr.Slider(
  714. label=i18n("Maximum Training Steps"),
  715. info=i18n(
  716. "recommend: max_steps = num_audios // batch_size * (2 to 5)"
  717. ),
  718. interactive=True,
  719. minimum=1,
  720. maximum=10000,
  721. step=1,
  722. value=50,
  723. )
  724. with gr.Row(equal_height=False):
  725. llama_base_config = gr.Dropdown(
  726. label=i18n("Model Size"),
  727. choices=[
  728. "text2semantic_finetune",
  729. ],
  730. value="text2semantic_finetune",
  731. )
  732. llama_data_num_workers_slider = gr.Slider(
  733. label=i18n("Number of Workers"),
  734. minimum=1,
  735. maximum=32,
  736. step=1,
  737. value=4,
  738. )
  739. with gr.Row(equal_height=False):
  740. llama_data_batch_size_slider = gr.Slider(
  741. label=i18n("Batch Size"),
  742. interactive=True,
  743. minimum=1,
  744. maximum=32,
  745. step=1,
  746. value=2,
  747. )
  748. llama_data_max_length_slider = gr.Slider(
  749. label=i18n("Maximum Length per Sample"),
  750. interactive=True,
  751. minimum=1024,
  752. maximum=4096,
  753. step=128,
  754. value=2048,
  755. )
  756. with gr.Row(equal_height=False):
  757. llama_precision_dropdown = gr.Dropdown(
  758. label=i18n("Precision"),
  759. info=i18n(
  760. "bf16-true is recommended for 30+ series GPU, 16-mixed is recommended for 10+ series GPU"
  761. ),
  762. interactive=True,
  763. choices=["32", "bf16-true", "16-mixed"],
  764. value="bf16-true",
  765. )
  766. llama_check_interval_slider = gr.Slider(
  767. label=i18n("Save model every n steps"),
  768. info=i18n(
  769. "make sure that it's not greater than max_steps"
  770. ),
  771. interactive=True,
  772. minimum=1,
  773. maximum=1000,
  774. step=1,
  775. value=50,
  776. )
  777. with gr.Row(equal_height=False):
  778. llama_grad_batches = gr.Slider(
  779. label=i18n("Accumulate Gradient Batches"),
  780. interactive=True,
  781. minimum=1,
  782. maximum=20,
  783. step=1,
  784. value=init_llama_yml["trainer"][
  785. "accumulate_grad_batches"
  786. ],
  787. )
  788. llama_use_speaker = gr.Slider(
  789. label=i18n(
  790. "Probability of applying Speaker Condition"
  791. ),
  792. interactive=True,
  793. minimum=0.1,
  794. maximum=1.0,
  795. step=0.05,
  796. value=init_llama_yml["train_dataset"][
  797. "interactive_prob"
  798. ],
  799. )
  800. with gr.Tab(label=i18n("Merge LoRA"), id=4):
  801. with gr.Row(equal_height=False):
  802. llama_weight = gr.Dropdown(
  803. label=i18n("Base LLAMA Model"),
  804. info=i18n(
  805. "Type the path or select from the dropdown"
  806. ),
  807. choices=[
  808. "checkpoints/fish-speech-1.4/model.pth",
  809. ],
  810. value="checkpoints/fish-speech-1.4/model.pth",
  811. allow_custom_value=True,
  812. interactive=True,
  813. )
  814. with gr.Row(equal_height=False):
  815. lora_weight = gr.Dropdown(
  816. label=i18n("LoRA Model to be merged"),
  817. info=i18n(
  818. "Type the path or select from the dropdown"
  819. ),
  820. choices=[
  821. str(p)
  822. for p in Path("results").glob("lora*/**/*.ckpt")
  823. ],
  824. allow_custom_value=True,
  825. interactive=True,
  826. )
  827. lora_llama_config = gr.Dropdown(
  828. label=i18n("LLAMA Model Config"),
  829. info=i18n(
  830. "Type the path or select from the dropdown"
  831. ),
  832. choices=[
  833. "text2semantic_finetune",
  834. ],
  835. value="text2semantic_finetune",
  836. allow_custom_value=True,
  837. )
  838. with gr.Row(equal_height=False):
  839. llama_lora_output = gr.Dropdown(
  840. label=i18n("Output Path"),
  841. info=i18n(
  842. "Type the path or select from the dropdown"
  843. ),
  844. value="checkpoints/merged",
  845. choices=["checkpoints/merged"],
  846. allow_custom_value=True,
  847. interactive=True,
  848. )
  849. with gr.Row(equal_height=False):
  850. llama_lora_merge_btn = gr.Button(
  851. value=i18n("Merge"), variant="primary"
  852. )
  853. with gr.Tab(label=i18n("Model Quantization"), id=5):
  854. with gr.Row(equal_height=False):
  855. llama_weight_to_quantify = gr.Dropdown(
  856. label=i18n("Base LLAMA Model"),
  857. info=i18n(
  858. "Type the path or select from the dropdown"
  859. ),
  860. choices=list_llama_models(),
  861. value="checkpoints/fish-speech-1.4",
  862. allow_custom_value=True,
  863. interactive=True,
  864. )
  865. quantify_mode = gr.Dropdown(
  866. label=i18n("Post-quantification Precision"),
  867. info=i18n(
  868. "The lower the quantitative precision, the more the effectiveness may decrease, but the greater the efficiency will increase"
  869. ),
  870. choices=["int8", "int4"],
  871. value="int8",
  872. allow_custom_value=False,
  873. interactive=True,
  874. )
  875. with gr.Row(equal_height=False):
  876. llama_quantify_btn = gr.Button(
  877. value=i18n("Quantify"), variant="primary"
  878. )
  879. with gr.Tab(label="Tensorboard", id=6):
  880. with gr.Row(equal_height=False):
  881. tb_host = gr.Textbox(
  882. label=i18n("Tensorboard Host"), value="127.0.0.1"
  883. )
  884. tb_port = gr.Textbox(
  885. label=i18n("Tensorboard Port"), value="11451"
  886. )
  887. with gr.Row(equal_height=False):
  888. tb_dir = gr.Dropdown(
  889. label=i18n("Tensorboard Log Path"),
  890. allow_custom_value=True,
  891. choices=[
  892. str(p)
  893. for p in Path("results").glob("**/tensorboard/")
  894. ],
  895. )
  896. with gr.Row(equal_height=False):
  897. if_tb = gr.Checkbox(
  898. label=i18n("Open Tensorboard"),
  899. )
  900. with gr.Tab("\U0001F9E0 " + i18n("Inference Configuration")):
  901. with gr.Column():
  902. with gr.Row():
  903. with gr.Accordion(
  904. label="\U0001F5A5 "
  905. + i18n("Inference Server Configuration"),
  906. open=False,
  907. ):
  908. with gr.Row():
  909. infer_host_textbox = gr.Textbox(
  910. label=i18n("WebUI Host"), value="127.0.0.1"
  911. )
  912. infer_port_textbox = gr.Textbox(
  913. label=i18n("WebUI Port"), value="7862"
  914. )
  915. with gr.Row():
  916. infer_decoder_model = gr.Dropdown(
  917. label=i18n("Decoder Model Path"),
  918. info=i18n(
  919. "Type the path or select from the dropdown"
  920. ),
  921. choices=list_decoder_models(),
  922. value="checkpoints/fish-speech-1.4/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
  923. allow_custom_value=True,
  924. )
  925. infer_decoder_config = gr.Dropdown(
  926. label=i18n("Decoder Model Config"),
  927. info=i18n("Changing with the Model Path"),
  928. value="firefly_gan_vq",
  929. choices=[
  930. "firefly_gan_vq",
  931. ],
  932. allow_custom_value=True,
  933. )
  934. with gr.Row():
  935. infer_llama_model = gr.Dropdown(
  936. label=i18n("LLAMA Model Path"),
  937. info=i18n(
  938. "Type the path or select from the dropdown"
  939. ),
  940. value="checkpoints/fish-speech-1.4",
  941. choices=list_llama_models(),
  942. allow_custom_value=True,
  943. )
  944. with gr.Row():
  945. infer_compile = gr.Radio(
  946. label=i18n("Compile Model"),
  947. info=i18n(
  948. "Compile the model can significantly reduce the inference time, but will increase cold start time"
  949. ),
  950. choices=["Yes", "No"],
  951. value=(
  952. "Yes" if (sys.platform == "linux") else "No"
  953. ),
  954. interactive=is_module_installed("triton"),
  955. )
  956. with gr.Row():
  957. infer_checkbox = gr.Checkbox(
  958. label=i18n("Open Inference Server")
  959. )
  960. infer_error = gr.HTML(label=i18n("Inference Server Error"))
  961. with gr.Column():
  962. train_error = gr.HTML(label=i18n("Training Error"))
  963. checkbox_group = gr.CheckboxGroup(
  964. label="\U0001F4CA " + i18n("Data Source"),
  965. info=i18n(
  966. "The path of the input folder on the left or the filelist. Whether checked or not, it will be used for subsequent training in this list."
  967. ),
  968. elem_classes=["data_src"],
  969. )
  970. train_box = gr.Textbox(
  971. label=i18n("Data Preprocessing Path"),
  972. value=str(data_pre_output),
  973. interactive=False,
  974. )
  975. model_box = gr.Textbox(
  976. label="\U0001F4BE " + i18n("Model Output Path"),
  977. value=str(default_model_output),
  978. interactive=False,
  979. )
  980. with gr.Accordion(
  981. i18n(
  982. "View the status of the preprocessing folder (use the slider to control the depth of the tree)"
  983. ),
  984. elem_classes=["scrollable-component"],
  985. elem_id="file_accordion",
  986. ):
  987. tree_slider = gr.Slider(
  988. minimum=0,
  989. maximum=3,
  990. value=0,
  991. step=1,
  992. show_label=False,
  993. container=False,
  994. )
  995. file_markdown = new_explorer(str(data_pre_output), 0)
  996. with gr.Row(equal_height=False):
  997. admit_btn = gr.Button(
  998. "\U00002705 " + i18n("File Preprocessing"),
  999. variant="primary",
  1000. )
  1001. fresh_btn = gr.Button("\U0001F503", scale=0, min_width=80)
  1002. help_button = gr.Button("\U00002753", scale=0, min_width=80) # question
  1003. train_btn = gr.Button(i18n("Start Training"), variant="primary")
  1004. footer = load_data_in_raw("fish_speech/webui/html/footer.html")
  1005. footer = footer.format(
  1006. versions=versions_html(),
  1007. api_docs="https://speech.fish.audio/inference/#http-api",
  1008. )
  1009. gr.HTML(footer, elem_id="footer")
  1010. vqgan_page.select(lambda: "VQGAN", None, model_type_radio)
  1011. llama_page.select(lambda: "LLAMA", None, model_type_radio)
  1012. add_button.click(
  1013. fn=add_item,
  1014. inputs=[textbox, output_radio, label_radio, if_initial_prompt, initial_prompt],
  1015. outputs=[checkbox_group, error],
  1016. )
  1017. remove_button.click(
  1018. fn=remove_items, inputs=[checkbox_group], outputs=[checkbox_group, error]
  1019. )
  1020. checkbox_group.change(fn=show_selected, inputs=checkbox_group, outputs=[error])
  1021. help_button.click(
  1022. fn=None,
  1023. js='() => { window.open("https://speech.fish.audio/", "newwindow", "height=100, width=400, '
  1024. 'toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")}',
  1025. )
  1026. if_label.change(fn=change_label, inputs=[if_label], outputs=[error])
  1027. if_initial_prompt.change(
  1028. fn=lambda x: gr.Textbox(value="", interactive=x),
  1029. inputs=[if_initial_prompt],
  1030. outputs=[initial_prompt],
  1031. )
  1032. train_btn.click(
  1033. fn=train_process,
  1034. inputs=[
  1035. train_box,
  1036. model_type_radio,
  1037. # llama config
  1038. llama_ckpt,
  1039. llama_base_config,
  1040. llama_lr_slider,
  1041. llama_maxsteps_slider,
  1042. llama_data_num_workers_slider,
  1043. llama_data_batch_size_slider,
  1044. llama_data_max_length_slider,
  1045. llama_precision_dropdown,
  1046. llama_check_interval_slider,
  1047. llama_grad_batches,
  1048. llama_use_speaker,
  1049. llama_use_lora,
  1050. ],
  1051. outputs=[train_error],
  1052. )
  1053. if_tb.change(
  1054. fn=tensorboard_process,
  1055. inputs=[if_tb, tb_dir, tb_host, tb_port],
  1056. outputs=[train_error],
  1057. )
  1058. tb_dir.change(fn=fresh_tb_dir, inputs=[], outputs=[tb_dir])
  1059. infer_decoder_model.change(
  1060. fn=fresh_decoder_model, inputs=[], outputs=[infer_decoder_model]
  1061. )
  1062. infer_llama_model.change(
  1063. fn=fresh_llama_model, inputs=[], outputs=[infer_llama_model]
  1064. )
  1065. llama_weight.change(fn=fresh_llama_model, inputs=[], outputs=[llama_weight])
  1066. admit_btn.click(
  1067. fn=check_files,
  1068. inputs=[train_box, tree_slider, label_model, label_device],
  1069. outputs=[error, file_markdown],
  1070. )
  1071. fresh_btn.click(
  1072. fn=new_explorer, inputs=[train_box, tree_slider], outputs=[file_markdown]
  1073. )
  1074. llama_use_lora.change(
  1075. fn=fresh_llama_ckpt, inputs=[llama_use_lora], outputs=[llama_ckpt]
  1076. )
  1077. llama_ckpt.change(
  1078. fn=fresh_llama_ckpt, inputs=[llama_use_lora], outputs=[llama_ckpt]
  1079. )
  1080. lora_weight.change(
  1081. fn=lambda: gr.Dropdown(choices=list_lora_llama_models()),
  1082. inputs=[],
  1083. outputs=[lora_weight],
  1084. )
  1085. llama_lora_merge_btn.click(
  1086. fn=llama_lora_merge,
  1087. inputs=[llama_weight, lora_llama_config, lora_weight, llama_lora_output],
  1088. outputs=[train_error],
  1089. )
  1090. llama_quantify_btn.click(
  1091. fn=llama_quantify,
  1092. inputs=[llama_weight_to_quantify, quantify_mode],
  1093. outputs=[train_error],
  1094. )
  1095. infer_checkbox.change(
  1096. fn=change_infer,
  1097. inputs=[
  1098. infer_checkbox,
  1099. infer_host_textbox,
  1100. infer_port_textbox,
  1101. infer_decoder_model,
  1102. infer_decoder_config,
  1103. infer_llama_model,
  1104. infer_compile,
  1105. ],
  1106. outputs=[infer_error],
  1107. )
  1108. demo.launch(inbrowser=True)