Skip to content

Commit 7e499df

Browse files
committed
ljspeech/hificaptain from shivammehta25#99
1 parent 0735e65 commit 7e499df

File tree

7 files changed

+301
-3
lines changed

7 files changed

+301
-3
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,4 @@ generator_v1
161161
g_02500000
162162
gradio_cached_examples/
163163
synth_output/
164+
/data

configs/data/hi-fi_en-US_female.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ defaults:
55
# Dataset URL: https://ast-astrec.nict.go.jp/en/release/hi-fi-captain/
66
_target_: matcha.data.text_mel_datamodule.TextMelDataModule
77
name: hi-fi_en-US_female
8-
train_filelist_path: data/filelists/hi-fi-captain-en-us-female_train.txt
9-
valid_filelist_path: data/filelists/hi-fi-captain-en-us-female_val.txt
8+
train_filelist_path: data/hi-fi_en-US_female/train.txt
9+
valid_filelist_path: data/hi-fi_en-US_female/val.txt
1010
batch_size: 32
1111
cleaners: [english_cleaners_piper]
1212
data_statistics: # Computed for this dataset

data

Lines changed: 0 additions & 1 deletion
This file was deleted.

matcha/utils/data/__init__.py

Whitespace-only changes.

matcha/utils/data/hificaptain.py

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
#!/usr/bin/env python
2+
import argparse
3+
import os
4+
import sys
5+
import tempfile
6+
from pathlib import Path
7+
8+
import torchaudio
9+
from torch.hub import download_url_to_file
10+
from tqdm import tqdm
11+
12+
from matcha.utils.data.utils import _extract_zip
13+
14+
URLS = {
15+
"en-US": {
16+
"female": "https://ast-astrec.nict.go.jp/release/hi-fi-captain/hfc_en-US_F.zip",
17+
"male": "https://ast-astrec.nict.go.jp/release/hi-fi-captain/hfc_en-US_M.zip",
18+
},
19+
"ja-JP": {
20+
"female": "https://ast-astrec.nict.go.jp/release/hi-fi-captain/hfc_ja-JP_F.zip",
21+
"male": "https://ast-astrec.nict.go.jp/release/hi-fi-captain/hfc_ja-JP_M.zip",
22+
},
23+
}
24+
25+
INFO_PAGE = "https://ast-astrec.nict.go.jp/en/release/hi-fi-captain/"
26+
27+
# On their website they say "We NICT open-sourced Hi-Fi-CAPTAIN",
28+
# but they use this very-much-not-open-source licence.
29+
# Dunno if this is open washing or stupidity.
30+
LICENCE = "CC BY-NC-SA 4.0"
31+
32+
# I'd normally put the citation here. It's on their website.
33+
# Boo to non-open-source stuff.
34+
35+
36+
def get_args():
37+
parser = argparse.ArgumentParser()
38+
39+
parser.add_argument("-s", "--save-dir", type=str, default=None, help="Place to store the downloaded zip files")
40+
parser.add_argument(
41+
"-r",
42+
"--skip-resampling",
43+
action="store_true",
44+
default=False,
45+
help="Skip resampling the data (from 48 to 22.05)",
46+
)
47+
parser.add_argument(
48+
"-l", "--language", type=str, choices=["en-US", "ja-JP"], default="en-US", help="The language to download"
49+
)
50+
parser.add_argument(
51+
"-g",
52+
"--gender",
53+
type=str,
54+
choices=["male", "female"],
55+
default="female",
56+
help="The gender of the speaker to download",
57+
)
58+
parser.add_argument(
59+
"-o",
60+
"--output_dir",
61+
type=str,
62+
default="data",
63+
help="Place to store the converted data. Top-level only, the subdirectory will be created",
64+
)
65+
66+
return parser.parse_args()
67+
68+
69+
def process_text(infile, outpath: Path):
70+
outmode = "w"
71+
if infile.endswith("dev.txt"):
72+
outfile = outpath / "valid.txt"
73+
elif infile.endswith("eval.txt"):
74+
outfile = outpath / "test.txt"
75+
else:
76+
outfile = outpath / "train.txt"
77+
if outfile.exists():
78+
outmode = "a"
79+
with (
80+
open(infile, encoding="utf-8") as inf,
81+
open(outfile, outmode, encoding="utf-8") as of,
82+
):
83+
for line in inf.readlines():
84+
line = line.strip()
85+
fileid, rest = line.split(" ", maxsplit=1)
86+
outfile = str(outpath / f"{fileid}.wav")
87+
of.write(f"{outfile}|{rest}\n")
88+
89+
90+
def process_files(zipfile, outpath, resample=True):
91+
with tempfile.TemporaryDirectory() as tmpdirname:
92+
for filename in tqdm(_extract_zip(zipfile, tmpdirname)):
93+
if not filename.startswith(tmpdirname):
94+
filename = os.path.join(tmpdirname, filename)
95+
if filename.endswith(".txt"):
96+
process_text(filename, outpath)
97+
elif filename.endswith(".wav"):
98+
filepart = filename.rsplit("/", maxsplit=1)[-1]
99+
outfile = str(outpath / filepart)
100+
arr, sr = torchaudio.load(filename)
101+
if resample:
102+
arr = torchaudio.functional.resample(arr, orig_freq=sr, new_freq=22050)
103+
torchaudio.save(outfile, arr, 22050)
104+
else:
105+
continue
106+
107+
108+
def main():
109+
args = get_args()
110+
111+
save_dir = None
112+
if args.save_dir:
113+
save_dir = Path(args.save_dir)
114+
if not save_dir.is_dir():
115+
save_dir.mkdir()
116+
117+
if not args.output_dir:
118+
print("output directory not specified, exiting")
119+
sys.exit(1)
120+
121+
URL = URLS[args.language][args.gender]
122+
dirname = f"hi-fi_{args.language}_{args.gender}"
123+
124+
outbasepath = Path(args.output_dir)
125+
if not outbasepath.is_dir():
126+
outbasepath.mkdir()
127+
outpath = outbasepath / dirname
128+
if not outpath.is_dir():
129+
outpath.mkdir()
130+
131+
resample = True
132+
if args.skip_resampling:
133+
resample = False
134+
135+
if save_dir:
136+
zipname = URL.rsplit("/", maxsplit=1)[-1]
137+
zipfile = save_dir / zipname
138+
if not zipfile.exists():
139+
download_url_to_file(URL, zipfile, progress=True)
140+
process_files(zipfile, outpath, resample)
141+
else:
142+
with tempfile.NamedTemporaryFile(suffix=".zip", delete=True) as zf:
143+
download_url_to_file(URL, zf.name, progress=True)
144+
process_files(zf.name, outpath, resample)
145+
146+
147+
if __name__ == "__main__":
148+
main()

