|
import re |
|
import json |
|
from pathlib import Path |
|
from typing import Callable, Concatenate |
|
|
|
ENTRY = re.compile(r"{\n\s+\"speaker\": \"(.*)\",\n\s+\"text\": \"(.*)\"\n\s+}", re.M) |
|
|
|
|
|
def compact_entry(output: str) -> str: |
|
""" |
|
Collapse the following: |
|
{ |
|
"speaker": "...", |
|
"text": "..." |
|
}, |
|
into this: |
|
{"speaker": "...", "text": "..."}, |
|
""" |
|
return ENTRY.sub(r'{"speaker": "\1", "text": "\2"}', output) |
|
|
|
|
|
def dump_conversation(conversation, output_path: Path): |
|
with output_path.open("w") as fo: |
|
output = json.dumps(conversation, ensure_ascii=False, indent=2) |
|
output = compact_entry(output) |
|
print(output, file=fo) |
|
|
|
|
|
def map_to_file_or_dir[**P]( |
|
fn: Callable[Concatenate[Path, P], None], |
|
path: Path, |
|
*args: P.args, |
|
**kwargs: P.kwargs, |
|
): |
|
if path.is_dir(): |
|
for p in path.iterdir(): |
|
print(f"Processing {p}") |
|
fn(p, *args, **kwargs) |
|
else: |
|
fn(path, *args, **kwargs) |
|
|
|
|
|
def is_protagonist(speaker: str) -> bool: |
|
return speaker == "protagonist" or speaker == "我" |
|
|
|
|
|
def is_heroine(speaker: str) -> bool: |
|
return not (is_protagonist(speaker) or speaker == "narrator") |
|
|