ukr-dev-kit 0.2.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.
Files changed (34) hide show
  1. ukr_dev_kit/__init__.py +7 -0
  2. ukr_dev_kit/cli.py +50 -0
  3. ukr_dev_kit/skills/ukr-data/SKILL.md +80 -0
  4. ukr_dev_kit/skills/ukr-data/references/validators.md +179 -0
  5. ukr_dev_kit/skills/ukr-data/scripts/ukr_data.py +630 -0
  6. ukr_dev_kit/skills/ukr-i18n/SKILL.md +61 -0
  7. ukr_dev_kit/skills/ukr-i18n/references/formats.md +75 -0
  8. ukr_dev_kit/skills/ukr-i18n/references/plurals.md +144 -0
  9. ukr_dev_kit/skills/ukr-i18n/references/ui-glossary.md +97 -0
  10. ukr_dev_kit/skills/ukr-i18n/scripts/i18n_check.py +479 -0
  11. ukr_dev_kit/skills/ukr-proofread/SKILL.md +67 -0
  12. ukr_dev_kit/skills/ukr-proofread/references/it-glossary.md +101 -0
  13. ukr_dev_kit/skills/ukr-proofread/references/style-guide.md +64 -0
  14. ukr_dev_kit/skills/ukr-proofread/references/typography.md +36 -0
  15. ukr_dev_kit/skills/ukr-proofread/rules/calque.txt +45 -0
  16. ukr_dev_kit/skills/ukr-proofread/rules/style.txt +13 -0
  17. ukr_dev_kit/skills/ukr-proofread/rules/surzhyk.txt +75 -0
  18. ukr_dev_kit/skills/ukr-proofread/rules/term.txt +17 -0
  19. ukr_dev_kit/skills/ukr-proofread/scripts/ukr_lint.py +826 -0
  20. ukr_dev_kit/skills/ukr-voice/SKILL.md +120 -0
  21. ukr_dev_kit/skills/ukr-voice/assets/gemini_voices.json +32 -0
  22. ukr_dev_kit/skills/ukr-voice/assets/presets.json +52 -0
  23. ukr_dev_kit/skills/ukr-voice/references/holos.md +46 -0
  24. ukr_dev_kit/skills/ukr-voice/references/markup.md +48 -0
  25. ukr_dev_kit/skills/ukr-voice/scripts/gemini_tts.py +157 -0
  26. ukr_dev_kit/skills/ukr-voice/scripts/holos_engine.py +356 -0
  27. ukr_dev_kit/skills/ukr-voice/scripts/markup.py +163 -0
  28. ukr_dev_kit/skills/ukr-voice/scripts/subtitles.py +210 -0
  29. ukr_dev_kit/skills/ukr-voice/scripts/ukr_voice.py +767 -0
  30. ukr_dev_kit-0.2.0.dist-info/METADATA +54 -0
  31. ukr_dev_kit-0.2.0.dist-info/RECORD +34 -0
  32. ukr_dev_kit-0.2.0.dist-info/WHEEL +4 -0
  33. ukr_dev_kit-0.2.0.dist-info/entry_points.txt +5 -0
  34. ukr_dev_kit-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,356 @@
