odant-work 1.0.45 → 1.0.47

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.
@@ -22,7 +22,11 @@ try:
22
22
  import torch
23
23
  import torch.nn.functional as F
24
24
  HAS_TORCH = True
25
- torch.set_num_threads(max(1, (os.cpu_count() or 4) // 2))
25
+ torch.set_num_threads(max(4, min(16, (os.cpu_count() or 8))))
26
+ try:
27
+ torch.backends.mkldnn.enabled = True
28
+ except Exception:
29
+ pass
26
30
  DTYPE_MAP = {
27
31
  "BF16": torch.bfloat16,
28
32
  "F16": torch.float16,
@@ -440,7 +444,10 @@ def _load_embed_model(weights_dir, cache):
440
444
  raise
441
445
  device, dtype = _best_device_and_dtype()
442
446
  try:
443
- mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
447
+ try:
448
+ mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype, attn_implementation="sdpa")
449
+ except Exception:
450
+ mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
444
451
  mdl.to(device).eval()
445
452
  except Exception:
446
453
  mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=torch.float32)
@@ -455,7 +462,11 @@ def handle_embed(req, cache):
455
462
  texts = req.get("input") or []
456
463
  if isinstance(texts, str):
457
464
  texts = [texts]
465
+ was_cached = ("embed", weights_dir) in cache
466
+ t_load0 = time.time()
458
467
  kind, tok, mdl, device = _load_embed_model(weights_dir, cache)
468
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
469
+ t_gen0 = time.time()
459
470
  if kind == "onnx":
460
471
  import numpy as np
461
472
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="np")
@@ -476,7 +487,8 @@ def handle_embed(req, cache):
476
487
  vecs = last_hidden
477
488
  norms = np.clip(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12, None)
478
489
  arr = (vecs / norms).tolist()
479
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0}
490
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
491
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
480
492
  with torch.inference_mode():
481
493
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="pt")
482
494
  encoded = {k: v.to(device) for k, v in encoded.items()}
@@ -487,7 +499,8 @@ def handle_embed(req, cache):
487
499
  counts = torch.clamp(mask.sum(dim=1), min=1e-9)
488
500
  vecs = F.normalize(summed / counts, p=2, dim=1)
489
501
  arr = vecs.cpu().tolist()
490
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0}
502
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
503
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
491
504
 
492
505
 
493
506
  def _load_rerank_model(weights_dir, cache):
@@ -510,7 +523,10 @@ def _load_rerank_model(weights_dir, cache):
510
523
  raise
511
524
  device, dtype = _best_device_and_dtype()
512
525
  try:
513
- mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
526
+ try:
527
+ mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype, attn_implementation="sdpa")
528
+ except Exception:
529
+ mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
514
530
  mdl.to(device).eval()
515
531
  except Exception:
516
532
  mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=torch.float32)
@@ -525,8 +541,12 @@ def handle_rerank(req, cache):
525
541
  query = str(req.get("query", ""))
526
542
  docs = req.get("documents") or []
527
543
  if not docs:
528
- return {"results": []}
544
+ return {"results": [], "loadMs": 0, "genMs": 0, "durationMs": 0}
545
+ was_cached = ("rerank", weights_dir) in cache
546
+ t_load0 = time.time()
529
547
  kind, tok, mdl, device = _load_rerank_model(weights_dir, cache)
548
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
549
+ t_gen0 = time.time()
530
550
  pairs = [[query, str(d.get("text", d) if isinstance(d, dict) else d)] for d in docs]
531
551
  if kind == "onnx":
532
552
  import math
@@ -554,7 +574,8 @@ def handle_rerank(req, cache):
554
574
  top_n = int(req.get("topN") or 0)
555
575
  if top_n > 0:
556
576
  ranked = ranked[:top_n]
