"""Parse the manual segmentation of the scenario into the final conversation format. e.g. from scenario-manual_seg/volume1/chapter1.jsonl: {"title": "..."} {"speaker": "(scene change)", "text": ""} {"speaker": "narrator", "text": "..."} {"speaker": "narrator", "text": "..."} {"speaker": "heroine", "text": "..."} {"speaker": "protagonist", "text": "..."} {"speaker": "heroine", "text": "..."} {"speaker": "protagonist", "text": "..."} ... to conversation/volume1/chapter1.json: { "title": "...", "conversation": [ { "request": [ {"speaker": "narrator", "text": "..."}, {"speaker": "narrator", "text": "..."}, ], "response": [ {"speaker": "heroine", "text": "..."} ] }, { "request": [ {"speaker": "protagonist", "text": "..."} ], "response": [ {"speaker": "heroine", "text": "..."} ] }, { "request": [ {"speaker": "protagonist", "text": "..."}, ... """ from ..utils import dump_conversation, map_to_file_or_dir, is_protagonist import json from sys import argv from pathlib import Path from typing import TypedDict def generate_seg(ks_path: Path): ks_name = f"{ks_path.parent.name}/{ks_path.stem}" output_base = Path("./conversation") output_base.mkdir(exist_ok=True) (output_base / ks_path.parent.name).mkdir(exist_ok=True) d = TypedDict("d", {"title": str, "conversation": list})( {"title": "", "conversation": []} ) key = "request" current_round = dict(request=[], response=[]) current_scene = "" warned = 5 with ks_path.open("r") as fi: d["title"] = json.loads(next(fi))["title"] for lineno, line in enumerate(fi, start=2): line = line.strip() if not line: # segmentation point if key == "request": key = "response" else: d["conversation"].append(current_round) current_round = dict(request=[], response=[]) key = "request" continue entry = json.loads(line) if entry["speaker"] == "(scene change)": dump_conversation(d, output_base / f"{ks_name}.json") assert ( not current_round["request"] and not current_round["response"] ), f"Unexpected scene change at line {lineno} in {ks_path}" current_scene = entry["text"] continue current_round[key].append(entry) if current_scene: current_round["scene"] = current_scene if entry["speaker"] != "narrator": if warned > 0 and (key == "request") != is_protagonist( entry["speaker"] ): warned -= 1 print(f"WARN: Unexpected speaker at line {lineno}") if current_round["request"]: assert current_round["response"], "Unexpected end of file" d["conversation"].append(current_round) else: assert d["conversation"][-1]["response"], "Unexpected end of file" dump_conversation(d, output_base / f"{ks_name}.json") if __name__ == "__main__": if len(argv) != 2: print(f"Usage: python -m {__package__} path/to/scenario_manual_seg.jsonl") exit(1) map_to_file_or_dir(generate_seg, Path(argv[1]))