odant-work 1.0.57 → 1.0.59

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.
@@ -12,6 +12,7 @@ import io
12
12
  import json
13
13
  import mmap
14
14
  import os
15
+ import re
15
16
  import struct
16
17
  import sys
17
18
  import threading
@@ -1669,6 +1670,126 @@ def _handle_tts_kokoro(req, cache, kokoro_files):
1669
1670
  }
1670
1671
 
1671
1672
 
1673
+ def _find_silero_tts_file(weights_dir):
1674
+ if not weights_dir or not os.path.isdir(weights_dir):
1675
+ return None
1676
+ try:
1677
+ for fn in sorted(os.listdir(weights_dir)):
1678
+ low = fn.lower()
1679
+ if re.match(r"^(v\d+(?:_\d+)?_ru|ru_v\d+|silero.*)\.pt$", low) and not low.endswith(".part"):
1680
+ return os.path.join(weights_dir, fn)
1681
+ except Exception:
1682
+ return None
1683
+ return None
1684
+
1685
+
1686
+ def _clean_silero_text(text):
1687
+ s = str(text or "").strip()
1688
+ s = s.replace("«", '"').replace("»", '"').replace("—", "-").replace("–", "-")
1689
+ s = re.sub(r"[`*_#~^{}\[\]|<>]", " ", s)
1690
+ s = re.sub(r"\s+", " ", s).strip()
1691
+ return s or "Привет! Проверка локального синтеза речи Силеро."
1692
+
1693
+
1694
+ def _split_silero_chunks(text, limit=650):
1695
+ if len(text) <= limit:
1696
+ return [text]
1697
+ parts = re.split(r"(?<=[.!?…])\s+", text)
1698
+ chunks = []
1699
+ cur = ""
1700
+ for p in parts:
1701
+ p = p.strip()
1702
+ if not p:
1703
+ continue
1704
+ if len(cur) + len(p) + 1 <= limit:
1705
+ cur = f"{cur} {p}".strip() if cur else p
1706
+ else:
1707
+ if cur:
1708
+ chunks.append(cur)
1709
+ if len(p) <= limit:
1710
+ cur = p
1711
+ else:
1712
+ words = p.split(" ")
1713
+ cur = ""
1714
+ for w in words:
1715
+ if len(cur) + len(w) + 1 <= limit:
1716
+ cur = f"{cur} {w}".strip() if cur else w
1717
+ else:
1718
+ if cur:
1719
+ chunks.append(cur)
1720
+ cur = w
1721
+ if cur:
1722
+ chunks.append(cur)
1723
+ return chunks or [text[:limit]]
1724
+
1725
+
1726
+ def _handle_tts_silero(req, cache, pt_path):
1727
+ text = _clean_silero_text(req.get("text") or "Привет! Локальный синтез речи платформы Ворк работает.")
1728
+ allowed_speakers = ("xenia", "baya", "kseniya", "aidar", "eugene")
1729
+ want = str(req.get("voice") or "xenia").strip().lower()
1730
+ speaker = want if want in allowed_speakers else "xenia"
1731
+ sr = 48000
1732
+
1733
+ key = ("tts_silero", pt_path)
1734
+ was_cached = key in cache
1735
+ t_load0 = time.time()
1736
+ if not was_cached:
1737
+ try:
1738
+ if hasattr(torch, "set_num_threads"):
1739
+ torch.set_num_threads(max(1, min(8, os.cpu_count() or 4)))
1740
+ except Exception:
1741
+ pass
1742
+ mdl = torch.package.PackageImporter(pt_path).load_pickle("tts_models", "model")
1743
+ mdl.to(torch.device("cpu"))
1744
+ cache[key] = mdl
1745
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1746
+ mdl = cache[key]
1747
+
1748
+ t_gen0 = time.time()
1749
+ audio_parts = []
1750
+ with torch.inference_mode():
1751
+ for chunk in _split_silero_chunks(text):
1752
+ try:
1753
+ wav = mdl.apply_tts(
1754
+ text=chunk,
1755
+ speaker=speaker,
1756
+ sample_rate=sr,
1757
+ put_accent=True,
1758
+ put_yo=True,
1759
+ )
1760
+ except TypeError:
1761
+ wav = mdl.apply_tts(text=chunk, speaker=speaker, sample_rate=sr)
1762
+ except Exception as e:
1763
+ # На моделях v2/16kHz 48000 может быть недоступен — откатываемся на 24000 / 16000
1764
+ if "sample_rate" in str(e).lower() or "48000" in str(e):
1765
+ sr = 24000
1766
+ try:
1767
+ wav = mdl.apply_tts(text=chunk, speaker=speaker, sample_rate=sr)
1768
+ except Exception:
1769
+ sr = 16000
1770
+ wav = mdl.apply_tts(text=chunk, speaker=speaker, sample_rate=sr)
1771
+ else:
1772
+ raise
1773
+ if wav is not None:
1774
+ audio_parts.append(wav.detach().cpu().float().flatten())
1775
+
1776
+ if not audio_parts:
1777
+ raise RuntimeError(json.dumps({"error": "Silero TTS не вернул аудиоданные для переданного текста."}))
1778
+ full_wav = torch.cat(audio_parts) if len(audio_parts) > 1 else audio_parts[0]
1779
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1780
+ return {
1781
+ "audioBase64": _pcm_to_wav_base64(full_wav, sr),
1782
+ "sampleRate": sr,
1783
+ "ttsKind": "silero",
1784
+ "voiceUsed": speaker,
1785
+ "instructUsed": "",
1786
+ "device": "CPU (Silero v5)",
1787
+ "loadMs": load_ms,
1788
+ "genMs": gen_ms,
1789
+ "durationMs": gen_ms,
1790
+ }
1791
+
1792
+
1672
1793
  def handle_tts(req, cache):