557
- return {"results": ranked}
577
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
578
+ return {"results": ranked, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
558
579
 
559
580
 
560
581
  def _load_image_pipeline(weights_dir, cache):
@@ -593,19 +614,25 @@ def handle_image(req, cache):
593
614
  w, h = [max(256, min(1536, int(v))) for v in size_str.lower().split("x")[:2]]
594
615
  except Exception:
595
616
  w, h = 512, 512
596
- steps = int(req.get("steps") or 8)
617
+ is_turbo = "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower()
618
+ steps = int(req.get("steps") or (4 if is_turbo else 8))
597
619
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
620
+ was_cached = ("image", weights_dir) in cache
621
+ t_load0 = time.time()
598
622
  pipe, device = _load_image_pipeline(weights_dir, cache)
623
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
624
+ t_gen0 = time.time()
599
625
  gen = torch.Generator(device=device).manual_seed(seed)
600
626
  kwargs = {"prompt": prompt, "width": w, "height": h, "num_inference_steps": steps, "generator": gen}
601
- if "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower():
627
+ if is_turbo:
602
628
  kwargs["guidance_scale"] = 0.0
603
629
  with torch.inference_mode():
604
630
  out = pipe(**kwargs)
605
631
  img = out.images[0]
606
632
  buf = io.BytesIO()
607
633
  img.save(buf, format="PNG")
608
- return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii")}
634
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
635
+ return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
609
636
 
610
637
 
611
638
  def _pcm_to_wav_base64(samples, sample_rate):
@@ -624,13 +651,245 @@ def _pcm_to_wav_base64(samples, sample_rate):
624
651
  return base64.b64encode(buf.getvalue()).decode("ascii")
625
652
 
626
653
 
654
+ DEFAULT_VOICE_DESIGN_INSTRUCT = (
655
+ "Male, 35 years old, deep warm baritone voice, calm confident professional tone, "
656
+ "natural pacing and clear articulation."
657
+ )
658
+
659
+ SUPPORTED_ASR_LANGUAGES = {
660
+ "chinese": "Chinese", "english": "English", "cantonese": "Cantonese",
661
+ "arabic": "Arabic", "german": "German", "french": "French",
662
+ "spanish": "Spanish", "portuguese": "Portuguese", "indonesian": "Indonesian",
663
+ "italian": "Italian", "korean": "Korean", "russian": "Russian",
664
+ "thai": "Thai", "vietnamese": "Vietnamese", "japanese": "Japanese",
665
+ "turkish": "Turkish", "hindi": "Hindi", "malay": "Malay",
666
+ "dutch": "Dutch", "swedish": "Swedish", "danish": "Danish",
667
+ "finnish": "Finnish", "polish": "Polish", "czech": "Czech",
668
+ "filipino": "Filipino", "persian": "Persian", "greek": "Greek",
669
+ "romanian": "Romanian", "hungarian": "Hungarian", "macedonian": "Macedonian",
670
+ }
671
+
672
+ TTS_LANGUAGE_ALIASES = {
673
+ "ru": "Russian", "rus": "Russian", "russian": "Russian", "русский": "Russian", "рус": "Russian",
674
+ "en": "English", "eng": "English", "english": "English", "английский": "English",
675
+ "zh": "Chinese", "cn": "Chinese", "zho": "Chinese", "chinese": "Chinese", "китайский": "Chinese",
676
+ "yue": "Cantonese", "cantonese": "Cantonese",
677
+ "de": "German", "deu": "German", "ger": "German", "german": "German", "немецкий": "German",
678
+ "fr": "French", "fra": "French", "fre": "French", "french": "French", "французский": "French",
679
+ "es": "Spanish", "spa": "Spanish", "spanish": "Spanish", "испанский": "Spanish",
680
+ "pt": "Portuguese", "por": "Portuguese", "portuguese": "Portuguese", "португальский": "Portuguese",
681
+ "it": "Italian", "ita": "Italian", "italian": "Italian", "итальянский": "Italian",
682
+ "ja": "Japanese", "jp": "Japanese", "jpn": "Japanese", "japanese": "Japanese", "японский": "Japanese",
683
+ "ko": "Korean", "kor": "Korean", "korean": "Korean", "корейский": "Korean",
684
+ "ar": "Arabic", "ara": "Arabic", "arabic": "Arabic", "арабский": "Arabic",
685
+ "tr": "Turkish", "tur": "Turkish", "turkish": "Turkish", "турецкий": "Turkish",
686
+ "hi": "Hindi", "hin": "Hindi", "hindi": "Hindi",
687
+ "pl": "Polish", "pol": "Polish", "polish": "Polish",
688
+ "cs": "Czech", "cze": "Czech", "ces": "Czech", "czech": "Czech",
689
+ "nl": "Dutch", "nld": "Dutch", "dut": "Dutch", "dutch": "Dutch",
690
+ "sv": "Swedish", "swe": "Swedish", "swedish": "Swedish",
691
+ "da": "Danish", "dan": "Danish", "danish": "Danish",
692
+ "fi": "Finnish", "fin": "Finnish", "finnish": "Finnish",
693
+ "el": "Greek", "ell": "Greek", "gre": "Greek", "greek": "Greek",
694
+ "ro": "Romanian", "ron": "Romanian", "rum": "Romanian", "romanian": "Romanian",
695
+ "hu": "Hungarian", "hun": "Hungarian", "hungarian": "Hungarian",
696
+ "mk": "Macedonian", "mkd": "Macedonian", "macedonian": "Macedonian",
697
+ "th": "Thai", "tha": "Thai", "thai": "Thai",
698
+ "vi": "Vietnamese", "vie": "Vietnamese", "vietnamese": "Vietnamese",
699
+ "id": "Indonesian", "ind": "Indonesian", "indonesian": "Indonesian",
700
+ "ms": "Malay", "msa": "Malay", "malay": "Malay",
701
+ "fa": "Persian", "fas": "Persian", "per": "Persian", "persian": "Persian",
702
+ "tl": "Filipino", "fil": "Filipino", "filipino": "Filipino",
703
+ "auto": "Auto", "": "Auto",
704
+ }
705
+
706
+
707
+ def _read_json_file(path):
708
+ try:
709
+ with open(path, "r", encoding="utf-8") as fh:
710
+ return json.load(fh)
711
+ except Exception:
712
+ return {}
713
+
714
+
715
+ def _tts_language(value):
716
+ raw = str(value or "").strip()
717
+ key = raw.lower().split("-")[0].split("_")[0]
718
+ if raw.lower() in TTS_LANGUAGE_ALIASES:
719
+ return TTS_LANGUAGE_ALIASES[raw.lower()]
720
+ if key in TTS_LANGUAGE_ALIASES:
721
+ return TTS_LANGUAGE_ALIASES[key]
722
+ if raw.lower() in SUPPORTED_ASR_LANGUAGES:
723
+ return SUPPORTED_ASR_LANGUAGES[raw.lower()]
724
+ return raw or "Auto"
725
+
726
+
727
+ def _asr_language(value):
728
+ """Нормализация языка для Qwen3-ASR: поддерживаются 30 полных английских названий или None (автоопределение)."""
729
+ raw = str(value or "").strip()
730
+ if not raw or raw.lower() in ("auto", "none", "null", "default"):
731
+ return None
732
+ norm = _tts_language(raw)
733
+ if norm == "Auto":
734
+ return None
735
+ canonical = SUPPORTED_ASR_LANGUAGES.get(norm.lower())
736
+ return canonical
737
+
738
+
739
+ def _normalize_voice_design_instruct(raw_instruct):
740
+ """Преобразовать русские и короткие описания голоса в детальный английский акустический профиль для Qwen3-TTS VoiceDesign.
741
+
742
+ Энкодер инструкций Qwen3-TTS-VoiceDesign обучен на развёрнутых английских/китайских описаниях
743
+ (пол, возраст, тембр, подача, темп). Короткая русская фраза («мужской голос») без перевода
744
+ даёт слабый сигнал и случайный тембр.
745
+ """
746
+ txt = str(raw_instruct or "").strip()
747
+ if not txt:
748
+ return DEFAULT_VOICE_DESIGN_INSTRUCT
749
+ low = txt.lower()
750
+ has_cyrillic = any("а" <= ch <= "я" or ch in "ёіїєґ" for ch in low)
751
+ if not has_cyrillic and len(txt) >= 32:
752
+ return txt
753
+
754
+ is_female = any(w in low for w in (
755
+ "женск", "женщин", "девушк", "девочк", "сопрано", "альт", "леди",
756
+ "female", "woman", "girl", "lady", "soprano", "alto",
757
+ ))
758
+ is_male = any(w in low for w in (
759
+ "мужск", "мужчин", "парен", "парн", "мальчик", "баритон", "бас", "тенор", "диктор",
760
+ "male", "man", "boy", "baritone", "bass", "tenor",
761
+ ))
762
+ if not is_female and not is_male:
763
+ is_male = True
764
+
765
+ if any(w in low for w in ("молод", "юный", "юная", "парен", "девушк", "young", "youth")):
766
+ age_part = "23 years old, youthful"
767
+ elif any(w in low for w in ("зрел", "стар", "взросл", "опытн", "mature", "older", "seasoned")):
768
+ age_part = "45 years old, mature seasoned"
769
+ else:
770
+ age_part = "30 years old, adult" if is_female else "35 years old, adult"
771
+
772
+ if is_female:
773
+ if any(w in low for w in ("низк", "альт", "глубок", "бархат", "alto", "deep", "warm")):
774
+ timbre = "warm rich alto female voice"
775
+ elif any(w in low for w in ("высок", "звонк", "нежных", "нежн", "сопрано", "soprano", "bright")):
776
+ timbre = "bright clear soprano female voice"
777
+ else:
778
+ timbre = "warm, clear, natural female voice"
779
+ gender_tag = "Female"
780
+ else:
781
+ if any(w in low for w in ("бас", "низк", "глубок", "густ", "bass", "deep")):
782
+ timbre = "deep resonant bass-baritone male voice"
783
+ elif any(w in low for w in ("тенор", "высок", "светл", "tenor")):
784
+ timbre = "clear expressive tenor male voice"
785
+ else:
786
+ timbre = "deep warm baritone male voice"
787
+ gender_tag = "Male"
788
+
789
+ style_parts = []
790
+ if any(w in low for w in ("диктор", "новост", "официальн", "делов", "презентац", "announcer", "broadcast", "professional")):
791
+ style_parts.append("authoritative professional broadcast announcer delivery with crystal-clear diction")
792
+ if any(w in low for w in ("энергич", "жив", "бодр", "весел", "радост", "эмоцион", "energetic", "lively", "happy", "upbeat")):
793
+ style_parts.append("energetic, lively, upbeat and expressive intonation")
794
+ elif any(w in low for w in ("строг", "серьез", "уверен", "тверд", "serious", "stern", "confident")):
795
+ style_parts.append("confident, composed, serious tone")
796
+ else:
797
+ style_parts.append("calm, confident, friendly and natural professional tone")
798
+
799
+ if any(w in low for w in ("быстр", "динамич", "fast", "brisk")):
800
+ pace_part = "brisk dynamic speaking pace"
801
+ elif any(w in low for w in ("медлен", "размерен", "неспеш", "slow", "measured")):
802
+ pace_part = "measured unhurried speaking pace"
803
+ else:
804
+ pace_part = "natural steady pacing and clean articulation"
805
+
806
+ return f"{gender_tag}, {age_part}, {timbre}, {', '.join(style_parts)}, {pace_part}."
807
+
808
+
809
+ def _tts_model_kind(weights_dir, mdl, instructions=""):
810
+ """Разновидность Qwen3-TTS: VoiceDesign / CustomVoice / Base (клонирование голоса).
811
+
812
+ Метод `generate_*` в пакете есть у всех моделей, но исполняется только «свой»:
813
+ вызов `generate_custom_voice` на VoiceDesign падает с ошибкой пакета.
814
+ Поэтому тип берём из `config.json` (`tts_model_type`), а не из наличия метода.
815
+ """
816
+ cfg = _read_json_file(os.path.join(weights_dir, "config.json"))
817
+ raw = str(cfg.get("tts_model_type") or "")
818
+ if not raw:
819
+ for attr in ("config", "model_config", "generation_config"):
820
+ raw = str(getattr(getattr(mdl, attr, None), "tts_model_type", "") or "")
821
+ if raw:
822
+ break
823
+ low = raw.lower().replace("-", "_")
824
+ if "voice_design" in low or "voicedesign" in low:
825
+ return "voice_design"
826
+ if "custom_voice" in low or "customvoice" in low:
827
+ return "custom_voice"
828
+ if "base" in low or "clone" in low:
829
+ return "base"
830
+ name = os.path.basename(os.path.normpath(weights_dir)).lower()
831
+ if "voicedesign" in name:
832
+ return "voice_design"
833
+ if "customvoice" in name:
834
+ return "custom_voice"
835
+ if "-base" in name or name.endswith("base"):
836
+ return "base"
837
+ return "voice_design" if instructions else "custom_voice"
838
+
839
+
840
+ def _resolve_tts_speaker(mdl, requested):
841
+ """Имена спикеров регистрозависимы (`Serena`, `Vivian`, …) — сопоставляем с реальным списком модели."""
842
+ try:
843
+ speakers = [str(s) for s in (mdl.get_supported_speakers() or [])]
844
+ except Exception:
845
+ speakers = []
846
+ want = str(requested or "").strip()
847
+ if not speakers:
848
+ return want or "Serena"
849
+ if want:
850
+ for s in speakers:
851
+ if s.lower() == want.lower():
852
+ return s
853
+ for s in speakers:
854
+ if want.lower() in s.lower():
855
+ return s
856
+ for s in speakers:
857
+ if s.lower() == "serena":
858
+ return s
859
+ return speakers[0]
860
+
861
+
862
+ def _seed_torch_deterministic(seed_val):
863
+ if not HAS_TORCH or torch is None:
864
+ return
865
+ try:
866
+ s = int(seed_val if seed_val is not None else 42)
867
+ torch.manual_seed(s)
868
+ if torch.cuda.is_available():
869
+ torch.cuda.manual_seed_all(s)
870
+ except Exception:
871
+ pass
872
+
873
+
874
+ def _call_tts_gen(fn, max_new_tokens, **kwargs):
875
+ try:
876
+ return fn(max_new_tokens=max_new_tokens, **kwargs)
877
+ except TypeError:
878
+ return fn(**kwargs)
879
+
880
+
627
881
  def handle_tts(req, cache):
628
882
  weights_dir = req["weightsDir"]
629
883
  text = str(req.get("text", "")).strip()
630
- language = str(req.get("language") or "Russian")
884
+ language = _tts_language(req.get("language") or "Russian")
631
885
  instructions = str(req.get("instructions") or "").strip()
886
+ seed = int(req.get("seed") if req.get("seed") is not None else 42)
887
+ # 12 Гц аудио-токенизатор: динамический потолок шагов декодера под реальную длину текста
888
+ max_new_tokens = max(128, min(1024, int(len(text) * 4.5) + 96))
632
889
  key = ("tts", weights_dir)
633
- if key not in cache:
890
+ was_cached = key in cache
891
+ t_load0 = time.time()
892
+ if not was_cached:
634
893
  try:
635
894
  from qwen_tts import Qwen3TTSModel
636
895
  except Exception as e:
@@ -640,7 +899,15 @@ def handle_tts(req, cache):
640
899
  })))
