#!/usr/bin/env python3 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): # Detect a span record if all(k in obj for k in ("title", "id_sp", "text_sec")): yield obj # Otherwise, recurse into values 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)") # If you ever need a different base suffix than '#1_0', change here: ap.add_argument("--base_suffix", default="#1_0", help="Suffix to append after title before _") args = ap.parse_args() input_path = Path(args.input) with input_path.open("r", encoding="utf-8") as f: data = json.load(f) # Dedup by exact text_sec (after strip) text_to_int = {} # normalized text_sec -> int_id next_id = 1 # Mapping from full key -> int_id key_to_int = {} # "#1_0_<id_sp>" -> int_id # For writing contents.jsonl only once per unique int_id seen_int_ids = set() # First pass: assign int IDs by text_sec 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 # Write mapping.json with open(args.mapping_out, "w", encoding="utf-8") as f: json.dump(key_to_int, f, ensure_ascii=False, indent=2) # Write contents.jsonl (one line per unique text_sec) # Ensure stable order by int_id # Invert text_to_int to {int_id: text_sec} 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()