SignVerse-2M / scripts /pipeline01_backfill_subtitles.py
ccbi's picture
Duplicate from SignerX/SignVerse-2M
0c2db8c
Raw
History Blame Contribute Delete
11.3 kB
#!/usr/bin/env python3
import argparse
import json
import sys
import time
from pathlib import Path
from typing import Dict, List, Sequence, Tuple
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from scripts.pipeline01_download_video_fix_caption import (
DEFAULT_DATASET_DIR,
DEFAULT_OUTPUT_METADATA_CSV,
DEFAULT_SOURCE_METADATA_CSV,
DEFAULT_STATUS_JOURNAL_PATH,
DEFAULT_YT_DLP_EXTRACTOR_ARGS,
DEFAULT_COLUMNS,
DEFAULT_RAW_METADATA_DIR,
build_subtitle_json_payload,
fetch_metadata,
filter_caption_languages,
load_subtitle_payloads,
lock_path_for_manifest,
merge_row_values,
persist_raw_metadata,
read_state_manifest,
repo_relative_or_absolute,
sanitize_cookie_file,
select_english_subtitle,
subtitle_dir_for_video,
update_video_stats_best_effort,
with_manifest_lock,
write_manifest,
write_subtitle_json,
download_subtitles,
)
EXTRA_COLUMNS = [
"subtitle_texts_json",
"subtitle_en",
"subtitle_json_path",
"raw_caption_dir",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Backfill subtitles only for SignVerse videos, without downloading video payloads."
)
parser.add_argument("--source-metadata-csv", type=Path, default=DEFAULT_SOURCE_METADATA_CSV)
parser.add_argument("--output-metadata-csv", type=Path, default=DEFAULT_OUTPUT_METADATA_CSV)
parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)
parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)
parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)
parser.add_argument("--stats-npz", type=Path, default=REPO_ROOT / 'stats.npz')
parser.add_argument("--limit", type=int, default=None)
parser.add_argument("--video-ids", nargs="*", default=None)
parser.add_argument("--force-metadata", action="store_true")
parser.add_argument("--force-subtitles", action="store_true")
parser.add_argument("--sleep-seconds", type=float, default=0.0)
parser.add_argument("--cookies", type=Path, default=None)
parser.add_argument("--cookies-from-browser", default=None)
parser.add_argument("--extractor-args", default=DEFAULT_YT_DLP_EXTRACTOR_ARGS)
parser.add_argument("--csv-lock-path", type=Path, default=None)
return parser.parse_args()
def ordered_fieldnames(fieldnames: Sequence[str]) -> List[str]:
ordered: List[str] = []
for column in list(DEFAULT_COLUMNS) + EXTRA_COLUMNS + list(fieldnames):
if column and column not in ordered:
ordered.append(column)
return ordered
def row_needs_subtitle_backfill(row: Dict[str, str], args: argparse.Namespace) -> bool:
if args.force_metadata or args.force_subtitles:
return True
return (row.get("subtitle_status") or "").strip() != "ok"
def selected_rows(rows: Sequence[Dict[str, str]], args: argparse.Namespace) -> List[Dict[str, str]]:
selected: List[Dict[str, str]] = []
video_id_filter = set(args.video_ids or [])
for row in rows:
video_id = (row.get("video_id") or "").strip()
if not video_id:
continue
if video_id_filter and video_id not in video_id_filter:
continue
if not row_needs_subtitle_backfill(row, args):
continue
selected.append(dict(row))
if args.limit is not None and len(selected) >= args.limit:
break
return selected
def persist_row_update(args: argparse.Namespace, video_id: str, updated_row: Dict[str, str], fieldnames: Sequence[str]) -> None:
lock_path = lock_path_for_manifest(args.output_metadata_csv, args.csv_lock_path)
handle = with_manifest_lock(lock_path)
try:
rows, current_fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv)
merged_fieldnames = ordered_fieldnames(list(current_fieldnames) + list(fieldnames))
found = False
for row in rows:
if (row.get("video_id") or "").strip() == video_id:
merge_row_values(row, updated_row, merged_fieldnames)
found = True
break
if not found:
new_row = {column: updated_row.get(column, "") for column in merged_fieldnames}
rows.append(new_row)
write_manifest(args.output_metadata_csv, rows, merged_fieldnames)
finally:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
handle.close()
def main() -> None:
args = parse_args()
temp_cookie_path: Path | None = None
if args.cookies:
temp_cookie_path = sanitize_cookie_file(args.cookies)
args._effective_cookies = temp_cookie_path
else:
args._effective_cookies = None
try:
rows, fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv)
fields = ordered_fieldnames(fieldnames)
pending = selected_rows(rows, args)
args.dataset_dir.mkdir(parents=True, exist_ok=True)
args.raw_metadata_dir.mkdir(parents=True, exist_ok=True)
print(f"subtitle_backfill_selected={len(pending)}")
ok_count = 0
missing_count = 0
failed_count = 0
partial_count = 0
for index, row in enumerate(pending, start=1):
video_id = (row.get("video_id") or "").strip()
print(f"[{index}/{len(pending)}] subtitle backfill {video_id}", flush=True)
subtitle_error = ""
metadata_error = ""
stats_record: Dict[str, object] = {}
try:
metadata_path = args.raw_metadata_dir / f"{video_id}.json"
if metadata_path.exists() and not args.force_metadata:
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
else:
metadata, metadata_error = fetch_metadata(video_id, args)
persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
row["metadata_status"] = "ok"
row["raw_metadata_path"] = repo_relative_or_absolute(metadata_path)
row["title"] = str(metadata.get("title") or row.get("title") or "")
row["duration_sec"] = str(metadata.get("duration") or row.get("duration_sec") or "")
row["start_sec"] = row.get("start_sec") or "0"
row["end_sec"] = str(metadata.get("duration") or row.get("end_sec") or "")
manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata)
preferred_manual = manual_langs[:1]
preferred_native_auto = [] if preferred_manual else native_automatic_langs[:1]
subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id)
need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt"))
if need_subtitles:
subtitle_error = download_subtitles(
video_id,
subtitle_dir,
preferred_manual,
preferred_native_auto,
english_translation_lang,
args,
)
subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
row["subtitle_status"] = "ok" if subtitle_payloads else "missing"
row["subtitle_languages"] = "|".join(sorted(subtitle_payloads))
row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else ""
subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads)
row["subtitle_en"] = subtitle_en
row["subtitle_en_source"] = subtitle_en_source
subtitle_json_path = write_subtitle_json(subtitle_dir, video_id, subtitle_payloads, subtitle_en, subtitle_en_source)
row["subtitle_json_path"] = repo_relative_or_absolute(subtitle_json_path) if subtitle_json_path else ""
row["subtitle_texts_json"] = json.dumps(
build_subtitle_json_payload(video_id, subtitle_payloads, subtitle_en, subtitle_en_source).get("subtitle_texts", {}),
ensure_ascii=False,
) if subtitle_payloads else ""
row["raw_caption_dir"] = row["subtitle_dir_path"]
row["download_status"] = row.get("download_status") or ""
row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
row["error"] = subtitle_error or metadata_error
stats_record.update({
"title": row["title"],
"duration_sec": row["duration_sec"],
"start_sec": row["start_sec"],
"end_sec": row["end_sec"],
"subtitle_languages": row["subtitle_languages"],
"subtitle_dir_path": row["subtitle_dir_path"],
"subtitle_en_source": row["subtitle_en_source"],
"raw_metadata_path": row["raw_metadata_path"],
"metadata_status": row["metadata_status"],
"subtitle_status": row["subtitle_status"],
"download_status": row["download_status"],
"updated_at": row["processed_at"],
"last_error": row["error"],
})
persist_row_update(args, video_id, row, fields)
update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
status = row["subtitle_status"]
if status == "ok":
ok_count += 1
elif status == "missing":
missing_count += 1
elif status == "partial":
partial_count += 1
else:
failed_count += 1
print(f" subtitle_status={status} langs={row['subtitle_languages']}", flush=True)
except Exception as exc:
row["subtitle_status"] = "failed"
row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
row["error"] = str(exc)
stats_record.update({
"subtitle_status": row["subtitle_status"],
"updated_at": row["processed_at"],
"last_error": row["error"],
})
persist_row_update(args, video_id, row, fields)
update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
failed_count += 1
print(f" subtitle_status=failed error={exc}", flush=True)
if args.sleep_seconds > 0:
time.sleep(args.sleep_seconds)
print(
f"subtitle_backfill_done ok={ok_count} missing={missing_count} partial={partial_count} failed={failed_count}",
flush=True,
)
finally:
if temp_cookie_path is not None:
temp_cookie_path.unlink(missing_ok=True)
if __name__ == '__main__':
main()