641
900
  device, dtype = _best_device_and_dtype()
642
901
  try:
643
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
902
+ try:
903
+ mdl = Qwen3TTSModel.from_pretrained(
904
+ weights_dir,
905
+ device_map=device,
906
+ dtype=dtype,
907
+ attn_implementation="sdpa",
908
+ )
909
+ except Exception:
910
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
644
911
  except Exception as e:
645
912
  # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
646
913
  # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
@@ -648,30 +915,109 @@ def handle_tts(req, cache):
648
915
  "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
649
916
  }))
650
917
  cache[key] = mdl
918
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
651
919
  mdl = cache[key]
652
- if hasattr(mdl, "generate_voice_design") and instructions:
653
- wavs, sr = mdl.generate_voice_design(text=text, language=language, instruct=instructions)
654
- elif hasattr(mdl, "generate_custom_voice"):
655
- wavs, sr = mdl.generate_custom_voice(text=text, language=language, speaker=str(req.get("voice") or "serena"), instruct=instructions or None)
656
- else:
657
- wavs, sr = mdl.generate_voice_design(text=text, language=language, instruct=instructions or "Natural clear voice")
920
+ kind = _tts_model_kind(weights_dir, mdl, instructions)
921
+ _seed_torch_deterministic(seed)
922
+ t_gen0 = time.time()
923
+ instruct_used = ""
924
+ try:
925
+ if kind == "voice_design":
926
+ # VoiceDesign синтезирует голос по текстовому описанию (`instruct`);
927
+ # переводим русские и короткие описания в полный акустический профиль на английском.
928
+ instruct_used = _normalize_voice_design_instruct(instructions)
929
+ wavs, sr = _call_tts_gen(
930
+ mdl.generate_voice_design,
931
+ max_new_tokens,
932
+ text=text,
933
+ language=language,
934
+ instruct=instruct_used,
935
+ )
936
+ elif kind == "custom_voice":
937
+ kwargs = {
938
+ "text": text,
939
+ "language": language,
940
+ "speaker": _resolve_tts_speaker(mdl, req.get("voice")),
941
+ }
942
+ if instructions:
943
+ kwargs["instruct"] = instructions
944
+ instruct_used = instructions
945
+ try:
946
+ wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
947
+ except Exception as e:
948
+ # CustomVoice 0.6B не принимает instruct — повторяем без него.
949
+ if "instruct" in kwargs and "instruct" in str(e).lower():
950
+ kwargs.pop("instruct")
951
+ instruct_used = ""
952
+ wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
953
+ else:
954
+ raise
955
+ else:
956
+ ref_b64 = str(req.get("refAudioBase64") or "")
957
+ if not ref_b64:
958
+ raise RuntimeError(json.dumps({
959
+ "error": "Модель Qwen3-TTS Base клонирует голос и требует эталонную запись "
960
+ "(refAudioBase64 + refText). Для синтеза без эталона используйте "
961
+ "Qwen3-TTS-12Hz-1.7B-VoiceDesign или -CustomVoice.",
962
+ }))
963
+ import tempfile
964
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
965
+ tf.write(base64.b64decode(ref_b64))
966
+ ref_path = tf.name
967
+ ref_text = str(req.get("refText") or "").strip()
968
+ try:
969
+ wavs, sr = _call_tts_gen(
970
+ mdl.generate_voice_clone,
971
+ max_new_tokens,
972
+ text=text,
973
+ language=language,
974
+ ref_audio=ref_path,
975
+ ref_text=ref_text,
976
+ x_vector_only_mode=not ref_text,
977
+ )
978
+ finally:
979
+ try:
980
+ os.remove(ref_path)
981
+ except Exception:
982
+ pass
983
+ except RuntimeError:
984
+ raise
985
+ except Exception as e:
986
+ raise RuntimeError(json.dumps({
987
+ "error": f"Синтез речи Qwen3-TTS ({kind}) не удался: {e}",
988
+ }))
989
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
658
990
  audio = wavs[0] if isinstance(wavs, (list, tuple)) else wavs
