Datasets:
Size:
10K<n<100K
ArXiv:
File size: 14,136 Bytes
b5824c6 97a925f b5824c6 97a925f b5824c6 97a925f b5824c6 a4d6d07 b5824c6 97a925f b5824c6 97a925f b5824c6 97a925f b5824c6 97a925f b5824c6 97a925f b5824c6 97a925f b5824c6 96a54e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# This scripts generates a self-contained dataset relase that can be uploaded to the HF-Hub or distributed as an archive file
# Apart from pip-installable packages this file should be self-contained for reproducibility
import json
import re
import shutil
from pathlib import Path
import jinja2
import pandas as pd
import uroman as ur
from unidecode import unidecode
from lnn.utils import load_audio
from tqdm.auto import tqdm
# Define some variables
NAME = "SpeechTaxi"
VERSION = "0.0.1"
HOMEPAGE = "github.com/LennartKeller"
CITATION = "TODO"
DESCRIPTION = "TODO"
SAVE_DIR = Path("/hdd/lennart/datasets")
# Define some arguments and 'constants'
# TODO think about ways to avoid having to do this
REWRITE_PATHS = (
"/Volumes/SanDiskData/bible-audio-scraper-data/processed",
"/hdd/lennart/bible-audio-scraper-data/processed",
)
REWRITE_MASS_PATHS = ("/Volumes/SanDiskData/", "/hdd/lennart/")
ALIGNED_TABLES_DIR = Path("aligned_tables")
INCLUDE_MASS_LANGUAGES = True
MASS_LANGUAGES = ("eng", "rus", "spa", "ron", "eus", "fra")
SKIP_LANGUAGES = ("ron", "eus", "spa", "hau", "bdv", "nep", "ben")
SCRIPT_TEMPLATE = Path("SpeechTaxi.py.jinja")
def rewrite_path(p: str | Path) -> str | Path:
if REWRITE_PATHS:
if isinstance(p, str):
p = p.replace(*REWRITE_PATHS)
p = Path(str(p).replace(*REWRITE_PATHS))
return p
def rewrite_mass_path(p: str | Path) -> str | Path:
if REWRITE_MASS_PATHS:
if isinstance(p, str):
p = p.replace(*REWRITE_MASS_PATHS)
p = Path(str(p).replace(*REWRITE_MASS_PATHS))
return p
# Define a 'filter_instances' function that holds the selection logic
# for selecting instances that shold end up in the final dataset
def filter_instances(
df: pd.DataFrame, table_file_path: str | Path = None
) -> pd.DataFrame:
df = df.copy() # Avoid warnings
# Some mass tables do not have them...
if "alignment_score" not in df.columns:
df["alignment_score"] = 1.0
df = df.query("score == 1.0 and alignment_score >= 0.8")
return df
def render_script_template(**kwargs):
templateLoader = jinja2.FileSystemLoader(
searchpath=SCRIPT_TEMPLATE.parent.as_posix()
)
templateEnv = jinja2.Environment(loader=templateLoader)
template = templateEnv.get_template(SCRIPT_TEMPLATE.name)
return template.render(**kwargs)
# BEGIN LIB:
# Define libs that are used to create the dataset.
# Do not change stuff here unless you really want to.
BOOK_ABBREVIATIONS = {
"Matthew": "MAT",
"Mark": "MRK",
"Luke": "LUK",
"John": "JHN",
"Acts": "ACT",
"Romans": "ROM",
"Corinthians": "COR", # Can be used as "1COR" or "2COR" based on context
"Galatians": "GAL",
"Ephesians": "EPH",
"Philippians": "PHP",
"Colossians": "COL",
"Thess": "THS", # Can be used as "1THS" or "2THS" based on context
"Timothy": "TIM", # Can be used as "1TIM" or "2TIM" based on context
"Titus": "TIT",
"Philemon": "PHM",
"Hebrews": "HEB",
"James": "JAS",
"Peter": "PET", # Can be used as "1PET" or "2PET" based on context
"Jude": "JUD",
"Revelation": "REV",
}
BOOK_ABBREVIATIONS_FR = {
"Matthieu": "MAT",
"Marc": "MRK",
"Luc": "LUC",
"Jean": "JHN",
"Actes": "ACT",
"Romains": "ROM",
"Corinthiens": "COR", # Can be used as "1COR" or "2COR" based on context
"Galates": "GAL",
"Éphésiens": "EPH",
"Philippiens": "PHP",
"Colossiens": "COL",
"Thessaloniciens": "THS", # Can be used as "1THS" or "2THS" based on context
"Timothée": "TIM", # Can be used as "1TIM" or "2TIM" based on context
"Tite": "TIT",
"Philémon": "PHM",
"Hébreux": "HEB",
"Jacques": "JAC",
"Pierre": "PIE", # Can be used as "1PIE" or "2PIE" based on context
"Jude": "JUD",
"Apocalypse": "APO",
}
BOOK_ABBREVIATIONS |= {
unidecode(k): unidecode(v) for k, v in BOOK_ABBREVIATIONS_FR.items()
}
MASS_LANGUAGE_IDS = [
"FRNTLSN2DA",
"ENGESVN1DA",
"RUSS76N2DA",
"SPNBDAN1DA",
"EUSEABN1DA",
"RONDCVN1DA",
]
def parse_reference_from_mass_file(filename: str | Path, language_id: str = ""):
filename = Path(filename).name
book_num, rest = filename.split("___", 1)
book_num = int(book_num.replace("B", ""))
chapter_num, rest = rest.split("_", 1)
chapter_num = int(chapter_num)
if language_id:
rest = rest.replace(language_id, "")
else:
# rest = "_".join(p for p in rest.split("_") if not p.endswith("DA"))
for language_id in MASS_LANGUAGE_IDS:
rest = rest.replace(language_id, "")
rest = rest.replace("_one_channel.wav", "")
book_ref, verse_ref = re.split(r"_+", rest, 1)
book_num = ""
if book_ref[0].isdigit():
book_num = book_ref[0]
book_ref = book_ref[1:]
try:
book_ref = BOOK_ABBREVIATIONS[book_ref]
except KeyError as e:
print(book_ref)
print(filename)
raise e
if book_num:
book_ref = book_num + book_ref
verse_num = int(verse_ref.split("_")[-1])
complete_ref = f"{book_ref}.{chapter_num}.{verse_num}"
return complete_ref
def copy_self(dst: str | Path) -> None:
dst = Path(dst)
path_to_self = Path(__file__)
dst = dst / path_to_self.name
dst.write_text(path_to_self.read_text())
def copy_bible_scrape_audio(file: str | Path, root: str | Path) -> Path:
file, root = map(Path, (file, root))
copied_file = (
root / file.parts[-4] / file.parts[-3] / file.parts[-2] / file.parts[-1]
)
copied_file.parent.mkdir(exist_ok=True, parents=True)
shutil.copy(file, copied_file)
return copied_file
def copy_mass_audio(file: str | Path, root: str | Path) -> Path:
file, root = map(Path, (file, root))
copied_file = root / file.parts[-2] / file.parts[-1]
copied_file.parent.mkdir(exist_ok=True, parents=True)
shutil.copy(file, copied_file)
return copied_file
uroman = ur.Uroman()
def read_mass_instance(audio_file: str | Path) -> dict:
audio_file = Path(audio_file)
audio_file = rewrite_path(audio_file)
if not audio_file.exists():
raise ValueError(f"Audio file {audio_file} does not exist.")
verse_ref = parse_reference_from_mass_file(audio_file)
transcription_file = (
audio_file.parent / f"{audio_file.stem.removesuffix('_one_channel')}.txt"
)
transcription = transcription_file.read_text()
machine_generated_transcriptions = {}
machine_generated_transcription_files = audio_file.parent.glob(
f"{audio_file.stem}-*-transcript.txt"
)
for machine_generated_transcription_file in machine_generated_transcription_files:
# Get transcription key
key = machine_generated_transcription_file.stem.split("_one_channel-")[-1]
key = key.removesuffix("-transcript")
# print(audio_file, "|", machine_generated_transcription_file, "|", key)
machine_generated_transcriptions[f"transription_{key}"] = (
machine_generated_transcription_file.read_text()
)
data = {
"verse_ref": verse_ref,
"transcription": transcription,
"transcription_romanized": uroman.romanize_string(transcription),
} | machine_generated_transcriptions
return data
def read_bible_scrape_instance(audio_file: str | Path) -> dict:
"""
Given the file to a verse this function loads all available metadata from disk.
And ensure that the audio files exists...
"""
audio_file = Path(audio_file)
audio_file = rewrite_path(audio_file)
if not audio_file.exists():
raise ValueError(f"Audio file {audio_file} does not exist.")
# 1. Load all avaiable transcriptions
transcription_file = audio_file.with_suffix(".json")
transcriptions = json.loads(transcription_file.read_text())
# Filter to only texts
try:
verse_ref = transcriptions.pop("verse_ref")
transcriptions = {
bible_id: content["content"] for bible_id, content in transcriptions.items()
}
except Exception as e:
print(transcriptions)
print(e)
# 2. Look for audio alignement scores
alignment_file = audio_file.parent / f"{audio_file.stem}-alignment-scores.json"
alignment_scores = json.loads(alignment_file.read_text())
# 3. Select the transcription with best audio alignment score
best_bible_id = max(alignment_scores.items(), key=lambda x: x[-1])[0]
transcription = transcriptions[str(best_bible_id)]
# 4. Load all available machine generated transcriptions
machine_generated_transcriptions = {}
machine_generated_transcription_files = audio_file.parent.glob(
f"{audio_file.stem}-*.txt"
)
for machine_generated_transcription_file in machine_generated_transcription_files:
# Get transcription key
key = (
machine_generated_transcription_file.stem.removeprefix(audio_file.stem)
.removesuffix("-transcript")
.strip("-")
)
# print(audio_file, "|", machine_generated_transcription_file, "|", key)
machine_generated_transcriptions[f"transription_{key}"] = (
machine_generated_transcription_file.read_text()
)
data = {
"verse_ref": verse_ref,
"transcription": transcription,
"transcription_romanized": uroman.romanize_string(transcription),
} | machine_generated_transcriptions
return data
def is_audio_valid(audio_path: str | Path):
audio_path = Path(audio_path)
if not audio_path.exists():
return False
try:
wv, sr = load_audio(audio_path, return_tensor="torch")
wv = wv[0].reshape(-1)
except Exception:
return False
# We need *at least* one second of audio
return wv.numel() >= sr
# Main logic
if __name__ == "__main__":
dataset_root = SAVE_DIR / NAME
# Setup the output directory (-ies)
if dataset_root.exists():
raise ValueError(
f"Dataset-Root-Directory {dataset_root} already exists, please remove manually to continue!"
)
print(f"Creating dataset release in {dataset_root}")
dataset_root.mkdir(parents=True)
data_dir = dataset_root / "data"
data_dir.mkdir(parents=True)
table_dir = dataset_root / "tables"
table_dir.mkdir(parents=True)
# Copy this script to dataset dir for reproducibility
copy_self(dataset_root)
# Create language datasets and copy the data to the dataset directory
# Load and filter alignment tables
language_tables = sorted(
[f for f in ALIGNED_TABLES_DIR.glob("*.tsv") if f.stem not in SKIP_LANGUAGES]
)
# Write code file
success_languages = []
pbar = tqdm(language_tables, desc="Creating dataset...")
invalid_counter = 0
for alignment_table in pbar:
df = pd.read_table(alignment_table)
try:
df = filter_instances(df, alignment_table)
except Exception as e:
print(alignment_table)
raise e
if not len(df):
continue
success_languages.append(alignment_table)
final_table_data = []
for _, row in df.iterrows():
if alignment_table.stem not in MASS_LANGUAGES:
audio_file = rewrite_path(Path(row["audio_path"]))
if not is_audio_valid(audio_file):
invalid_counter += 1
continue
copied_audio_file = copy_bible_scrape_audio(audio_file, root=data_dir)
english_text = row["en_text"]
try:
data = read_bible_scrape_instance(audio_file)
except Exception as e:
print("Error reading file", audio_file)
print(e)
print("_"*30)
continue
# Files that can't be read have zero alignment scores anyways so in most cases this isn't an issue
data = (
{"verse_ref": data.pop("verse_ref")}
| {"text_en": english_text}
| {"split": row["split"], "label": row["label"]}
| data
| {"audio": copied_audio_file.relative_to(data_dir).as_posix()}
)
final_table_data.append(data)
elif INCLUDE_MASS_LANGUAGES:
audio_file = rewrite_mass_path(Path(row["audio_path"]))
if not is_audio_valid(audio_file):
invalid_counter += 1
continue
copied_audio_file = copy_mass_audio(audio_file, root=data_dir)
try:
data = read_mass_instance(audio_file)
except Exception as e:
print("Error reading file", audio_file)
print(e)
print("_"*30)
continue
# Files that can't be read have zero alignment scores anyways so in most cases this isn't an issue
data = data | {
"split": row["split"],
"label": row["label"],
"text_en": row["en_text"],
"audio": copied_audio_file.relative_to(data_dir).as_posix(),
}
final_table_data.append(data)
pbar.set_description(f"{str(alignment_table)} | Total invalid: {invalid_counter}")
final_table = pd.DataFrame.from_records(final_table_data)
final_table.to_csv(table_dir / alignment_table.name, index=False, sep="\t")
# Now render dataset loading script and write to dataset dir
code_file = dataset_root / f"{NAME}.py"
code_file_content = render_script_template(
languages=[f.stem for f in success_languages],
version=VERSION,
homepage=HOMEPAGE,
citation=CITATION,
)
code_file.write_text(code_file_content)
# Zip data and tables dir
shutil.make_archive(dataset_root / "tables", "zip", table_dir)
shutil.rmtree(table_dir)
shutil.make_archive(dataset_root / "data", "zip", data_dir)
shutil.rmtree(data_dir)
|