odant-work 1.0.52 → 1.0.54

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.
@@ -571,6 +571,8 @@ def handle_check_deps():
571
571
  "soundfile": "soundfile",
572
572
  "qwen_tts": "qwen-tts",
573
573
  "qwen_asr": "qwen-asr",
574
+ "piper": "piper-tts",
575
+ "imageio": "imageio",
574
576
  "onnxruntime": ort_pkg,
575
577
  }
576
578
  status = {}
@@ -802,7 +804,11 @@ def handle_image(req, cache):
802
804
  w, h = [max(256, min(1536, int(v))) for v in size_str.lower().split("x")[:2]]
803
805
  except Exception:
804
806
  w, h = 512, 512
805
- is_turbo = "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower()
807
+ is_turbo = (
808
+ "z-image" in weights_dir.lower()
809
+ or "turbo" in weights_dir.lower()
810
+ or "schnell" in weights_dir.lower()
811
+ )
806
812
  steps = int(req.get("steps") or (4 if is_turbo else 8))
807
813
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
808
814
  was_cached = ("image", weights_dir) in cache
@@ -839,6 +845,176 @@ def handle_image(req, cache):
839
845
  return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
840
846
 
841
847
 
848
+ def _load_video_pipeline(weights_dir, cache):
849
+ key = ("video", weights_dir)
850
+ if key in cache:
851
+ return cache[key]
852
+ try:
853
+ import diffusers
854
+ import accelerate # noqa: F401
855
+ from PIL import Image # noqa: F401
856
+ except Exception as e:
857
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {
858
+ "diffusers": "diffusers",
859
+ "accelerate": "accelerate",
860
+ "PIL": "pillow",
861
+ })))
862
+ device, dtype = _best_device_and_dtype()
863
+ cls_name = ""
864
+ try:
865
+ idx_path = os.path.join(weights_dir, "model_index.json")
866
+ if os.path.isfile(idx_path):
867
+ with open(idx_path, "r", encoding="utf-8") as f:
868
+ cls_name = str(json.load(f).get("_class_name") or "")
869
+ except Exception:
870
+ cls_name = ""
871
+
872
+ low = (cls_name + " " + weights_dir).lower()
873
+ pipe = None
874
+ candidates = []
875
+ if "ltx" in low and hasattr(diffusers, "LTXPipeline"):
876
+ candidates.append(diffusers.LTXPipeline)
877
+ if "wan" in low and hasattr(diffusers, "WanPipeline"):
878
+ candidates.append(diffusers.WanPipeline)
879
+ if cls_name and hasattr(diffusers, cls_name):
880
+ candidates.append(getattr(diffusers, cls_name))
881
+ candidates.append(diffusers.DiffusionPipeline)
882
+
883
+ last_err = None
884
+ for cls in candidates:
885
+ try:
886
+ pipe = cls.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
887
+ break
888
+ except Exception as e:
889
+ last_err = e
890
+ pipe = None
891
+ if pipe is None:
892
+ raise last_err or RuntimeError(f"Не удалось загрузить видео-пайплайн из {weights_dir}")
893
+
894
+ try:
895
+ pipe.to(device)
896
+ except Exception:
897
+ if str(device).startswith("cuda") and HAS_TORCH:
898
+ try:
899
+ torch.cuda.empty_cache()
900
+ except Exception:
901
+ pass
902
+ device = "cpu"
903
+ pipe.to(device)
904
+ cache[key] = (pipe, device)
905
+ return cache[key]
906
+
907
+
908
+ def _encode_video_frames(frames, fps=16):
909
+ import tempfile
910
+ norm_frames = []
911
+ for fr in frames:
912
+ if hasattr(fr, "convert"):
913
+ norm_frames.append(fr.convert("RGB"))
914
+ else:
915
+ norm_frames.append(fr)
916
+
917
+ tmp_mp4 = None
918
+ try:
919
+ import imageio.v2 as imageio # noqa: F401
920
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:
921
+ tmp_mp4 = tf.name
922
+ try:
923
+ from diffusers.utils import export_to_video
924
+ export_to_video(norm_frames, tmp_mp4, fps=int(fps))
925
+ except Exception:
926
+ import numpy as np
927
+ with imageio.get_writer(tmp_mp4, fps=int(fps), codec="libx264") as writer:
928
+ for fr in norm_frames:
929
+ writer.append_data(np.asarray(fr))
930
+ with open(tmp_mp4, "rb") as f:
931
+ data = f.read()
932
+ if data:
933
+ return "video/mp4", base64.b64encode(data).decode("ascii")
934
+ except Exception:
935
+ pass
936
+ finally:
937
+ if tmp_mp4:
938
+ try:
939
+ os.remove(tmp_mp4)
940
+ except Exception:
941
+ pass
942
+
943
+ # Фоллбэк в анимированный GIF через Pillow, если ffmpeg не установлен
944
+ buf = io.BytesIO()
945
+ if norm_frames and hasattr(norm_frames[0], "save"):
946
+ norm_frames[0].save(
947
+ buf,
948
+ format="GIF",
949
+ save_all=True,
950
+ append_images=norm_frames[1:],
951
+ duration=max(30, int(1000 / max(1, int(fps)))),
952
+ loop=0,
953
+ )
954
+ return "image/gif", base64.b64encode(buf.getvalue()).decode("ascii")
955
+ raise RuntimeError("Для экспорта видео требуется пакет imageio[ffmpeg] или pillow.")
956
+
957
+
958
+ def handle_video(req, cache):
959
+ weights_dir = req["weightsDir"]
960
+ prompt = str(req.get("prompt", "")).strip()
961
+ size_str = str(req.get("size", "512x320"))
962
+ try:
963
+ w, h = [max(256, min(1280, (int(v) // 16) * 16)) for v in size_str.lower().split("x")[:2]]
964
+ except Exception:
965
+ w, h = 512, 320
966
+ num_frames = max(9, min(121, int(req.get("numFrames") or 17)))
967
+ fps = max(8, min(30, int(req.get("fps") or 16)))
968
+ is_ltx = "ltx" in weights_dir.lower()
969
+ steps = max(4, min(50, int(req.get("steps") or (12 if is_ltx else 18))))
970
+ seed = int(req.get("seed") if req.get("seed") is not None else 42)
971
+ was_cached = ("video", weights_dir) in cache
972
+ t_load0 = time.time()
973
+ pipe, device = _load_video_pipeline(weights_dir, cache)
974
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
975
+ t_gen0 = time.time()
976
+ gen = torch.Generator(device=device).manual_seed(seed)
977
+ kwargs = {
978
+ "prompt": prompt,
979
+ "width": w,
980
+ "height": h,
981
+ "num_frames": num_frames,
982
+ "num_inference_steps": steps,
983
+ "generator": gen,
984
+ }
985
+ try:
986
+ with torch.inference_mode():
987
+ out = pipe(**kwargs)
988
+ frames = out.frames[0] if hasattr(out, "frames") else out.images
989
+ except Exception as e:
990
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
991
+ try:
992
+ torch.cuda.empty_cache()
993
+ except Exception:
994
+ pass
995
+ device = "cpu"
996
+ pipe.to("cpu")
997
+ cache[("video", weights_dir)] = (pipe, "cpu")
998
+ kwargs["generator"] = torch.Generator(device="cpu").manual_seed(seed)
999
+ with torch.inference_mode():
1000
+ out = pipe(**kwargs)
1001
+ frames = out.frames[0] if hasattr(out, "frames") else out.images
1002
+ else:
1003
+ raise
1004
+ mime, b64 = _encode_video_frames(frames, fps=fps)
1005
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1006
+ return {
1007
+ "mime": mime,
1008
+ "base64": b64,
1009
+ "frames": len(frames) if frames is not None else num_frames,
1010
+ "fps": fps,
1011
+ "device": _describe_torch_device(device),
1012
+ "loadMs": load_ms,
1013
+ "genMs": gen_ms,
1014
+ "durationMs": gen_ms,
1015
+ }
1016
+
1017
+
842
1018
  def _pcm_to_wav_base64(samples, sample_rate):
843
1019
  import array
844
1020
  if hasattr(samples, "detach"):
@@ -1276,8 +1452,75 @@ def _load_qwen_tts_model(weights_dir):
1276
1452
  raise last_err
1277
1453
 
1278
1454
 
1455
+ def _find_piper_onnx_files(weights_dir):
1456
+ found = []
1457
+ if not weights_dir or not os.path.isdir(weights_dir):
1458
+ return found
1459
+ for root, dirs, files in os.walk(weights_dir):
1460
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d != "__pycache__"]
1461
+ for fn in sorted(files):
1462
+ if fn.lower().endswith(".onnx") and not fn.endswith(".part"):
1463
+ onnx_p = os.path.join(root, fn)
1464
+ cfg_p = onnx_p + ".json"
1465
+ if os.path.isfile(cfg_p):
1466
+ found.append((onnx_p, cfg_p))
1467
+ return found
1468
+
1469
+
1470
+ def _pick_piper_voice_file(piper_files, requested=""):
1471
+ want = str(requested or "").strip().lower()
1472
+ if any(k in want for k in ("irina", "жен", "serena", "vivian", "female")):
1473
+ for onnx_p, cfg_p in piper_files:
1474
+ if "irina" in onnx_p.lower():
1475
+ return onnx_p, cfg_p
1476
+ if any(k in want for k in ("dmitri", "муж", "ryan", "aiden", "dylan", "male")):
1477
+ for onnx_p, cfg_p in piper_files:
1478
+ if "dmitri" in onnx_p.lower():
1479
+ return onnx_p, cfg_p
1480
+ return piper_files[0]
1481
+
1482
+
1483
+ def _handle_tts_piper(req, cache, piper_files):
1484
+ text = str(req.get("text", "")).strip()
1485
+ onnx_p, cfg_p = _pick_piper_voice_file(piper_files, req.get("voice") or "")
1486
+ key = ("tts_piper", onnx_p)
1487
+ was_cached = key in cache
1488
+ t_load0 = time.time()
1489
+ if not was_cached:
1490
+ try:
1491
+ from piper.voice import PiperVoice
1492
+ except Exception as e:
1493
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {"piper": "piper-tts"})))
1494
+ cache[key] = PiperVoice.load(onnx_p, config_path=cfg_p)
1495
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1496
+ voice = cache[key]
1497
+ t_gen0 = time.time()
1498
+ buf = io.BytesIO()
1499
+ with wave.open(buf, "wb") as wf:
1500
+ if callable(getattr(voice, "synthesize_wav", None)):
1501
+ voice.synthesize_wav(text, wf)
1502
+ else:
1503
+ voice.synthesize(text, wf)
1504
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1505
+ sr = int(getattr(getattr(voice, "config", None), "sample_rate", 22050) or 22050)
1506
+ return {
1507
+ "audioBase64": base64.b64encode(buf.getvalue()).decode("ascii"),
1508
+ "sampleRate": sr,
1509
+ "ttsKind": "piper",
1510
+ "voiceUsed": os.path.basename(onnx_p).replace(".onnx", ""),
1511
+ "instructUsed": "",
1512
+ "device": "CPU (Piper ONNX)",
1513
+ "loadMs": load_ms,
1514
+ "genMs": gen_ms,
1515
+ "durationMs": gen_ms,
1516
+ }
1517
+
1518
+
1279
1519
  def handle_tts(req, cache):
