0416_10w_from_train90 / copy_audio_and_rewrite_jsonl.py
Prummn's picture
Add files using upload-large-folder tool
cb71ff8 verified
#!/usr/bin/env python3
import argparse
import json
import shutil
from pathlib import Path
def build_target_path(audio_path: Path, audio_root: Path) -> Path:
if audio_path.is_absolute():
relative_path = audio_path.relative_to("/")
else:
relative_path = audio_path
return audio_root / relative_path
def copy_audio(audio_path: Path, audio_root: Path, copied: dict[str, Path]) -> Path:
key = str(audio_path)
if key in copied:
return copied[key]
if not audio_path.exists():
raise FileNotFoundError(f"Audio file not found: {audio_path}")
target_path = build_target_path(audio_path, audio_root)
target_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(audio_path, target_path)
copied[key] = target_path
return target_path
def rewrite_record(item: dict, audio_root: Path, copied: dict[str, Path], input_path: Path, line_no: int) -> int:
rewritten = 0
if "audio" in item:
audio_path = Path(item["audio"])
item["audio"] = str(copy_audio(audio_path, audio_root, copied))
rewritten += 1
if "audios" in item:
audios = item["audios"]
if not isinstance(audios, list):
raise ValueError(f"{input_path}:{line_no} field 'audios' is not a list")
item["audios"] = [str(copy_audio(Path(audio), audio_root, copied)) for audio in audios]
rewritten += len(item["audios"])
if rewritten == 0:
raise ValueError(f"{input_path}:{line_no} has neither 'audio' nor 'audios'")
return rewritten
def process_jsonl(input_path: Path, output_path: Path, audio_root: Path) -> tuple[int, int, int]:
copied: dict[str, Path] = {}
line_count = 0
audio_refs = 0
with input_path.open("r", encoding="utf-8") as src, output_path.open("w", encoding="utf-8") as dst:
for line_no, line in enumerate(src, start=1):
if not line.strip():
continue
item = json.loads(line)
audio_refs += rewrite_record(item, audio_root, copied, input_path, line_no)
dst.write(json.dumps(item, ensure_ascii=False) + "\n")
line_count += 1
return line_count, audio_refs, len(copied)
def main() -> None:
parser = argparse.ArgumentParser(description="Copy referenced audio files and rewrite JSONL audio paths.")
parser.add_argument("--input", required=True, help="Input JSONL file.")
parser.add_argument("--output", required=True, help="Output rewritten JSONL file.")
parser.add_argument("--audio-root", required=True, help="Destination root for copied audio files.")
args = parser.parse_args()
input_path = Path(args.input).resolve()
output_path = Path(args.output).resolve()
audio_root = Path(args.audio_root).resolve()
output_path.parent.mkdir(parents=True, exist_ok=True)
audio_root.mkdir(parents=True, exist_ok=True)
line_count, audio_refs, unique_audio_count = process_jsonl(
input_path=input_path,
output_path=output_path,
audio_root=audio_root,
)
print(
f"Processed {line_count} lines, rewrote {audio_refs} audio references, "
f"copied {unique_audio_count} unique audio files"
)
if __name__ == "__main__":
main()