manage.py 46 KB

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