659
- return {"audioBase64": _pcm_to_wav_base64(audio, sr), "sampleRate": int(sr)}
991
+ return {
992
+ "audioBase64": _pcm_to_wav_base64(audio, sr),
993
+ "sampleRate": int(sr),
994
+ "ttsKind": kind,
995
+ "instructUsed": instruct_used,
996
+ "loadMs": load_ms,
997
+ "genMs": gen_ms,
998
+ "durationMs": gen_ms,
999
+ }
660
1000
 
661
1001
 
662
1002
  def handle_stt(req, cache):
663
1003
  weights_dir = req["weightsDir"]
664
1004
  audio_b64 = req.get("audioBase64", "")
665
- language = str(req.get("language") or "Russian")
1005
+ language = _asr_language(req.get("language"))
666
1006
  raw = base64.b64decode(audio_b64)
667
1007
  key = ("stt", weights_dir)
668
- if key not in cache:
1008
+ was_cached = key in cache
1009
+ t_load0 = time.time()
1010
+ if not was_cached:
669
1011
  device, dtype = _best_device_and_dtype()
670
1012
  errors = []
671
1013
  try:
672
1014
  from qwen_asr import Qwen3ASRModel
673
1015
  try:
674
- cache[key] = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
1016
+ try:
1017
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device, attn_implementation="sdpa")
1018
+ except Exception:
1019
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device)
1020
+ cache[key] = ("qwen_asr", loaded)
675
1021
  except Exception as e:
