build_dataset.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import re
  2. from collections import defaultdict
  3. from multiprocessing import Pool
  4. from pathlib import Path
  5. import click
  6. import numpy as np
  7. import yaml
  8. from loguru import logger
  9. from tqdm import tqdm
  10. from fish_speech.datasets.protos.text_data_pb2 import Semantics, Sentence, TextData
  11. from fish_speech.datasets.protos.text_data_stream import pack_pb_stream
  12. from fish_speech.text import g2p
  13. from fish_speech.utils.file import AUDIO_EXTENSIONS, list_files, load_filelist
  14. def task_generator_yaml(config):
  15. with open(config, "r") as f:
  16. config = yaml.load(f, Loader=yaml.FullLoader)
  17. for row in config["datasets"]:
  18. root, source, languages, extension, parent_level = (
  19. row["root"],
  20. row["source"],
  21. row["languages"],
  22. row["extension"],
  23. row["group_parent_level"],
  24. )
  25. if isinstance(parent_level, int):
  26. parent_level = [parent_level]
  27. # Load the files
  28. files = list_files(root, AUDIO_EXTENSIONS, recursive=True, sort=True)
  29. grouped_files = defaultdict(list)
  30. for file in files:
  31. all_parents = []
  32. pointer = file
  33. while pointer.parent.name:
  34. all_parents.append(pointer.parent.name)
  35. pointer = pointer.parent
  36. ps = []
  37. for level in parent_level:
  38. ps.append(all_parents[level - 1])
  39. p = "-".join(ps)
  40. grouped_files[p].append(file)
  41. logger.info(f"Found {len(grouped_files)} groups in {root}")
  42. for name, subset in grouped_files.items():
  43. yield name, subset, source, languages, extension
  44. def task_generator_filelist(filelist):
  45. grouped_files = defaultdict(list)
  46. for filename, speaker, languages, text in load_filelist(filelist):
  47. grouped_files[speaker].append((Path(filename), text, languages))
  48. logger.info(f"Found {len(grouped_files)} groups in {filelist}")
  49. for speaker, values in grouped_files.items():
  50. yield speaker, values, "filelist", languages, None
  51. def run_task(task):
  52. name, subset, source, languages, extension = task
  53. # Parse the files
  54. sentences = []
  55. for file in subset:
  56. if isinstance(file, tuple):
  57. file, text, languages = file
  58. else:
  59. text = None
  60. np_file = file.with_suffix(".npy")
  61. if np_file.exists() is False:
  62. logger.warning(f"Can't find {np_file}")
  63. continue
  64. if text is None:
  65. txt_file = file.with_suffix(extension)
  66. if txt_file.exists() is False:
  67. logger.warning(f"Can't find {txt_file}")
  68. continue
  69. with open(txt_file, "r") as f:
  70. text = f.read().strip()
  71. # Simple cleaning: replace { xxx } and < xxx > with space
  72. text = re.sub(r"\{.*?\}", " ", text)
  73. text = re.sub(r"<.*?>", " ", text)
  74. text = re.sub(r"\s+", " ", text)
  75. try:
  76. phones = [v for _, v in g2p(text, order=languages)]
  77. semantics = np.load(np_file)
  78. except Exception as e:
  79. logger.error(f"Failed to parse {file}: {e}")
  80. continue
  81. if isinstance(semantics, np.ndarray):
  82. semantics = semantics.tolist()
  83. sentences.append(
  84. Sentence(
  85. text=text,
  86. phones=phones,
  87. semantics=[Semantics(values=s) for s in semantics],
  88. )
  89. )
  90. # Pack the sentences
  91. return pack_pb_stream(
  92. TextData(
  93. source=source,
  94. name=name,
  95. languages=languages,
  96. sentences=sentences,
  97. )
  98. )
  99. @click.command()
  100. @click.option(
  101. "--config", type=click.Path(), default="fish_speech/configs/data/finetune.yaml"
  102. )
  103. @click.option("--output", type=click.Path(), default="data/quantized-dataset-ft.protos")
  104. @click.option("--filelist", type=click.Path(), default=None)
  105. @click.option("--num-workers", type=int, default=16)
  106. def main(config, output, filelist, num_workers):
  107. dataset_fp = open(output, "wb")
  108. generator_fn = (
  109. task_generator_yaml(config)
  110. if filelist is None
  111. else task_generator_filelist(filelist)
  112. )
  113. with Pool(num_workers) as p:
  114. for result in tqdm(p.imap_unordered(run_task, generator_fn)):
  115. dataset_fp.write(result)
  116. dataset_fp.close()
  117. if __name__ == "__main__":
  118. main()