manage.py 43 KB

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