manage.py 45 KB

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