asahi417 commited on
Commit
92bbc46
1 Parent(s): d7a6a9b
Files changed (4) hide show
  1. fetch_dataset_s2s.py +0 -1
  2. fetch_dataset_s2t.py +46 -83
  3. format_text.py +0 -1
  4. main_s2t.sh +1 -1
fetch_dataset_s2s.py CHANGED
@@ -107,7 +107,6 @@ def cleanup(features, feature_file):
107
 
108
 
109
  def get_audio(dataframe: pd.DataFrame):
110
- resampler = {}
111
  features = {"line_no": int(dataframe.pop('line_no').values[0])}
112
  feature_file = p_join(cache_dir_feature, f'{features["line_no"]}.json')
113
  for side, df in dataframe.groupby("side"):
 
107
 
108
 
109
  def get_audio(dataframe: pd.DataFrame):
 
110
  features = {"line_no": int(dataframe.pop('line_no').values[0])}
111
  feature_file = p_join(cache_dir_feature, f'{features["line_no"]}.json')
112
  for side, df in dataframe.groupby("side"):
fetch_dataset_s2t.py CHANGED
@@ -19,18 +19,17 @@ from datasets import Dataset, Audio, DatasetDict
19
  audio_loader = Audio()
20
  # dataset config
21
  url_metadata_dict = {
22
- "enA-jaA": "https://dl.fbaipublicfiles.com/seamless/data/seamless_align_nov2023_extension/seamless.dataset.metadata.public.enA-jaA.tsv.gz",
23
  "enA-jpn": "https://dl.fbaipublicfiles.com/seamless/data/seamless.dataset.metadata.public.enA-jpn.withduration.tsv.gz"
24
  }
25
  direction_speech = os.getenv("DIRECTION_SPEECH", "enA")
26
  direction_text = os.getenv("DIRECTION_TEXT", "jpn")
27
- direction = os.getenv("DIRECTION", "enA-jpn")
28
- sides = set(direction.split("-"))
29
- cache_dir_audio = p_join("download", "audio", direction)
30
  cache_dir_feature = p_join("download", "feature", direction)
 
31
  os.makedirs(cache_dir_feature, exist_ok=True)
32
- for s in sides:
33
- os.makedirs(p_join(cache_dir_audio, s), exist_ok=True)
34
  # processor config
35
  n_pool = int(os.getenv("N_POOL", 1))
36
  wget_max_retry = os.getenv("MAX_RETRY", "2")
@@ -43,6 +42,11 @@ hf_dataset = f"seamless-align-{direction}"
43
  skip_download = bool(int(os.getenv("SKIP_DOWNLOAD", 0)))
44
  sampling_rate = 16000 # seamless-align aligns audio in 16kHz
45
 
 
 
 
 
 
46
 
47
  def wget(url: str, output_file: Optional[str] = None):
48
  os.makedirs(os.path.dirname(output_file), exist_ok=True)
@@ -96,52 +100,49 @@ def to_json_serializable(val):
96
  def cleanup(features, feature_file):
97
  if os.path.exists(feature_file):
98
  os.remove(feature_file)
99
- for _side in sides:
100
- for _unrelated_audio_file in glob(p_join(cache_dir_audio, _side, f"{features['line_no']}.*")):
101
- os.remove(_unrelated_audio_file)
102
  # create a dummy so that we can skip from next run
103
  with open(feature_file, "w") as f:
104
  json.dump({"dummy": "dummy"}, f)
105
 
106
 
107
  def get_audio(dataframe: pd.DataFrame):
108
- resampler = {}
109
  features = {"line_no": int(dataframe.pop('line_no').values[0])}
 
 
 
110
  feature_file = p_join(cache_dir_feature, f'{features["line_no"]}.json')