1280
1520
  weights_dir = req["weightsDir"]
1521
+ piper_files = _find_piper_onnx_files(weights_dir)
1522
+ if piper_files:
1523
+ return _handle_tts_piper(req, cache, piper_files)
1281
1524
  text = str(req.get("text", "")).strip()
1282
1525
  language = _tts_language(req.get("language") or "Russian")
1283
1526
  instructions = str(req.get("instructions") or "").strip()
@@ -1390,6 +1633,85 @@ def handle_tts(req, cache):
1390
1633
  }
1391
1634
 
1392
1635
 
1636
+ def _load_music_pipeline(weights_dir, cache):
1637
+ key = ("music", weights_dir)
1638
+ if key in cache:
1639
+ return cache[key]
1640
+ try:
1641
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
1642
+ except Exception as e:
1643
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {"transformers": "transformers"})))
1644
+ device, dtype = _best_device_and_dtype()
1645
+ proc = AutoProcessor.from_pretrained(weights_dir, local_files_only=True)
1646
+ # MusicGen в float16/bfloat16 на ROCm/CUDA заметно быстрее, при сбое — откат на CPU float32
1647
+ load_dtype = dtype if str(device).startswith("cuda") else torch.float32
1648
+ try:
1649
+ mdl = MusicgenForConditionalGeneration.from_pretrained(
1650
+ weights_dir, local_files_only=True, torch_dtype=load_dtype
1651
+ )
1652
+ mdl.to(device)
1653
+ except Exception:
1654
+ if str(device).startswith("cuda") and HAS_TORCH:
1655
+ try:
1656
+ torch.cuda.empty_cache()
1657
+ except Exception:
1658
+ pass
1659
+ device = "cpu"
1660
+ mdl = MusicgenForConditionalGeneration.from_pretrained(
1661
+ weights_dir, local_files_only=True, torch_dtype=torch.float32
1662
+ )
1663
+ mdl.to("cpu")
1664
+ cache[key] = (mdl, proc, device)
1665
+ return cache[key]
1666
+
1667
+
1668
+ def handle_music(req, cache):
1669
+ weights_dir = req["weightsDir"]
1670
+ prompt = str(req.get("prompt", "")).strip() or "upbeat modern ambient corporate piano melody"
1671
+ duration_sec = max(2.0, min(30.0, float(req.get("durationSec") or 8.0)))
1672
+ seed = int(req.get("seed") if req.get("seed") is not None else 42)
1673
+ was_cached = ("music", weights_dir) in cache
1674
+ t_load0 = time.time()
1675
+ mdl, proc, device = _load_music_pipeline(weights_dir, cache)
1676
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1677
+ _seed_torch_deterministic(seed)
1678
+ t_gen0 = time.time()
1679
+ # MusicGen ~50 аудио-токенов на секунду
1680
+ frame_rate = int(getattr(getattr(mdl.config, "audio_encoder", None), "frame_rate", 50) or 50)
1681
+ max_new_tokens = max(50, min(1500, int(duration_sec * frame_rate)))
1682
+ inputs = proc(text=[prompt], padding=True, return_tensors="pt")
1683
+ try:
1684
+ inputs_dev = {k: (v.to(device) if hasattr(v, "to") else v) for k, v in inputs.items()}
1685
+ with torch.inference_mode():
1686
+ audio_values = mdl.generate(**inputs_dev, max_new_tokens=max_new_tokens)
1687
+ except Exception as e:
1688
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
1689
+ try:
1690
+ torch.cuda.empty_cache()
1691
+ except Exception:
1692
+ pass
1693
+ device = "cpu"
1694
+ mdl = mdl.float().to("cpu")
1695
+ cache[("music", weights_dir)] = (mdl, proc, "cpu")
1696
+ inputs_cpu = {k: (v.to("cpu") if hasattr(v, "to") else v) for k, v in inputs.items()}
1697
+ with torch.inference_mode():
1698
+ audio_values = mdl.generate(**inputs_cpu, max_new_tokens=max_new_tokens)
1699
+ else:
1700
+ raise
1701
+ sr = int(getattr(getattr(mdl.config, "audio_encoder", None), "sampling_rate", 32000) or 32000)
1702
+ wav_tensor = audio_values[0, 0] if getattr(audio_values, "ndim", 0) >= 3 else audio_values[0]
1703
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1704
+ return {
1705
+ "mime": "audio/wav",
1706
+ "audioBase64": _pcm_to_wav_base64(wav_tensor, sr),
1707
+ "sampleRate": sr,
1708
+ "device": _describe_torch_device(device),
1709
+ "loadMs": load_ms,
1710
+ "genMs": gen_ms,
1711
+ "durationMs": gen_ms,
1712
+ }
1713
+
1714
+
1393
1715
  def handle_stt(req, cache):
