File size: 1,231 Bytes
df03d35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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")