| |
| import argparse |
| import json |
| from pathlib import Path |
|
|
| def iter_spans(obj): |
| """ |
| Yield dicts that look like spans with fields: |
| title, id_sp, text_sec |
| Works whether the JSON is a dict-of-dicts (with numeric keys) or nested. |
| """ |
| if isinstance(obj, dict): |
| |
| if all(k in obj for k in ("title", "id_sp", "text_sec")): |
| yield obj |
| |
| for v in obj.values(): |
| yield from iter_spans(v) |
| elif isinstance(obj, list): |
| for v in obj: |
| yield from iter_spans(v) |
|
|
| def main(): |
| ap = argparse.ArgumentParser(description="Build ID mapping and unique content from multidoc2dial spans.") |
| ap.add_argument("--input", required=True, help="Path to multidoc2dial_doc.json") |
| ap.add_argument("--mapping_out", default="mapping.json", help="Output path for mapping dict (JSON)") |
| ap.add_argument("--contents_out", default="contents.jsonl", help="Output path for contents (JSONL)") |
| |
| ap.add_argument("--base_suffix", default="#1_0", help="Suffix to append after title before _<id_sp>") |
| args = ap.parse_args() |
|
|
| input_path = Path(args.input) |
| with input_path.open("r", encoding="utf-8") as f: |
| data = json.load(f) |
|
|
| |
| text_to_int = {} |
| next_id = 1 |
|
|
| |
| key_to_int = {} |
|
|
| |
| seen_int_ids = set() |
|
|
| |
| for span in iter_spans(data): |
| title = span["title"].strip() |
| id_sp = str(span["id_sp"]).strip() |
| text_sec = span["text_sec"].strip() |
|
|
| full_key = f"{title}{args.base_suffix}_{id_sp}" |
|
|
| if text_sec not in text_to_int: |
| text_to_int[text_sec] = next_id |
| next_id += 1 |
|
|
| int_id = text_to_int[text_sec] |
| key_to_int[full_key] = int_id |
|
|
| |
| with open(args.mapping_out, "w", encoding="utf-8") as f: |
| json.dump(key_to_int, f, ensure_ascii=False, indent=2) |
|
|
| |
| |
| |
| int_to_text = {v: k for k, v in text_to_int.items()} |
| with open(args.contents_out, "w", encoding="utf-8") as f: |
| for int_id in sorted(int_to_text.keys()): |
| obj = {"id": int_id, "contents": int_to_text[int_id]} |
| f.write(json.dumps(obj, ensure_ascii=False) + "\n") |
|
|
| print(f"Wrote {len(key_to_int):,} mappings to {args.mapping_out}") |
| print(f"Wrote {len(int_to_text):,} unique contents to {args.contents_out}") |
|
|
| if __name__ == "__main__": |
| main() |
|
|