manage.py 45 KB

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