1394
1716
  weights_dir = req["weightsDir"]
1395
1717
  audio_b64 = req.get("audioBase64", "")
@@ -1557,7 +1879,7 @@ def _evict_memory_if_needed(
1557
1879
  def _do():
1558
1880
  low_mem = free_gb is not None and free_gb < min_free_gb
1559
1881
  for k in list(mod_cache.keys()):
1560
- if not (isinstance(k, tuple) and len(k) >= 1 and k[0] == "image"):
1882
+ if not (isinstance(k, tuple) and len(k) >= 1 and k[0] in ("image", "video", "music")):
1561
1883
  continue
1562
1884
  if k == keep_mod_key:
1563
1885
  continue
@@ -1648,14 +1970,22 @@ def main():
1648
1970
  if op == "check_deps":
1649
1971
  print(json.dumps({"id": req_id, "event": "result", "data": handle_check_deps()}), flush=True)
1650
1972
  continue
1651
- if not HAS_TORCH and not (op in ("embed", "rerank") and _find_onnx_file(str(req.get("weightsDir") or ""))):
1973
+ is_onnx_fast = (
1974
+ (op in ("embed", "rerank") and _find_onnx_file(str(req.get("weightsDir") or "")))
1975
+ or (op == "tts" and _find_piper_onnx_files(str(req.get("weightsDir") or "")))
1976
+ )
1977
+ if not HAS_TORCH and not is_onnx_fast:
1652
1978
  needed = ["torch"]
1653
1979
  if op in ("embed", "rerank"):
1654
1980
  needed.append("transformers")
1655
1981
  elif op == "image":
1656
1982
  needed.extend(["diffusers", "accelerate", "pillow", "transformers"])
1983
+ elif op == "video":
1984
+ needed.extend(["diffusers", "accelerate", "pillow", "transformers", "imageio", "imageio-ffmpeg"])
1657
1985
  elif op == "tts":
1658
1986
  needed.extend(["qwen-tts", "soundfile", "transformers"])
1987
+ elif op == "music":
1988
+ needed.extend(["transformers", "accelerate", "soundfile"])
1659
1989
  elif op == "stt":
1660
1990
  needed.extend(["qwen-asr", "soundfile", "transformers"])
1661
1991
  print(json.dumps({
@@ -1665,7 +1995,7 @@ def main():
1665
1995
  "missingDeps": needed,
1666
1996
  }), flush=True)
1667
1997
  continue
1668
- if op in ("embed", "rerank", "image", "tts", "stt"):
1998
+ if op in ("embed", "rerank", "image", "video", "music", "tts", "stt"):
1669
1999
  t0 = time.time()
1670
2000
  mod_key = (op, str(req.get("weightsDir") or ""))
1671
2001
  _evict_memory_if_needed(
@@ -1676,13 +2006,15 @@ def main():
1676
2006
  "embed": handle_embed,
1677
2007
  "rerank": handle_rerank,
1678
2008
  "image": handle_image,
2009
+ "video": handle_video,
2010
+ "music": handle_music,
1679
2011
  "tts": handle_tts,
1680
2012
  "stt": handle_stt,
1681
2013
  }[op]
1682
2014
  with cache_lock:
1683
2015
  res = fn(req, mod_cache)
1684
2016
  mod_last_used[mod_key] = time.time()
1685
- if op == "image":
2017
+ if op in ("image", "video", "music"):
1686
2018
  _schedule_image_idle_eviction()
1687
2019
  if "durationMs" not in res:
1688
2020
  res["durationMs"] = int((time.time() - t0) * 1000)