1
+ """Рушій синтезу HolosTTS — запускається ЛИШЕ інтерпретатором оточення (див. ukr_voice.py setup holos).
2
+
3
+ HolosTTS — модель української мови від patriotyk (MIT): https://github.com/patriotyk/HolosTTS
4
+
5
+ Модель живе тільки під час виконання: завантажилась → озвучила всі завдання → процес завершився,
6
+ памʼять звільнена. Тому для локального бекенда нема чого «вимикати».
7
+
8
+ holos_engine.py voices
9
+ holos_engine.py batch jobs.json # [{"text", "voice", "out", "light"?, "speed"?, "expr"?, "pitch"?}]
10
+
11
+ Текст може містити режисерську розмітку (див. MARKUP нижче і SKILL.md): емоції, паузи, темп, виділення.
12
+ """
13
+ import contextlib, io, json, os, re, sys
14
+ from unicodedata import normalize
15
+
16
+ DATA = os.environ.get('UKR_VOICE_HOME', os.path.expanduser('~/.local/share/ukr-voice'))
17
+ sys.path.insert(0, os.path.join(DATA, 'HolosTTS'))
18
+
19
+ import numpy as np
20
+ import soundfile as sf
21
+ import torch
22
+ from ipa_uk import ipa
23
+ from ukrainian_word_stress import Stressifier, StressSymbol
24
+ import holos.models as _hm
25
+ from holos.models import HolosTTS
26
+
27
+ # Ваги на Hugging Face оновлюються разом із кодом. Закріплюємо ревізію, з якою сумісний закріплений
28
+ # коміт коду (див. HOLOS_COMMIT у ukr_voice.py) — інакше нова версія ваг ламає завантаження моделі.
29
+ _REV = os.environ.get('UKR_VOICE_HF_REVISION')
30
+ if _REV:
31
+ _orig_dl = _hm.hf_hub_download
32
+ _hm.hf_hub_download = lambda *a, **k: _orig_dl(*a, **{**k, 'revision': k.get('revision') or _REV})
33
+
34
+ SR = 24000
35
+ ACUTE = StressSymbol.CombiningAcuteAccent
36
+ VOWELS = 'аеєиіїоуюяАЕЄИІЇОУЮЯ'
37
+ IPA_VOWELS = 'aɑɐeɛəiɪɨoɔuʊyʉæ'
38
+ _model = _stress = None
39
+
40
+
41
+ def model():
42
+ global _model, _stress
43
+ if _model is None:
44
+ torch.set_num_threads(max(1, (os.cpu_count() or 4) - 1))
45
+ _model = HolosTTS('patriotyk/HolosTTS', device='cpu')
46
+ _stress = Stressifier()
47
+ return _model
48
+
49
+
50
+ def light_stress(t):
51
+ """Прибирає наголос з односкладових слів («ти́», «на́», «не́») — мова плавніша, без «рубаності»."""
52
+ def fix(m):
53
+ w = m.group(0)
54
+ return w.replace(ACUTE, '') if sum(ch in VOWELS for ch in w) <= 1 else w
55
+ return re.sub(r"[\w'" + ACUTE + r"]+", fix, t)
56
+
57
+
58
+ LEXICON = os.environ.get('UKR_VOICE_LEXICON', os.path.expanduser('~/.config/ukr-voice/lexicon.json'))
59
+
60
+
61
+ def lexicon(t):
62
+ """Словник вимови користувача: {"Ніко": "Ніко+"} — імена й слова, яких не знає словник наголосів."""
63
+ if not os.path.exists(LEXICON):
64
+ return t
65
+ for w, r in json.load(open(LEXICON)).items():
66
+ t = re.sub(r'(?<![\w+])' + re.escape(w) + r'(?![\w+])', r, t)
67
+ return t
68
+
69
+
70
+ def prep(t, light=True, final=True):
71
+ """Підготовка як у демо HolosTTS: «+» після голосної — ручний наголос, тире → пауза.
72
+ final=False — шматок перед паузою всередині репліки: крапку в кінці не дописуємо, інтонація «висить»."""
73
+ t = lexicon(t.strip()).replace('"', '').replace('+', ACUTE)
74
+ t = normalize('NFKC', t)
75
+ t = re.sub(r'[᠆‐‑‒–—―⁻₋−⸺⸻]', '-', t)
76
+ if final and t and t[-1] not in '.?!:-…':
77
+ t += '.'
78
+ t = re.sub(r' - ', ': ', t)
79
+ t = _stress(t)
80
+ return ipa(light_stress(t) if light else t)
81
+
82
+
83
+ def _mix(spec):
84
+ m = model()
85
+ vec = 0
86
+ for part in spec.split('+'):
87
+ name, w = (part.rsplit('*', 1) + ['1'])[:2] if '*' in part else (part, '1')
88
+ name = name.strip()
89
+ if name not in m.voices:
90
+ raise SystemExit(f'Немає голосу «{name}». Список: ukr_voice.py voices --engine holos')
91
+ vec = vec + m.voices[name] * float(w)
92
+ return vec
93
+
94
+
95
+ def voice_vec(spec):
96
+ """Голос: 'Speaker_43'; суміш 'Speaker_43*0.5+Speaker_37*0.5';
97
+ або окремо тембр і манеру: 'timbre=<суміш>;prosody=<суміш>'.
98
+ Вектор голосу HolosTTS = 128 чисел тембру + 128 чисел просодії (паузи, ритм, інтонація)."""
99
+ if 'timbre=' in spec:
100
+ d = dict(p.split('=', 1) for p in spec.split(';'))
101
+ t, pr = _mix(d['timbre']), _mix(d.get('prosody', d['timbre']))
102
+ return torch.cat([t[:128], pr[128:]])
103
+ return _mix(spec)
104
+
105
+
106
+ # ============================ керування подачею ============================
107
+ def _shape(f0, energy, pred_dur, c):
108
+ """Покадрово міняє криву висоти й гучність: розмах інтонації (expr), висоту (pitch), гучність (energy).
109
+ Значення задані на кожен звук; розгортаємо їх на кадри й згладжуємо, щоб не було сходинок."""
110
+ reps = (pred_dur * 2).cpu().numpy()
111
+ n = f0.shape[-1]
112
+
113
+ def frames(a):
114
+ x = np.repeat(np.asarray(a, np.float32), reps)[:n]
115
+ x = np.pad(x, (0, n - len(x)), mode='edge')
116
+ return np.convolve(np.pad(x, 4, mode='edge'), np.ones(9, np.float32) / 9, mode='valid')
117
+
118
+ expr, pitch, egain = frames(c['expr']), frames(c['pitch']), frames(c['energy'])
119
+ f = f0[0].cpu().numpy().astype(np.float32)
120
+ voiced = f > 60
121
+ if voiced.sum() > 5:
122
+ lf = np.log(np.maximum(f, 1))
123
+ mid = np.median(lf[voiced])
124
+ f = np.where(voiced, np.clip(np.exp(mid + expr * (lf - mid)) * pitch, 70, 650), f)
125
+ e = energy[0].cpu().numpy().astype(np.float32) + egain
126
+ return torch.from_numpy(f).unsqueeze(0).to(f0.dtype), torch.from_numpy(e).unsqueeze(0).to(energy.dtype)
127
+
128
+
129
+ def _encode_ctrl(self, tokens, voice, input_lengths, speed=1.0):
130
+ """Копія HolosTTS.encode з керуванням: темп (self.speed і тривалість кожного звука з self.ctrl['dur']),
131
+ а після передбачення — висота, розмах інтонації й гучність (див. _shape)."""
132
+ c = getattr(self, 'ctrl', None)
133
+ voice_acoustic, voice_prosodic = voice[:, :128], voice[:, 128:]
134
+ t_en = self.prosodic_text_encoder(tokens, input_lengths)
135
+ d_en = t_en.transpose(1, 2)
136
+ d = self.duration_predictor(d_en, voice_prosodic, input_lengths)
137
+ duration = torch.sigmoid(d).sum(axis=-1)[0] / (getattr(self, 'speed', 1.0) * float(speed or 1.0))
138
+ if c is not None and len(c['dur']) == duration.shape[0]:
139
+ duration = duration * torch.tensor(c['dur'], dtype=duration.dtype)
140
+ else:
141
+ c = None
142
+ pred_dur = torch.round(duration).long()
143
+ aln = self.onnx_alignment(pred_dur, d_en.size(1))
144
+ en = d_en.transpose(-1, -2) @ aln
145
+ wav_lengths = pred_dur.sum(dim=0, keepdim=True) * 2
146
+ f0, energy = self.prosodic_predictor(en, voice_prosodic, wav_lengths)
147
+ if c is not None and c.get('shape'):
148
+ f0, energy = _shape(f0, energy, pred_dur, c)
149
+ return self.text_encoder(tokens, input_lengths) @ aln, f0, energy, voice_acoustic, wav_lengths
150
+
151
+
152
+ HolosTTS.encode = _encode_ctrl
153
+
154
+ # ============================ розмітка ============================
155
+ MARKUP = """
156
+ (радісно) … емоція з цього місця до кінця репліки чи до наступної емоції
157
+ / // /// пауза 0,12 / 0,3 / 0,5 с; [0.6] — пауза точно в секундах
158
+ *слово* виділити: трохи повільніше, вище й гучніше (можна кілька слів: *ну дуже*)
159
+ О~го протягнути голосну перед «~» (останню голосну слова, якщо «~» в кінці)
160
+ {швидко: …} шматок з особливою подачею; слова можна поєднувати: {тихо повільно: …}
161
+ """
162
+ # емоція → (розмах інтонації, висота, темп, гучність)
163
+ EMOTIONS = {
164
+ 'спокійно': (1.0, 1.0, 1.0, 0.0),
165
+ 'радісно': (1.35, 1.05, 1.06, .3),
166
+ 'захоплено': (1.55, 1.09, 1.08, .5),
167
+ 'здивовано': (1.6, 1.1, .98, .4),
168
+ 'обурено': (1.35, 1.03, 1.1, .6),
169
+ 'таємниче': (.75, .94, .92, -.7),
170
+ 'сумно': (.7, .94, .92, -.5),
171
+ 'задумливо': (.85, .97, .95, -.3),
172
+ 'гордо': (1.2, .98, .98, .3),
173
+ 'налякано': (1.45, 1.1, 1.12, -.2),
174
+ 'хитро': (1.25, 1.0, .98, -.2),
175
+ }
176
+ ALIASES = {'весело': 'радісно', 'сердито': 'обурено', 'злякано': 'налякано', 'пошепки': 'таємниче'}
177
+ SPAN = {'швидко': ('speed', 1.2), 'повільно': ('speed', .82), 'тихо': ('energy', -.8), 'голосно': ('energy', .7),
178
+ 'високо': ('pitch', 1.1), 'низько': ('pitch', .9), 'рівно': ('expr', .6), 'жваво': ('expr', 1.5)}
179
+ PAUSES = {1: .12, 2: .3, 3: .5}
180
+ _TOKEN = re.compile(r'\((?P<emo>[^()\s]+)\)|\[(?P<sec>\d+(?:[.,]\d+)?)\]|(?P<slash>/{1,3})|\{(?P<mods>[^:{}]+):'
181
+ r'|(?P<close>\})|(?P<star>\*)|(?P<ws>\s+)|(?P<ch>.)', re.S)
182
+
183
+
184
+ def parse(text):
185
+ """Розмічений текст → [('pause', сек) | ('word', текст, {expr, pitch, speed, energy, emph, stretch})]."""
186
+ emo, span, emph = EMOTIONS['спокійно'], {}, False
187
+ out, word, attrs = [], '', {}
188
+
189
+ def cur():
190
+ a = dict(expr=emo[0], pitch=emo[1], speed=emo[2], energy=emo[3], emph=emph)
191
+ for k, v in span.items():
192
+ a[k] = a[k] + v if k == 'energy' else a[k] * v
193
+ return a
194
+
195
+ def flush():
196
+ nonlocal word, attrs
197
+ if word.strip():
198
+ out.append(('word', word, attrs))
199
+ word, attrs = '', {}
200
+
201
+ for m in _TOKEN.finditer(text):
202
+ g = m.lastgroup
203
+ if g == 'emo':
204
+ name = ALIASES.get(m['emo'].lower(), m['emo'].lower())
205
+ if name not in EMOTIONS:
206
+ raise SystemExit(f'Невідома емоція «{m["emo"]}». Є: {", ".join(EMOTIONS)}')
207
+ flush(); emo = EMOTIONS[name]
208
+ elif g in ('sec', 'slash'):
209
+ flush()
210
+ out.append(('pause', float(m['sec'].replace(',', '.')) if g == 'sec' else PAUSES[len(m['slash'])]))
211
+ elif g == 'mods':
212
+ flush(); span = {}
213
+ for mod in m['mods'].split():
214
+ if mod.lower() not in SPAN:
215
+ raise SystemExit(f'Невідома подача «{mod}». Є: {", ".join(SPAN)}')
216
+ k, v = SPAN[mod.lower()]
217
+ span[k] = span.get(k, 0) + v if k == 'energy' else span.get(k, 1.0) * v
218
+ elif g == 'close':
219
+ flush(); span = {}
220
+ elif g == 'star':
221
+ flush(); emph = not emph
222
+ elif g == 'ws':
223
+ flush()
224
+ elif m['ch'] == '~':
225
+ if word:
226
+ attrs['stretch'] = len(re.sub(r'[^' + VOWELS + ']', '', word)) # котра за ліком голосна
227
+ elif not word and m['ch'] in '.,!?…:;»)' and out and out[-1][0] == 'word':
228
+ out[-1] = ('word', out[-1][1] + m['ch'], out[-1][2]) # «*Котів*!» — знак лишається при слові
229
+ else:
230
+ if not word:
231
+ attrs = cur()
232
+ word += m['ch']
233
+ flush()
234
+ return out
235
+
236
+
237
+ def _neutral(a):
238
+ return a['expr'] == 1 and a['pitch'] == 1 and a['speed'] == 1 and a['energy'] == 0 and not a['emph'] \
239
+ and not a.get('stretch')
240
+
241
+
242
+ def _segments(items, limit=120):
243
+ """Слова між паузами; довгі шматки — групами речень до ~120 символів (інтонація не обривається)."""
244
+ segs, cur = [], []
245
+ for it in items:
246
+ if it[0] == 'pause':
247
+ if cur:
248
+ segs.append((cur, it[1])); cur = []
249
+ elif segs:
250
+ segs[-1] = (segs[-1][0], segs[-1][1] + it[1])
251
+ else:
252
+ if cur and re.search(r'[.?!…]["»)]*$', cur[-1][1]) and \
253
+ len(' '.join(w[1] for w in cur)) + len(it[1]) > limit:
254
+ segs.append((cur, 0.0)); cur = []
255
+ cur.append(it)
256
+ if cur:
257
+ segs.append((cur, 0.0))
258
+ return segs
259
+
260
+
261
+ def _ipa_words(words, light, final):
262
+ """IPA для шматка; транскрибуємо цілим (кращі наголоси), а слова зіставляємо за пробілами."""
263
+ whole = prep(' '.join(w[1] for w in words), light, final)
264
+ parts = whole.split(' ')
265
+ if len(parts) == len(words):
266
+ return parts
267
+ return [prep(w[1], light, final and k == len(words) - 1) for k, w in enumerate(words)]
268
+
269
+
270
+ def _control(words, parts, base_expr, base_pitch):
271
+ """Значення на кожен токен моделі (разом із крайовими нулями) + рядок IPA."""
272
+ tok = model().tokenizer.dict
273
+ dur, expr, pitch, energy = [1.0], [base_expr], [base_pitch], [0.0]
274
+ text = ' '.join(parts)
275
+ for k, (w, p) in enumerate(zip(words, parts)):
276
+ a = w[2]
277
+ vow = [i for i, ch in enumerate(p) if ch in IPA_VOWELS]
278
+ sv = vow[min(a['stretch'], len(vow)) - 1] if a.get('stretch') and vow else -1
279
+ for i, ch in enumerate(p + (' ' if k < len(words) - 1 else '')):
280
+ if ch not in tok:
281
+ continue
282
+ em = a['emph'] and ch != ' '
283
+ dur.append((1 / a['speed']) * (1.25 if em else 1) * (2.4 if i == sv else 1))
284
+ expr.append(base_expr * a['expr'] * (1.2 if em else 1))
285
+ pitch.append(base_pitch * a['pitch'] * (1.1 if em else 1))
286
+ energy.append(a['energy'] + (.5 if em else 0))
287
+ dur.append(1.0); expr.append(expr[-1]); pitch.append(pitch[-1]); energy.append(energy[-1])
288
+ return text, dict(dur=dur, expr=expr, pitch=pitch, energy=energy)
289
+
290
+
291
+ def _tighten(x, max_gap=.3, keep=.2, edge=.03, thr_db=-42):
292
+ """Довгі паузи моделі всередині шматка (> 0,4 с) стискаємо до 0,28 с; тишу по краях обрізаємо."""
293
+ hop = SR // 100
294
+ n = len(x) // hop
295
+ if n < 3:
296
+ return x
297
+ rms = np.sqrt(np.mean(x[:n * hop].reshape(n, hop) ** 2, axis=1) + 1e-12)
298
+ loud = 20 * np.log10(rms / (np.abs(x).max() + 1e-9)) > thr_db
299
+ if not loud.any():
300
+ return x
301
+ a, b = int(np.argmax(loud)), n - int(np.argmax(loud[::-1]))
302
+ half, out, k = int(keep * 50), [], a
303
+ while k < b:
304
+ j = k
305
+ while j < b and loud[j] == loud[k]:
306
+ j += 1
307
+ if not loud[k] and j - k > max_gap * 100:
308
+ out += [x[k * hop:(k + half) * hop], x[(j - half) * hop:j * hop]]
309
+ else:
310
+ out.append(x[k * hop:j * hop])
311
+ k = j
312
+ e = int(edge * SR)
313
+ return np.concatenate([x[max(0, a * hop - e):a * hop]] + out + [x[b * hop:b * hop + e]])
314
+
315
+
316
+ def say(text, voice, light=True, speed=1.0, expr=1.0, pitch=1.0):
317
+ """Розмічений текст → хвиля. Без розмітки й з expr=pitch=1 звучить як звичайний синтез."""
318
+ m = model()
319
+ m.speed = speed
320
+ v = voice_vec(voice)
321
+ segs = _segments(parse(text))
322
+ wavs = []
323
+ with torch.no_grad():
324
+ for n, (words, pause) in enumerate(segs):
325
+ last = n == len(segs) - 1
326
+ parts = _ipa_words(words, light, last or not pause)
327
+ ps, c = _control(words, parts, expr, pitch)
328
+ if not m.tokenizer(ps):
329
+ continue
330
+ c['shape'] = not (expr == 1 and pitch == 1 and all(_neutral(w[2]) for w in words))
331
+ m.ctrl = c
332
+ with contextlib.redirect_stdout(io.StringIO()): # модель друкує налагоджувальні тензори
333
+ wavs.append(_tighten(m.generate(ps, v).squeeze().cpu().numpy()))
334
+ if pause and not last:
335
+ wavs.append(np.zeros(int(pause * SR), np.float32))
336
+ m.ctrl = None
337
+ x = np.concatenate(wavs) if wavs else np.zeros(SR // 4, np.float32)
338
+ return (x / (np.abs(x).max() or 1) * .9).astype(np.float32)
339
+
340
+
341
+ if __name__ == '__main__':
342
+ cmd = sys.argv[1] if len(sys.argv) > 1 else ''
343
+ if cmd == 'voices':
344
+ print('\n'.join(model().voices.keys()))
345
+ elif cmd == 'batch':
346
+ jobs = json.load(open(sys.argv[2]))
347
+ for j in jobs:
348
+ if os.path.exists(j['out']) and not j.get('force'):
349
+ print('є', j['out'], flush=True)
350
+ continue
351
+ os.makedirs(os.path.dirname(os.path.abspath(j['out'])), exist_ok=True)
352
+ sf.write(j['out'], say(j['text'], j['voice'], j.get('light', True), j.get('speed', 1.0),
353
+ j.get('expr', 1.0), j.get('pitch', 1.0)), SR)
354
+ print('ok', j['out'], flush=True)
355
+ else:
356
+ raise SystemExit(__doc__)
@@ -0,0 +1,163 @@
1
+ """Режисерська розмітка ukr-voice і її переклад для Gemini TTS. Лише стандартна бібліотека.
2
+
3
+ Одна розмітка для обох рушіїв:
4
+ (радісно) … емоція з цього місця до кінця репліки чи до наступної емоції
5
+ / // /// пауза: коротка / середня / довга; [0.6] — пауза в секундах
6
+ *слово* логічний наголос фрази (виділення)
7
+ О~го протягнути голосну
8
+ {швидко: …} особлива подача шматка: швидко, повільно, тихо, голосно, високо, низько, рівно, жваво
9
+ за+мок ручний наголос: «+» після наголошеної голосної
10
+
11
+ HolosTTS виконує її сам (holos_engine.py). Для Gemini текст розбивається на частини з описом подачі
12
+ (speechMetadata.style), паузи стають тегами [short pause]/[pause]/[long pause], «+» — знаком наголосу U+0301.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+
20
+ EMOTIONS = ['спокійно', 'радісно', 'захоплено', 'здивовано', 'обурено', 'таємниче', 'сумно', 'задумливо',
21
+ 'гордо', 'налякано', 'хитро']
22
+ ALIASES = {'весело': 'радісно', 'сердито': 'обурено', 'злякано': 'налякано', 'пошепки': 'таємниче'}
23
+ SPANS = ['швидко', 'повільно', 'тихо', 'голосно', 'високо', 'низько', 'рівно', 'жваво']
24
+
25
+ EMO_STYLE = {
26
+ 'спокійно': 'calm, even',
27
+ 'радісно': 'joyful, smiling, warm',
28
+ 'захоплено': 'excited, enthusiastic, energetic',
29
+ 'здивовано': 'surprised, amazed',
30
+ 'обурено': 'indignant, annoyed',
31
+ 'таємниче': 'mysterious, hushed, almost whispering',
32
+ 'сумно': 'sad, soft, slower',
33
+ 'задумливо': 'thoughtful, pensive, unhurried',
34
+ 'гордо': 'proud, confident',
35
+ 'налякано': 'frightened, tense, breathless',
36
+ 'хитро': 'sly, playful, conspiratorial',
37
+ }
38
+ SPAN_STYLE = {'швидко': 'faster pace', 'повільно': 'slower pace', 'тихо': 'quietly', 'голосно': 'loudly',
39
+ 'високо': 'higher pitch', 'низько': 'lower pitch', 'рівно': 'flat, neutral intonation',
40
+ 'жваво': 'lively, animated'}
41
+ VOWELS = 'аеєиіїоуюяАЕЄИІЇОУЮЯ'
42
+ ACUTE = '́'
43
+
44
+ _TOKEN = re.compile(r'\((?P<emo>[^()\s]+)\)|\[(?P<sec>\d+(?:[.,]\d+)?)\]|(?P<slash>/{1,3})|\{(?P<mods>[^:{}]+):'
45
+ r'|(?P<close>\})|(?P<star>\*)|(?P<ch>.)', re.S)
46
+
47
+
48
+ def apply_lexicon(text: str, path: str) -> str:
49
+ """Словник вимови {"Ніко": "Ніко+"} — імена й слова з незвичним наголосом."""
50
+ if not path or not os.path.exists(path):
51
+ return text
52
+ try:
53
+ lex = json.load(open(path, encoding='utf-8'))
54
+ except (OSError, ValueError):
55
+ return text
56
+ for w, r in lex.items():
57
+ text = re.sub(r'(?<![\w+])' + re.escape(w) + r'(?![\w+])', r, text)
58
+ return text
59
+
60
+
61
+ def emotion(name: str):
62
+ n = ALIASES.get(name.lower(), name.lower())
63
+ return n if n in EMO_STYLE else None
64
+
65
+
66
+ def _pause_tag(sec: float) -> str:
67
+ return '[short pause]' if sec < 0.2 else '[pause]' if sec < 0.45 else '[long pause]'
68
+
69
+
70
+ def to_gemini(text: str) -> list:
71
+ """Розмічений текст → [(текст, [описи подачі])] для частин запиту Gemini."""
72
+ parts, buf = [], ''
73
+ emo, mods, emph_words, cur_emph, in_emph = None, [], [], '', False
74
+
75
+ def style():
76
+ s = []
77
+ if emo:
78
+ s.append(EMO_STYLE[emo])
79
+ s += [SPAN_STYLE[m] for m in mods]
80
+ if emph_words:
81
+ s.append('stress the words: ' + ', '.join(f'«{w}»' for w in emph_words))
82
+ return s
83
+
84
+ def flush():
85
+ nonlocal buf, emph_words
86
+ if buf.strip():
87
+ parts.append((re.sub(r'\s+', ' ', buf).strip(), style()))
88
+ buf, emph_words = '', []
89
+
90
+ for m in _TOKEN.finditer(text):
91
+ g = m.lastgroup
92
+ if g == 'emo':
93
+ e = emotion(m['emo'])
94
+ if e is None: # звичайні дужки в тексті — лишаємо як є
95
+ buf += m.group()
96
+ continue
97
+ flush()
98
+ emo = e
99
+ elif g == 'sec':
100
+ buf += ' ' + _pause_tag(float(m['sec'].replace(',', '.'))) + ' '
101
+ elif g == 'slash':
102
+ buf += ' ' + ['[short pause]', '[pause]', '[long pause]'][len(m['slash']) - 1] + ' '
103
+ elif g == 'mods':
104
+ ms = [x for x in m['mods'].lower().split() if x in SPAN_STYLE]
105
+ if not ms:
106
+ buf += m.group()
107
+ continue
108
+ flush()
109
+ mods = ms
110
+ elif g == 'close':
111
+ if mods:
112
+ flush()
113
+ mods = []
114
+ else:
115
+ buf += '}'
116
+ elif g == 'star':
117
+ if in_emph:
118
+ emph_words.append(cur_emph.strip().replace('+', ''))
119
+ cur_emph = ''
120
+ in_emph = not in_emph
121
+ else:
122
+ ch = m['ch']
123
+ if ch == '~':
124
+ continue
125
+ if ch == '+' and buf and buf[-1] in VOWELS:
126
+ ch = ACUTE
127
+ buf += ch
128
+ if in_emph:
129
+ cur_emph += m['ch']
130
+ flush()
131
+ # сусідні частини з однаковою подачею — разом
132
+ merged = []
133
+ for t, s in parts:
134
+ if merged and merged[-1][1] == s:
135
+ merged[-1] = (merged[-1][0] + ' ' + t, s)
136
+ else:
137
+ merged.append((t, s))
138
+ return merged
139
+
140
+
141
+ def plain(text: str) -> str:
142
+ """Текст без розмітки — для субтитрів і перевірки розбірливості."""
143
+ t = re.sub(r'\((?:' + '|'.join(EMOTIONS + list(ALIASES)) + r')\)', ' ', text, flags=re.I)
144
+ t = re.sub(r'\[\d+(?:[.,]\d+)?\]|/{1,3}', ' ', t)
145
+ t = re.sub(r'\{(?:[^:{}]+):', '', t).replace('}', '')
146
+ t = t.replace('*', '').replace('~', '').replace('+', '')
147
+ return re.sub(r'\s+', ' ', t).strip()
148
+
149
+
150
+ def split_sentences(text: str, limit: int) -> list:
151
+ """Ріже довгий текст на шматки до limit символів по межах речень (для довгих запитів)."""
152
+ if len(text) <= limit:
153
+ return [text]
154
+ chunks, cur = [], ''
155
+ for sent in re.split(r'(?<=[.!?…])\s+', text):
156
+ if cur and len(cur) + len(sent) + 1 > limit:
157
+ chunks.append(cur)
158
+ cur = sent
159
+ else:
160
+ cur = f'{cur} {sent}'.strip()
161
+ if cur:
162
+ chunks.append(cur)
163
+ return chunks