1673
1794
  weights_dir = req["weightsDir"]
1674
1795
  piper_files = _find_piper_onnx_files(weights_dir)
@@ -1677,6 +1798,9 @@ def handle_tts(req, cache):
1677
1798
  kokoro_files = _find_kokoro_files(weights_dir)
1678
1799
  if kokoro_files:
1679
1800
  return _handle_tts_kokoro(req, cache, kokoro_files)
1801
+ silero_pt = _find_silero_tts_file(weights_dir)
1802
+ if silero_pt:
1803
+ return _handle_tts_silero(req, cache, silero_pt)
1680
1804
  text = str(req.get("text", "")).strip()
1681
1805
  language = _tts_language(req.get("language") or "Russian")
1682
1806
  instructions = str(req.get("instructions") or "").strip()
@@ -2139,8 +2263,11 @@ def main():
2139
2263
  elif op == "video":
2140
2264
  needed.extend(["diffusers", "accelerate", "pillow", "transformers", "imageio", "imageio-ffmpeg"])
2141
2265
  elif op == "tts":
2142
- if _find_kokoro_files(str(req.get("weightsDir") or "")):
2266
+ w_dir_arg = str(req.get("weightsDir") or "")
2267
+ if _find_kokoro_files(w_dir_arg):
2143
2268
  needed.extend(["kokoro", "soundfile"])
2269
+ elif _find_silero_tts_file(w_dir_arg):
2270
+ pass # torch уже в needed
2144
2271
  else:
2145
2272
  needed.extend(["qwen-tts", "soundfile", "transformers"])
2146
2273
  elif op == "music":
@@ -41,7 +41,7 @@ export const MEMBERS = Object.freeze({
41
41
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
42
42
  work_zone: L.READ, places: L.READ,
43
43
  data_access: L.READ, link_tree: L.READ, search_tree: L.USER,
44
- voice_config: L.READ, dot_look: L.READ, voice_speak: L.CALL, voice_transcribe: L.CALL, voice_interim: L.CALL,
44
+ voice_config: L.READ, dot_look: L.READ, voice_speak: L.CALL, voice_transcribe: L.CALL, voice_interim: L.CALL, voice_set_prefs: L.USER,
45
45
  // геттеры (свойства и списки)
46
46
  size: L.READ, METADATA: L.READ, type: L.READ, type_chain: L.READ, label: L.READ, icon: L.READ,
47
47
  id: L.READ, name: L.READ, path: L.READ, short: L.READ, online: L.READ, lastModified: L.READ,
@@ -798,7 +798,25 @@ export class $class extends $folder {
798
798
  /** Голосовой режим на уровне класса/подразделения/кабинета (до создания файла .task). */
799
799
  async voice_config(params = {}) {
800
800
  await this.assertAccess(params, $class.ACCESS_LEVEL.READ);
801
- return (await WORK_AGENT_CORE()).voice.voiceConfig(this);
801
+ return (await WORK_AGENT_CORE()).voice.voiceConfig(this, { uid: params.session?.principal?.id || params.session?.uid });
802
+ }
803
+
804
+ async voice_set_prefs(params = {}) {
805
+ await this.assertAccess(params, $class.ACCESS_LEVEL.READ);
806
+ let payload = {};
807
+ if (typeof params.post === 'string') {
808
+ try { payload = JSON.parse(params.post) || {}; } catch { payload = {}; }
809
+ }
810
+ else if (params.post && typeof params.post === 'object') {
811
+ payload = params.post;
812
+ }
813
+ const uid = params.session?.principal?.id || params.session?.uid;
814
+ return (await WORK_AGENT_CORE()).voice.setUserVoicePrefs({
815
+ uid,
816
+ ttsModel: params.ttsModel ?? payload.ttsModel,
817
+ ttsVoice: params.ttsVoice ?? payload.ttsVoice,
818
+ ttsInstructions: params.ttsInstructions ?? payload.ttsInstructions,
819
+ });
802
820
  }
803
821
 
804
822
  async dot_look(params = {}) {
@@ -808,8 +826,21 @@ export class $class extends $folder {
808
826
 
809
827
  async voice_speak(params = {}) {
810
828
  await this.assertAccess(params, $class.ACCESS_LEVEL.READ);
811
- const text = params.text ?? (typeof params.post === 'string' ? params.post : params.post?.text);
812
- return (await WORK_AGENT_CORE()).voice.speak(this, { text, language: params.language, instructions: params.instructions, uid: params.session?.principal?.id || params.session?.uid });
829
+ let payload = {};
830
+ if (typeof params.post === 'string') {
831
+ const raw = params.post.trim();
832
+ if (raw.startsWith('{')) {
833
+ try { payload = JSON.parse(raw) || {}; } catch { payload = { text: params.post }; }
834
+ }
835
+ else {
836
+ payload = { text: params.post };
837
+ }
838
+ }
839
+ else if (params.post && typeof params.post === 'object') {
840
+ payload = params.post;
841
+ }
842
+ const text = params.text ?? payload.text;
843
+ return (await WORK_AGENT_CORE()).voice.speak(this, { text, language: params.language ?? payload.language, instructions: params.instructions ?? payload.instructions, voice: params.voice ?? payload.voice, ttsModel: params.ttsModel ?? payload.ttsModel, uid: params.session?.principal?.id || params.session?.uid });
813
844
  }
814
845
 
815
846
  async voice_transcribe(params = {}) {