matcha/utils/data/ljspeech.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#!/usr/bin/env python
2+
import argparse
3+
import random
4+
import tempfile
5+
from pathlib import Path
6+
7+
from torch.hub import download_url_to_file
8+
9+
from matcha.utils.data.utils import _extract_tar
10+
11+
URL = "https://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2"
12+
13+
INFO_PAGE = "https://keithito.com/LJ-Speech-Dataset/"
14+
15+
LICENCE = "Public domain (LibriVox copyright disclaimer)"
16+
17+
CITATION = """
18+
@misc{ljspeech17,
19+
author = {Keith Ito and Linda Johnson},
20+
title = {The LJ Speech Dataset},
21+
howpublished = {\\url{https://keithito.com/LJ-Speech-Dataset/}},
22+
year = 2017
23+
}
24+
"""
25+
26+
27+
def decision():
28+
return random.random() < 0.98
29+
30+
31+
def get_args():
32+
parser = argparse.ArgumentParser()
33+
34+
parser.add_argument("-s", "--save-dir", type=str, default=None, help="Place to store the downloaded zip files")
35+
parser.add_argument(
36+
"output_dir",
37+
type=str,
38+
nargs="?",
39+
default="data",
40+
help="Place to store the converted data (subdirectory LJSpeech-1.1 will be created)",
41+
)
42+
43+
return parser.parse_args()
44+
45+
46+
def process_csv(ljpath: Path):
47+
if (ljpath / "metadata.csv").exists():
48+
basepath = ljpath
49+
elif (ljpath / "LJSpeech-1.1" / "metadata.csv").exists():
50+
basepath = ljpath / "LJSpeech-1.1"
51+
csvpath = basepath / "metadata.csv"
52+
wavpath = basepath / "wavs"
53+
54+
with (
55+
open(csvpath, encoding="utf-8") as csvf,
56+
open(basepath / "train.txt", "w", encoding="utf-8") as tf,
57+
open(basepath / "val.txt", "w", encoding="utf-8") as vf,
58+
):
59+
for line in csvf.readlines():
60+
line = line.strip()
61+
parts = line.split("|")
62+
wavfile = str(wavpath / f"{parts[0]}.wav")
63+
if decision():
64+
tf.write(f"{wavfile}|{parts[1]}\n")
65+
else:
66+
vf.write(f"{wavfile}|{parts[1]}\n")
67+
68+
69+
def main():
70+
args = get_args()
71+
72+
save_dir = None
73+
if args.save_dir:
74+
save_dir = Path(args.save_dir)
75+
if not save_dir.is_dir():
76+
save_dir.mkdir()
77+
78+
outpath = Path(args.output_dir)
79+
if not outpath.is_dir():
80+
outpath.mkdir()
81+
82+
if save_dir:
83+
tarname = URL.rsplit("/", maxsplit=1)[-1]
84+
tarfile = save_dir / tarname
85+
if not tarfile.exists():
86+
download_url_to_file(URL, str(tarfile), progress=True)
87+
_extract_tar(tarfile, outpath)
88+
process_csv(outpath)
89+
else:
90+
with tempfile.NamedTemporaryFile(suffix=".tar.bz2", delete=True) as zf:
91+
download_url_to_file(URL, zf.name, progress=True)
92+
_extract_tar(zf.name, outpath)
93+
process_csv(outpath)
94+
95+
96+
if __name__ == "__main__":
97+
main()

