File size: 2,184 Bytes
79b2661 | 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 | """Read local and Hub audio manifests with the same column and delimiter rules."""
import csv
import re
from itertools import chain
from pathlib import Path
AUDIO_COLUMNS = ("audio_file", "audio", "audio_filename", "path", "file", "wav")
TEXT_COLUMNS = ("transcript", "text", "transcription", "normalized_text")
def read_manifest(path, *, language=None, speaker=None):
with Path(path).open(encoding="utf-8-sig", newline="") as stream:
first = next((line for line in stream if line.strip()), "")
stream.seek(0)
# The first separator follows the audio path in headerless manifests.
# CSV quoting keeps separators inside a transcript or filename intact.
separator = re.match(r'^(?:"(?:[^"]|"")*"|[^|,\t]*)([|,\t])', first)
delimiter = separator.group(1) if separator else "|"
rows = (row for row in csv.reader(stream, delimiter=delimiter) if row and any(row))
first_row = next(rows, None)
if first_row is None:
return
names = [col.strip().lower() for col in first_row]
def column(options):
return next((names.index(name) for name in options if name in names), None)
audio_col, text_col = column(AUDIO_COLUMNS), column(TEXT_COLUMNS)
if audio_col is None or text_col is None:
rows = chain([first_row], rows)
audio_col, text_col = 0, 1
names = []
spk_col, lang_col = column(("speaker", "speaker_id")), column(("language", "lang"))
if (speaker and spk_col is None) or (language and lang_col is None):
raise ValueError("Requested speaker or language filter has no matching manifest column.")
for row in rows:
def field(index):
return row[index].strip() if index is not None and index < len(row) else ""
audio, text = field(audio_col), field(text_col)
spk, lang = field(spk_col), field(lang_col)
if audio and text and (not speaker or speaker == spk) and (not language or language == lang):
yield {"audio_path": audio, "text": text, "speaker": spk, "language": lang}
|