111
- for side, df in dataframe.groupby("side"):
112
- df.pop("side")
113
- features.update({f"{side}.{k}": to_json_serializable(v) for k, v in df.iloc[0].to_dict().items()})
114
- identifier = os.path.basename(features[f"{side}.url"]).split(".")[-1]
115
- features[f"{side}.path"] = str(p_join(cache_dir_audio, side, f"{features['line_no']}.{identifier}"))
116
- start, end = features[f"{side}.duration_start"], features[f"{side}.duration_end"]
117
- if not os.path.exists(features[f"{side}.path"]):
118
- print(f"WGET {features[f'{side}.url']}")
119
- flag = wget(features[f"{side}.url"], output_file=features[f"{side}.path"])
120
- if not flag:
121
- print("\n#### ERROR: wget failure ####\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  cleanup(features, feature_file)
123
  return None
124
- else:
125
- try:
126
- print(f"LOAD AUDIO FROM {features[f'{side}.path']}")
127
- wav, sr = sf.read(features[f"{side}.path"])
128
- print(f"wav shape:{wav.shape}")
129
- if wav.ndim > 1:
130
- wav = wav[:, 0]
131
- wav = wav[floor(start / sampling_rate * sr):ceil(end / sampling_rate * sr)]
132
- print(f"wav shape (after truncate):{wav.shape}")
133
- wav = wav[:int(end/sampling_rate * sr) + sr]
134
- print(f"SAVING: {features[f'{side}.path']}")
135
- sf.write(features[f"{side}.path"], wav, sr)
136
- # if sr != sampling_rate:
137
- # print(f"RESAMPLING: {wav.shape} length audio")
138
- # wav = librosa.resample(wav, orig_sr=sr, target_sr=sampling_rate)
139
- # sf.write(features[f"{side}.path"], wav[start:end], sampling_rate)
140
-
141
- except Exception as e:
142
- print(f"\n#### ERROR ####\n {e}")
143
- cleanup(features, feature_file)
144
- return None
145
  print(f"\n### SUCCESS! ###\n:{features['line_no']}")
146
  with open(feature_file, "w") as f:
147
  json.dump(features, f)
@@ -164,10 +165,7 @@ if __name__ == '__main__':
164
  )
165
  ]
166
  print(f"filtered unique lines: {len(inputs)}")
167
- if direction == "enA-jaA":
168
- inputs = [g for g in inputs if len(g["side"].unique()) == 2 and set(g["side"].unique()) == sides]
169
- print(f"removed side != 2: {len(inputs)}")
170
-
171
  if n_pool == 1:
172
  for g in tqdm(inputs, total=len(inputs)):
173
  line_no = get_audio(g)
@@ -187,46 +185,11 @@ if __name__ == '__main__':
187
  print(f"- dummy removed: {len(features)}")
188
  print(f"push {len(features)} records to hub")
189
  data_dict = {}
190
- for side in sides:
191
- data_dict.update({f"{side}.audio": [i.pop(f"{side}.path") for i in features]})
192
  data_dict.update({k: [i[k] for i in features] for k in features[0].keys()})
193
  audio_dataset = Dataset.from_dict(data_dict)
194
- for side in sides:
195
- audio_dataset = audio_dataset.cast_column(f"{side}.audio", Audio())
196
  DatasetDict({"train": audio_dataset}).push_to_hub(
197
  f"{hf_org}/{hf_dataset}",
198
  config_name=f"subset_{dataset_id}"
199
  )
200
-
201
-
202
- # DatasetDict({"train": audio_dataset.select(list(range(1000)))}).push_to_hub(
203
- # f"{hf_org}/{hf_dataset}",
204
- # config_name=f"subset_{dataset_id}"
205
- # )
206
-
207
- # # 2 panel
208
- # dataset_id = 75
209
- # DatasetDict({"train": audio_dataset.select(list(range(3000, len(audio_dataset))))}).push_to_hub(
210
- # f"{hf_org}/{hf_dataset}",
211
- # config_name=f"subset_{dataset_id}"
212
- # )
213
- #
214
- #
215
-
216
-
217
- # audio_dataset = audio_dataset.select(list(range(2500)))
218
- # dataset_to_push = DatasetDict({"train": audio_dataset})
219
- # repo_name = f"{hf_org}/{hf_dataset}"
220
- # dataset_to_push.push_to_hub(repo_name, config_name=f"subset_{dataset_id}")
221
- # dataset_to_push.push_to_hub(repo_name, config_name=f"subset_{dataset_id}", max_shard_size="2GiB")
222
- # dataset_to_push.push_to_hub(repo_name, config_name=f"subset_{dataset_id}", num_shards={"train": 1})
223
-
224
- # while True:
225
- # try:
226
- # dataset_to_push.push_to_hub(repo_name, config_name=f"subset_{dataset_id}")
227
- # break
228
- # except Exception:
229
- # print(f"FAILED: push_to_hub on {repo_name} failed. wait 60 sec and retry soon...")
230
- # time.sleep(60)
231
-
232
-
 