matcha/utils/data/utils.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# taken from https://github.com/pytorch/audio/blob/main/src/torchaudio/datasets/utils.py
2+
# Copyright (c) 2017 Facebook Inc. (Soumith Chintala)
3+
# Licence: BSD 2-Clause
4+
# pylint: disable=C0123
5+
6+
import logging
7+
import os
8+
import tarfile
9+
import zipfile
10+
from pathlib import Path
11+
from typing import Any, List, Optional, Union
12+
13+
_LG = logging.getLogger(__name__)
14+
15+
16+
def _extract_tar(from_path: Union[str, Path], to_path: Optional[str] = None, overwrite: bool = False) -> List[str]:
17+
if type(from_path) is Path:
18+
from_path = str(Path)
19+
20+
if to_path is None:
21+
to_path = os.path.dirname(from_path)
22+
23+
with tarfile.open(from_path, "r") as tar:
24+
files = []
25+
for file_ in tar: # type: Any
26+
file_path = os.path.join(to_path, file_.name)
27+
if file_.isfile():
28+
files.append(file_path)
29+
if os.path.exists(file_path):
30+
_LG.info("%s already extracted.", file_path)
31+
if not overwrite:
32+
continue
33+
tar.extract(file_, to_path)
34+
return files
35+
36+
37+
def _extract_zip(from_path: Union[str, Path], to_path: Optional[str] = None, overwrite: bool = False) -> List[str]:
38+
if type(from_path) is Path:
39+
from_path = str(Path)
40+
41+
if to_path is None:
42+
to_path = os.path.dirname(from_path)
43+
44+
with zipfile.ZipFile(from_path, "r") as zfile:
45+
files = zfile.namelist()
46+
for file_ in files:
47+
file_path = os.path.join(to_path, file_)
48+
if os.path.exists(file_path):
49+
_LG.info("%s already extracted.", file_path)
50+
if not overwrite:
51+
continue
52+
zfile.extract(file_, to_path)
53+
return files

0 commit comments

Comments
 (0)