manage.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  1. from __future__ import annotations
  2. import html
  3. import json
  4. import os
  5. import platform
  6. import shutil
  7. import signal
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. import gradio as gr
  12. import psutil
  13. import yaml
  14. from loguru import logger
  15. from tqdm import tqdm
  16. PYTHON = os.path.join(os.environ.get("PYTHON_FOLDERPATH", ""), "python")
  17. sys.path.insert(0, "")
  18. print(sys.path)
  19. cur_work_dir = Path(os.getcwd()).resolve()
  20. print("You are in ", str(cur_work_dir))
  21. from fish_speech.i18n import i18n
  22. from fish_speech.webui.launch_utils import Seafoam, is_module_installed, versions_html
  23. config_path = cur_work_dir / "fish_speech" / "configs"
  24. vqgan_yml_path = config_path / "firefly_gan_vq.yaml"
  25. llama_yml_path = config_path / "text2semantic_finetune.yaml"
  26. vits_yml_path = config_path / "vits_decoder_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 change_decoder_config(decoder_model_path):
  108. if "vits" in decoder_model_path:
  109. choices = ["vits_decoder_finetune", "vits_decoder_pretrain"]
  110. return gr.Dropdown(choices=choices, value=choices[0])
  111. elif "vqgan" in decoder_model_path or "vq-gan" in decoder_model_path:
  112. choices = ["firefly_gan_vq", "firefly_gan_vq"]
  113. return gr.Dropdown(choices=choices, value=choices[0])
  114. else:
  115. raise ValueError("Invalid decoder name")
  116. def change_llama_config(llama_model_path):
  117. if "large" in llama_model_path:
  118. return gr.Dropdown(value="dual_ar_2_codebook_large", interactive=False)
  119. elif "medium" in llama_model_path:
  120. return gr.Dropdown(value="dual_ar_2_codebook_medium", interactive=False)
  121. else:
  122. raise ValueError("Invalid model size")
  123. def clean_infer_cache():
  124. import tempfile
  125. temp_dir = Path(tempfile.gettempdir())
  126. gradio_dir = str(temp_dir / "gradio")
  127. try:
  128. shutil.rmtree(gradio_dir)
  129. logger.info(f"Deleted cached audios: {gradio_dir}")
  130. except PermissionError:
  131. logger.info(f"Permission denied: Unable to delete {gradio_dir}")
  132. except FileNotFoundError:
  133. logger.info(f"{gradio_dir} was not found")
  134. except Exception as e:
  135. logger.info(f"An error occurred: {e}")
  136. def change_infer(
  137. if_infer,
  138. host,
  139. port,
  140. infer_decoder_model,
  141. infer_decoder_config,
  142. infer_llama_model,
  143. infer_llama_config,
  144. infer_compile,
  145. ):
  146. global p_infer
  147. if if_infer == True and p_infer == None:
  148. env = os.environ.copy()
  149. env["GRADIO_SERVER_NAME"] = host
  150. env["GRADIO_SERVER_PORT"] = port
  151. # 启动第二个进程
  152. url = f"http://{host}:{port}"
  153. yield build_html_ok_message(
  154. i18n("Inferring interface is launched at {}").format(url)
  155. )
  156. clean_infer_cache()
  157. p_infer = subprocess.Popen(
  158. [
  159. PYTHON,
  160. "tools/webui.py",
  161. "--decoder-checkpoint-path",
  162. infer_decoder_model,
  163. "--decoder-config-name",
  164. infer_decoder_config,
  165. "--llama-checkpoint-path",
  166. infer_llama_model,
  167. "--llama-config-name",
  168. infer_llama_config,
  169. "--tokenizer",
  170. "checkpoints",
  171. ]
  172. + (["--compile"] if infer_compile == "Yes" else []),
  173. env=env,
  174. )
  175. elif if_infer == False and p_infer is not None:
  176. kill_process(p_infer.pid)
  177. p_infer = None
  178. yield build_html_error_message(i18n("Infer interface is closed"))
  179. js = load_data_in_raw("fish_speech/webui/js/animate.js")
  180. css = load_data_in_raw("fish_speech/webui/css/style.css")
  181. data_pre_output = (cur_work_dir / "data").resolve()
  182. default_model_output = (cur_work_dir / "results").resolve()
  183. default_filelist = data_pre_output / "detect.list"
  184. data_pre_output.mkdir(parents=True, exist_ok=True)
  185. items = []
  186. dict_items = {}
  187. def load_yaml_data_in_fact(yml_path):
  188. with open(yml_path, "r", encoding="utf-8") as file:
  189. yml = yaml.safe_load(file)
  190. return yml
  191. def write_yaml_data_in_fact(yml, yml_path):
  192. with open(yml_path, "w", encoding="utf-8") as file:
  193. yaml.safe_dump(yml, file, allow_unicode=True)
  194. return yml
  195. def generate_tree(directory, depth=0, max_depth=None, prefix=""):
  196. if max_depth is not None and depth > max_depth:
  197. return ""
  198. tree_str = ""
  199. files = []
  200. directories = []
  201. for item in os.listdir(directory):
  202. if os.path.isdir(os.path.join(directory, item)):
  203. directories.append(item)
  204. else:
  205. files.append(item)
  206. entries = directories + files
  207. for i, entry in enumerate(entries):
  208. connector = "├── " if i < len(entries) - 1 else "└── "
  209. tree_str += f"{prefix}{connector}{entry}<br />"
  210. if i < len(directories):
  211. extension = "│ " if i < len(entries) - 1 else " "
  212. tree_str += generate_tree(
  213. os.path.join(directory, entry),
  214. depth + 1,
  215. max_depth,
  216. prefix=prefix + extension,
  217. )
  218. return tree_str
  219. def new_explorer(data_path, max_depth):
  220. return gr.Markdown(
  221. elem_classes=["scrollable-component"],
  222. value=generate_tree(data_path, max_depth=max_depth),
  223. )
  224. def add_item(folder: str, method: str, label_lang: str):
  225. folder = folder.strip(" ").strip('"')
  226. folder_path = Path(folder)
  227. if folder and folder not in items and data_pre_output not in folder_path.parents:
  228. if folder_path.is_dir():
  229. items.append(folder)
  230. dict_items[folder] = dict(
  231. type="folder", method=method, label_lang=label_lang
  232. )
  233. elif folder:
  234. err = folder
  235. return gr.Checkboxgroup(choices=items), build_html_error_message(
  236. i18n("Invalid path: {}").format(err)
  237. )
  238. formatted_data = json.dumps(dict_items, ensure_ascii=False, indent=4)
  239. logger.info(formatted_data)
  240. return gr.Checkboxgroup(choices=items), build_html_ok_message(
  241. i18n("Added path successfully!")
  242. )
  243. def remove_items(selected_items):
  244. global items, dict_items
  245. to_remove = [item for item in items if item in selected_items]
  246. for item in to_remove:
  247. del dict_items[item]
  248. items = [item for item in items if item in dict_items.keys()]
  249. formatted_data = json.dumps(dict_items, ensure_ascii=False, indent=4)
  250. logger.info(formatted_data)
  251. return gr.Checkboxgroup(choices=items, value=[]), build_html_ok_message(
  252. i18n("Removed path successfully!")
  253. )
  254. def show_selected(options):
  255. selected_options = ", ".join(options)
  256. if options:
  257. return i18n("Selected: {}").format(selected_options)
  258. else:
  259. return i18n("No selected options")
  260. from pydub import AudioSegment
  261. def convert_to_mono_in_place(audio_path: Path):
  262. audio = AudioSegment.from_file(audio_path)
  263. if audio.channels > 1:
  264. mono_audio = audio.set_channels(1)
  265. mono_audio.export(audio_path, format=audio_path.suffix[1:])
  266. logger.info(f"Convert {audio_path} successfully")
  267. def list_copy(list_file_path, method):
  268. wav_root = data_pre_output
  269. lst = []
  270. with list_file_path.open("r", encoding="utf-8") as file:
  271. for line in tqdm(file, desc="Processing audio/transcript"):
  272. wav_path, speaker_name, language, text = line.strip().split("|")
  273. original_wav_path = Path(wav_path)
  274. target_wav_path = (
  275. wav_root / original_wav_path.parent.name / original_wav_path.name
  276. )
  277. lst.append(f"{target_wav_path}|{speaker_name}|{language}|{text}")
  278. if target_wav_path.is_file():
  279. continue
  280. target_wav_path.parent.mkdir(parents=True, exist_ok=True)
  281. if method == i18n("Copy"):
  282. shutil.copy(original_wav_path, target_wav_path)
  283. else:
  284. shutil.move(original_wav_path, target_wav_path.parent)
  285. convert_to_mono_in_place(target_wav_path)
  286. original_lab_path = original_wav_path.with_suffix(".lab")
  287. target_lab_path = (
  288. wav_root
  289. / original_wav_path.parent.name
  290. / original_wav_path.with_suffix(".lab").name
  291. )
  292. if target_lab_path.is_file():
  293. continue
  294. if method == i18n("Copy"):
  295. shutil.copy(original_lab_path, target_lab_path)
  296. else:
  297. shutil.move(original_lab_path, target_lab_path.parent)
  298. if method == i18n("Move"):
  299. with list_file_path.open("w", encoding="utf-8") as file:
  300. file.writelines("\n".join(lst))
  301. del lst
  302. return build_html_ok_message(i18n("Use filelist"))
  303. def check_files(data_path: str, max_depth: int, label_model: str, label_device: str):
  304. global dict_items
  305. data_path = Path(data_path)
  306. for item, content in dict_items.items():
  307. item_path = Path(item)
  308. tar_path = data_path / item_path.name
  309. if content["type"] == "folder" and item_path.is_dir():
  310. if content["method"] == i18n("Copy"):
  311. os.makedirs(tar_path, exist_ok=True)
  312. shutil.copytree(
  313. src=str(item_path), dst=str(tar_path), dirs_exist_ok=True
  314. )
  315. elif not tar_path.is_dir():
  316. shutil.move(src=str(item_path), dst=str(tar_path))
  317. for suf in ["wav", "flac", "mp3"]:
  318. for audio_path in tar_path.glob(f"**/*.{suf}"):
  319. convert_to_mono_in_place(audio_path)
  320. cur_lang = content["label_lang"]
  321. if cur_lang != "IGNORE":
  322. try:
  323. subprocess.run(
  324. [
  325. PYTHON,
  326. "tools/whisper_asr.py",
  327. "--model-size",
  328. label_model,
  329. "--device",
  330. label_device,
  331. "--audio-dir",
  332. tar_path,
  333. "--save-dir",
  334. tar_path,
  335. "--language",
  336. cur_lang,
  337. ],
  338. env=env,
  339. )
  340. except Exception:
  341. print("Transcription error occurred")
  342. elif content["type"] == "file" and item_path.is_file():
  343. list_copy(item_path, content["method"])
  344. return build_html_ok_message(i18n("Move files successfully")), new_explorer(
  345. data_path, max_depth=max_depth
  346. )
  347. def train_process(
  348. data_path: str,
  349. option: str,
  350. min_duration: float,
  351. max_duration: float,
  352. # vq-gan config
  353. vqgan_ckpt,
  354. vqgan_lr,
  355. vqgan_maxsteps,
  356. vqgan_data_num_workers,
  357. vqgan_data_batch_size,
  358. vqgan_data_val_batch_size,
  359. vqgan_precision,
  360. vqgan_check_interval,
  361. # vits config
  362. vits_ckpt,
  363. vits_lr,
  364. vits_maxsteps,
  365. vits_data_num_workers,
  366. vits_data_batch_size,
  367. vits_data_val_batch_size,
  368. vits_precision,
  369. vits_check_interval,
  370. # llama config
  371. llama_ckpt,
  372. llama_base_config,
  373. llama_lr,
  374. llama_maxsteps,
  375. llama_data_num_workers,
  376. llama_data_batch_size,
  377. llama_data_max_length,
  378. llama_precision,
  379. llama_check_interval,
  380. llama_grad_batches,
  381. llama_use_speaker,
  382. llama_use_lora,
  383. ):
  384. import datetime
  385. def generate_folder_name():
  386. now = datetime.datetime.now()
  387. folder_name = now.strftime("%Y%m%d_%H%M%S")
  388. return folder_name
  389. backend = "nccl" if sys.platform == "linux" else "gloo"
  390. new_project = generate_folder_name()
  391. print("New Project Name: ", new_project)
  392. if min_duration > max_duration:
  393. min_duration, max_duration = max_duration, min_duration
  394. if option == "VQGAN" or option == "VITS":
  395. subprocess.run(
  396. [
  397. PYTHON,
  398. "tools/vqgan/create_train_split.py",
  399. str(data_pre_output.relative_to(cur_work_dir)),
  400. "--min-duration",
  401. str(min_duration),
  402. "--max-duration",
  403. str(max_duration),
  404. ]
  405. )
  406. if option == "VQGAN":
  407. latest = next(
  408. iter(
  409. sorted(
  410. [
  411. str(p.relative_to("results"))
  412. for p in Path("results").glob("vqgan_*/")
  413. ],
  414. reverse=True,
  415. )
  416. ),
  417. ("vqgan_" + new_project),
  418. )
  419. project = (
  420. ("vqgan_" + new_project)
  421. if vqgan_ckpt == i18n("new")
  422. else (
  423. latest
  424. if vqgan_ckpt == i18n("latest")
  425. else Path(vqgan_ckpt).relative_to("results")
  426. )
  427. )
  428. logger.info(project)
  429. train_cmd = [
  430. PYTHON,
  431. "fish_speech/train.py",
  432. "--config-name",
  433. "firefly_gan_vq",
  434. f"project={project}",
  435. f"trainer.strategy.process_group_backend={backend}",
  436. f"model.optimizer.lr={vqgan_lr}",
  437. f"trainer.max_steps={vqgan_maxsteps}",
  438. f"data.num_workers={vqgan_data_num_workers}",
  439. f"data.batch_size={vqgan_data_batch_size}",
  440. f"data.val_batch_size={vqgan_data_val_batch_size}",
  441. f"trainer.precision={vqgan_precision}",
  442. f"trainer.val_check_interval={vqgan_check_interval}",
  443. f"train_dataset.filelist={str(data_pre_output / 'vq_train_filelist.txt')}",
  444. f"val_dataset.filelist={str(data_pre_output / 'vq_val_filelist.txt')}",
  445. ]
  446. logger.info(train_cmd)
  447. subprocess.run(train_cmd)
  448. if option == "VITS":
  449. latest = next(
  450. iter(
  451. sorted(
  452. [
  453. str(p.relative_to("results"))
  454. for p in Path("results").glob("vits_*/")
  455. ],
  456. reverse=True,
  457. )
  458. ),
  459. ("vits_" + new_project),
  460. )
  461. project = (
  462. ("vits_" + new_project)
  463. if vits_ckpt == i18n("new")
  464. else (
  465. latest
  466. if vits_ckpt == i18n("latest")
  467. else Path(vits_ckpt).relative_to("results")
  468. )
  469. )
  470. ckpt_path = str(Path("checkpoints/vits_decoder_v1.1.ckpt"))
  471. logger.info(project)
  472. train_cmd = [
  473. PYTHON,
  474. "fish_speech/train.py",
  475. "--config-name",
  476. "vits_decoder_finetune",
  477. f"project={project}",
  478. f"ckpt_path={ckpt_path}",
  479. f"trainer.strategy.process_group_backend={backend}",
  480. "tokenizer.pretrained_model_name_or_path=checkpoints",
  481. f"model.optimizer.lr={vits_lr}",
  482. f"trainer.max_steps={vits_maxsteps}",
  483. f"data.num_workers={vits_data_num_workers}",
  484. f"data.batch_size={vits_data_batch_size}",
  485. f"data.val_batch_size={vits_data_val_batch_size}",
  486. f"trainer.precision={vits_precision}",
  487. f"trainer.val_check_interval={vits_check_interval}",
  488. f"train_dataset.filelist={str(data_pre_output / 'vq_train_filelist.txt')}",
  489. f"val_dataset.filelist={str(data_pre_output / 'vq_val_filelist.txt')}",
  490. ]
  491. logger.info(train_cmd)
  492. subprocess.run(train_cmd)
  493. if option == "LLAMA":
  494. subprocess.run(
  495. [
  496. PYTHON,
  497. "tools/vqgan/extract_vq.py",
  498. str(data_pre_output),
  499. "--num-workers",
  500. "1",
  501. "--batch-size",
  502. "16",
  503. "--config-name",
  504. "firefly_gan_vq",
  505. "--checkpoint-path",
  506. "checkpoints/fish-speech-1.2/firefly-gan-vq-fsq-4x1024-42hz-generator.pth",
  507. ]
  508. )
  509. subprocess.run(
  510. [
  511. PYTHON,
  512. "tools/llama/build_dataset.py",
  513. "--input",
  514. str(data_pre_output),
  515. "--text-extension",
  516. ".lab",
  517. "--num-workers",
  518. "16",
  519. ]
  520. )
  521. ckpt_path = (
  522. "text2semantic-sft-medium-v1.1-4k.pth"
  523. if llama_base_config == "dual_ar_2_codebook_medium"
  524. else "text2semantic-sft-large-v1.1-4k.pth"
  525. )
  526. lora_prefix = "lora_" if llama_use_lora else ""
  527. llama_size = "large_" if ("large" in llama_base_config) else "medium_"
  528. llama_name = lora_prefix + "text2semantic_" + llama_size + new_project
  529. latest = next(
  530. iter(
  531. sorted(
  532. [
  533. str(p.relative_to("results"))
  534. for p in Path("results").glob(lora_prefix + "text2sem*/")
  535. ],
  536. reverse=True,
  537. )
  538. ),
  539. llama_name,
  540. )
  541. project = (
  542. llama_name
  543. if llama_ckpt == i18n("new")
  544. else (
  545. latest
  546. if llama_ckpt == i18n("latest")
  547. else Path(llama_ckpt).relative_to("results")
  548. )
  549. )
  550. logger.info(project)
  551. train_cmd = [
  552. PYTHON,
  553. "fish_speech/train.py",
  554. "--config-name",
  555. "text2semantic_finetune",
  556. f"project={project}",
  557. f"ckpt_path=checkpoints/{ckpt_path}",
  558. f"trainer.strategy.process_group_backend={backend}",
  559. f"model@model.model={llama_base_config}",
  560. "tokenizer.pretrained_model_name_or_path=checkpoints",
  561. f"train_dataset.proto_files={str(['data/quantized-dataset-ft'])}",
  562. f"val_dataset.proto_files={str(['data/quantized-dataset-ft'])}",
  563. f"model.optimizer.lr={llama_lr}",
  564. f"trainer.max_steps={llama_maxsteps}",
  565. f"data.num_workers={llama_data_num_workers}",
  566. f"data.batch_size={llama_data_batch_size}",
  567. f"max_length={llama_data_max_length}",
  568. f"trainer.precision={llama_precision}",
  569. f"trainer.val_check_interval={llama_check_interval}",
  570. f"trainer.accumulate_grad_batches={llama_grad_batches}",
  571. f"train_dataset.use_speaker={llama_use_speaker}",
  572. ] + ([f"+lora@model.lora_config=r_8_alpha_16"] if llama_use_lora else [])
  573. logger.info(train_cmd)
  574. subprocess.run(train_cmd)
  575. return build_html_ok_message(i18n("Training stopped"))
  576. def tensorboard_process(
  577. if_tensorboard: bool,
  578. tensorboard_dir: str,
  579. host: str,
  580. port: str,
  581. ):
  582. global p_tensorboard
  583. if if_tensorboard == True and p_tensorboard == None:
  584. url = f"http://{host}:{port}"
  585. yield build_html_ok_message(
  586. i18n("Tensorboard interface is launched at {}").format(url)
  587. )
  588. prefix = ["tensorboard"]
  589. if Path("fishenv").exists():
  590. prefix = ["fishenv/env/python.exe", "fishenv/env/Scripts/tensorboard.exe"]
  591. p_tensorboard = subprocess.Popen(
  592. prefix
  593. + [
  594. "--logdir",
  595. tensorboard_dir,
  596. "--host",
  597. host,
  598. "--port",
  599. port,
  600. "--reload_interval",
  601. "120",
  602. ]
  603. )
  604. elif if_tensorboard == False and p_tensorboard != None:
  605. kill_process(p_tensorboard.pid)
  606. p_tensorboard = None
  607. yield build_html_error_message(i18n("Tensorboard interface is closed"))
  608. def fresh_tb_dir():
  609. return gr.Dropdown(
  610. choices=[str(p) for p in Path("results").glob("**/tensorboard/")]
  611. )
  612. def list_decoder_models():
  613. paths = (
  614. [str(p) for p in Path("checkpoints").glob("vits*.*")]
  615. + [str(p) for p in Path("checkpoints").glob("vq*.*")]
  616. + [str(p) for p in Path("results").glob("vqgan*/**/*.ckpt")]
  617. + [str(p) for p in Path("results").glob("vits*/**/*.ckpt")]
  618. )
  619. if not paths:
  620. logger.warning("No decoder model found")
  621. return paths
  622. def list_llama_models():
  623. choices = [
  624. str(p).replace("\\", "/") for p in Path("checkpoints").glob("text2sem*.*")
  625. ]
  626. choices += [str(p) for p in Path("results").glob("text2sem*/**/*.ckpt")]
  627. if not choices:
  628. logger.warning("No LLaMA model found")
  629. return choices
  630. def list_lora_llama_models():
  631. choices = [str(p) for p in Path("results").glob("lora*/**/*.ckpt")]
  632. if not choices:
  633. logger.warning("No LoRA LLaMA model found")
  634. return choices
  635. def fresh_decoder_model():
  636. return gr.Dropdown(choices=list_decoder_models())
  637. def fresh_vqgan_ckpt():
  638. return gr.Dropdown(
  639. choices=[i18n("latest"), i18n("new")]
  640. + [str(p) for p in Path("results").glob("vqgan_*/")]
  641. )
  642. def fresh_vits_ckpt():
  643. return gr.Dropdown(
  644. choices=[i18n("latest"), i18n("new")]
  645. + [str(p) for p in Path("results").glob("vits_*/")]
  646. )
  647. def fresh_llama_ckpt(llama_use_lora):
  648. return gr.Dropdown(
  649. choices=[i18n("latest"), i18n("new")]
  650. + (
  651. [str(p) for p in Path("results").glob("text2sem*/")]
  652. if not llama_use_lora
  653. else [str(p) for p in Path("results").glob("lora_*/")]
  654. )
  655. )
  656. def fresh_llama_model():
  657. choices = [
  658. str(p).replace("\\", "/") for p in Path("checkpoints").glob("text2sem*.*")
  659. ]
  660. choices += [str(p) for p in Path("results").glob("text2sem*/**/*.ckpt")]
  661. return gr.Dropdown(choices=choices)
  662. def llama_lora_merge(llama_weight, lora_llama_config, lora_weight, llama_lora_output):
  663. if (
  664. lora_weight is None
  665. or not Path(lora_weight).exists()
  666. or not Path(llama_weight).exists()
  667. ):
  668. return build_html_error_message(
  669. i18n(
  670. "Path error, please check the model file exists in the corresponding path"
  671. )
  672. )
  673. merge_cmd = [
  674. PYTHON,
  675. "tools/llama/merge_lora.py",
  676. "--llama-config",
  677. lora_llama_config,
  678. "--lora-config",
  679. "r_8_alpha_16",
  680. "--llama-weight",
  681. llama_weight,
  682. "--lora-weight",
  683. lora_weight,
  684. "--output",
  685. llama_lora_output,
  686. ]
  687. logger.info(merge_cmd)
  688. subprocess.run(merge_cmd)
  689. return build_html_ok_message(i18n("Merge successfully"))
  690. init_vqgan_yml = load_yaml_data_in_fact(vqgan_yml_path)
  691. init_llama_yml = load_yaml_data_in_fact(llama_yml_path)
  692. init_vits_yml = load_yaml_data_in_fact(vits_yml_path)
  693. with gr.Blocks(
  694. head="<style>\n" + css + "\n</style>",
  695. js=js,
  696. theme=seafoam,
  697. analytics_enabled=False,
  698. title="Fish Speech",
  699. ) as demo:
  700. with gr.Row():
  701. with gr.Column():
  702. with gr.Tab("\U0001F4D6 " + i18n("Data Preprocessing")):
  703. with gr.Row():
  704. textbox = gr.Textbox(
  705. label="\U0000270F "
  706. + i18n("Input Audio & Source Path for Transcription"),
  707. info=i18n("Speaker is identified by the folder name"),
  708. interactive=True,
  709. )
  710. with gr.Row(equal_height=False):
  711. with gr.Column():
  712. output_radio = gr.Radio(
  713. label="\U0001F4C1 "
  714. + i18n("Select source file processing method"),
  715. choices=[i18n("Copy"), i18n("Move")],
  716. value=i18n("Copy"),
  717. interactive=True,
  718. )
  719. with gr.Column():
  720. error = gr.HTML(label=i18n("Error Message"))
  721. if_label = gr.Checkbox(
  722. label=i18n("Open Labeler WebUI"), scale=0, show_label=True
  723. )
  724. with gr.Row():
  725. min_duration = gr.Slider(
  726. label=i18n("Minimum Audio Duration"),
  727. value=1.5,
  728. step=0.1,
  729. minimum=0.4,
  730. maximum=30,
  731. )
  732. max_duration = gr.Slider(
  733. label=i18n("Maximum Audio Duration"),
  734. value=30,
  735. step=0.1,
  736. minimum=0.4,
  737. maximum=30,
  738. )
  739. with gr.Row():
  740. add_button = gr.Button(
  741. "\U000027A1 " + i18n("Add to Processing Area"),
  742. variant="primary",
  743. )
  744. remove_button = gr.Button(
  745. "\U000026D4 " + i18n("Remove Selected Data")
  746. )
  747. with gr.Row():
  748. label_device = gr.Dropdown(
  749. label=i18n("Labeling Device"),
  750. info=i18n(
  751. "It is recommended to use CUDA, if you have low configuration, use CPU"
  752. ),
  753. choices=["cpu", "cuda"],
  754. value="cuda",
  755. interactive=True,
  756. )
  757. label_model = gr.Dropdown(
  758. label=i18n("Whisper Model"),
  759. info=i18n(
  760. "Use large for 10G+ GPU, medium for 5G, small for 2G"
  761. ),
  762. choices=["large", "medium", "small"],
  763. value="small",
  764. interactive=True,
  765. )
  766. label_radio = gr.Dropdown(
  767. label=i18n("Optional Label Language"),
  768. info=i18n(
  769. "If there is no corresponding text for the audio, apply ASR for assistance, support .txt or .lab format"
  770. ),
  771. choices=[
  772. (i18n("Chinese"), "ZH"),
  773. (i18n("English"), "EN"),
  774. (i18n("Japanese"), "JA"),
  775. (i18n("Disabled"), "IGNORE"),
  776. ],
  777. value="IGNORE",
  778. interactive=True,
  779. )
  780. with gr.Tab("\U0001F6E0 " + i18n("Training Configuration")):
  781. with gr.Row():
  782. model_type_radio = gr.Radio(
  783. label=i18n(
  784. "Select the model to be trained (Depending on the Tab page you are on)"
  785. ),
  786. interactive=False,
  787. choices=["VQGAN", "VITS", "LLAMA"],
  788. value="VQGAN",
  789. )
  790. with gr.Row():
  791. with gr.Tabs():
  792. with gr.Tab(label=i18n("VQGAN Configuration")) as vqgan_page:
  793. with gr.Row(equal_height=False):
  794. vqgan_ckpt = gr.Dropdown(
  795. label=i18n("Select VQGAN ckpt"),
  796. choices=[i18n("latest"), i18n("new")]
  797. + [
  798. str(p) for p in Path("results").glob("vqgan_*/")
  799. ],
  800. value=i18n("latest"),
  801. interactive=True,
  802. )
  803. with gr.Row(equal_height=False):
  804. vqgan_lr_slider = gr.Slider(
  805. label=i18n("Initial Learning Rate"),
  806. interactive=True,
  807. minimum=1e-5,
  808. maximum=1e-4,
  809. step=1e-5,
  810. value=init_vqgan_yml["model"]["optimizer"]["lr"],
  811. )
  812. vqgan_maxsteps_slider = gr.Slider(
  813. label=i18n("Maximum Training Steps"),
  814. interactive=True,
  815. minimum=1000,
  816. maximum=100000,
  817. step=1000,
  818. value=init_vqgan_yml["trainer"]["max_steps"],
  819. )
  820. with gr.Row(equal_height=False):
  821. vqgan_data_num_workers_slider = gr.Slider(
  822. label=i18n("Number of Workers"),
  823. interactive=True,
  824. minimum=1,
  825. maximum=16,
  826. step=1,
  827. value=init_vqgan_yml["data"]["num_workers"],
  828. )
  829. vqgan_data_batch_size_slider = gr.Slider(
  830. label=i18n("Batch Size"),
  831. interactive=True,
  832. minimum=1,
  833. maximum=32,
  834. step=1,
  835. value=init_vqgan_yml["data"]["batch_size"],
  836. )
  837. with gr.Row(equal_height=False):
  838. vqgan_data_val_batch_size_slider = gr.Slider(
  839. label=i18n("Validation Batch Size"),
  840. interactive=True,
  841. minimum=1,
  842. maximum=32,
  843. step=1,
  844. value=init_vqgan_yml["data"]["val_batch_size"],
  845. )
  846. vqgan_precision_dropdown = gr.Dropdown(
  847. label=i18n("Precision"),
  848. interactive=True,
  849. choices=["32", "bf16-true", "bf16-mixed"],
  850. info=i18n(
  851. "bf16-true is recommended for 30+ series GPU, 16-mixed is recommended for 10+ series GPU"
  852. ),
  853. value=str(init_vqgan_yml["trainer"]["precision"]),
  854. )
  855. with gr.Row(equal_height=False):
  856. vqgan_check_interval_slider = gr.Slider(
  857. label=i18n("Save model every n steps"),
  858. interactive=True,
  859. minimum=500,
  860. maximum=10000,
  861. step=500,
  862. value=init_vqgan_yml["trainer"][
  863. "val_check_interval"
  864. ],
  865. )
  866. with gr.Tab(label=i18n("VITS Configuration")) as vits_page:
  867. with gr.Row(equal_height=False):
  868. vits_ckpt = gr.Dropdown(
  869. label=i18n("Select VITS ckpt"),
  870. choices=[i18n("latest"), i18n("new")]
  871. + [str(p) for p in Path("results").glob("vits_*/")],
  872. value=i18n("latest"),
  873. interactive=True,
  874. )
  875. with gr.Row(equal_height=False):
  876. vits_lr_slider = gr.Slider(
  877. label=i18n("Initial Learning Rate"),
  878. interactive=True,
  879. minimum=1e-5,
  880. maximum=1e-4,
  881. step=1e-5,
  882. value=init_vits_yml["model"]["optimizer"]["lr"],
  883. )
  884. vits_maxsteps_slider = gr.Slider(
  885. label=i18n("Maximum Training Steps"),
  886. interactive=True,
  887. minimum=1000,
  888. maximum=100000,
  889. step=1000,
  890. value=init_vits_yml["trainer"]["max_steps"],
  891. )
  892. with gr.Row(equal_height=False):
  893. vits_data_num_workers_slider = gr.Slider(
  894. label=i18n("Number of Workers"),
  895. interactive=True,
  896. minimum=1,
  897. maximum=16,
  898. step=1,
  899. value=init_vits_yml["data"]["num_workers"],
  900. )
  901. vits_data_batch_size_slider = gr.Slider(
  902. label=i18n("Batch Size"),
  903. interactive=True,
  904. minimum=1,
  905. maximum=32,
  906. step=1,
  907. value=init_vits_yml["data"]["batch_size"],
  908. )
  909. with gr.Row(equal_height=False):
  910. vits_data_val_batch_size_slider = gr.Slider(
  911. label=i18n("Validation Batch Size"),
  912. interactive=True,
  913. minimum=1,
  914. maximum=32,
  915. step=1,
  916. value=init_vits_yml["data"]["val_batch_size"],
  917. )
  918. vits_precision_dropdown = gr.Dropdown(
  919. label=i18n("Precision"),
  920. interactive=True,
  921. choices=["32", "bf16-mixed"],
  922. info=i18n(
  923. "16-mixed is recommended for 10+ series GPU"
  924. ),
  925. value=str(init_vits_yml["trainer"]["precision"]),
  926. )
  927. with gr.Row(equal_height=False):
  928. vits_check_interval_slider = gr.Slider(
  929. label=i18n("Save model every n steps"),
  930. interactive=True,
  931. minimum=1,
  932. maximum=2000,
  933. step=1,
  934. value=init_vits_yml["trainer"][
  935. "val_check_interval"
  936. ],
  937. )
  938. with gr.Tab(
  939. label=i18n("LLAMA Configuration"), id=3
  940. ) as llama_page:
  941. with gr.Row(equal_height=False):
  942. llama_use_lora = gr.Checkbox(
  943. label=i18n("Use LoRA"),
  944. info=i18n(
  945. "Use LoRA can save GPU memory, but may reduce the quality of the model"
  946. ),
  947. value=True,
  948. )
  949. llama_ckpt = gr.Dropdown(
  950. label=i18n("Select LLAMA ckpt"),
  951. choices=[i18n("latest"), i18n("new")]
  952. + [
  953. str(p)
  954. for p in Path("results").glob("text2sem*/")
  955. ]
  956. + [str(p) for p in Path("results").glob("lora*/")],
  957. value=i18n("latest"),
  958. interactive=True,
  959. )
  960. with gr.Row(equal_height=False):
  961. llama_lr_slider = gr.Slider(
  962. label=i18n("Initial Learning Rate"),
  963. interactive=True,
  964. minimum=1e-5,
  965. maximum=1e-4,
  966. step=1e-5,
  967. value=init_llama_yml["model"]["optimizer"]["lr"],
  968. )
  969. llama_maxsteps_slider = gr.Slider(
  970. label=i18n("Maximum Training Steps"),
  971. interactive=True,
  972. minimum=50,
  973. maximum=10000,
  974. step=50,
  975. value=init_llama_yml["trainer"]["max_steps"],
  976. )
  977. with gr.Row(equal_height=False):
  978. llama_base_config = gr.Dropdown(
  979. label=i18n("Model Size"),
  980. choices=[
  981. "dual_ar_2_codebook_large",
  982. "dual_ar_2_codebook_medium",
  983. ],
  984. value="dual_ar_2_codebook_medium",
  985. )
  986. llama_data_num_workers_slider = gr.Slider(
  987. label=i18n("Number of Workers"),
  988. minimum=1,
  989. maximum=16,
  990. step=1,
  991. value=(
  992. init_llama_yml["data"]["num_workers"]
  993. if sys.platform == "linux"
  994. else 1
  995. ),
  996. )
  997. with gr.Row(equal_height=False):
  998. llama_data_batch_size_slider = gr.Slider(
  999. label=i18n("Batch Size"),
  1000. interactive=True,
  1001. minimum=1,
  1002. maximum=32,
  1003. step=1,
  1004. value=init_llama_yml["data"]["batch_size"],
  1005. )
  1006. llama_data_max_length_slider = gr.Slider(
  1007. label=i18n("Maximum Length per Sample"),
  1008. interactive=True,
  1009. minimum=1024,
  1010. maximum=4096,
  1011. step=128,
  1012. value=init_llama_yml["max_length"],
  1013. )
  1014. with gr.Row(equal_height=False):
  1015. llama_precision_dropdown = gr.Dropdown(
  1016. label=i18n("Precision"),
  1017. info=i18n(
  1018. "bf16-true is recommended for 30+ series GPU, 16-mixed is recommended for 10+ series GPU"
  1019. ),
  1020. interactive=True,
  1021. choices=["32", "bf16-true", "16-mixed"],
  1022. value="bf16-true",
  1023. )
  1024. llama_check_interval_slider = gr.Slider(
  1025. label=i18n("Save model every n steps"),
  1026. interactive=True,
  1027. minimum=50,
  1028. maximum=1000,
  1029. step=50,
  1030. value=init_llama_yml["trainer"][
  1031. "val_check_interval"
  1032. ],
  1033. )
  1034. with gr.Row(equal_height=False):
  1035. llama_grad_batches = gr.Slider(
  1036. label=i18n("Accumulate Gradient Batches"),
  1037. interactive=True,
  1038. minimum=1,
  1039. maximum=20,
  1040. step=1,
  1041. value=init_llama_yml["trainer"][
  1042. "accumulate_grad_batches"
  1043. ],
  1044. )
  1045. llama_use_speaker = gr.Slider(
  1046. label=i18n(
  1047. "Probability of applying Speaker Condition"
  1048. ),
  1049. interactive=True,
  1050. minimum=0.1,
  1051. maximum=1.0,
  1052. step=0.05,
  1053. value=init_llama_yml["train_dataset"][
  1054. "use_speaker"
  1055. ],
  1056. )
  1057. with gr.Tab(label=i18n("Merge LoRA"), id=4):
  1058. with gr.Row(equal_height=False):
  1059. llama_weight = gr.Dropdown(
  1060. label=i18n("Base LLAMA Model"),
  1061. info=i18n(
  1062. "Type the path or select from the dropdown"
  1063. ),
  1064. choices=[
  1065. "checkpoints/text2semantic-sft-large-v1.1-4k.pth",
  1066. "checkpoints/text2semantic-sft-medium-v1.1-4k.pth",
  1067. ],
  1068. value=init_llama_yml["ckpt_path"],
  1069. allow_custom_value=True,
  1070. interactive=True,
  1071. )
  1072. with gr.Row(equal_height=False):
  1073. lora_weight = gr.Dropdown(
  1074. label=i18n("LoRA Model to be merged"),
  1075. info=i18n(
  1076. "Type the path or select from the dropdown"
  1077. ),
  1078. choices=[
  1079. str(p)
  1080. for p in Path("results").glob("lora*/**/*.ckpt")
  1081. ],
  1082. allow_custom_value=True,
  1083. interactive=True,
  1084. )
  1085. lora_llama_config = gr.Dropdown(
  1086. label=i18n("LLAMA Model Config"),
  1087. info=i18n(
  1088. "Type the path or select from the dropdown"
  1089. ),
  1090. choices=[
  1091. "dual_ar_2_codebook_large",
  1092. "dual_ar_2_codebook_medium",
  1093. ],
  1094. value="dual_ar_2_codebook_medium",
  1095. allow_custom_value=True,
  1096. )
  1097. with gr.Row(equal_height=False):
  1098. llama_lora_output = gr.Dropdown(
  1099. label=i18n("Output Path"),
  1100. info=i18n(
  1101. "Type the path or select from the dropdown"
  1102. ),
  1103. value="checkpoints/merged.ckpt",
  1104. choices=["checkpoints/merged.ckpt"],
  1105. allow_custom_value=True,
  1106. interactive=True,
  1107. )
  1108. with gr.Row(equal_height=False):
  1109. llama_lora_merge_btn = gr.Button(
  1110. value=i18n("Merge"), variant="primary"
  1111. )
  1112. with gr.Tab(label="Tensorboard", id=5):
  1113. with gr.Row(equal_height=False):
  1114. tb_host = gr.Textbox(
  1115. label=i18n("Tensorboard Host"), value="127.0.0.1"
  1116. )
  1117. tb_port = gr.Textbox(
  1118. label=i18n("Tensorboard Port"), value="11451"
  1119. )
  1120. with gr.Row(equal_height=False):
  1121. tb_dir = gr.Dropdown(
  1122. label=i18n("Tensorboard Log Path"),
  1123. allow_custom_value=True,
  1124. choices=[
  1125. str(p)
  1126. for p in Path("results").glob("**/tensorboard/")
  1127. ],
  1128. )
  1129. with gr.Row(equal_height=False):
  1130. if_tb = gr.Checkbox(
  1131. label=i18n("Open Tensorboard"),
  1132. )
  1133. with gr.Tab("\U0001F9E0 " + i18n("Inference Configuration")):
  1134. with gr.Column():
  1135. with gr.Row():
  1136. with gr.Accordion(
  1137. label="\U0001F5A5 "
  1138. + i18n("Inference Server Configuration"),
  1139. open=False,
  1140. ):
  1141. with gr.Row():
  1142. infer_host_textbox = gr.Textbox(
  1143. label=i18n("WebUI Host"), value="127.0.0.1"
  1144. )
  1145. infer_port_textbox = gr.Textbox(
  1146. label=i18n("WebUI Port"), value="7862"
  1147. )
  1148. with gr.Row():
  1149. infer_decoder_model = gr.Dropdown(
  1150. label=i18n("Decoder Model Path"),
  1151. info=i18n(
  1152. "Type the path or select from the dropdown"
  1153. ),
  1154. choices=list_decoder_models(),
  1155. value=init_vits_yml["ckpt_path"],
  1156. allow_custom_value=True,
  1157. )
  1158. infer_decoder_config = gr.Dropdown(
  1159. label=i18n("Decoder Model Config"),
  1160. info=i18n("Changing with the Model Path"),
  1161. value="vits_decoder_finetune",
  1162. choices=[
  1163. "vits_decoder_finetune",
  1164. "vits_decoder_pretrain",
  1165. "firefly_gan_vq",
  1166. "firefly_gan_vq",
  1167. ],
  1168. allow_custom_value=True,
  1169. )
  1170. with gr.Row():
  1171. infer_llama_model = gr.Dropdown(
  1172. label=i18n("LLAMA Model Path"),
  1173. info=i18n(
  1174. "Type the path or select from the dropdown"
  1175. ),
  1176. value=init_llama_yml["ckpt_path"],
  1177. choices=list_llama_models(),
  1178. allow_custom_value=True,
  1179. )
  1180. infer_llama_config = gr.Dropdown(
  1181. label=i18n("LLAMA Model Config"),
  1182. info=i18n("Changing with the Model Path"),
  1183. choices=[
  1184. "dual_ar_2_codebook_large",
  1185. "dual_ar_2_codebook_medium",
  1186. ],
  1187. value="dual_ar_2_codebook_medium",
  1188. allow_custom_value=True,
  1189. )
  1190. with gr.Row():
  1191. infer_compile = gr.Radio(
  1192. label=i18n("Compile Model"),
  1193. info=i18n(
  1194. "Compile the model can significantly reduce the inference time, but will increase cold start time"
  1195. ),
  1196. choices=["Yes", "No"],
  1197. value=(
  1198. "Yes" if (sys.platform == "linux") else "No"
  1199. ),
  1200. interactive=is_module_installed("triton"),
  1201. )
  1202. with gr.Row():
  1203. infer_checkbox = gr.Checkbox(
  1204. label=i18n("Open Inference Server")
  1205. )
  1206. infer_error = gr.HTML(label=i18n("Inference Server Error"))
  1207. with gr.Column():
  1208. train_error = gr.HTML(label=i18n("Training Error"))
  1209. checkbox_group = gr.CheckboxGroup(
  1210. label="\U0001F4CA " + i18n("Data Source"),
  1211. info=i18n(
  1212. "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."
  1213. ),
  1214. elem_classes=["data_src"],
  1215. )
  1216. train_box = gr.Textbox(
  1217. label=i18n("Data Preprocessing Path"),
  1218. value=str(data_pre_output),
  1219. interactive=False,
  1220. )
  1221. model_box = gr.Textbox(
  1222. label="\U0001F4BE " + i18n("Model Output Path"),
  1223. value=str(default_model_output),
  1224. interactive=False,
  1225. )
  1226. with gr.Accordion(
  1227. i18n(
  1228. "View the status of the preprocessing folder (use the slider to control the depth of the tree)"
  1229. ),
  1230. elem_classes=["scrollable-component"],
  1231. elem_id="file_accordion",
  1232. ):
  1233. tree_slider = gr.Slider(
  1234. minimum=0,
  1235. maximum=3,
  1236. value=0,
  1237. step=1,
  1238. show_label=False,
  1239. container=False,
  1240. )
  1241. file_markdown = new_explorer(str(data_pre_output), 0)
  1242. with gr.Row(equal_height=False):
  1243. admit_btn = gr.Button(
  1244. "\U00002705 " + i18n("File Preprocessing"),
  1245. variant="primary",
  1246. )
  1247. fresh_btn = gr.Button("\U0001F503", scale=0, min_width=80)
  1248. help_button = gr.Button("\U00002753", scale=0, min_width=80) # question
  1249. train_btn = gr.Button(i18n("Start Training"), variant="primary")
  1250. footer = load_data_in_raw("fish_speech/webui/html/footer.html")
  1251. footer = footer.format(
  1252. versions=versions_html(),
  1253. api_docs="https://speech.fish.audio/inference/#http-api",
  1254. )
  1255. gr.HTML(footer, elem_id="footer")
  1256. vqgan_page.select(lambda: "VQGAN", None, model_type_radio)
  1257. vits_page.select(lambda: "VITS", None, model_type_radio)
  1258. llama_page.select(lambda: "LLAMA", None, model_type_radio)
  1259. add_button.click(
  1260. fn=add_item,
  1261. inputs=[textbox, output_radio, label_radio],
  1262. outputs=[checkbox_group, error],
  1263. )
  1264. remove_button.click(
  1265. fn=remove_items, inputs=[checkbox_group], outputs=[checkbox_group, error]
  1266. )
  1267. checkbox_group.change(fn=show_selected, inputs=checkbox_group, outputs=[error])
  1268. help_button.click(
  1269. fn=None,
  1270. js='() => { window.open("https://speech.fish.audio/", "newwindow", "height=100, width=400, '
  1271. 'toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")}',
  1272. )
  1273. if_label.change(fn=change_label, inputs=[if_label], outputs=[error])
  1274. train_btn.click(
  1275. fn=train_process,
  1276. inputs=[
  1277. train_box,
  1278. model_type_radio,
  1279. min_duration,
  1280. max_duration,
  1281. # vq-gan config
  1282. vqgan_ckpt,
  1283. vqgan_lr_slider,
  1284. vqgan_maxsteps_slider,
  1285. vqgan_data_num_workers_slider,
  1286. vqgan_data_batch_size_slider,
  1287. vqgan_data_val_batch_size_slider,
  1288. vqgan_precision_dropdown,
  1289. vqgan_check_interval_slider,
  1290. # vits config
  1291. vits_ckpt,
  1292. vits_lr_slider,
  1293. vits_maxsteps_slider,
  1294. vits_data_num_workers_slider,
  1295. vits_data_batch_size_slider,
  1296. vits_data_val_batch_size_slider,
  1297. vits_precision_dropdown,
  1298. vits_check_interval_slider,
  1299. # llama config
  1300. llama_ckpt,
  1301. llama_base_config,
  1302. llama_lr_slider,
  1303. llama_maxsteps_slider,
  1304. llama_data_num_workers_slider,
  1305. llama_data_batch_size_slider,
  1306. llama_data_max_length_slider,
  1307. llama_precision_dropdown,
  1308. llama_check_interval_slider,
  1309. llama_grad_batches,
  1310. llama_use_speaker,
  1311. llama_use_lora,
  1312. ],
  1313. outputs=[train_error],
  1314. )
  1315. if_tb.change(
  1316. fn=tensorboard_process,
  1317. inputs=[if_tb, tb_dir, tb_host, tb_port],
  1318. outputs=[train_error],
  1319. )
  1320. tb_dir.change(fn=fresh_tb_dir, inputs=[], outputs=[tb_dir])
  1321. infer_decoder_model.change(
  1322. fn=change_decoder_config,
  1323. inputs=[infer_decoder_model],
  1324. outputs=[infer_decoder_config],
  1325. )
  1326. infer_llama_model.change(
  1327. fn=change_llama_config, inputs=[infer_llama_model], outputs=[infer_llama_config]
  1328. )
  1329. infer_decoder_model.change(
  1330. fn=fresh_decoder_model, inputs=[], outputs=[infer_decoder_model]
  1331. )
  1332. infer_llama_model.change(
  1333. fn=fresh_llama_model, inputs=[], outputs=[infer_llama_model]
  1334. )
  1335. llama_weight.change(fn=fresh_llama_model, inputs=[], outputs=[llama_weight])
  1336. admit_btn.click(
  1337. fn=check_files,
  1338. inputs=[train_box, tree_slider, label_model, label_device],
  1339. outputs=[error, file_markdown],
  1340. )
  1341. fresh_btn.click(
  1342. fn=new_explorer, inputs=[train_box, tree_slider], outputs=[file_markdown]
  1343. )
  1344. vqgan_ckpt.change(fn=fresh_vqgan_ckpt, inputs=[], outputs=[vqgan_ckpt])
  1345. vits_ckpt.change(fn=fresh_vits_ckpt, inputs=[], outputs=[vits_ckpt])
  1346. llama_use_lora.change(
  1347. fn=fresh_llama_ckpt, inputs=[llama_use_lora], outputs=[llama_ckpt]
  1348. )
  1349. llama_ckpt.change(
  1350. fn=fresh_llama_ckpt, inputs=[llama_use_lora], outputs=[llama_ckpt]
  1351. )
  1352. lora_weight.change(
  1353. fn=change_llama_config, inputs=[lora_weight], outputs=[lora_llama_config]
  1354. )
  1355. lora_weight.change(
  1356. fn=lambda: gr.Dropdown(choices=list_lora_llama_models()),
  1357. inputs=[],
  1358. outputs=[lora_weight],
  1359. )
  1360. llama_lora_merge_btn.click(
  1361. fn=llama_lora_merge,
  1362. inputs=[llama_weight, lora_llama_config, lora_weight, llama_lora_output],
  1363. outputs=[train_error],
  1364. )
  1365. infer_checkbox.change(
  1366. fn=change_infer,
  1367. inputs=[
  1368. infer_checkbox,
  1369. infer_host_textbox,
  1370. infer_port_textbox,
  1371. infer_decoder_model,
  1372. infer_decoder_config,
  1373. infer_llama_model,
  1374. infer_llama_config,
  1375. infer_compile,
  1376. ],
  1377. outputs=[infer_error],
  1378. )
  1379. demo.launch(inbrowser=True)