19
  audio_loader = Audio()
20
  # dataset config
21
  url_metadata_dict = {
 
22
  "enA-jpn": "https://dl.fbaipublicfiles.com/seamless/data/seamless.dataset.metadata.public.enA-jpn.withduration.tsv.gz"
23
  }
24
  direction_speech = os.getenv("DIRECTION_SPEECH", "enA")
25
  direction_text = os.getenv("DIRECTION_TEXT", "jpn")
26
+ direction = f"{direction_speech}-{direction_text}"
27
+ if direction not in url_metadata_dict:
28
+ url_metadata_dict[direction] = f"https://dl.fbaipublicfiles.com/seamless/data/seamless.dataset.metadata.public.{direction}.withduration.tsv.gz"
29
  cache_dir_feature = p_join("download", "feature", direction)
30
+ cache_dir_audio = p_join("download", "audio", direction)
31
  os.makedirs(cache_dir_feature, exist_ok=True)
32
+ os.makedirs(p_join(cache_dir_audio, direction_speech), exist_ok=True)
 
33
  # processor config
34
  n_pool = int(os.getenv("N_POOL", 1))
35
  wget_max_retry = os.getenv("MAX_RETRY", "2")
 
42
  skip_download = bool(int(os.getenv("SKIP_DOWNLOAD", 0)))
43
  sampling_rate = 16000 # seamless-align aligns audio in 16kHz
44
 
45
+ text_corpus = p_join("text_corpus", f"text.{direction_speech}-{direction_text}.json")
46
+ assert os.path.exists(text_corpus)
47
+ with open(text_corpus) as f:
48
+ line_no_to_text = json.load(f)
49
+
50
 
51
  def wget(url: str, output_file: Optional[str] = None):
52
  os.makedirs(os.path.dirname(output_file), exist_ok=True)
 
100
  def cleanup(features, feature_file):
101
  if os.path.exists(feature_file):
102
  os.remove(feature_file)
103
+ for _unrelated_audio_file in glob(p_join(cache_dir_audio, direction_speech, f"{features['line_no']}.*")):
104
+ os.remove(_unrelated_audio_file)
 
105
  # create a dummy so that we can skip from next run
106
  with open(feature_file, "w") as f:
107
  json.dump({"dummy": "dummy"}, f)
108
 
109
 
110
  def get_audio(dataframe: pd.DataFrame):
 
111
  features = {"line_no": int(dataframe.pop('line_no').values[0])}
112
+ if features["line_no"] not in text_corpus:
113
+ return None
114
+ features[f"{direction_text}.text"] = text_corpus[features["line_no"]]
115
  feature_file = p_join(cache_dir_feature, f'{features["line_no"]}.json')
