SpeechTaxi / create_release.py
Lennart Keller
add zipped data
96a54e3
raw
history blame
13.1 kB
# 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
# 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
# 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]
)[:3]
# Write code file
success_languages = []
for alignment_table in language_tables:
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"]))
copied_audio_file = copy_bible_scrape_audio(audio_file, root=data_dir)
english_text = row["en_text"]
data = read_bible_scrape_instance(audio_file)
# copied_audio = copy_file(audio_file, data_dir)
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"]))
copied_audio_file = copy_mass_audio(audio_file, root=data_dir)
data = read_mass_instance(audio_file)
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)
fina_table = pd.DataFrame.from_records(final_table_data)
# Reorder columns
# cols = [
# "verse_ref",
# "text_en",
# "split",
# "label",
# "transcription",
# "transcription_romanized",
# "transription_mms-zeroshot-300m",
# "transription_whisper-large-v3",
# "transription_mms-1b-all",
# "audio",
# ]
# fina_table = fina_table[cols]
fina_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)