#!/usr/bin/env python3 """Extract answer markers from text and populate the `answer` field.""" from __future__ import annotations import argparse import json import re from pathlib import Path ANSWER_PATTERN = re.compile( r"\*\*\s*answer\s*:\s*(.+?)\s*\*\*", flags=re.IGNORECASE | re.DOTALL, ) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( "Extract `**Answer:x**` from each item's `text` and fill `answer`." ) ) parser.add_argument( "--input", default="video_dataset.json", help="Input JSON path (default: video_dataset.json).", ) parser.add_argument( "--output", default="", help="Output JSON path (default: overwrite --input in place).", ) parser.add_argument( "--overwrite", action="store_true", help="Overwrite non-empty existing `answer` values.", ) parser.add_argument( "--dry-run", action="store_true", help="Only report stats; do not write output.", ) parser.add_argument( "--ensure-ascii", action="store_true", help="Write escaped unicode (default keeps unicode characters).", ) return parser def extract_answer(text: str) -> str: match = ANSWER_PATTERN.search(text or "") if not match: return "" raw = match.group(1).strip() return re.sub(r"\s+", " ", raw) def main() -> None: args = build_parser().parse_args() input_path = Path(args.input) output_path = Path(args.output) if args.output else input_path with input_path.open("r", encoding="utf-8") as f: data = json.load(f) if not isinstance(data, list): raise ValueError("Input JSON must be a list of objects.") total = 0 with_marker = 0 updated = 0 skipped_existing = 0 no_marker = 0 for item in data: if not isinstance(item, dict): continue total += 1 text = "" if item.get("text") is None else str(item.get("text")) extracted = extract_answer(text) if not extracted: no_marker += 1 continue with_marker += 1 current = "" if item.get("answer") is None else str(item.get("answer")).strip() if current and not args.overwrite: skipped_existing += 1 continue if current != extracted: item["answer"] = extracted updated += 1 if not args.dry_run: with output_path.open("w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=args.ensure_ascii, indent=2) f.write("\n") print( "Processed " f"{total} items | markers: {with_marker} | updated: {updated} | " f"skipped_existing: {skipped_existing} | no_marker: {no_marker} | " f"output: {output_path if not args.dry_run else '(dry-run)'}" ) if __name__ == "__main__": main()