676
1022
  errors.append(f"qwen-asr: {e}")
677
1023
  except Exception as e:
@@ -701,14 +1047,22 @@ def handle_stt(req, cache):
701
1047
  raise RuntimeError(json.dumps({
702
1048
  "error": f"Не удалось загрузить модель распознавания речи из {weights_dir}: {msg}",
703
1049
  }))
1050
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
704
1051
  kind, mdl = cache[key]
705
1052
  import tempfile
706
1053
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
707
1054
  tf.write(raw)
708
1055
  tmp_path = tf.name
1056
+ t_gen0 = time.time()
709
1057
  try:
710
1058
  if kind == "qwen_asr":
711
- res = mdl.transcribe(audio=tmp_path, language=language)
1059
+ try:
1060
+ res = mdl.transcribe(audio=tmp_path, language=language)
1061
+ except Exception as e:
1062
+ if "unsupported language" in str(e).lower() and language is not None:
1063
+ res = mdl.transcribe(audio=tmp_path, language=None)
1064
+ else:
1065
+ raise
712
1066
  txt = res[0].text if isinstance(res, list) and res else getattr(res, "text", str(res))
713
1067
  else:
714
1068
  res = mdl(tmp_path)
@@ -718,7 +1072,8 @@ def handle_stt(req, cache):
718
1072
  os.remove(tmp_path)
