ndlocr-lite 2.0.0.dev1__py3-none-any.whl → 2.0.0.dev2__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.
character_inclusion.py ADDED
@@ -0,0 +1,63 @@
1
+ import csv
2
+ import re
3
+ from pathlib import Path
4
+
5
+
6
+ MAPPING_SOURCE_URL = (
7
+ "https://github.com/ndl-lab/tugidigi-web/blob/master/"
8
+ "src/main/resources/config/index/jd_book.json"
9
+ )
10
+ MAPPING_PATH = Path(__file__).resolve().parent / "config" / "character_inclusion_mapping.csv"
11
+
12
+
13
+ def _load_mapping_tables():
14
+ single_character_mappings = {}
15
+ multi_character_mappings = {}
16
+
17
+ with MAPPING_PATH.open("r", encoding="utf-8", newline="") as stream:
18
+ reader = csv.DictReader(stream)
19
+ expected_fields = {
20
+ "source",
21
+ "target",
22
+ "source_codepoints",
23
+ "target_codepoints",
24
+ }
25
+ if set(reader.fieldnames or ()) != expected_fields:
26
+ raise ValueError(f"Unexpected inclusion mapping columns: {reader.fieldnames}")
27
+
28
+ for row in reader:
29
+ source = row["source"]
30
+ target = row["target"]
31
+ if not source:
32
+ raise ValueError("Inclusion mapping sources must not be empty")
33
+ if source in single_character_mappings or source in multi_character_mappings:
34
+ raise ValueError(f"Duplicate inclusion mapping source: {source!r}")
35
+ if len(source) == 1:
36
+ single_character_mappings[source] = target
37
+ else:
38
+ multi_character_mappings[source] = target
39
+
40
+ translation_table = str.maketrans(single_character_mappings)
41
+ multi_pattern = None
42
+ if multi_character_mappings:
43
+ sources = sorted(multi_character_mappings, key=len, reverse=True)
44
+ multi_pattern = re.compile("|".join(re.escape(source) for source in sources))
45
+ return translation_table, multi_character_mappings, multi_pattern
46
+
47
+
48
+ _TRANSLATION_TABLE, _MULTI_CHARACTER_MAPPINGS, _MULTI_CHARACTER_PATTERN = (
49
+ _load_mapping_tables()
50
+ )
51
+
52
+
53
+ def _replace_multi_character_mapping(match):
54
+ return _MULTI_CHARACTER_MAPPINGS[match.group(0)]
55
+
56
+
57
+ def apply_character_inclusion(text: str) -> str:
58
+ """Apply the jd_book mapping char filter with longest matches first."""
59
+ if not text:
60
+ return text
61
+ if _MULTI_CHARACTER_PATTERN is not None:
62
+ text = _MULTI_CHARACTER_PATTERN.sub(_replace_multi_character_mapping, text)
63
+ return text.translate(_TRANSLATION_TABLE)