opencc-py-tw2 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
opencc_py/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """Pure Python OpenCC converter."""
2
+
3
+ from . import locale, presets
4
+ from .core import (
5
+ Converter,
6
+ ConverterOptions,
7
+ Dict,
8
+ DictEntry,
9
+ DictGroup,
10
+ LocalePreset,
11
+ OpenCCError,
12
+ Trie,
13
+ converter,
14
+ converter_builder,
15
+ converter_factory,
16
+ converter_with_options,
17
+ custom_converter,
18
+ )
19
+ from .html import HTMLConverter, HtmlConverter, html_converter
20
+
21
+ __all__ = [
22
+ "Converter",
23
+ "ConverterOptions",
24
+ "Dict",
25
+ "DictEntry",
26
+ "DictGroup",
27
+ "HTMLConverter",
28
+ "HtmlConverter",
29
+ "LocalePreset",
30
+ "OpenCCError",
31
+ "Trie",
32
+ "converter",
33
+ "converter_builder",
34
+ "converter_factory",
35
+ "converter_with_options",
36
+ "custom_converter",
37
+ "html_converter",
38
+ "locale",
39
+ "presets",
40
+ ]
opencc_py/cli.py ADDED
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from .core import OpenCCError, converter
8
+
9
+
10
+ def main(argv: list[str] | None = None) -> int:
11
+ parser = argparse.ArgumentParser(
12
+ prog="opencc-py",
13
+ description="Convert Chinese text between OpenCC locales.",
14
+ )
15
+ parser.add_argument("file", help="Input UTF-8 text file")
16
+ parser.add_argument("from_locale", help="Source locale: cn, hk, tw, tw2, twp, jp, or t")
17
+ parser.add_argument("to_locale", help="Target locale: cn, hk, tw, tw2, twp, jp, or t")
18
+ output_group = parser.add_mutually_exclusive_group()
19
+ output_group.add_argument("-o", "--output", help="Output file path")
20
+ output_group.add_argument("-i", "--in-place", action="store_true", help="Overwrite the input file")
21
+
22
+ args = parser.parse_args(argv)
23
+
24
+ try:
25
+ input_path = Path(args.file)
26
+ content = input_path.read_text(encoding="utf-8")
27
+ converted = converter(args.from_locale, args.to_locale).convert(content)
28
+
29
+ if args.output:
30
+ Path(args.output).write_text(converted, encoding="utf-8")
31
+ elif args.in_place:
32
+ input_path.write_text(converted, encoding="utf-8")
33
+ else:
34
+ sys.stdout.write(converted)
35
+ if converted and not converted.endswith("\n"):
36
+ sys.stdout.write("\n")
37
+ except (OSError, OpenCCError, UnicodeError) as exc:
38
+ print(f"Error: {exc}", file=sys.stderr)
39
+ return 1
40
+
41
+ return 0
42
+
43
+
44
+ if __name__ == "__main__":
45
+ raise SystemExit(main())
opencc_py/core.py ADDED
@@ -0,0 +1,275 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Iterable, Mapping, Sequence
4
+ from dataclasses import dataclass
5
+
6
+
7
+ class OpenCCError(ValueError):
8
+ """Raised when a converter cannot be built from the requested options."""
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class ConverterOptions:
13
+ from_: str = ""
14
+ to: str = ""
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class DictEntry:
19
+ source: str
20
+ target: str
21
+
22
+
23
+ class Dict:
24
+ def __init__(self, raw: str | None = None, entries: Iterable[DictEntry] | None = None) -> None:
25
+ if raw is None and entries is None:
26
+ raise ValueError("Either raw or entries must be provided.")
27
+ if raw is not None and entries is not None:
28
+ raise ValueError("Only one of raw or entries can be provided.")
29
+ self._raw = raw
30
+ self._entries = tuple(entries) if entries is not None else None
31
+
32
+ @classmethod
33
+ def from_string(cls, data: str) -> Dict:
34
+ if data is None:
35
+ raise TypeError("data cannot be None")
36
+ return cls(raw=data)
37
+
38
+ @classmethod
39
+ def from_entries(cls, entries: Iterable[DictEntry | tuple[str, str]]) -> Dict:
40
+ if entries is None:
41
+ raise TypeError("entries cannot be None")
42
+ if isinstance(entries, Mapping):
43
+ entries = entries.items()
44
+ converted = []
45
+ for entry in entries:
46
+ if isinstance(entry, DictEntry):
47
+ converted.append(entry)
48
+ else:
49
+ source, target = entry
50
+ converted.append(DictEntry(source, target))
51
+ return cls(entries=converted)
52
+
53
+ def load_into(self, trie: Trie) -> None:
54
+ if self._raw is not None:
55
+ trie.load_dict(self._raw)
56
+ else:
57
+ trie.load_entries(self._entries or ())
58
+
59
+
60
+ class DictGroup(Sequence[Dict]):
61
+ def __init__(self, dicts: Iterable[Dict]) -> None:
62
+ if dicts is None:
63
+ raise TypeError("dicts cannot be None")
64
+ self._dicts = tuple(dicts)
65
+
66
+ @classmethod
67
+ def from_strings(cls, *dicts: str) -> DictGroup:
68
+ if dicts is None:
69
+ raise TypeError("dicts cannot be None")
70
+ return cls(Dict.from_string(data) for data in dicts)
71
+
72
+ @classmethod
73
+ def from_entries(cls, *dicts: Iterable[DictEntry | tuple[str, str]]) -> DictGroup:
74
+ if dicts is None:
75
+ raise TypeError("dicts cannot be None")
76
+ return cls(Dict.from_entries(entries) for entries in dicts)
77
+
78
+ def concat(self, dict_or_dicts: Dict | Iterable[Dict]) -> DictGroup:
79
+ if isinstance(dict_or_dicts, Dict):
80
+ return DictGroup((*self._dicts, dict_or_dicts))
81
+ return DictGroup((*self._dicts, *tuple(dict_or_dicts)))
82
+
83
+ def __getitem__(self, index: int) -> Dict:
84
+ return self._dicts[index]
85
+
86
+ def __len__(self) -> int:
87
+ return len(self._dicts)
88
+
89
+
90
+ class _Node:
91
+ __slots__ = ("children", "value")
92
+
93
+ def __init__(self) -> None:
94
+ self.children: dict[str, _Node] = {}
95
+ self.value: str | None = None
96
+
97
+
98
+ class Trie:
99
+ def __init__(self) -> None:
100
+ self._root = _Node()
101
+
102
+ def add_word(self, source: str, target: str) -> None:
103
+ if source is None:
104
+ raise TypeError("source cannot be None")
105
+ if target is None:
106
+ raise TypeError("target cannot be None")
107
+
108
+ node = self._root
109
+ for char in source:
110
+ node = node.children.setdefault(char, _Node())
111
+ node.value = target
112
+
113
+ def load_dict(self, dict_data: str) -> None:
114
+ if dict_data is None:
115
+ raise TypeError("dict_data cannot be None")
116
+
117
+ for line in dict_data.split("|"):
118
+ if not line:
119
+ continue
120
+ separator_index = line.find("\t")
121
+ if separator_index < 0:
122
+ separator_index = line.find(" ")
123
+ if separator_index < 0:
124
+ continue
125
+ self.add_word(line[:separator_index], line[separator_index + 1 :])
126
+
127
+ def load_entries(self, entries: Iterable[DictEntry | tuple[str, str]]) -> None:
128
+ if entries is None:
129
+ raise TypeError("entries cannot be None")
130
+ for entry in entries:
131
+ if isinstance(entry, DictEntry):
132
+ self.add_word(entry.source, entry.target)
133
+ else:
134
+ source, target = entry
135
+ self.add_word(source, target)
136
+
137
+ def load_dict_like(self, dict_like: Dict) -> None:
138
+ if dict_like is None:
139
+ raise TypeError("dict_like cannot be None")
140
+ dict_like.load_into(self)
141
+
142
+ def load_dict_group(self, dicts: Iterable[Dict]) -> None:
143
+ if dicts is None:
144
+ raise TypeError("dicts cannot be None")
145
+ for dict_like in dicts:
146
+ self.load_dict_like(dict_like)
147
+
148
+ def convert(self, input_text: str) -> str:
149
+ if input_text is None:
150
+ raise TypeError("input_text cannot be None")
151
+ if input_text == "":
152
+ return ""
153
+
154
+ result: list[str] = []
155
+ pending: list[str] = []
156
+ i = 0
157
+ length = len(input_text)
158
+
159
+ while i < length:
160
+ node = self._root
161
+ matched_end = -1
162
+ matched_value: str | None = None
163
+ j = i
164
+
165
+ while j < length:
166
+ next_node = node.children.get(input_text[j])
167
+ if next_node is None:
168
+ break
169
+ j += 1
170
+ node = next_node
171
+ if node.value is not None:
172
+ matched_end = j
173
+ matched_value = node.value
174
+
175
+ if matched_end >= 0:
176
+ if pending:
177
+ result.append("".join(pending))
178
+ pending.clear()
179
+ result.append(matched_value or "")
180
+ i = matched_end
181
+ else:
182
+ pending.append(input_text[i])
183
+ i += 1
184
+
185
+ if pending:
186
+ result.append("".join(pending))
187
+ return "".join(result)
188
+
189
+
190
+ @dataclass(frozen=True, slots=True)
191
+ class LocalePreset:
192
+ from_map: Mapping[str, DictGroup]
193
+ to_map: Mapping[str, DictGroup]
194
+
195
+
196
+ class Converter:
197
+ def __init__(self, dict_groups: Iterable[DictGroup]) -> None:
198
+ if dict_groups is None:
199
+ raise TypeError("dict_groups cannot be None")
200
+ self._tries = []
201
+ for group in dict_groups:
202
+ if group is None:
203
+ raise ValueError("Dictionary group cannot be None.")
204
+ trie = Trie()
205
+ trie.load_dict_group(group)
206
+ self._tries.append(trie)
207
+
208
+ def convert(self, input_text: str) -> str:
209
+ if input_text is None:
210
+ raise TypeError("input_text cannot be None")
211
+ result = input_text
212
+ for trie in self._tries:
213
+ result = trie.convert(result)
214
+ return result
215
+
216
+ def __call__(self, input_text: str) -> str:
217
+ return self.convert(input_text)
218
+
219
+
220
+ def converter(from_: str, to: str) -> Converter:
221
+ return converter_with_options(ConverterOptions(from_, to))
222
+
223
+
224
+ def converter_with_options(options: ConverterOptions) -> Converter:
225
+ from .locale_data import full_preset
226
+
227
+ return converter_builder(full_preset())(options)
228
+
229
+
230
+ def converter_builder(locale_preset: LocalePreset) -> Callable[[ConverterOptions], Converter]:
231
+ if locale_preset is None:
232
+ raise TypeError("locale_preset cannot be None")
233
+
234
+ def build(options: ConverterOptions) -> Converter:
235
+ if options is None:
236
+ raise TypeError("options cannot be None")
237
+ dict_groups: list[DictGroup] = []
238
+ _add_dict_group("from", options.from_, locale_preset.from_map, dict_groups)
239
+ _add_dict_group("to", options.to, locale_preset.to_map, dict_groups)
240
+ return converter_factory(*dict_groups)
241
+
242
+ return build
243
+
244
+
245
+ def converter_factory(*dict_groups: DictGroup | Iterable[DictGroup]) -> Converter:
246
+ if dict_groups is None:
247
+ raise TypeError("dict_groups cannot be None")
248
+ if len(dict_groups) == 1 and not isinstance(dict_groups[0], DictGroup):
249
+ return Converter(dict_groups[0])
250
+ return Converter(dict_groups)
251
+
252
+
253
+ def custom_converter(dict_data: str | Iterable[DictEntry | tuple[str, str]]) -> Converter:
254
+ if dict_data is None:
255
+ raise TypeError("dict_data cannot be None")
256
+ if isinstance(dict_data, str):
257
+ return converter_factory(DictGroup([Dict.from_string(dict_data)]))
258
+ return converter_factory(DictGroup([Dict.from_entries(dict_data)]))
259
+
260
+
261
+ def _add_dict_group(
262
+ kind: str,
263
+ locale: str,
264
+ mapping: Mapping[str, DictGroup],
265
+ dict_groups: list[DictGroup],
266
+ ) -> None:
267
+ if locale is None or locale.strip() == "":
268
+ raise OpenCCError(f"Please provide the `{kind}` option")
269
+ if locale == "t":
270
+ return
271
+ try:
272
+ group = mapping[locale]
273
+ except KeyError as exc:
274
+ raise OpenCCError(f"Unknown locale `{locale}` for `{kind}` option") from exc
275
+ dict_groups.append(group)