trkit-aea 0.5.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.
trkit/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ """trkit -- Turkish text hygiene for programmers.
2
+
3
+ Spec 1.0.0 / Unicode 16.0.0. Zero runtime dependencies.
4
+
5
+ >>> import trkit
6
+ >>> trkit.lower("ISPARTA")
7
+ 'ısparta'
8
+ >>> trkit.title("ankara'nın kitapları")
9
+ "Ankara'nın Kitapları"
10
+ >>> trkit.slug("Çığlık Şöleni 2026!")
11
+ 'ciglik-soleni-2026'
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from ._case import APOSTROPHES, lower, title, upper
17
+ from ._data import (
18
+ abbreviations,
19
+ data_manifest,
20
+ data_path,
21
+ exceptions,
22
+ letters,
23
+ load_exceptions,
24
+ stopwords,
25
+ )
26
+ from ._deasciify import deasciify
27
+ from ._normalize import casefold, clean, fix_mojibake, fold, normalize, slug
28
+ from ._numbers import numwords
29
+ from ._search import meilisearch_preset, search_key, search_tokens, stem_f5
30
+ from ._stem import stem
31
+ from ._suffix import SUFFIX_KINDS, canonical_kind, suffix
32
+ from ._tokenize import tokenize
33
+ from ._unicode import nfc, nfd, spec_version, unicode_version
34
+
35
+ __spec_version__ = spec_version()
36
+
37
+ __version__ = "0.5.0"
38
+
39
+ __all__ = [
40
+ # case
41
+ "lower",
42
+ "upper",
43
+ "title",
44
+ "APOSTROPHES",
45
+ # normalize
46
+ "nfc",
47
+ "nfd",
48
+ "clean",
49
+ "normalize",
50
+ "fold",
51
+ "casefold",
52
+ "slug",
53
+ "fix_mojibake",
54
+ # search
55
+ "search_key",
56
+ "stem_f5",
57
+ "search_tokens",
58
+ "meilisearch_preset",
59
+ # text
60
+ "tokenize",
61
+ "stem",
62
+ "deasciify",
63
+ # suffix
64
+ "suffix",
65
+ "canonical_kind",
66
+ "SUFFIX_KINDS",
67
+ "numwords",
68
+ # data
69
+ "exceptions",
70
+ "letters",
71
+ "abbreviations",
72
+ "stopwords",
73
+ "load_exceptions",
74
+ "data_path",
75
+ "data_manifest",
76
+ # meta
77
+ "spec_version",
78
+ "unicode_version",
79
+ "__spec_version__",
80
+ "__version__",
81
+ ]
trkit/_case.py ADDED
@@ -0,0 +1,101 @@
1
+ """Turkish-aware casing -- spec/01-case.md.
2
+
3
+ Every function is pure, NFC-normalises its input first and returns "" for "".
4
+ Implementation order is fixed by the spec: NFC -> Turkish table -> stdlib.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import unicodedata
10
+
11
+ from ._unicode import check_str, nfc
12
+
13
+ __all__ = ["lower", "upper", "title", "APOSTROPHES"]
14
+
15
+ # spec 01 section 2.6 -- the apostrophe set title() collapses to U+0027.
16
+ APOSTROPHES = frozenset("'\u2019\u02bc\u2018\u00b4`")
17
+
18
+ # spec 01 section 2.2 -- the only four code points with a non-standard mapping.
19
+ _L_I_LOWER = "\u0131" # I -> ı
20
+ _L_I_UPPER = "\u0130" # i -> İ
21
+ _L_DOTLESS_UPPER = "I" # ı -> I
22
+
23
+ _I_DOTTED = "i\u0307"
24
+ _DOT_ABOVE = "\u0307"
25
+
26
+
27
+ def _nfc_tr(s: str) -> str:
28
+ """NFC, plus the composition NFC deliberately skips.
29
+
30
+ U+0130 sits on Unicode's composition exclusion list, so NFC does NOT
31
+ recompose "i" + U+0307 back into "İ". Turkish text arrives decomposed all
32
+ the time, so trkit performs that one composition itself and drops any stray
33
+ U+0307 afterwards -- in Turkish no casing output ever keeps the dot above.
34
+ """
35
+ return nfc(s).replace(_I_DOTTED, _L_I_UPPER)
36
+
37
+
38
+ def lower(s: str) -> str:
39
+ """`I` -> `ı`, `İ` -> `i`, everything else -> standard lower().
40
+
41
+ The two code points are rewritten *before* `str.lower()` so the stdlib keeps
42
+ its context-sensitive behaviour for every other script (Greek final sigma).
43
+ """
44
+ s = check_str(s, "lower")
45
+ if not s:
46
+ return ""
47
+ out = _nfc_tr(s).replace("I", _L_I_LOWER).replace(_L_I_UPPER, "i").lower()
48
+ # spec 01 section 2.7: dropping U+0307 can expose a composable pair
49
+ return nfc(out.replace(_DOT_ABOVE, ""))
50
+
51
+
52
+ def upper(s: str) -> str:
53
+ """`i` -> `İ`, `ı` -> `I`, everything else -> standard upper()."""
54
+ s = check_str(s, "upper")
55
+ if not s:
56
+ return ""
57
+ # spec 01 P4 holds by construction: upper works on lower's output
58
+ out = lower(s).replace("i", _L_I_UPPER).replace(_L_DOTLESS_UPPER, "I").upper()
59
+ return nfc(out.replace(_DOT_ABOVE, ""))
60
+
61
+
62
+ def _upper1(c: str) -> str:
63
+ """Uppercase exactly one character using the Turkish table."""
64
+ if c == "i":
65
+ return _L_I_UPPER
66
+ if c == "\u0131":
67
+ return "I"
68
+ return c.upper()
69
+
70
+
71
+ def title(s: str) -> str:
72
+ """Title-case that does not uppercase after an apostrophe or a digit.
73
+
74
+ `"ankara'nın kitapları"` -> `"Ankara'nın Kitapları"`.
75
+ """
76
+ s = check_str(s, "title")
77
+ if not s:
78
+ return ""
79
+
80
+ out: list[str] = []
81
+ at_start = True # START in the spec pseudo-code
82
+ for c in _nfc_tr(s):
83
+ if c in APOSTROPHES:
84
+ out.append("'")
85
+ at_start = False
86
+ continue
87
+ if c == _DOT_ABOVE:
88
+ continue
89
+ if unicodedata.category(c).startswith("M"):
90
+ out.append(c) # a combining mark belongs to the letter before it
91
+ continue
92
+ if not c.isalpha():
93
+ out.append(c)
94
+ at_start = not c.isdigit()
95
+ continue
96
+ if at_start:
97
+ out.append(_upper1(c))
98
+ at_start = False
99
+ else:
100
+ out.append(c)
101
+ return nfc("".join(out))
trkit/_data.py ADDED
@@ -0,0 +1,117 @@
1
+ """Loader for the normative data files -- spec/05-data.md.
2
+
3
+ Data ships inside the package (`trkit/data/`), copied from the repository root
4
+ by `tools/sync_data.py` and hash-pinned by `data/MANIFEST.json`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import json
11
+ import tomllib
12
+ import warnings
13
+ from functools import cache
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from ._unicode import SPEC_VERSION
18
+
19
+ __all__ = [
20
+ "data_path",
21
+ "exceptions",
22
+ "letters",
23
+ "abbreviations",
24
+ "stopwords",
25
+ "load_exceptions",
26
+ "data_manifest",
27
+ ]
28
+
29
+ # spec 05 section 8 -- abuse guards.
30
+ MAX_DATA_BYTES = 2 * 1024 * 1024
31
+ MAX_KEYS = 100_000
32
+
33
+
34
+ class DataError(RuntimeError):
35
+ """Raised when a data file is missing, malformed or fails a guard."""
36
+
37
+
38
+ def data_path() -> Path:
39
+ return Path(__file__).resolve().parent / "data"
40
+
41
+
42
+ def _read_toml(name: str) -> dict[str, Any]:
43
+ path = data_path() / name
44
+ if not path.exists():
45
+ raise DataError(f"missing data file: {name}")
46
+ size = path.stat().st_size
47
+ if size > MAX_DATA_BYTES:
48
+ raise DataError(f"{name} exceeds {MAX_DATA_BYTES} bytes ({size})")
49
+ with path.open("rb") as fh:
50
+ doc = tomllib.load(fh)
51
+ if "schema" not in doc:
52
+ # spec 05 section 8: a missing schema field means a version mismatch.
53
+ raise DataError(f"{name}: missing 'schema' field (version mismatch)")
54
+ if doc.get("spec") not in (None, SPEC_VERSION):
55
+ warnings.warn(
56
+ f"{name}: spec {doc.get('spec')!r} != port spec {SPEC_VERSION!r}",
57
+ stacklevel=2,
58
+ )
59
+ return doc
60
+
61
+
62
+ def _check_keys(doc: dict[str, Any], name: str) -> None:
63
+ count = sum(len(v) for v in doc.values() if isinstance(v, dict))
64
+ count += sum(len(v) for v in doc.values() if isinstance(v, list))
65
+ if count > MAX_KEYS:
66
+ raise DataError(f"{name}: {count} keys exceeds the {MAX_KEYS} limit")
67
+
68
+
69
+ @cache
70
+ def _cached(name: str) -> dict[str, Any]:
71
+ doc = _read_toml(name)
72
+ _check_keys(doc, name)
73
+ return doc
74
+
75
+
76
+ def exceptions() -> dict[str, Any]:
77
+ """Dictionary exceptions: `words`, `softening_exempt`, `no_buffer`, ..."""
78
+ return _cached("exceptions.toml")
79
+
80
+
81
+ def letters() -> dict[str, str]:
82
+ """Turkish letter names, e.g. `Ç` -> `çe`."""
83
+ return dict(_cached("letters.toml").get("letter", {}))
84
+
85
+
86
+ def abbreviations() -> dict[str, str]:
87
+ """Known abbreviation readings, e.g. `TBMM` -> `tebe emme emme`."""
88
+ return dict(_cached("abbreviations.toml").get("abbr", {}))
89
+
90
+
91
+ def stopwords() -> list[str]:
92
+ """Search stopwords, stored already folded to ASCII."""
93
+ return list(_cached("stopwords.tr.toml").get("list", []))
94
+
95
+
96
+ def load_exceptions(overrides: dict[str, Any]) -> dict[str, Any]:
97
+ """Return a copy of the exception table merged with caller overrides.
98
+
99
+ `tomllib` is read-only, so users who need runtime edits get a copy back
100
+ instead of mutating the packaged file.
101
+ """
102
+ merged: dict[str, Any] = copy.deepcopy(exceptions())
103
+ for section, values in overrides.items():
104
+ if isinstance(values, dict) and isinstance(merged.get(section), dict):
105
+ merged[section].update(values)
106
+ else:
107
+ merged[section] = values
108
+ return merged
109
+
110
+
111
+ def data_manifest() -> dict[str, Any]:
112
+ """Parsed `MANIFEST.json` (packaged copy)."""
113
+ path = data_path() / "MANIFEST.json"
114
+ if not path.exists():
115
+ raise DataError("missing MANIFEST.json")
116
+ manifest: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
117
+ return manifest
trkit/_deasciify.py ADDED
@@ -0,0 +1,92 @@
1
+ """deasciify: restore Turkish letters in ASCII-typed text (spec 09).
2
+
3
+ Deniz Yüret's decision-list method (turkish.el, MIT). Each ASCII c/g/i/o/s/u
4
+ is judged by the patterns that match its context; Turkish letters already in
5
+ the input are never changed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import string
12
+ from functools import cache
13
+ from typing import Any
14
+
15
+ from ._data import data_path
16
+ from ._unicode import check_str
17
+
18
+ __all__ = ["deasciify"]
19
+
20
+ _TOGGLE = {
21
+ "c": "ç", "C": "Ç", "g": "ğ", "G": "Ğ", "i": "ı", "I": "İ",
22
+ "o": "ö", "O": "Ö", "s": "ş", "S": "Ş", "u": "ü", "U": "Ü",
23
+ } # fmt: skip
24
+
25
+ _LOWER_ASCII = {c: c.lower() for c in string.ascii_letters}
26
+ # Right context: every letter as plain lowercase ASCII.
27
+ _RIGHT = {
28
+ **_LOWER_ASCII,
29
+ "ç": "c", "Ç": "c", "ğ": "g", "Ğ": "g", "ı": "i", "İ": "i",
30
+ "ö": "o", "Ö": "o", "ş": "s", "Ş": "s", "ü": "u", "Ü": "u",
31
+ } # fmt: skip
32
+ # Left context: Turkish letters as uppercase ASCII, the rest lowercase.
33
+ _LEFT = {
34
+ **_LOWER_ASCII,
35
+ "ç": "C", "Ç": "C", "ğ": "G", "Ğ": "G", "ı": "I", "İ": "i",
36
+ "ö": "O", "Ö": "O", "ş": "S", "Ş": "S", "ü": "U", "Ü": "U",
37
+ } # fmt: skip
38
+
39
+
40
+ @cache
41
+ def _table() -> tuple[int, dict[str, dict[str, int]]]:
42
+ path = data_path() / "json" / "deasciify.json"
43
+ doc: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
44
+ return int(doc["context_size"]), doc["patterns"]
45
+
46
+
47
+ def _context(chars: list[str], point: int, size: int) -> str:
48
+ s = [" "] * (2 * size + 1)
49
+ s[size] = "X"
50
+ i, index, space = size + 1, point + 1, False
51
+ while i < len(s) and not space and index < len(chars):
52
+ x = _RIGHT.get(chars[index])
53
+ if x is None:
54
+ i, space = i + 1, True
55
+ else:
56
+ s[i], i, space = x, i + 1, False
57
+ index += 1
58
+ s = s[:i]
59
+ i, index, space = size - 1, point - 1, False
60
+ while i >= 0 and index >= 0:
61
+ x = _LEFT.get(chars[index])
62
+ if x is None:
63
+ if not space:
64
+ i, space = i - 1, True
65
+ else:
66
+ s[i], i, space = x, i - 1, False
67
+ index -= 1
68
+ return "".join(s)
69
+
70
+
71
+ def _matches(patterns: dict[str, int], context: str, size: int) -> bool:
72
+ rank = 2 * len(patterns)
73
+ for start in range(size + 1):
74
+ for end in range(size + 1, len(context) + 1):
75
+ r = patterns.get(context[start:end], 0)
76
+ if r and abs(r) < abs(rank):
77
+ rank = r
78
+ return rank > 0
79
+
80
+
81
+ def deasciify(s: str) -> str:
82
+ """Restore Turkish letters: `deasciify("Opusmegi cagristiran") == "Öpüşmeği çağrıştıran"`."""
83
+ s = check_str(s, "deasciify")
84
+ size, table = _table()
85
+ chars = list(s)
86
+ for i, c in enumerate(chars):
87
+ if c not in _TOGGLE:
88
+ continue
89
+ m = _matches(table[c.lower()], _context(chars, i, size), size)
90
+ if m != (c == "I"):
91
+ chars[i] = _TOGGLE[c]
92
+ return "".join(chars)
trkit/_normalize.py ADDED
@@ -0,0 +1,315 @@
1
+ """Cleaning, folding, slugging and mojibake repair -- spec/02-normalize.md."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unicodedata
6
+ from typing import Literal
7
+
8
+ from ._case import lower
9
+ from ._unicode import check_str, nfc, nfd
10
+
11
+ __all__ = [
12
+ "clean",
13
+ "fold",
14
+ "casefold",
15
+ "slug",
16
+ "fix_mojibake",
17
+ "normalize",
18
+ ]
19
+
20
+ # Unicode normalisation forms accepted by `clean` / `normalize` / `slug`
21
+ # (spec 02 section 6). `None` skips normalisation entirely.
22
+ Form = Literal["NFC", "NFD", "NFKC", "NFKD"]
23
+
24
+ # --- spec 02 section 2.1 -------------------------------------------------
25
+ _ZERO_WIDTH = frozenset("\u200b\u200c\u200d\ufeff\u2060")
26
+ _DIRECTIONS = frozenset(
27
+ "\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069"
28
+ )
29
+ _SOFT_HYPHEN = "\u00ad"
30
+
31
+ # --- spec 02 section 2.3 -------------------------------------------------
32
+ _PUNCT_MAP = {
33
+ "\u2019": "'", # right single quote
34
+ "\u02bc": "'", # modifier letter apostrophe
35
+ "\u2018": "'", # left single quote
36
+ "\u00b4": "'", # acute accent
37
+ "`": "'", # grave accent
38
+ "\u201c": '"', # left double quote
39
+ "\u201d": '"', # right double quote
40
+ "\u2013": "-", # en dash
41
+ "\u2014": "-", # em dash
42
+ "\u2012": "-", # figure dash
43
+ "\u2212": "-", # minus sign
44
+ }
45
+
46
+ # --- spec 02 section 2.2 -------------------------------------------------
47
+ _SPACES = frozenset(
48
+ "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009"
49
+ "\u200a\u202f\u205f\u3000"
50
+ "\t\n\r\u000b\u000c"
51
+ )
52
+
53
+ # --- spec 02 section 3 ---------------------------------------------------
54
+ _FOLD_MAP = {
55
+ "\u00e7": "c", # ç
56
+ "\u011f": "g", # ğ
57
+ "\u0131": "i", # ı
58
+ "\u00f6": "o", # ö
59
+ "\u015f": "s", # ş
60
+ "\u00fc": "u", # ü
61
+ "\u00e2": "a", # â
62
+ "\u00ee": "i", # î
63
+ "\u00fb": "u", # û
64
+ "\u00e9": "e", # é
65
+ "\u00e8": "e", # è
66
+ "\u00f1": "n", # ñ
67
+ }
68
+
69
+ # Latin combining diacritical marks only -- Arabic/Devanagari marks stay.
70
+ _LATIN_MARKS = frozenset(chr(cp) for cp in range(0x0300, 0x0370))
71
+
72
+
73
+ def clean(
74
+ s: str,
75
+ *,
76
+ form: Form | None = "NFC",
77
+ collapse_spaces: bool = True,
78
+ trim: bool = True,
79
+ directions: bool = False,
80
+ keep_zwnj: bool = False,
81
+ ) -> str:
82
+ """Strip invisible characters, unify punctuation, normalise whitespace.
83
+
84
+ `directions=False` (default) keeps bidi marks; `keep_zwnj=True` keeps
85
+ U+200C. See the note in spec 02 section 2.1.
86
+ """
87
+ s = check_str(s, "clean")
88
+ if not s:
89
+ return ""
90
+
91
+ # 1. Directional marks.
92
+ if directions:
93
+ s = "".join(c for c in s if c not in _DIRECTIONS)
94
+ # 2. Invisible characters: zero width always, ZWNJ only when kept.
95
+ s = "".join(
96
+ c
97
+ for c in s
98
+ if c not in _ZERO_WIDTH or (keep_zwnj and c == "\u200c")
99
+ )
100
+ s = "".join(c for c in s if c != _SOFT_HYPHEN)
101
+ # 3. Unicode normalisation after removals, so a removed character cannot
102
+ # leave a composable pair behind for a second pass (spec 02 P1).
103
+ if form:
104
+ s = unicodedata.normalize(form, s)
105
+ # 4. Punctuation unification.
106
+ s = "".join(_PUNCT_MAP.get(c, c) for c in s)
107
+ # 5. Whitespace unification.
108
+ s = "".join(" " if c in _SPACES else c for c in s)
109
+ # 6. Collapse and trim.
110
+ if collapse_spaces:
111
+ s = " ".join(s.split())
112
+ if trim:
113
+ s = s.strip()
114
+ return s
115
+
116
+
117
+ def fold(s: str, *, diacritics: bool = False) -> str:
118
+ """Fold to ASCII: `fold(s) = fold_map(lower(NFC(s)))` (spec 02 section 3)."""
119
+ s = lower(s)
120
+ if not s:
121
+ return ""
122
+ if diacritics:
123
+ s = "".join(c for c in nfd(s) if c not in _LATIN_MARKS)
124
+ # spec 02 section 3: folding can expose a composable pair (û + U+0301, o + U+0308),
125
+ # so fold again until nothing changes; a changing pass always composes, so it ends.
126
+ out = _fold_pass(s)
127
+ while (again := _fold_pass(out)) != out:
128
+ out = again
129
+ return out
130
+
131
+
132
+ def _fold_pass(s: str) -> str:
133
+ return nfc("".join(_FOLD_MAP.get(c, c) for c in s))
134
+
135
+
136
+ # Alias so `normalize(fold=True)` can use the spec's option name.
137
+ _fold = fold
138
+
139
+
140
+ def casefold(s: str, *, diacritics: bool = False) -> str:
141
+ """Comparison key. Required to be identical to `fold()` (spec 02 section 3.1)."""
142
+ return fold(s, diacritics=diacritics)
143
+
144
+
145
+ def slug(
146
+ s: str,
147
+ *,
148
+ sep: str = "-",
149
+ keep: str = "",
150
+ max_len: int | None = None,
151
+ min_len: int = 1,
152
+ form: Form | None = "NFC",
153
+ collapse_spaces: bool = True,
154
+ trim: bool = True,
155
+ directions: bool = False,
156
+ keep_zwnj: bool = False,
157
+ ) -> str:
158
+ """URL/ID safe key. Output never contains a Turkish letter.
159
+
160
+ Apostrophes are dropped rather than turned into a separator, so
161
+ `İstanbul'da yağmur` -> `istanbulda-yagmur` (spec 02 section 4, example
162
+ table; the Turkish apostrophe marks a suffix and must not split a word).
163
+
164
+ The remaining options are `clean()`'s and are applied before folding.
165
+ """
166
+ s = fold(
167
+ clean(
168
+ s,
169
+ form=form,
170
+ collapse_spaces=collapse_spaces,
171
+ trim=trim,
172
+ directions=directions,
173
+ keep_zwnj=keep_zwnj,
174
+ )
175
+ )
176
+ if not s:
177
+ return ""
178
+
179
+ keep_set = frozenset(keep)
180
+ out: list[str] = []
181
+ for c in s:
182
+ if c == "'" and c not in keep_set:
183
+ continue
184
+ if ("a" <= c <= "z") or ("0" <= c <= "9") or c in keep_set:
185
+ out.append(c)
186
+ else:
187
+ out.append(sep)
188
+
189
+ # collapse runs of separators, then trim the edges.
190
+ collapsed: list[str] = []
191
+ for c in out:
192
+ if c == sep and collapsed and collapsed[-1] == sep:
193
+ continue
194
+ collapsed.append(c)
195
+ result = "".join(collapsed).strip(sep)
196
+
197
+ if max_len is not None and len(result) > max_len:
198
+ cut = result.rfind(sep, 0, max_len)
199
+ result = result[:cut] if cut > 0 else result[:max_len]
200
+ result = result.strip(sep)
201
+
202
+ return result if len(result) >= min_len else ""
203
+
204
+
205
+ # --- spec 02 section 5 ---------------------------------------------------
206
+ # NOTE: `ç` was removed from this set (2026-10-15). Counting it made the most
207
+ # common repair impossible: "Ãç" scores 1 and "ç" also scored 1, so the
208
+ # strict-decrease rule rejected the fix. `ç` is a core Turkish letter and must
209
+ # never be treated as a mojibake marker.
210
+ _MOJI_SCORE_CHARS = frozenset("ÂÃÄÅàáâãäåèéêëìíîïðñòóôõö")
211
+ _MOJI_ENCODINGS = ("latin-1", "cp1252", "cp1254", "iso-8859-9")
212
+
213
+
214
+ def _moji_score(s: str) -> int:
215
+ return sum(1 for c in s if c in _MOJI_SCORE_CHARS or "\u0080" <= c <= "\u009f")
216
+
217
+
218
+ def _decodable(c: str) -> bool:
219
+ if c.isascii(): # fast path: latin-1 covers all of ASCII
220
+ return True
221
+ return any(_encode(c, enc) is not None for enc in _MOJI_ENCODINGS)
222
+
223
+
224
+ def _encode(s: str, encoding: str) -> bytes | None:
225
+ try:
226
+ return s.encode(encoding)
227
+ except (UnicodeEncodeError, LookupError):
228
+ return None
229
+
230
+
231
+ def _repair_segment(segment: str) -> str:
232
+ best = segment
233
+ best_score = _moji_score(segment)
234
+ for enc in _MOJI_ENCODINGS:
235
+ raw = _encode(segment, enc)
236
+ if raw is None:
237
+ continue
238
+ try:
239
+ candidate = raw.decode("utf-8")
240
+ except UnicodeDecodeError:
241
+ continue
242
+ score = _moji_score(candidate)
243
+ if score < best_score: # only accepted when the score drops
244
+ best, best_score = candidate, score
245
+ return best
246
+
247
+
248
+ def _repair_pass(s: str) -> str:
249
+ """One decoding pass: split into encodable segments, repair each of them."""
250
+ result: list[str] = []
251
+ segment: list[str] = []
252
+ for c in s:
253
+ if _decodable(c):
254
+ segment.append(c)
255
+ continue
256
+ if segment:
257
+ result.append(_repair_segment("".join(segment)))
258
+ segment.clear()
259
+ result.append(c)
260
+ if segment:
261
+ result.append(_repair_segment("".join(segment)))
262
+ return "".join(result)
263
+
264
+
265
+ def fix_mojibake(s: str) -> str:
266
+ """Undo UTF-8 text that was decoded as latin-1/cp1252/cp1254/iso-8859-9.
267
+
268
+ Idempotent: a change is only kept when the mojibake score strictly drops.
269
+ Mixed encodings inside one word are a documented limitation (spec 02 5.5).
270
+ """
271
+ s = check_str(s, "fix_mojibake")
272
+ if not s:
273
+ return ""
274
+
275
+ for _ in range(2): # double-encoded text is at most two passes deep
276
+ candidate = _repair_pass(s)
277
+ if candidate == s:
278
+ break
279
+ s = candidate
280
+ return s
281
+
282
+
283
+ def normalize(
284
+ s: str,
285
+ *,
286
+ form: Form | None = "NFC",
287
+ mojibake: bool = False,
288
+ collapse_spaces: bool = True,
289
+ trim: bool = True,
290
+ fold: bool = False,
291
+ strip_diacritics: bool = False,
292
+ directions: bool = False,
293
+ keep_zwnj: bool = False,
294
+ ) -> str:
295
+ """Public one-call pipeline (spec 02 section 6).
296
+
297
+ `fold` shadows the module-level function inside this scope only; the public
298
+ option name matches the spec (`opts.fold`).
299
+ """
300
+ s = check_str(s, "normalize")
301
+ if not s:
302
+ return ""
303
+ if mojibake:
304
+ s = fix_mojibake(s)
305
+ s = clean(
306
+ s,
307
+ form=form,
308
+ collapse_spaces=collapse_spaces,
309
+ trim=trim,
310
+ directions=directions,
311
+ keep_zwnj=keep_zwnj,
312
+ )
313
+ if fold or strip_diacritics:
314
+ s = _fold(s, diacritics=strip_diacritics)
315
+ return s