ruaccent 1.6.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.
ruaccent/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Russian accentizer"""
2
+
3
+ __version__ = "1.6.0"
4
+
5
+
6
+ from .ruaccent import RUAccent
@@ -0,0 +1,46 @@
1
+ import json
2
+ from os.path import join as join_path
3
+
4
+ import numpy as np
5
+
6
+ from .char_tokenizer import CharTokenizer
7
+ from .session_helper import create_session
8
+ from .token_classifier import softmax
9
+
10
+
11
+ class AccentModel:
12
+ """Character-level model that puts a stress mark into a single word."""
13
+
14
+ threshold = 0.55
15
+
16
+ def load(self, path, device="CPU"):
17
+ self.session = create_session(join_path(path, "model.onnx"), device=device)
18
+ with open(join_path(path, "config.json"), "r", encoding="utf-8") as f:
19
+ config = json.load(f)
20
+ self.id2label = config["id2label"]
21
+ self.max_word_length = config.get("max_position_embeddings", 60) - 2 # [bos], [eos]
22
+ self.primary_id = next(int(i) for i, label in self.id2label.items() if label == "STRESS_PRIMARY")
23
+ self.tokenizer = CharTokenizer.from_pretrained(path)
24
+ self.input_names = {i.name for i in self.session.get_inputs()}
25
+
26
+ def put_accent(self, word):
27
+ if len(word) > self.max_word_length:
28
+ return word
29
+ inputs = self.tokenizer(word.lower(), return_tensors="np")
30
+ feed = {k: v.astype(np.int64) for k, v in inputs.items() if k in self.input_names}
31
+ if "token_type_ids" in self.input_names and "token_type_ids" not in feed:
32
+ feed["token_type_ids"] = np.zeros_like(feed["input_ids"])
33
+ logits = self.session.run(["logits"], feed)[0][0]
34
+ probs = softmax(logits)[1:-1] # drop [bos]/[eos]
35
+
36
+ # A word has exactly one primary stress: take the most confident
37
+ # character among those the model labels as primary.
38
+ candidates = [
39
+ (p[self.primary_id], i)
40
+ for i, p in enumerate(probs[: len(word)])
41
+ if p.argmax() == self.primary_id and p[self.primary_id] >= self.threshold
42
+ ]
43
+ if not candidates:
44
+ return word
45
+ _, pos = max(candidates)
46
+ return word[:pos] + "+" + word[pos:]
@@ -0,0 +1,106 @@
1
+ import os
2
+ from typing import Optional, Tuple, List
3
+ from collections import OrderedDict
4
+
5
+ from transformers import PreTrainedTokenizer
6
+
7
+
8
+ def load_vocab(vocab_file):
9
+ vocab = OrderedDict()
10
+ with open(vocab_file, "r", encoding="utf-8") as reader:
11
+ tokens = reader.readlines()
12
+ for index, token in enumerate(tokens):
13
+ token = token.rstrip("\n")
14
+ vocab[token] = index
15
+ return vocab
16
+
17
+
18
+ class CharTokenizer(PreTrainedTokenizer):
19
+ vocab_files_names = {"vocab_file": "vocab.txt"}
20
+
21
+ def __init__(
22
+ self,
23
+ vocab_file=None,
24
+ pad_token="[pad]",
25
+ unk_token="[unk]",
26
+ bos_token="[bos]",
27
+ eos_token="[eos]",
28
+ do_lower_case=False,
29
+ *args,
30
+ **kwargs
31
+ ):
32
+ self.vocab = load_vocab(vocab_file)
33
+ super().__init__(
34
+ pad_token=pad_token,
35
+ unk_token=unk_token,
36
+ bos_token=bos_token,
37
+ eos_token=eos_token,
38
+ do_lower_case=do_lower_case,
39
+ **kwargs
40
+ )
41
+ self.do_lower_case = do_lower_case
42
+
43
+ @property
44
+ def vocab_size(self):
45
+ return len(self.vocab)
46
+
47
+ def get_vocab(self):
48
+ return dict(self.vocab)
49
+
50
+ def _convert_token_to_id(self, token):
51
+ if self.do_lower_case:
52
+ token = token.lower()
53
+ return self.vocab.get(token, self.vocab[self.unk_token])
54
+
55
+ def _convert_id_to_token(self, index):
56
+ return self.ids_to_tokens[index]
57
+
58
+ def _tokenize(self, text):
59
+ if self.do_lower_case:
60
+ text = text.lower()
61
+ return list(text)
62
+
63
+ def convert_tokens_to_string(self, tokens):
64
+ return "".join(tokens)
65
+
66
+ def build_inputs_with_special_tokens(
67
+ self,
68
+ token_ids_0: List[int],
69
+ token_ids_1: Optional[List[int]] = None
70
+ ) -> List[int]:
71
+ bos = [self.bos_token_id]
72
+ eos = [self.eos_token_id]
73
+ return bos + token_ids_0 + eos
74
+
75
+ def get_special_tokens_mask(
76
+ self,
77
+ token_ids_0: List[int],
78
+ token_ids_1: Optional[List[int]] = None
79
+ ) -> List[int]:
80
+ return [1] + ([0] * len(token_ids_0)) + [1]
81
+
82
+ def create_token_type_ids_from_sequences(
83
+ self,
84
+ token_ids_0: List[int],
85
+ token_ids_1: Optional[List[int]] = None
86
+ ) -> List[int]:
87
+ return (len(token_ids_0) + 2) * [0]
88
+
89
+ def save_vocabulary(
90
+ self,
91
+ save_directory: str,
92
+ filename_prefix: Optional[str] = None
93
+ ) -> Tuple[str]:
94
+ assert os.path.isdir(save_directory)
95
+ vocab_file = os.path.join(
96
+ save_directory,
97
+ (filename_prefix + "-" if filename_prefix else "") +
98
+ self.vocab_files_names["vocab_file"]
99
+ )
100
+ index = 0
101
+ with open(vocab_file, "w", encoding="utf-8") as writer:
102
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
103
+ assert index == token_index
104
+ writer.write(token + "\n")
105
+ index += 1
106
+ return (vocab_file,)
@@ -0,0 +1,52 @@
1
+ import re
2
+
3
+ import numpy as np
4
+ from transformers import AutoTokenizer
5
+
6
+ from .session_helper import create_session
7
+ from .token_classifier import softmax
8
+
9
+ _SPACE_BEFORE_PUNCT = re.compile(r"\s+(?=[,.?!:;…])")
10
+
11
+
12
+ class OmographModel:
13
+ """Cross-encoder that scores (context, stressed variant) pairs."""
14
+
15
+ batch_size = 32
16
+
17
+ def load(self, path, device="CPU"):
18
+ self.session = create_session(f"{path}/model.onnx", device=device)
19
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
20
+ self.input_names = {i.name for i in self.session.get_inputs()}
21
+
22
+ def _score(self, texts, hypotheses):
23
+ """Probability that each hypothesis is the right reading of its text."""
24
+ probs = []
25
+ for i in range(0, len(texts), self.batch_size):
26
+ inputs = self.tokenizer(
27
+ texts[i:i + self.batch_size],
28
+ hypotheses[i:i + self.batch_size],
29
+ return_tensors="np",
30
+ padding=True,
31
+ truncation=True,
32
+ max_length=512,
33
+ )
34
+ feed = {k: v.astype(np.int64) for k, v in inputs.items() if k in self.input_names}
35
+ logits = self.session.run(None, feed)[0]
36
+ probs.extend(softmax(logits)[:, 1].tolist())
37
+ return probs
38
+
39
+ def classify(self, texts, hypotheses, num_hypotheses):
40
+ """Pick the best variant for every homograph.
41
+
42
+ ``texts`` and ``hypotheses`` are flat, aligned lists; ``num_hypotheses``
43
+ says how many consecutive entries belong to each homograph.
44
+ """
45
+ texts = [_SPACE_BEFORE_PUNCT.sub("", t) for t in texts]
46
+ probs = self._score(texts, hypotheses)
47
+ outs, start = [], 0
48
+ for n in num_hypotheses:
49
+ group = probs[start:start + n]
50
+ outs.append(hypotheses[start + group.index(max(group))])
51
+ start += n
52
+ return outs
ruaccent/ruaccent.py ADDED
@@ -0,0 +1,242 @@
1
+ import bisect
2
+ import gzip
3
+ import json
4
+ import os
5
+ import pathlib
6
+ import re
7
+ from os.path import join as join_path
8
+
9
+ from huggingface_hub import snapshot_download
10
+
11
+ from .accent_model import AccentModel
12
+ from .omograph_model import OmographModel
13
+ from .stress_usage_model import StressUsagePredictorModel
14
+ from .text_postprocessor import fix_capital, transfer_stress
15
+ from .text_preprocessor import CAPS_WORD, TextPreprocessor
16
+ from .yo_homograph_model import YoHomographModel
17
+
18
+ OMOGRAPH_MODELS = (
19
+ "big_poetry", "medium_poetry", "small_poetry",
20
+ "turbo", "turbo2", "turbo3", "turbo3.1",
21
+ "tiny", "tiny2", "tiny2.1",
22
+ )
23
+ VOWELS = set("аеёиоуыэюяАЕЁИОУЫЭЮЯ")
24
+ PACKAGE_DIR = str(pathlib.Path(__file__).resolve().parent)
25
+
26
+
27
+ class _SpanLookup:
28
+ """Find the model prediction covering a character offset."""
29
+
30
+ def __init__(self, entities):
31
+ self.entities = entities
32
+ self.starts = [e["start"] for e in entities]
33
+
34
+ def label(self, pos, default):
35
+ i = bisect.bisect_right(self.starts, pos) - 1
36
+ if i >= 0 and pos < self.entities[i]["end"]:
37
+ return self.entities[i]["entity"]
38
+ return default
39
+
40
+
41
+ class RUAccent:
42
+ def __init__(self):
43
+ self.omograph_model = OmographModel()
44
+ self.accent_model = AccentModel()
45
+ self.stress_usage_predictor = StressUsagePredictorModel()
46
+ self.yo_homograph_model = YoHomographModel()
47
+ self.omograph_models_paths = {name: f"/nn/nn_omograph/{name}" for name in OMOGRAPH_MODELS}
48
+ self.letters_accent = {"о": "+о", "О": "+О"}
49
+ self.tiny_mode = False
50
+
51
+ # ------------------------------------------------------------------ loading
52
+
53
+ def _accents_file(self, use_dictionary):
54
+ # The full dictionary is big; without it the accent model covers the rest.
55
+ return "accents.json.gz" if use_dictionary and not self.tiny_mode else "accents_nn.json.gz"
56
+
57
+ def _required_files(self, omograph_model_size, use_dictionary):
58
+ files = [
59
+ f"dictionary/{name}"
60
+ for name in ("omographs.json.gz", "yo_words.json.gz", "yo_homographs.json.gz",
61
+ self._accents_file(use_dictionary))
62
+ ]
63
+ dirs = ["nn/nn_accent", "nn/nn_yo_homograph_resolver", f"nn/nn_omograph/{omograph_model_size}"]
64
+ if not self.tiny_mode:
65
+ dirs.append("nn/nn_stress_usage_predictor")
66
+ return files, dirs
67
+
68
+ def _fetch(self, repo, workdir, files, dirs):
69
+ def present(root):
70
+ return all(os.path.exists(join_path(root, f)) for f in files) and all(
71
+ os.path.exists(join_path(root, d, "model.onnx")) for d in dirs
72
+ )
73
+
74
+ # Models downloaded by older versions into the package directory.
75
+ if workdir is None and present(PACKAGE_DIR):
76
+ return PACKAGE_DIR
77
+ if workdir is not None and present(workdir):
78
+ return workdir
79
+ return snapshot_download(
80
+ repo_id=repo,
81
+ local_dir=workdir,
82
+ allow_patterns=files + [f"{d}/*" for d in dirs],
83
+ ignore_patterns=["nn/nn_accent/big.onnx"],
84
+ )
85
+
86
+ def load(
87
+ self,
88
+ omograph_model_size="turbo2",
89
+ use_dictionary=False,
90
+ custom_dict=None,
91
+ custom_homographs=None,
92
+ device="CPU",
93
+ repo="ruaccent/accentuator",
94
+ workdir=None,
95
+ tiny_mode=False,
96
+ ):
97
+ """Download (if needed) and load models and dictionaries.
98
+
99
+ ``workdir``: where to keep the files. By default they go to the
100
+ Hugging Face cache (``HF_HOME``).
101
+ """
102
+ if omograph_model_size not in self.omograph_models_paths:
103
+ raise ValueError(
104
+ f"Unknown omograph_model_size {omograph_model_size!r}; "
105
+ f"choose one of: {', '.join(OMOGRAPH_MODELS)}"
106
+ )
107
+ self.tiny_mode = tiny_mode
108
+ files, dirs = self._required_files(omograph_model_size, use_dictionary)
109
+ self.workdir = self._fetch(repo, workdir, files, dirs)
110
+
111
+ def load_json(name):
112
+ with gzip.open(join_path(self.workdir, "dictionary", name)) as f:
113
+ return json.load(f)
114
+
115
+ self.omographs = load_json("omographs.json.gz")
116
+ self.omographs["коса"] = ["к+оса", "кос+а"]
117
+ self.omographs.update(custom_homographs or {})
118
+
119
+ self.yo_words = load_json("yo_words.json.gz")
120
+ self.yo_homographs = load_json("yo_homographs.json.gz")
121
+
122
+ self.accents = load_json(self._accents_file(use_dictionary))
123
+ self.accents.update(custom_dict or {})
124
+ self.accents.update(self.letters_accent)
125
+
126
+ nn = join_path(self.workdir, "nn")
127
+ self.omograph_model.load(join_path(nn, "nn_omograph", omograph_model_size), device=device)
128
+ self.accent_model.load(join_path(nn, "nn_accent"), device=device)
129
+ self.yo_homograph_model.load(join_path(nn, "nn_yo_homograph_resolver"), device=device)
130
+ if not self.tiny_mode:
131
+ self.stress_usage_predictor.load(join_path(nn, "nn_stress_usage_predictor"), device=device)
132
+
133
+ # --------------------------------------------------------------- pipeline
134
+
135
+ @staticmethod
136
+ def count_vowels(text):
137
+ return sum(1 for ch in text if ch in VOWELS)
138
+
139
+ # The sentence-level models are case-sensitive and get confused by ALL-CAPS
140
+ # words ("БЕЛКИ ЕЛИ" -> "БЕЛК+И"), so those are lowercased before inference.
141
+
142
+ def _apply_yo(self, sent, words):
143
+ """words: {token index: current text}; updates it in place."""
144
+ yo = None
145
+ lower = sent.model_text.lower()
146
+ if "е" in lower:
147
+ yo = _SpanLookup(self.yo_homograph_model.predict_yo_homographs(lower))
148
+ for i, token in enumerate(sent.tokens):
149
+ if i not in words:
150
+ continue
151
+ lower = token.text.lower()
152
+ words[i] = fix_capital(token.text, self.yo_words.get(lower, token.text))
153
+ if yo is not None and lower in self.yo_homographs and yo.label(token.start, "NO_YO") == "YO":
154
+ words[i] = fix_capital(token.text, self.yo_homographs[lower])
155
+
156
+ def _apply_omographs(self, sent, words):
157
+ context = [
158
+ words.get(i, t.text).lower() if CAPS_WORD.fullmatch(t.text) else words.get(i, t.text)
159
+ for i, t in enumerate(sent.tokens)
160
+ ]
161
+ found = []
162
+ for i, word in words.items():
163
+ variants = self.omographs.get(word.lower())
164
+ if variants:
165
+ found.append((i, variants))
166
+ if not found:
167
+ return
168
+ texts, hypotheses = [], []
169
+ for i, variants in found:
170
+ marked = context.copy()
171
+ # The homograph model is case-sensitive; it was trained on lowercase targets.
172
+ marked[i] = " <w>" + marked[i].lower() + "</w> "
173
+ text = TextPreprocessor.join_for_model(marked)
174
+ texts.extend([text] * len(variants))
175
+ hypotheses.extend(variants)
176
+ chosen = self.omograph_model.classify(texts, hypotheses, [len(v) for _, v in found])
177
+ for (i, _), variant in zip(found, chosen):
178
+ words[i] = transfer_stress(words[i], variant)
179
+
180
+ def _apply_accents(self, sent, words):
181
+ if self.tiny_mode:
182
+ usage = None
183
+ else:
184
+ usage = _SpanLookup(self.stress_usage_predictor.predict_stress_usage(sent.case_normalized_text))
185
+ for i, word in words.items():
186
+ if "+" in word:
187
+ continue
188
+ if usage is not None and usage.label(sent.tokens[i].start, "STRESS") != "STRESS":
189
+ continue
190
+ stressed = self.accents.get(word.lower())
191
+ if stressed is not None:
192
+ words[i] = transfer_stress(word, stressed)
193
+ elif self.count_vowels(word) > 1:
194
+ words[i] = self.accent_model.put_accent(word)
195
+
196
+ def _process_sentence(self, sentence, yo_only=False):
197
+ sent = TextPreprocessor.analyze(sentence)
198
+ # Only touch words whose original text is exactly what the models saw;
199
+ # anything with user stress marks or unusual characters stays as is.
200
+ words = {i: t.text for i, t in enumerate(sent.tokens) if t.is_word and t.is_clean}
201
+ if not words:
202
+ return sentence
203
+ self._apply_yo(sent, words)
204
+ if not yo_only:
205
+ self._apply_omographs(sent, words)
206
+ self._apply_accents(sent, words)
207
+
208
+ out, pos = [], 0
209
+ for i, word in sorted(words.items()):
210
+ token = sent.tokens[i]
211
+ out.append(sentence[pos:token.orig_start])
212
+ out.append(word)
213
+ pos = token.orig_end
214
+ out.append(sentence[pos:])
215
+ return "".join(out)
216
+
217
+ def _process(self, text, yo_only, skip_regex=None):
218
+ def run(chunk):
219
+ return "".join(
220
+ self._process_sentence(s, yo_only) for s in TextPreprocessor.split_by_sentences(chunk)
221
+ )
222
+
223
+ if not skip_regex:
224
+ return run(text)
225
+ out, pos = [], 0
226
+ for m in re.finditer(skip_regex, text):
227
+ out.append(run(text[pos:m.start()]))
228
+ out.append(m.group())
229
+ pos = m.end()
230
+ out.append(run(text[pos:]))
231
+ return "".join(out)
232
+
233
+ def process_yo(self, text, skip_regex=None):
234
+ """Restore ё in the text."""
235
+ return self._process(text, yo_only=True, skip_regex=skip_regex)
236
+
237
+ def process_all(self, text, skip_regex=None):
238
+ """Restore ё and put stress marks ("+" before the stressed vowel).
239
+
240
+ Text matching ``skip_regex`` is left untouched.
241
+ """
242
+ return self._process(text, yo_only=False, skip_regex=skip_regex)
@@ -0,0 +1,41 @@
1
+ from onnxruntime import InferenceSession, SessionOptions, get_available_providers
2
+
3
+
4
+ def create_session(model_path: str, device: str = "CPU") -> InferenceSession:
5
+ """
6
+ Creates an ONNX Runtime InferenceSession configured for the specified device/provider.
7
+
8
+ Supported device values:
9
+ - 'CPU': Standard CPU execution provider (default).
10
+ - 'CoreML' / 'MPS' / 'Apple': Uses CoreMLExecutionProvider for hardware acceleration
11
+ on Apple Silicon (M1/M2/M3/M4 via Neural Engine and GPU) with CPU fallback.
12
+ - 'CUDA': Uses CUDAExecutionProvider for NVIDIA GPUs with CPU fallback.
13
+ - 'auto': Automatically selects CoreML on Apple Silicon, CUDA on NVIDIA, or CPU.
14
+ """
15
+ device_upper = (device or "CPU").upper()
16
+ sess_opts = SessionOptions()
17
+ sess_opts.log_severity_level = 3 # Suppress partition warnings on CoreML
18
+
19
+ available = get_available_providers()
20
+
21
+ if device_upper in ("COREML", "MPS", "APPLE", "ANE"):
22
+ if "CoreMLExecutionProvider" in available:
23
+ providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"]
24
+ else:
25
+ providers = ["CPUExecutionProvider"]
26
+ elif device_upper == "CUDA":
27
+ if "CUDAExecutionProvider" in available:
28
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
29
+ else:
30
+ providers = ["CPUExecutionProvider"]
31
+ elif device_upper in ("AUTO", "DETECT"):
32
+ if "CoreMLExecutionProvider" in available:
33
+ providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"]
34
+ elif "CUDAExecutionProvider" in available:
35
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
36
+ else:
37
+ providers = ["CPUExecutionProvider"]
38
+ else:
39
+ providers = ["CPUExecutionProvider"]
40
+
41
+ return InferenceSession(model_path, sess_options=sess_opts, providers=providers)
@@ -0,0 +1,8 @@
1
+ from .token_classifier import TokenClassifier
2
+
3
+
4
+ class StressUsagePredictorModel(TokenClassifier):
5
+ """Predicts which words of a sentence should get a stress mark."""
6
+
7
+ def predict_stress_usage(self, text):
8
+ return self.predict(text)
@@ -0,0 +1,24 @@
1
+ def fix_capital(source, target):
2
+ """Copy letter case from ``source`` onto ``target`` of the same length."""
3
+ if len(source) != len(target):
4
+ return target
5
+ return "".join(t.upper() if s.isupper() else t.lower() for s, t in zip(source, target))
6
+
7
+
8
+ def transfer_stress(word, stressed):
9
+ """Put the "+" marks of ``stressed`` into ``word``, keeping its letters and case.
10
+
11
+ >>> transfer_stress("Замок", "зам+ок")
12
+ 'Зам+ок'
13
+ """
14
+ letters = stressed.replace("+", "")
15
+ if len(letters) != len(word):
16
+ return stressed
17
+ out, j = [], 0
18
+ for ch in stressed:
19
+ if ch == "+":
20
+ out.append("+")
21
+ else:
22
+ out.append(word[j])
23
+ j += 1
24
+ return "".join(out)
@@ -0,0 +1,87 @@
1
+ import re
2
+ from dataclasses import dataclass
3
+ from typing import List
4
+
5
+ from razdel import sentenize
6
+
7
+ # Characters the neural models were trained on. Everything else (emoji, %, /,
8
+ # user stress marks "+", ...) is hidden from the models but kept in the output.
9
+ MODEL_CHARS = re.compile(r"[a-zA-Z0-9\sа-яА-ЯёЁ—.,!?:;\"'(){}\[\]«»„“”-]")
10
+ CAPS_WORD = re.compile(r"\b[A-ZА-ЯЁ]{2,}\b")
11
+ TOKEN = re.compile(r"\w+|[^\w\s]+")
12
+
13
+
14
+ @dataclass
15
+ class Token:
16
+ text: str # token as the models see it
17
+ start: int # span in the model text
18
+ end: int
19
+ orig_start: int # span in the original text
20
+ orig_end: int
21
+ original: str # original text of the span
22
+
23
+ @property
24
+ def is_word(self):
25
+ return self.text[0].isalnum() or self.text[0] == "_"
26
+
27
+ @property
28
+ def is_clean(self):
29
+ """True if the original span is exactly what the models saw."""
30
+ return self.original == self.text
31
+
32
+
33
+ @dataclass
34
+ class Sentence:
35
+ original: str
36
+ model_text: str
37
+ tokens: List[Token]
38
+
39
+ @property
40
+ def case_normalized_text(self):
41
+ """Model text with ALL-CAPS words lowercased (same length and offsets)."""
42
+ return CAPS_WORD.sub(lambda m: m.group().lower(), self.model_text)
43
+
44
+
45
+ class TextPreprocessor:
46
+ @staticmethod
47
+ def split_by_sentences(string):
48
+ """Split text into chunks whose concatenation is exactly ``string``."""
49
+ sentences = list(sentenize(string))
50
+ if not sentences:
51
+ return [string] if string else []
52
+ result, prev_stop = [], 0
53
+ for s in sentences:
54
+ result.append(string[prev_stop:s.stop])
55
+ prev_stop = s.stop
56
+ result[-1] += string[prev_stop:]
57
+ return result
58
+
59
+ @staticmethod
60
+ def analyze(sentence):
61
+ """Build the model view of a sentence and map its tokens back."""
62
+ keep = [i for i, ch in enumerate(sentence) if MODEL_CHARS.match(ch)]
63
+ model_text = "".join(sentence[i] for i in keep)
64
+ # A free-standing dash is marked as "~" so the homograph model input
65
+ # keeps the spaces around it (see join_for_model).
66
+ tokens = []
67
+ for m in TOKEN.finditer(model_text.replace(" - ", " ~ ")):
68
+ orig_start, orig_end = keep[m.start()], keep[m.end() - 1] + 1
69
+ tokens.append(Token(
70
+ text=m.group(),
71
+ start=m.start(),
72
+ end=m.end(),
73
+ orig_start=orig_start,
74
+ orig_end=orig_end,
75
+ original=sentence[orig_start:orig_end],
76
+ ))
77
+ return Sentence(sentence, model_text, tokens)
78
+
79
+ @staticmethod
80
+ def join_for_model(words):
81
+ """Join tokens the way the homograph model saw text during training."""
82
+ text = " ".join(words)
83
+ for char in "!\"#$%&'()*,./:;<=>?@[\\]^_`{|}-":
84
+ if char == "-":
85
+ text = text.replace(" -", "-").replace("- ", "-")
86
+ text = text.replace(" " + char, char)
87
+ return text.replace("~", "-")
@@ -0,0 +1,89 @@
1
+ import json
2
+ from os.path import join as join_path
3
+
4
+ import numpy as np
5
+ from transformers import AutoTokenizer
6
+
7
+ from .session_helper import create_session
8
+
9
+
10
+ def softmax(x):
11
+ e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
12
+ return e_x / e_x.sum(axis=-1, keepdims=True)
13
+
14
+
15
+ class TokenClassifier:
16
+ """ONNX token-classification model that returns one label per word.
17
+
18
+ Word boundaries follow the tokenizer: sub-word tokens are merged into the
19
+ preceding word and their class probabilities are averaged. Every returned
20
+ entity carries character offsets (``start``/``end``) into the input text,
21
+ so callers can align predictions with their own tokenization.
22
+ """
23
+
24
+ def load(self, path, device="CPU"):
25
+ self.session = create_session(join_path(path, "model.onnx"), device=device)
26
+ with open(join_path(path, "config.json"), "r", encoding="utf-8") as f:
27
+ self.id2label = json.load(f)["id2label"]
28
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
29
+ self.input_names = {i.name for i in self.session.get_inputs()}
30
+ self._has_subword_prefix = bool(
31
+ getattr(self.tokenizer._tokenizer.model, "continuing_subword_prefix", None)
32
+ )
33
+
34
+ def _collect_tokens(self, text, input_ids, scores, offset_mapping, special_tokens_mask):
35
+ tokens = []
36
+ for idx, token_scores in enumerate(scores):
37
+ if special_tokens_mask[idx]:
38
+ continue
39
+ token = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx]))
40
+ start, end = int(offset_mapping[idx][0]), int(offset_mapping[idx][1])
41
+ if self._has_subword_prefix:
42
+ is_subword = len(token) != len(text[start:end])
43
+ else:
44
+ is_subword = start > 0 and text[start - 1:start] != " "
45
+ if int(input_ids[idx]) == self.tokenizer.unk_token_id:
46
+ is_subword = False
47
+ tokens.append({"scores": token_scores, "start": start, "end": end, "is_subword": is_subword})
48
+ return tokens
49
+
50
+ def _aggregate(self, group, text):
51
+ average = np.nanmean(np.stack([t["scores"] for t in group]), axis=0)
52
+ idx = int(average.argmax())
53
+ start, end = group[0]["start"], group[-1]["end"]
54
+ return {
55
+ "entity": self.id2label[str(idx)],
56
+ "score": float(average[idx]),
57
+ "word": text[start:end],
58
+ "start": start,
59
+ "end": end,
60
+ }
61
+
62
+ def predict(self, text):
63
+ inputs = self.tokenizer(
64
+ text,
65
+ return_offsets_mapping=True,
66
+ return_special_tokens_mask=True,
67
+ return_tensors="np",
68
+ truncation=True,
69
+ max_length=512,
70
+ )
71
+ offset_mapping = inputs.pop("offset_mapping")[0]
72
+ special_tokens_mask = inputs.pop("special_tokens_mask")[0]
73
+ input_ids = inputs["input_ids"][0]
74
+ feed = {k: v.astype(np.int64) for k, v in inputs.items() if k in self.input_names}
75
+ if "token_type_ids" in self.input_names and "token_type_ids" not in feed:
76
+ feed["token_type_ids"] = np.zeros_like(feed["input_ids"])
77
+ logits = self.session.run(None, feed)[0]
78
+ scores = softmax(logits)[0]
79
+
80
+ tokens = self._collect_tokens(text, input_ids, scores, offset_mapping, special_tokens_mask)
81
+ words, group = [], []
82
+ for token in tokens:
83
+ if group and not token["is_subword"]:
84
+ words.append(self._aggregate(group, text))
85
+ group = []
86
+ group.append(token)
87
+ if group:
88
+ words.append(self._aggregate(group, text))
89
+ return words
@@ -0,0 +1,8 @@
1
+ from .token_classifier import TokenClassifier
2
+
3
+
4
+ class YoHomographModel(TokenClassifier):
5
+ """Predicts whether an е/ё homograph should be written with ё."""
6
+
7
+ def predict_yo_homographs(self, text):
8
+ return self.predict(text)
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: ruaccent
3
+ Version: 1.6.0
4
+ Summary: A Russian text accentuation tool
5
+ Author-email: Denis Petrov <arduino4b@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Den4ikAI/ruaccent
8
+ Project-URL: Models, https://huggingface.co/ruaccent/accentuator
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Natural Language :: Russian
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Text Processing :: Linguistic
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: huggingface_hub>=0.23
19
+ Requires-Dist: numpy
20
+ Requires-Dist: onnxruntime
21
+ Requires-Dist: razdel
22
+ Requires-Dist: transformers>=4.30
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # RUAccent
28
+
29
+ RUAccent — библиотека для автоматической расстановки ударений и буквы «ё» в русском тексте.
30
+
31
+ Лицензия — MIT.
32
+
33
+ ## Установка
34
+
35
+ ```
36
+ pip install ruaccent
37
+ ```
38
+
39
+ Свежая версия из репозитория:
40
+
41
+ ```
42
+ pip install git+https://github.com/Den4ikAI/ruaccent.git
43
+ ```
44
+
45
+ ## Пример использования
46
+
47
+ ```python
48
+ from ruaccent import RUAccent
49
+
50
+ accentizer = RUAccent()
51
+ accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
52
+
53
+ print(accentizer.process_all('на двери висит замок.'))
54
+ # на двер+и вис+ит зам+ок.
55
+
56
+ print(accentizer.process_yo('Все елки зеленые.'))
57
+ # Все ёлки зелёные.
58
+ ```
59
+
60
+ Ударение ставится знаком `+` перед ударной гласной. Остальной текст (пробелы, переносы строк, символы, эмодзи) возвращается без изменений. Слова, в которых ударение уже стоит (`пр+ивет`), не трогаются.
61
+
62
+ ## Параметры
63
+
64
+ ```python
65
+ load(omograph_model_size='turbo2', use_dictionary=False, custom_dict=None,
66
+ custom_homographs=None, device='CPU', workdir=None, tiny_mode=False)
67
+ ```
68
+
69
+ - **omograph_model_size** — модель для омографов: `tiny`, `tiny2`, `tiny2.1`, `turbo`, `turbo2`, `turbo3`, `turbo3.1`, `small_poetry`, `medium_poetry`, `big_poetry`.
70
+ - **use_dictionary** — загрузить полный словарь ударений (требуется больше ОЗУ). Иначе слова, которых нет в малом словаре, размечает нейросеть.
71
+ - **custom_dict** — свои ударения: `{'слово': 'сл+ово'}`.
72
+ - **custom_homographs** — свои омографы: `{'слово': ['вариант+1', 'вар+иант2']}`.
73
+ - **device** — `CPU` (по умолчанию), `CUDA` (нужен `onnxruntime-gpu`), `CoreML` для Apple Silicon или `auto` — выбрать лучший доступный.
74
+ - **workdir** — папка для моделей. По умолчанию они скачиваются в кэш Hugging Face (`HF_HOME`). Для работы без сети после первой загрузки: `HF_HUB_OFFLINE=1`.
75
+ - **tiny_mode** — облегчённый режим: без модели выбора слов для ударения и без полного словаря.
76
+
77
+ `process_all(text, skip_regex=None)` и `process_yo(text, skip_regex=None)` не трогают фрагменты, подходящие под `skip_regex` (например, `r"<[^>]+>"` для HTML-тегов).
78
+
79
+ Для стабильной работы требуется минимум 512 МБ ОЗУ (модель омографов `tiny`).
80
+
81
+ Файлы моделей и словарей: [huggingface.co/ruaccent/accentuator](https://huggingface.co/ruaccent/accentuator). Будем признательны за фидбек в [Telegram](https://t.me/bceloss).
82
+
83
+ ## Разработка
84
+
85
+ ```
86
+ pip install -e .[test]
87
+ pytest # быстрые тесты
88
+ RUACCENT_TEST_MODELS=1 pytest # с загрузкой моделей
89
+ ```
90
+
91
+ ## Донат
92
+
93
+ Вы можете поддержать проект деньгами. Это поможет быстрее разрабатывать более качественные новые версии.
94
+ CloudTips: https://pay.cloudtips.ru/p/b9d86686
@@ -0,0 +1,16 @@
1
+ ruaccent/__init__.py,sha256=qT3fLz8MNtfSKuErTGEewAfYNmofdLWUUcJF1c7W88M,81
2
+ ruaccent/accent_model.py,sha256=dK6BYm-lHInE2Cus_qdcsY6Y33zC4YNXX_NM8VAAvOg,1926
3
+ ruaccent/char_tokenizer.py,sha256=n40jUvxwrCqkCCrcyQ-IpU-VEGC_i3Wiss7NxeC0HKk,2999
4
+ ruaccent/omograph_model.py,sha256=78QzfcGarXn2sGHFUVwl-9pR7LDqP9MmjiCJ-RL62j0,1878
5
+ ruaccent/ruaccent.py,sha256=L-G-y7dS-mAQXMr9sBBvs_heyU1qbyMbXy0mY_OR9t4,9630
6
+ ruaccent/session_helper.py,sha256=ArXZGSGn5nhl2DvVCxjfr3171s6x6n4ID53h91HChgA,1865
7
+ ruaccent/stress_usage_model.py,sha256=27FcwlKt2s49OWKaSbknZd2Cgi-MCBZfeQoksJqxsOw,246
8
+ ruaccent/text_postprocessor.py,sha256=ZW4RpEPwU4HJ6oNgRfwdomWjiByysJpMzo-EN7FBUPY,746
9
+ ruaccent/text_preprocessor.py,sha256=0FSqaln4sdd0Wkd-wcPkdpALbh8agYjlRtfcsTSDPfk,3002
10
+ ruaccent/token_classifier.py,sha256=RPVK1B5d7CuKdfS252xaeuDASkFAyukMBK8AQqMnqIc,3626
11
+ ruaccent/yo_homograph_model.py,sha256=cg5Mj9izLHp6qnYbzfOBGZnxhUHe22-ANHm-QRIf5Wo,240
12
+ ruaccent-1.6.0.dist-info/licenses/LICENSE,sha256=XMt5bR-iWu7AzH062kkVljzsO3ys-iyznOAMZXYeetY,1060
13
+ ruaccent-1.6.0.dist-info/METADATA,sha256=ytitWL9jZ87YENKuRd-nTagN6t_u0PbV8wRS-CXvbRg,4453
14
+ ruaccent-1.6.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ ruaccent-1.6.0.dist-info/top_level.txt,sha256=rLQiuT1ATg3UXm_fQuMVk7se1kDvNITcH1ACDwExnHE,9
16
+ ruaccent-1.6.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,7 @@
1
+ Copyright 2026 Denis Petrov
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ ruaccent