116
+ features.update({f"{direction_speech}.{k}": to_json_serializable(v) for k, v in dataframe.iloc[0].to_dict().items()})
117
+ identifier = os.path.basename(features[f"{direction_speech}.url"]).split(".")[-1]
118
+ features[f"{direction_speech}.path"] = p_join(
119
+ cache_dir_audio, direction_speech, f"{features['line_no']}.{identifier}"
120
+ )
121
+ start, end = features[f"{direction_speech}.duration_start"], features[f"{direction_speech}.duration_end"]
122
+ if not os.path.exists(features[f"{direction_speech}.path"]):
123
+ print(f"WGET {features[f'{direction_speech}.url']}")
124
+ flag = wget(features[f"{direction_speech}.url"], output_file=features[f"{direction_speech}.path"])
125
+ if not flag:
126
+ print("\n#### ERROR: wget failure ####\n")
127
+ cleanup(features, feature_file)
128
+ return None
129
+ else:
130
+ try:
131
+ print(f"LOAD AUDIO FROM {features[f'{direction_speech}.path']}")
132
+ wav, sr = sf.read(features[f"{direction_speech}.path"])
133
+ print(f"wav shape:{wav.shape}")
134
+ if wav.ndim > 1:
135
+ wav = wav[:, 0]
136
+ wav = wav[floor(start / sampling_rate * sr):ceil(end / sampling_rate * sr)]
137
+ print(f"wav shape (after truncate):{wav.shape}")
138
+ wav = wav[:int(end/sampling_rate * sr) + sr]
139
+ print(f"SAVING: {features[f'{direction_speech}.path']}")
140
+ sf.write(features[f"{direction_speech}.path"], wav, sr)
141
+
142
+ except Exception as e:
143
+ print(f"\n#### ERROR ####\n {e}")
144
  cleanup(features, feature_file)
145
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  print(f"\n### SUCCESS! ###\n:{features['line_no']}")
147
  with open(feature_file, "w") as f:
148
  json.dump(features, f)
 
165
  )
166
  ]
167
  print(f"filtered unique lines: {len(inputs)}")
168
+ inputs = [g for g in inputs if len(g) == 1]
 
 
 
169
  if n_pool == 1:
170
  for g in tqdm(inputs, total=len(inputs)):
171
  line_no = get_audio(g)
 
185
  print(f"- dummy removed: {len(features)}")
186
  print(f"push {len(features)} records to hub")
187
  data_dict = {}
188
+ data_dict.update({f"{direction_speech}.audio": [i.pop(f"{direction_speech}.path") for i in features]})
 
189
  data_dict.update({k: [i[k] for i in features] for k in features[0].keys()})
190
  audio_dataset = Dataset.from_dict(data_dict)
191
+ audio_dataset = audio_dataset.cast_column(f"{direction_speech}.audio", Audio())
 
192
  DatasetDict({"train": audio_dataset}).push_to_hub(
193
  f"{hf_org}/{hf_dataset}",
194
  config_name=f"subset_{dataset_id}"
195
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
format_text.py CHANGED
@@ -7,7 +7,6 @@ import pandas as pd
7
 
8
  direction_speech = os.getenv("DIRECTION_SPEECH", "enA")
9
  direction_text = os.getenv("DIRECTION_TEXT", "jpn")
10
- direction = os.getenv("DIRECTION", "enA-jpn")
11
 
12
  df = pd.concat([
13
  pd.read_csv(i, quoting=csv.QUOTE_NONE, encoding='utf-8', sep='\t', header=None, on_bad_lines='skip')
 
7
 
8
  direction_speech = os.getenv("DIRECTION_SPEECH", "enA")
9
  direction_text = os.getenv("DIRECTION_TEXT", "jpn")
 
10
 
11
  df = pd.concat([
12
  pd.read_csv(i, quoting=csv.QUOTE_NONE, encoding='utf-8', sep='\t', header=None, on_bad_lines='skip')
main_s2t.sh CHANGED
@@ -47,7 +47,7 @@ done
47
  # text
48
  export DIRECTION_SPEECH="enA"
49
  export DIRECTION_TEXT="jpn"
50
- export CHUNK_SIZE=10
51
  python download_s2t_metadata.py
52
  for i in $(seq 1 ${CHUNK_SIZE});
53
  do
 
47
  # text
48
  export DIRECTION_SPEECH="enA"
49
  export DIRECTION_TEXT="jpn"
50
+ export CHUNK_SIZE=20
51
  python download_s2t_metadata.py
52
  for i in $(seq 1 ${CHUNK_SIZE});
53
  do