ce-tagger 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.
ce_tagger/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """ce-tagger: finds the words of a Chechen text that are not Chechen.
2
+
3
+ The core has no third-party dependency and makes no network call. The optional origin check through a Gemini
4
+ endpoint lives in ``ce_tagger.ai`` and is imported only when asked for.
5
+ """
6
+
7
+ from ce_tagger._normalize import normalize_word
8
+ from ce_tagger._origin import AnswerStore
9
+ from ce_tagger._tagger import Tagger
10
+ from ce_tagger._types import OriginChecker, OriginVerdict, TagResult, Token, WordQuery
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "AnswerStore",
16
+ "OriginChecker",
17
+ "OriginVerdict",
18
+ "TagResult",
19
+ "Tagger",
20
+ "Token",
21
+ "WordQuery",
22
+ "__version__",
23
+ "normalize_word",
24
+ ]
ce_tagger/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from ce_tagger._cli import main
4
+
5
+ sys.exit(main())
ce_tagger/_cli.py ADDED
@@ -0,0 +1,200 @@
1
+ """Command line: ce-tagger INPUT [-o FILE] [--marked FILE] [--review FILE] [--unknown FILE] [--ai ...]."""
2
+
3
+ import argparse
4
+ import csv
5
+ import gzip
6
+ import json
7
+ import os
8
+ import sys
9
+ import time
10
+ from collections import Counter
11
+ from typing import Any
12
+
13
+ from ce_tagger import AnswerStore, Tagger, __version__
14
+ from ce_tagger._origin import WORDS_PER_REQUEST
15
+ from ce_tagger.errors import CheckAPIError, CheckError, MissingAIDependencyError, ModelFileError
16
+
17
+ _REVIEW_FROM = 0.2 # words above this probability and not marked go to the review list
18
+ _DEFAULT_ANSWERS = "ce-tagger-answers.jsonl"
19
+ _HEAD = ["doc", "offset", "word", "p_not_chechen", "kind", "decided_by", "in_dictionaries_0_1_2", "context"]
20
+ _DESCRIPTION = """Mark the words of a Chechen text that are not Chechen: Russian speech and loans the dictionaries
21
+ do not attest. Runs locally. With --ai, words the model has no knowledge of are sent to a Gemini endpoint."""
22
+ _EPILOG = """INPUT is a text file, or a .json / .json.gz corpus: a list of objects with a "text" field.
23
+ --ai reads the key from the GEMINI_API_KEY environment variable; GEMINI_MODEL, GEMINI_BASE_URL and
24
+ GEMINI_THINKING_LEVEL are used when the matching option is not given."""
25
+
26
+
27
+ def _parser() -> argparse.ArgumentParser:
28
+ ap = argparse.ArgumentParser(prog="ce-tagger", description=_DESCRIPTION, epilog=_EPILOG)
29
+ ap.add_argument("input", help="text file, .json/.json.gz corpus, or - for standard input")
30
+ out = ap.add_argument_group("output files (each option takes a file name and writes that file)")
31
+ out.add_argument("-o", "--output", metavar="FILE", help="the cleaned text: marked words replaced by spaces")
32
+ out.add_argument("--marked", metavar="FILE", help="the marked words: probability, kind, who decided, context")
33
+ out.add_argument("--review", metavar="FILE",
34
+ help=f"words kept, but the model was unsure ({_REVIEW_FROM} < P <= threshold)")
35
+ out.add_argument("--unknown", metavar="FILE",
36
+ help="words --ai would ask about, with the examples it would send")
37
+ ap.add_argument("--model", metavar="FILE", help="model file (default: the bundled model)")
38
+ ap.add_argument("--threshold", type=float, metavar="P", help="mark words with probability above P (default: the model's)")
39
+ ap.add_argument("--answers", metavar="FILE",
40
+ help=f"file with a large model's answers about words; applied when it exists, extended by --ai "
41
+ f"(default with --ai: {_DEFAULT_ANSWERS})")
42
+ ai = ap.add_argument_group("origin check by a large model (off by default; sends examples from the text)")
43
+ ai.add_argument("--ai", action="store_true", help="ask a Gemini endpoint about words the model has no knowledge of")
44
+ ai.add_argument("--ai-model", metavar="NAME", help="model name served by the endpoint")
45
+ ai.add_argument("--ai-base-url", metavar="URL", help="service root of a Gemini-protocol gateway (default: Google's API)")
46
+ ai.add_argument("--ai-thinking", metavar="LEVEL", help="minimal, low, medium, high or xhigh (default: the endpoint's)")
47
+ ai.add_argument("--ai-workers", type=int, default=4, metavar="N", help="requests sent in parallel (default: 4)")
48
+ ap.add_argument("--version", action="version", version=f"ce-tagger {__version__}")
49
+ return ap
50
+
51
+
52
+ def _read(path: str) -> tuple[list[dict[str, Any]], bool]:
53
+ if path == "-":
54
+ return [{"text": sys.stdin.read()}], False
55
+ opener = gzip.open if path.endswith(".gz") else open
56
+ with opener(path, "rt", encoding="utf-8") as source:
57
+ raw = source.read()
58
+ if not path.endswith((".json", ".json.gz")):
59
+ return [{"text": raw}], False
60
+ docs = json.loads(raw)
61
+ if not isinstance(docs, list) or any(not isinstance(d, dict) or not isinstance(d.get("text"), str) for d in docs):
62
+ raise ValueError('a JSON corpus must be a list of objects with a "text" string')
63
+ return docs, True
64
+
65
+
66
+ def _context(text: str, start: int, end: int) -> str:
67
+ return " ".join(f"{text[max(0, start - 40):start]}[[{text[start:end]}]]{text[end:end + 40]}".split())
68
+
69
+
70
+ def _write_tsv(path: str, rows: list[list[Any]], head: list[str]) -> None:
71
+ with open(path, "w", encoding="utf-8", newline="") as output:
72
+ writer = csv.writer(output, delimiter="\t", lineterminator="\n")
73
+ writer.writerow(head)
74
+ writer.writerows(rows)
75
+
76
+
77
+ def _say(message: str) -> None:
78
+ print(message, file=sys.stderr, flush=True)
79
+
80
+
81
+ def _checker(args: argparse.Namespace) -> Any:
82
+ key = os.environ.get("GEMINI_API_KEY", "").strip()
83
+ model = (args.ai_model or os.environ.get("GEMINI_MODEL", "")).strip()
84
+ if not key:
85
+ raise SystemExit("ce-tagger: --ai needs the API key in the GEMINI_API_KEY environment variable.")
86
+ if not model:
87
+ raise SystemExit("ce-tagger: --ai needs a model name: --ai-model NAME or the GEMINI_MODEL environment variable.")
88
+ from ce_tagger.ai import GeminiOriginChecker
89
+
90
+ try:
91
+ return GeminiOriginChecker(
92
+ api_key=key,
93
+ model=model,
94
+ base_url=args.ai_base_url or os.environ.get("GEMINI_BASE_URL") or None,
95
+ thinking_level=args.ai_thinking or os.environ.get("GEMINI_THINKING_LEVEL") or None,
96
+ workers=args.ai_workers,
97
+ )
98
+ except (ValueError, MissingAIDependencyError) as error:
99
+ raise SystemExit(f"ce-tagger: {error}") from None
100
+
101
+
102
+ def main(argv: list[str] | None = None) -> int:
103
+ args = _parser().parse_args(argv)
104
+ started = time.perf_counter()
105
+ try:
106
+ docs, is_corpus = _read(args.input)
107
+ except (OSError, ValueError) as error:
108
+ raise SystemExit(f"ce-tagger: cannot read {args.input}: {error}") from None
109
+ answers_path = args.answers or (_DEFAULT_ANSWERS if args.ai else None)
110
+ checker = _checker(args) if args.ai else None
111
+ try:
112
+ answers = AnswerStore(answers_path) if answers_path else None
113
+ tagger = Tagger(args.model, threshold=args.threshold, answers=answers, checker=checker)
114
+ except (ModelFileError, ValueError) as error:
115
+ raise SystemExit(f"ce-tagger: {error}") from None
116
+ texts = [d["text"] for d in docs]
117
+ loaded = time.perf_counter()
118
+
119
+ unknown = tagger.unknown_words(texts)
120
+ if args.unknown:
121
+ _write_tsv(args.unknown, [[q.word, *q.examples] for q in unknown], ["word", "example_1", "example_2", "example_3"])
122
+ if checker is not None and unknown:
123
+ requests = 2 * -(-len(unknown) // WORDS_PER_REQUEST)
124
+ _say(f"origin check: {len(unknown)} words to ask, {requests} requests or more, to {checker.endpoint} "
125
+ f"(model {checker.model}); answers go to {answers_path}")
126
+ try:
127
+ warning = checker.check_connection()
128
+ except CheckError as error:
129
+ _say(f"ce-tagger: {error}")
130
+ return 1
131
+ if warning:
132
+ _say(f"origin check: {warning}")
133
+
134
+ def progress(done: int, total: int) -> None:
135
+ _say(f"origin check: request {done}/{total} answered")
136
+
137
+ try:
138
+ results = tagger.tag_many(texts, on_progress=progress)
139
+ except CheckError as error:
140
+ _say(f"ce-tagger: {error}")
141
+ if isinstance(error, CheckAPIError) and error.retry_after:
142
+ _say(f"ce-tagger: the endpoint asks to wait {error.retry_after:.0f} s.")
143
+ _say(f"ce-tagger: the answers received so far are kept in {answers_path}; run the same command to continue.")
144
+ return 1
145
+ finally:
146
+ if checker is not None:
147
+ checker.close()
148
+ tagged = time.perf_counter()
149
+
150
+ marked, review = [], []
151
+ words = {"ru": Counter(), "other": Counter()}
152
+ n_tokens = by_ai = cleared = 0
153
+ for number, (doc, result) in enumerate(zip(docs, results, strict=True)):
154
+ n_tokens += len(result.tokens)
155
+ for t in result.tokens:
156
+ cleared += t.decided_by == "ai" and not t.marked
157
+ if not t.marked and not (t.decided_by == "model" and _REVIEW_FROM < t.p <= tagger.threshold):
158
+ continue
159
+ row = [number, t.start, t.word, round(t.p, 3), t.kind or "", t.decided_by, t.attested,
160
+ _context(result.text, t.start, t.end)]
161
+ if t.marked:
162
+ marked.append(row)
163
+ words[t.kind][t.word] += 1 # type: ignore[index]
164
+ by_ai += t.decided_by == "ai"
165
+ else:
166
+ review.append(row)
167
+ doc["text"] = result.cleaned()
168
+ if args.output:
169
+ opener = gzip.open if args.output.endswith(".gz") else open
170
+ with opener(args.output, "wt", encoding="utf-8") as output:
171
+ output.write(json.dumps(docs, ensure_ascii=False) if is_corpus else docs[0]["text"])
172
+ if args.marked:
173
+ _write_tsv(args.marked, marked, _HEAD)
174
+ if args.review:
175
+ _write_tsv(args.review, review, _HEAD)
176
+
177
+ seconds = max(1e-9, tagged - loaded)
178
+ _say(f"{len(docs)} text(s), {n_tokens} words; model loaded in {loaded - started:.1f} s, tagged in {seconds:.1f} s")
179
+ share = 100 * len(marked) / max(1, n_tokens)
180
+ _say(f"marked as not Chechen: {len(marked)} words ({share:.2f}%): ru {sum(words['ru'].values())} "
181
+ f"({len(words['ru'])} different), other {sum(words['other'].values())} ({len(words['other'])} different); "
182
+ f"for review: {len(review)}")
183
+ if answers is not None:
184
+ left = len(tagger.unknown_words(texts)) if checker is None else 0
185
+ _say(f"decided by the large model's answers: marked {by_ai}, cleared {cleared}"
186
+ + (f"; still unknown: {left} words" if left else ""))
187
+ elif unknown:
188
+ _say(f"{len(unknown)} words are in neither the dictionaries nor the training corpus; the model judged them by "
189
+ f"their letters and neighbours. --ai asks a large model about them.")
190
+ if checker is not None:
191
+ usage = checker.usage
192
+ _say(f"origin check: {usage['requests']} requests, {usage['total_tokens']} tokens")
193
+ for kind in ("ru", "other"):
194
+ if words[kind]:
195
+ _say(f"most frequent {kind}: " + ", ".join(f"{w} ({c})" for w, c in words[kind].most_common(20)))
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ sys.exit(main())
ce_tagger/_model.py ADDED
@@ -0,0 +1,440 @@
1
+ """The local model: lexical evidence, two logistic regressions and a subtitle classifier. Standard library only.
2
+
3
+ Per word token:
4
+ 1. lexical evidence: word-unigram + character 5-gram language models, Chechen vs Russian; counts; whether the
5
+ dictionaries attest the word (2 = listed, also in old/new spelling; 1 = a form of a listed word; 0 = no);
6
+ whether the word starts with a Russian word (RB) or is a Russian adjective minus its ending (RA); for an
7
+ unattested word also whether it begins or ends with a listed form (CB, CS) and its letters
8
+ 2. stage 1: logistic regression over these values for the token and its neighbours
9
+ 3. stage 2: the same plus the stage-1 probabilities of the neighbours
10
+ 4. subtitle ("ru" or "other"): a third logistic regression over the letters of the word
11
+ The feature functions below are the ones the model was trained with; changing them needs a retraining.
12
+ """
13
+
14
+ import math
15
+ import re
16
+ import zlib
17
+ from collections import Counter, defaultdict
18
+
19
+ BOS, EOS = "^", "$"
20
+ CYR = re.compile(r"^[а-яёӏ]+(?:-[а-яёӏ]+)*$")
21
+ TOK = re.compile(r"[\w\-]+")
22
+ STRONG = re.compile(r"[.!?…«»\"„“”()\[\]\n:;–—]|\s-\s")
23
+ MARKERS = ("ӏ", "кх", "къ", "хь", "аь", "оь", "уь", "юь", "яь", "гӏ", "еь")
24
+ HASH_BITS = 20
25
+ MASK = (1 << HASH_BITS) - 1
26
+ CE_EDGES = (1, 2, 5, 20, 100)
27
+ RU_EDGES = (1, 5, 50, 500, 5000)
28
+ MIN_BASE = 3
29
+ CLITICS = frozenset({"м", "кх", "те", "а", "ткъа", "й", "хӏун", "хьа", "ма", "ца"})
30
+
31
+
32
+ def fhash(s):
33
+ return zlib.crc32(s.encode("utf-8")) & MASK
34
+
35
+
36
+ def loose(w):
37
+ """Old and new spelling made equal (йа = я, йу = ю, йе = е, ё = е)."""
38
+ return w.replace("йа", "я").replace("йу", "ю").replace("йе", "е").replace("ё", "е")
39
+
40
+
41
+ class CharLM:
42
+ """Character n-gram model over word types, interpolated Witten-Bell."""
43
+
44
+ def __init__(self, order=5):
45
+ self.n = order
46
+ self.counts = defaultdict(Counter)
47
+ self._cache = {}
48
+
49
+ def fit(self, types):
50
+ vocab = set()
51
+ for w in types:
52
+ s = BOS * (self.n - 1) + w + EOS
53
+ for i in range(self.n - 1, len(s)):
54
+ ch = s[i]
55
+ vocab.add(ch)
56
+ for k in range(0, self.n):
57
+ self.counts[s[i - k:i]][ch] += 1.0
58
+ self.V = len(vocab) + 1
59
+ return self._finish()
60
+
61
+ def _finish(self):
62
+ self.tot = {c: sum(v.values()) for c, v in self.counts.items()}
63
+ self.types = {c: sum(1 for x in v.values() if x > 1e-9) for c, v in self.counts.items()}
64
+ self._cache = {}
65
+ return self
66
+
67
+ def _p(self, ctx, ch):
68
+ p = 1.0 / self.V
69
+ for k in range(0, len(ctx) + 1):
70
+ c = ctx[len(ctx) - k:] if k else ""
71
+ cnt = self.counts.get(c)
72
+ if cnt is None or self.tot[c] <= 1e-9:
73
+ break
74
+ types, total = self.types[c], self.tot[c]
75
+ lam = total / (total + types)
76
+ p = lam * max(cnt.get(ch, 0.0), 0.0) / total + (1 - lam) * p
77
+ return p
78
+
79
+ def logprob(self, w):
80
+ r = self._cache.get(w)
81
+ if r is None:
82
+ s = BOS * (self.n - 1) + w + EOS
83
+ r = sum(math.log(max(self._p(s[i - self.n + 1:i], s[i]), 1e-300)) for i in range(self.n - 1, len(s)))
84
+ self._cache[w] = r
85
+ return r
86
+
87
+ def dump(self):
88
+ return {"n": self.n, "V": self.V, "counts": {c: dict(v) for c, v in self.counts.items()}}
89
+
90
+ @classmethod
91
+ def from_dump(cls, d):
92
+ m = cls(d["n"])
93
+ m.V = d["V"]
94
+ m.counts = d["counts"]
95
+ return m._finish()
96
+
97
+
98
+ class DictLookup:
99
+ """Do the dictionaries attest the word?
100
+
101
+ A form of a listed word is recognised by cutting the word into stem + ending and trying the endings that go
102
+ together with this ending in at least 20 paradigms of the orthographic dictionary.
103
+ """
104
+
105
+ def __init__(self, lemma, par, other, pairs, pairs_hw, returned=()):
106
+ self.lemma = {w for w in lemma if "-" not in w} # headwords and Chechen equivalents
107
+ self.par = {w for w in par if "-" not in w} # listed paradigm forms
108
+ self.exact = set(lemma) | set(par) | set(other)
109
+ self.loose = {loose(w) for w in self.exact}
110
+ self.returned = set(returned) # forms whose initial form a large model named
111
+ self.by_e = defaultdict(set) # ending of the text form -> endings of listed forms
112
+ self.by_e_hw = defaultdict(set)
113
+ for a, b in pairs:
114
+ if a:
115
+ self.by_e[b].add(a)
116
+ for a, b in pairs_hw:
117
+ self.by_e_hw[b].add(a)
118
+ self._memo = {}
119
+
120
+ def stem_hit(self, w):
121
+ for n in range(len(w), MIN_BASE - 1, -1):
122
+ if len(w) - n > 10:
123
+ break
124
+ stem, e = w[:n], w[n:]
125
+ for e0 in self.by_e_hw.get(e, ()):
126
+ if len(e0) <= 10 and stem + e0 in self.lemma:
127
+ return True
128
+ if e:
129
+ for e0 in self.by_e.get(e, ()):
130
+ if len(e0) <= 10 and stem + e0 in self.par:
131
+ return True
132
+ return False
133
+
134
+ def level(self, w, allow_hyph=True, use_returned=True):
135
+ """2 = listed (exact or old/new spelling), 1 = form of a listed word, 0 = not attested.
136
+
137
+ ``use_returned=False`` leaves out the forms that entered the data through the initial-form check, so the
138
+ answer is the one the dictionaries alone give."""
139
+ key = (w, allow_hyph, use_returned)
140
+ r = self._memo.get(key)
141
+ if r is None:
142
+ r = self._memo[key] = self._level(w, allow_hyph, use_returned)
143
+ return r
144
+
145
+ def _level(self, w, allow_hyph, use_returned):
146
+ if w in self.exact:
147
+ return 2
148
+ lw = loose(w)
149
+ if lw in self.loose:
150
+ return 2
151
+ if self.stem_hit(w) or (lw != w and self.stem_hit(lw)):
152
+ return 1
153
+ if allow_hyph and "-" in w:
154
+ parts = w.split("-")
155
+ ok = [(i > 0 and q in CLITICS) or self.level(q, False, use_returned) > 0 for i, q in enumerate(parts)]
156
+ if all(ok) and any(not (i > 0 and q in CLITICS) for i, q in enumerate(parts)):
157
+ return 1
158
+ if use_returned and w in self.returned:
159
+ return 1
160
+ return 0
161
+
162
+
163
+ def ru_base(w, ru_counts):
164
+ """-> (RB, RA). RB: the longest beginning of the word (4+ letters) that is itself a frequent Russian word,
165
+ as "<its length, capped at 7>.<letters left, capped at 4>" or "0". RA: the word ends in -и and becomes a
166
+ Russian adjective when the ending is restored (аккуратни -> аккуратный, аргунски -> аргунский)."""
167
+ rb = "0"
168
+ for n in range(len(w), 3, -1):
169
+ if ru_counts.get(w[:n], 0) >= 20:
170
+ rb = f"{min(n, 7)}.{min(len(w) - n, 4)}"
171
+ break
172
+ ra = 0
173
+ if len(w) >= 5 and w.endswith("и"):
174
+ if ru_counts.get(w + "й", 0) >= 5 or ru_counts.get(w[:-1] + "ый", 0) >= 5 or ru_counts.get(w[:-1] + "ой", 0) >= 5:
175
+ ra = 1
176
+ return rb, ra
177
+
178
+
179
+ def dict_affix(w, exact):
180
+ """-> (CB, CS) for a word the dictionaries do not attest. CB: its longest beginning (3+ letters, not the whole
181
+ word) that is a listed form, as "<length, capped at 7>.<letters left, capped at 4>" or "0". CS: its longest
182
+ ending (4+ letters) that is a listed form, same notation (a preverb + a listed form: тӏе + етталуш)."""
183
+ cb = cs = "0"
184
+ for n in range(len(w) - 1, 2, -1):
185
+ if w[:n] in exact:
186
+ cb = f"{min(n, 7)}.{min(len(w) - n, 4)}"
187
+ break
188
+ for n in range(1, len(w) - 3):
189
+ if w[n:] in exact:
190
+ cs = f"{min(len(w) - n, 7)}.{min(n, 4)}"
191
+ break
192
+ return cb, cs
193
+
194
+
195
+ def bucket(c, edges):
196
+ for i, e in enumerate(edges):
197
+ if c < e:
198
+ return i
199
+ return len(edges)
200
+
201
+
202
+ def unichar_lp(c, lb, n_tokens, n_types):
203
+ return math.log((c + n_types * math.exp(lb)) / (n_tokens + n_types))
204
+
205
+
206
+ def base_record(w, cap, lp_ce, lp_ru, c_ce, c_ru, c_rl, d_level, rb, ra, cb="0", cs="0"):
207
+ """Lexical values of one word token. None for a non-word token."""
208
+ if not w:
209
+ return None
210
+ llr = lp_ru - lp_ce
211
+ lb = max(-7, min(7, int(math.floor(llr / 3.0))))
212
+ return (lb, bucket(c_ce, CE_EDGES), bucket(c_ru, RU_EDGES), min(int(c_rl), 2), int(d_level),
213
+ int(any(m in w for m in MARKERS)), int(cap), w, rb, int(ra), cb, cs)
214
+
215
+
216
+ def _lc(lb):
217
+ return "a" if lb <= -3 else "b" if lb <= -1 else "c" if lb <= 1 else "d" if lb <= 3 else "e"
218
+
219
+
220
+ def features1(recs, cx, i, flags):
221
+ """Stage-1 feature strings of token i. recs: base records (None = non-word token);
222
+ cx[i] = (strong boundary before the token, punctuation class of the gap before it, inside quotes)."""
223
+ r = recs[i]
224
+ L, CE, RU, RL, D, M, CAP, w, RB, RA, CB, CS = r # noqa: N806 (names of the trained features)
225
+ n = len(recs)
226
+ f = ["b", f"L={L}", f"CE={CE}", f"RU={RU}", f"RL={RL}", f"D={D}", f"M={M}", f"CAP={CAP}",
227
+ f"L={L}|CE={CE}", f"L={L}|RU={RU}", f"CE={CE}|RU={RU}|D={D}", f"L={L}|D={D}", f"RL={RL}|CE={CE}",
228
+ "s1=" + w[-1:], "s2=" + w[-2:], "s3=" + w[-3:], f"len={min(len(w), 12)}",
229
+ f"bb={cx[i][0]}", f"ba={cx[i + 1][0] if i + 1 < n else 1}"]
230
+ f += [f"D={D}|CE={CE}|RL={RL}", f"D={D}|RU={RU}", f"D={D}|M={M}", f"D={D}|L={L}|CE={CE}"]
231
+ if flags["rb"]:
232
+ f += [f"RB={RB}", f"RB={RB}|D={D}", f"RB={RB}|CE={CE}", f"RB={RB}|M={M}", f"RA={RA}|D={D}", f"RA={RA}|CE={CE}"]
233
+ if D == 0: # a word no dictionary attests is judged by what it is made of
234
+ if flags["aff"]:
235
+ f += [f"CB={CB}", f"CS={CS}", f"CB={CB}|CS={CS}", f"CB={CB}|RB={RB}", f"CS={CS}|RB={RB}", f"CB={CB}|CE={CE}",
236
+ f"CB={CB}|M={M}", f"CS={CS}|M={M}"]
237
+ if flags["ng"]:
238
+ s = "^" + w + "$"
239
+ for k in (1, 2, 3):
240
+ f += [f"n{k}:" + s[j:j + k] for j in range(len(s) - k + 1)]
241
+ f += ["n4:" + s[:4], "n4:" + s[-4:], "n5:" + s[-5:]]
242
+ gb, ga, inq = cx[i][1], (cx[i + 1][1] if i + 1 < n else "END"), cx[i][2]
243
+ f += [f"gb={gb}", f"ga={ga}", f"gb={gb}|ga={ga}", f"inq={inq}", f"CAP={CAP}|bb={cx[i][0]}", f"CAP={CAP}|inq={inq}",
244
+ f"inq={inq}|L={L}", f"gb={gb}|CAP={CAP}"]
245
+ lc = {}
246
+ for k in (-2, -1, 1, 2):
247
+ j = i + k
248
+ if j < 0 or j >= n:
249
+ f.append(f"{k}:PAD")
250
+ lc[k] = "P"
251
+ continue
252
+ q = recs[j]
253
+ if q is None:
254
+ f.append(f"{k}:NW")
255
+ lc[k] = "N"
256
+ continue
257
+ lc[k] = _lc(q[0])
258
+ f += [f"{k}:L={q[0]}", f"{k}:CE={q[1]}", f"{k}:RU={q[2]}", f"{k}:D={q[4]}", f"{k}:RL={q[3]}"]
259
+ if abs(k) == 1:
260
+ strong = cx[i][0] if k == -1 else cx[j][0]
261
+ f.append(f"{k}:L={lc[k]}|s={strong}")
262
+ c0 = _lc(L)
263
+ f += [f"c0={c0}|c-1={lc[-1]}", f"c0={c0}|c+1={lc[1]}", f"c-1={lc[-1]}|c+1={lc[1]}",
264
+ f"c0={c0}|c-1={lc[-1]}|c+1={lc[1]}"]
265
+ S = C = 0 # noqa: N806
266
+ for j in range(max(0, i - 4), min(n, i + 5)):
267
+ q = recs[j]
268
+ if j != i and q is not None:
269
+ S += q[0] >= 1 # noqa: N806
270
+ C += q[0] <= -2 # noqa: N806
271
+ S, C = min(S, 4), min(C, 6) # noqa: N806
272
+ f += [f"WS={S}", f"WC={C}", f"c0={c0}|WS={S}", f"c0={c0}|WC={C}", f"WS={S}|WC={C}", f"c0={c0}|inq={inq}|WS={S}",
273
+ f"c0={c0}|gb={gb}", f"c0={c0}|ga={ga}"]
274
+ if RU >= 4 and CE >= 3:
275
+ f += ["hg=" + w, f"hg={w}|c-1={lc[-1]}", f"hg={w}|c+1={lc[1]}", f"hg={w}|WS={S}"]
276
+ return f
277
+
278
+
279
+ def _pb(p):
280
+ return max(-12, min(12, int(round(2 * math.log(max(p, 1e-6) / max(1 - p, 1e-6))))))
281
+
282
+
283
+ def features2(recs, cx, P, i, flags): # noqa: N803
284
+ """Stage-2 feature strings: everything of stage 1 plus the stage-1 probabilities of the token and its neighbours
285
+ (lets a short homograph such as "и" or "а" follow the Russian or Chechen words around it)."""
286
+ n = len(recs)
287
+ r = recs[i]
288
+ p0 = _pb(P[i])
289
+ f = features1(recs, cx, i, flags)
290
+ f += [f"2:P={p0}", f"2:P={p0}|D={r[4]}", f"2:P={p0}|CE={r[1]}", f"2:P={p0}|RU={r[2]}", f"2:P={p0 // 3}|inq={cx[i][2]}"]
291
+ nb = {}
292
+ for k in (-3, -2, -1, 1, 2, 3):
293
+ j = i + k
294
+ if j < 0 or j >= n:
295
+ nb[k] = "PAD"
296
+ elif recs[j] is None:
297
+ nb[k] = "NW"
298
+ else:
299
+ nb[k] = _pb(P[j]) // 3
300
+ f.append(f"2:{k}:P={nb[k]}")
301
+ c0 = p0 // 3
302
+ f += [f"2:P={c0}|-1:P={nb[-1]}", f"2:P={c0}|1:P={nb[1]}", f"2:-1:P={nb[-1]}|1:P={nb[1]}",
303
+ f"2:P={c0}|-1:P={nb[-1]}|1:P={nb[1]}", f"2:-2:P={nb[-2]}|-1:P={nb[-1]}", f"2:1:P={nb[1]}|2:P={nb[2]}"]
304
+ hi = lo = 0
305
+ for j in range(max(0, i - 5), min(n, i + 6)):
306
+ if j != i and recs[j] is not None:
307
+ hi += P[j] > 0.5
308
+ lo += P[j] < 0.1
309
+ hi, lo = min(hi, 6), min(lo, 8)
310
+ f += [f"2:hi={hi}", f"2:lo={lo}", f"2:P={c0}|hi={hi}", f"2:hi={hi}|lo={lo}"]
311
+ if r[2] >= 4 and r[1] >= 3:
312
+ f += [f"2:hg={r[7]}|-1:P={nb[-1]}", f"2:hg={r[7]}|1:P={nb[1]}", f"2:hg={r[7]}|hi={hi}"]
313
+ return f
314
+
315
+
316
+ def features_sub(r):
317
+ """Subtitle of a marked token ("other" against "ru"): the letters of the word and how Russian it looks."""
318
+ w = r[7]
319
+ s = "^" + w + "$"
320
+ f = ["b", f"L={r[0]}", f"RU={r[2]}", f"M={r[5]}", f"RB={r[8]}", f"len={min(len(w), 12)}", f"RU={r[2]}|M={r[5]}"]
321
+ for k in (1, 2, 3, 4):
322
+ f += [f"g{k}:" + s[j:j + k] for j in range(len(s) - k + 1)]
323
+ return f
324
+
325
+
326
+ def sigmoid(z):
327
+ return 1.0 / (1.0 + math.exp(-z)) if z > -700 else 0.0
328
+
329
+
330
+ def gap_class(g):
331
+ c = ""
332
+ if any(ch in g for ch in "«»\"„“”"):
333
+ c += "q"
334
+ if "!" in g or "?" in g:
335
+ c += "e"
336
+ if "." in g or "…" in g:
337
+ c += "s"
338
+ if "\n" in g:
339
+ c += "n"
340
+ if "–" in g or "—" in g or " - " in g:
341
+ c += "d"
342
+ if ":" in g or ";" in g:
343
+ c += "c"
344
+ if any(ch in g for ch in "()[]"):
345
+ c += "p"
346
+ if "," in g:
347
+ c += "k"
348
+ return c or "_"
349
+
350
+
351
+ def tokenize(text, normalize):
352
+ """-> list of (start, end, word or '', strong_boundary_before, capitalised, gap_class_before, inside_quotes)."""
353
+ out, prev = [], 0
354
+ stack = [] # open quotes of the current paragraph
355
+ for m in TOK.finditer(text):
356
+ gap = text[prev:m.start()]
357
+ for ch in gap:
358
+ if ch == "\n":
359
+ stack = []
360
+ elif ch in "«„":
361
+ stack.append(ch)
362
+ elif ch == "»" or ch == "”":
363
+ if stack:
364
+ stack.pop()
365
+ elif ch == "“":
366
+ if stack and stack[-1] == "„":
367
+ stack.pop()
368
+ else:
369
+ stack.append(ch)
370
+ elif ch == '"':
371
+ if stack and stack[-1] == '"':
372
+ stack.pop()
373
+ else:
374
+ stack.append(ch)
375
+ w = normalize(m.group()) or ""
376
+ if not CYR.match(w):
377
+ w = ""
378
+ b = 1 if (not out or STRONG.search(gap)) else 0
379
+ out.append((m.start(), m.end(), w, b, int(text[m.start()].isupper()), gap_class(gap) if out else "START",
380
+ int(bool(stack))))
381
+ prev = m.end()
382
+ return out
383
+
384
+
385
+ class Scorer:
386
+ """The saved model: lexicons, character models, dictionary data and weights."""
387
+
388
+ def __init__(self, model):
389
+ self.meta = {k: model[k] for k in ("name", "version", "created", "rule", "trained_on") if k in model}
390
+ self.ce, self.ru, self.rl = model["ce"], model["ru"], model["rl"]
391
+ self.char_ce = CharLM.from_dump(model["char_ce"])
392
+ self.char_ru = CharLM.from_dump(model["char_ru"])
393
+ dc = model["dict"]
394
+ self.dict = DictLookup(dc["lemma"], dc["par"], dc["other"], dc["pairs"], dc["pairs_hw"], dc["returned"])
395
+ self.w1 = {int(k): v for k, v in model["w1"].items()}
396
+ self.w2 = {int(k): v for k, v in model["w2"].items()}
397
+ self.ws = {int(k): v for k, v in model["ws"].items()}
398
+ self.threshold = model.get("threshold", 0.5)
399
+ self.flags = {"rb": True, "aff": True, "ng": True, **model.get("flags", {})}
400
+ self._lex = {}
401
+ self._sub = {}
402
+
403
+ def lex(self, w):
404
+ """(log P Chechen, log P Russian, count in Chechen text, count in Russian reference, count as not Chechen,
405
+ dictionary level, RB, RA, CB, CS)."""
406
+ r = self._lex.get(w)
407
+ if r is None:
408
+ c_ce = self.ce["counts"].get(w, 0)
409
+ c_ru = self.ru["counts"].get(w, 0)
410
+ r = (unichar_lp(c_ce, self.char_ce.logprob(w), self.ce["N"], self.ce["T"]),
411
+ unichar_lp(c_ru, self.char_ru.logprob(w), self.ru["N"], self.ru["T"]),
412
+ c_ce, c_ru, self.rl["counts"].get(w, 0), self.dict.level(w), *ru_base(w, self.ru["counts"]),
413
+ *dict_affix(w, self.dict.exact))
414
+ self._lex[w] = r
415
+ return r
416
+
417
+ def seen(self, w):
418
+ """Did the word occur in the training corpus (as Chechen or as not Chechen)?"""
419
+ return w in self.ce["counts"] or w in self.rl["counts"]
420
+
421
+ def _score(self, weights, feats):
422
+ return sigmoid(sum(weights.get(fhash(x), 0.0) for x in feats))
423
+
424
+ def score(self, text, normalize):
425
+ """-> list of (start, end, word, P(not Chechen)); word is "" and P is None for a token that is not a word."""
426
+ toks = tokenize(text, normalize)
427
+ recs = [base_record(t[2], t[4], *self.lex(t[2])) if t[2] else None for t in toks]
428
+ cx = [(t[3], t[5], t[6]) for t in toks]
429
+ n = len(toks)
430
+ p1 = [self._score(self.w1, features1(recs, cx, i, self.flags)) if recs[i] is not None else 0.0 for i in range(n)]
431
+ return [(t[0], t[1], t[2], self._score(self.w2, features2(recs, cx, p1, i, self.flags)) if recs[i] is not None
432
+ else None) for i, t in enumerate(toks)]
433
+
434
+ def subtitle(self, w):
435
+ """"ru" or "other" for a marked word: which kind of foreign word its letters look like."""
436
+ r = self._sub.get(w)
437
+ if r is None:
438
+ rec = base_record(w, 0, *self.lex(w))
439
+ r = self._sub[w] = "other" if self._score(self.ws, features_sub(rec)) > 0.5 else "ru"
440
+ return r