manage.py 54 KB

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