719
1073
  except Exception:
720
1074
  pass
721
- return {"text": str(txt or "").strip()}
1075
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1076
+ return {"text": str(txt or "").strip(), "language": language or "Auto", "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
722
1077
 
723
1078
 
724
1079
  def main():
@@ -756,34 +1111,18 @@ def main():
756
1111
  "missingDeps": needed,
757
1112
  }), flush=True)
758
1113
  continue
759
- if op == "embed":
760
- t0 = time.time()
761
- res = handle_embed(req, mod_cache)
762
- res["durationMs"] = int((time.time() - t0) * 1000)
763
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
764
- continue
765
- if op == "rerank":
766
- t0 = time.time()
767
- res = handle_rerank(req, mod_cache)
768
- res["durationMs"] = int((time.time() - t0) * 1000)
769
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
770
- continue
771
- if op == "image":
772
- t0 = time.time()
773
- res = handle_image(req, mod_cache)
774
- res["durationMs"] = int((time.time() - t0) * 1000)
775
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
776
- continue
777
- if op == "tts":
778
- t0 = time.time()
779
- res = handle_tts(req, mod_cache)
780
- res["durationMs"] = int((time.time() - t0) * 1000)
781
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
782
- continue
783
- if op == "stt":
1114
+ if op in ("embed", "rerank", "image", "tts", "stt"):
784
1115
  t0 = time.time()
785
- res = handle_stt(req, mod_cache)
786
- res["durationMs"] = int((time.time() - t0) * 1000)
1116
+ fn = {
1117
+ "embed": handle_embed,
1118
+ "rerank": handle_rerank,
1119
+ "image": handle_image,
1120
+ "tts": handle_tts,
1121
+ "stt": handle_stt,
1122
+ }[op]
1123
+ res = fn(req, mod_cache)
1124
+ if "durationMs" not in res:
1125
+ res["durationMs"] = int((time.time() - t0) * 1000)
787
1126
  print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
788
1127
  continue
789
1128