-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathannotation_file.py
More file actions
235 lines (187 loc) · 6.18 KB
/
Copy pathannotation_file.py
File metadata and controls
235 lines (187 loc) · 6.18 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# AF is a relax format in JSON
# unknown keys are ignored
# run validate() for stricter checks
import dataclasses
from dataclasses import dataclass
from enum import IntEnum
import json
@dataclass
class PlainAnnotation:
"""a plain text chunk without ruby."""
text: str
def get_normalized(self) -> str:
return self.text
def serialize(self) -> dict:
return {'text': self.text}
@classmethod
def deserialize(cls, d: dict):
return cls(text=d['text'])
def validate(self):
if not isinstance(self.text, str):
raise AssertionError
@dataclass
class KanjiCharacters:
"""smallest part in a kanji word that has an inseparable reading."""
base: str
reading: str = ''
def get_normalized(self) -> str:
return self.base
def serialize(self) -> dict:
return {'base': self.base, 'reading': self.reading}
@classmethod
def deserialize(cls, d: dict):
return cls(base=d['base'], reading=d['reading'])
def validate(self):
if not isinstance(self.base, str):
raise AssertionError
if not isinstance(self.reading, str):
raise AssertionError
@dataclass
class KanjiAnnotation:
"""a series of kanji_chars that belong to the same word"""
fragments: list[KanjiCharacters] = dataclasses.field(default_factory=list)
def get_normalized(self) -> str:
return ''.join(x.get_normalized() for x in self.fragments)
def serialize(self) -> dict:
return {'fragments': [x.serialize() for x in self.fragments]}
@classmethod
def deserialize(cls, d: dict):
return cls(fragments=[KanjiCharacters.deserialize(x) for x in d['fragments']])
def validate(self):
if not isinstance(self.fragments, list):
raise AssertionError
for x in self.fragments:
if not isinstance(x, KanjiCharacters):
raise AssertionError
x.validate()
@dataclass
class LoanAnnotation:
"""a loan word."""
base: str
romanized: str = ''
def get_normalized(self) -> str:
return self.base
def serialize(self) -> dict:
return {'base': self.base, 'romanized': self.romanized}
@classmethod
def deserialize(cls, d: dict):
return cls(base=d['base'], romanized=d['romanized'])
def validate(self):
if not isinstance(self.base, str):
raise AssertionError
if not isinstance(self.romanized, str):
raise AssertionError
class AnnotationType(IntEnum):
PLAIN_ANNOTATION = 0
KANJI_ANNOTATION = 1
LOAN_ANNOTATION = 2
@dataclass
class Annotation:
"""wrapper. for metadata.
please access the real annotation object via `inner'."""
inner: PlainAnnotation | KanjiAnnotation | LoanAnnotation
unfinished: bool = False
ignore: bool = False
checked: bool = False
def get_normalized(self) -> str:
return self.inner.get_normalized()
def serialize(self) -> dict:
if isinstance(self.inner, PlainAnnotation):
kind = AnnotationType.PLAIN_ANNOTATION
elif isinstance(self.inner, KanjiAnnotation):
kind = AnnotationType.KANJI_ANNOTATION
elif isinstance(self.inner, LoanAnnotation):
kind = AnnotationType.LOAN_ANNOTATION
else:
raise AssertionError('unhandled annotation type')
return {
'unfinished': self.unfinished,
'ignore': self.ignore,
'checked': self.checked,
'type': int(kind),
'inner': self.inner.serialize(),
}
def validate(self):
if not isinstance(self.inner, (PlainAnnotation, KanjiAnnotation, LoanAnnotation)):
raise AssertionError
self.inner.validate()
if not isinstance(self.unfinished, bool):
raise AssertionError
if not isinstance(self.ignore, bool):
raise AssertionError
if not isinstance(self.checked, bool):
raise AssertionError
@classmethod
def deserialize(cls, d: dict):
kind = AnnotationType(d['type'])
match kind:
case AnnotationType.PLAIN_ANNOTATION:
inner = PlainAnnotation.deserialize(d['inner'])
case AnnotationType.KANJI_ANNOTATION:
inner = KanjiAnnotation.deserialize(d['inner'])
case AnnotationType.LOAN_ANNOTATION:
inner = LoanAnnotation.deserialize(d['inner'])
case _:
raise ValueError(f'unhandled annotation type {kind}')
return cls(
unfinished=d['unfinished'],
ignore=d['ignore'],
checked=d['checked'],
inner=inner,
)
@dataclass
class DialogueLine:
"""total content displayed as a subtitle line."""
fragments: list[Annotation] = dataclasses.field(default_factory=list)
def get_normalized(self) -> str:
"""converts this line back into plaintext again"""
return ''.join(x.get_normalized() for x in self.fragments)
def serialize(self, lineno: int = -1) -> dict:
return {
'fragments': [x.serialize() for x in self.fragments],
# these fields are intentionally ignored when reading
'lineno': lineno,
'orig_line': self.get_normalized(),
}
@classmethod
def deserialize(cls, d: dict):
return cls(fragments=[Annotation.deserialize(x) for x in d['fragments']])
def validate(self):
if not isinstance(self.fragments, list):
raise AssertionError
for x in self.fragments:
if not isinstance(x, Annotation):
raise AssertionError
x.validate()
VER_CURRENT = 0
@dataclass
class AnnotationFile:
version: int = VER_CURRENT
lines: list[DialogueLine] = dataclasses.field(default_factory=list)
def serialize(self) -> dict:
return {
'version': self.version,
'lines': [x.serialize(i) for i, x in enumerate(self.lines, start=1)],
}
@classmethod
def deserialize(cls, d: dict):
return cls(
version=d['version'],
lines=[DialogueLine.deserialize(x) for x in d['lines']],
)
def validate(self):
if not isinstance(self.version, int):
raise AssertionError
if not isinstance(self.lines, list):
raise AssertionError
for x in self.lines:
if not isinstance(x, DialogueLine):
raise AssertionError
x.validate()
def annotation_parse(s: str) -> AnnotationFile:
"""parse the input string as
Annotation File that were previously saved."""
return AnnotationFile.deserialize(json.loads(s))
def annotation_save(af: AnnotationFile) -> str:
"""format AF object as string that can be stored on disk."""
return json.dumps(af.serialize(), sort_keys=True, indent=2, ensure_ascii=False)