odant-work 1.0.37 → 1.0.39
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.
- package/#system/package-manifest.json +27 -27
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +18 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/docs.js +15 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +7 -3
- package/$server/$folder/handlers/pages/form/$handler/form.js +1 -1
- package/$server/$folder/lib/consultant/consultant.js +18 -45
- package/MODELS/$ai/$folder/$class/$ai/class.js +135 -10
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +183 -10
- package/MODELS/$ai/$folder/$class/$ai/methods/chat/$method/class.js +19 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +91 -0
- package/package.json +1 -1
- package/sources/data/progress.md +13 -0
- package/sources/modules/agent/index.js +47 -3
- package/sources/modules/agent/loop.js +6 -0
- package/sources/modules/agent/session.js +2 -2
- package/sources/modules/agent/voice.js +29 -1
- package/sources/modules/rag/config.js +75 -75
- package/sources/modules/rag/embedder.js +118 -81
- package/sources/modules/rag/search.js +31 -5
- package/sources/modules/rag/store.js +3 -1
- package/sources/modules/trainer/index.js +210 -0
- package/sources/modules/trainer/local-engine.js +335 -5
- package/sources/modules/trainer/worker/local_infer_worker.py +319 -1
- package/sources/server/class.js +6 -0
|
@@ -4,13 +4,17 @@
|
|
|
4
4
|
Поддерживает архитектуры Qwen3, Qwen2.5, Llama-3, DeepSeek-R1-Distill, Gemma, Mistral (включая многофайловые шарды).
|
|
5
5
|
Общается с Node.js-сервером WORK по протоколу JSONL (stdin -> stdout), удерживая веса модели в памяти между запросами.
|
|
6
6
|
"""
|
|
7
|
+
import base64
|
|
7
8
|
import glob
|
|
9
|
+
import io
|
|
8
10
|
import json
|
|
9
11
|
import mmap
|
|
10
12
|
import os
|
|
11
13
|
import struct
|
|
12
14
|
import sys
|
|
15
|
+
import time
|
|
13
16
|
import warnings
|
|
17
|
+
import wave
|
|
14
18
|
|
|
15
19
|
warnings.filterwarnings("ignore")
|
|
16
20
|
|
|
@@ -248,8 +252,276 @@ class LocalCausalLM:
|
|
|
248
252
|
return int(sorted_indices[sampled_idx].item())
|
|
249
253
|
|
|
250
254
|
|
|
255
|
+
def _best_device_and_dtype():
|
|
256
|
+
if torch.cuda.is_available():
|
|
257
|
+
return "cuda", torch.bfloat16
|
|
258
|
+
return "cpu", torch.float32
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _missing_pkg_error(exc, required_map):
|
|
262
|
+
msg = str(exc)
|
|
263
|
+
missing = []
|
|
264
|
+
for mod, pkg in required_map.items():
|
|
265
|
+
if mod in msg or f"'{mod}'" in msg:
|
|
266
|
+
missing.append(pkg)
|
|
267
|
+
if not missing:
|
|
268
|
+
missing = list(dict.fromkeys(required_map.values()))
|
|
269
|
+
return {
|
|
270
|
+
"error": f"В Python-окружении отсутствуют пакеты ({', '.join(missing)}): {msg}",
|
|
271
|
+
"missingDeps": missing,
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def handle_check_deps():
|
|
276
|
+
mods = {
|
|
277
|
+
"torch": "torch",
|
|
278
|
+
"transformers": "transformers",
|
|
279
|
+
"diffusers": "diffusers",
|
|
280
|
+
"accelerate": "accelerate",
|
|
281
|
+
"PIL": "pillow",
|
|
282
|
+
"soundfile": "soundfile",
|
|
283
|
+
"qwen_tts": "qwen-tts",
|
|
284
|
+
"qwen_asr": "qwen-asr",
|
|
285
|
+
}
|
|
286
|
+
status = {}
|
|
287
|
+
for mod, pkg in mods.items():
|
|
288
|
+
try:
|
|
289
|
+
__import__(mod)
|
|
290
|
+
status[pkg] = True
|
|
291
|
+
except Exception:
|
|
292
|
+
status[pkg] = False
|
|
293
|
+
cuda = False
|
|
294
|
+
device_name = "CPU"
|
|
295
|
+
try:
|
|
296
|
+
cuda = bool(torch.cuda.is_available())
|
|
297
|
+
if cuda:
|
|
298
|
+
device_name = torch.cuda.get_device_name(0)
|
|
299
|
+
except Exception:
|
|
300
|
+
pass
|
|
301
|
+
return {
|
|
302
|
+
"packages": status,
|
|
303
|
+
"cuda": cuda,
|
|
304
|
+
"deviceName": device_name,
|
|
305
|
+
"python": sys.executable,
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _load_embed_model(weights_dir, cache):
|
|
310
|
+
key = ("embed", weights_dir)
|
|
311
|
+
if key in cache:
|
|
312
|
+
return cache[key]
|
|
313
|
+
try:
|
|
314
|
+
from transformers import AutoTokenizer, AutoModel
|
|
315
|
+
except Exception as e:
|
|
316
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e, {"transformers": "transformers"})))
|
|
317
|
+
device, dtype = _best_device_and_dtype()
|
|
318
|
+
tok = AutoTokenizer.from_pretrained(weights_dir, local_files_only=True)
|
|
319
|
+
mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype if device == "cuda" else torch.float32)
|
|
320
|
+
mdl.to(device).eval()
|
|
321
|
+
cache[key] = (tok, mdl, device)
|
|
322
|
+
return cache[key]
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def handle_embed(req, cache):
|
|
326
|
+
weights_dir = req["weightsDir"]
|
|
327
|
+
texts = req.get("input") or []
|
|
328
|
+
if isinstance(texts, str):
|
|
329
|
+
texts = [texts]
|
|
330
|
+
tok, mdl, device = _load_embed_model(weights_dir, cache)
|
|
331
|
+
with torch.inference_mode():
|
|
332
|
+
encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="pt")
|
|
333
|
+
encoded = {k: v.to(device) for k, v in encoded.items()}
|
|
334
|
+
out = mdl(**encoded)
|
|
335
|
+
last_hidden = out.last_hidden_state
|
|
336
|
+
mask = encoded["attention_mask"].unsqueeze(-1).expand(last_hidden.size()).float()
|
|
337
|
+
summed = torch.sum(last_hidden.float() * mask, dim=1)
|
|
338
|
+
counts = torch.clamp(mask.sum(dim=1), min=1e-9)
|
|
339
|
+
vecs = F.normalize(summed / counts, p=2, dim=1)
|
|
340
|
+
arr = vecs.cpu().tolist()
|
|
341
|
+
return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0}
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _load_rerank_model(weights_dir, cache):
|
|
345
|
+
key = ("rerank", weights_dir)
|
|
346
|
+
if key in cache:
|
|
347
|
+
return cache[key]
|
|
348
|
+
try:
|
|
349
|
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
|
350
|
+
except Exception as e:
|
|
351
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e, {"transformers": "transformers"})))
|
|
352
|
+
device, dtype = _best_device_and_dtype()
|
|
353
|
+
tok = AutoTokenizer.from_pretrained(weights_dir, local_files_only=True)
|
|
354
|
+
mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype if device == "cuda" else torch.float32)
|
|
355
|
+
mdl.to(device).eval()
|
|
356
|
+
cache[key] = (tok, mdl, device)
|
|
357
|
+
return cache[key]
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def handle_rerank(req, cache):
|
|
361
|
+
weights_dir = req["weightsDir"]
|
|
362
|
+
query = str(req.get("query", ""))
|
|
363
|
+
docs = req.get("documents") or []
|
|
364
|
+
if not docs:
|
|
365
|
+
return {"results": []}
|
|
366
|
+
tok, mdl, device = _load_rerank_model(weights_dir, cache)
|
|
367
|
+
pairs = [[query, str(d.get("text", d) if isinstance(d, dict) else d)] for d in docs]
|
|
368
|
+
with torch.inference_mode():
|
|
369
|
+
inputs = tok(pairs, padding=True, truncation=True, max_length=int(req.get("maxLength", 1024)), return_tensors="pt")
|
|
370
|
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
|
371
|
+
logits = mdl(**inputs).logits.view(-1).float()
|
|
372
|
+
scores = torch.sigmoid(logits).cpu().tolist()
|
|
373
|
+
ranked = sorted(
|
|
374
|
+
[{"index": i, "relevance_score": float(s), "document": docs[i]} for i, s in enumerate(scores)],
|
|
375
|
+
key=lambda x: x["relevance_score"],
|
|
376
|
+
reverse=True,
|
|
377
|
+
)
|
|
378
|
+
top_n = int(req.get("topN") or 0)
|
|
379
|
+
if top_n > 0:
|
|
380
|
+
ranked = ranked[:top_n]
|
|
381
|
+
return {"results": ranked}
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _load_image_pipeline(weights_dir, cache):
|
|
385
|
+
key = ("image", weights_dir)
|
|
386
|
+
if key in cache:
|
|
387
|
+
return cache[key]
|
|
388
|
+
try:
|
|
389
|
+
import diffusers
|
|
390
|
+
import accelerate # noqa: F401
|
|
391
|
+
from PIL import Image # noqa: F401
|
|
392
|
+
except Exception as e:
|
|
393
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e, {
|
|
394
|
+
"diffusers": "diffusers",
|
|
395
|
+
"accelerate": "accelerate",
|
|
396
|
+
"PIL": "pillow",
|
|
397
|
+
})))
|
|
398
|
+
device, dtype = _best_device_and_dtype()
|
|
399
|
+
pipe = None
|
|
400
|
+
if hasattr(diffusers, "ZImagePipeline"):
|
|
401
|
+
try:
|
|
402
|
+
pipe = diffusers.ZImagePipeline.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
|
|
403
|
+
except Exception:
|
|
404
|
+
pipe = None
|
|
405
|
+
if pipe is None:
|
|
406
|
+
pipe = diffusers.AutoPipelineForText2Image.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
|
|
407
|
+
pipe.to(device)
|
|
408
|
+
cache[key] = (pipe, device)
|
|
409
|
+
return cache[key]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def handle_image(req, cache):
|
|
413
|
+
weights_dir = req["weightsDir"]
|
|
414
|
+
prompt = str(req.get("prompt", "")).strip()
|
|
415
|
+
size_str = str(req.get("size", "512x512"))
|
|
416
|
+
try:
|
|
417
|
+
w, h = [max(256, min(1536, int(v))) for v in size_str.lower().split("x")[:2]]
|
|
418
|
+
except Exception:
|
|
419
|
+
w, h = 512, 512
|
|
420
|
+
steps = int(req.get("steps") or 8)
|
|
421
|
+
seed = int(req.get("seed") if req.get("seed") is not None else 42)
|
|
422
|
+
pipe, device = _load_image_pipeline(weights_dir, cache)
|
|
423
|
+
gen = torch.Generator(device=device).manual_seed(seed)
|
|
424
|
+
kwargs = {"prompt": prompt, "width": w, "height": h, "num_inference_steps": steps, "generator": gen}
|
|
425
|
+
if "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower():
|
|
426
|
+
kwargs["guidance_scale"] = 0.0
|
|
427
|
+
with torch.inference_mode():
|
|
428
|
+
out = pipe(**kwargs)
|
|
429
|
+
img = out.images[0]
|
|
430
|
+
buf = io.BytesIO()
|
|
431
|
+
img.save(buf, format="PNG")
|
|
432
|
+
return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii")}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _pcm_to_wav_base64(samples, sample_rate):
|
|
436
|
+
import array
|
|
437
|
+
if hasattr(samples, "detach"):
|
|
438
|
+
samples = samples.detach().cpu().float().flatten().tolist()
|
|
439
|
+
elif hasattr(samples, "tolist"):
|
|
440
|
+
samples = samples.flatten().tolist()
|
|
441
|
+
pcm = array.array("h", (max(-32767, min(32767, int(float(s) * 32767.0))) for s in samples))
|
|
442
|
+
buf = io.BytesIO()
|
|
443
|
+
with wave.open(buf, "wb") as wf:
|
|
444
|
+
wf.setnchannels(1)
|
|
445
|
+
wf.setsampwidth(2)
|
|
446
|
+
wf.setframerate(int(sample_rate))
|
|
447
|
+
wf.writeframes(pcm.tobytes())
|
|
448
|
+
return base64.b64encode(buf.getvalue()).decode("ascii")
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def handle_tts(req, cache):
|
|
452
|
+
weights_dir = req["weightsDir"]
|
|
453
|
+
text = str(req.get("text", "")).strip()
|
|
454
|
+
language = str(req.get("language") or "Russian")
|
|
455
|
+
instructions = str(req.get("instructions") or "").strip()
|
|
456
|
+
key = ("tts", weights_dir)
|
|
457
|
+
if key not in cache:
|
|
458
|
+
try:
|
|
459
|
+
from qwen_tts import Qwen3TTSModel
|
|
460
|
+
except Exception as e:
|
|
461
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e, {
|
|
462
|
+
"qwen_tts": "qwen-tts",
|
|
463
|
+
"soundfile": "soundfile",
|
|
464
|
+
})))
|
|
465
|
+
device, dtype = _best_device_and_dtype()
|
|
466
|
+
mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
|
|
467
|
+
cache[key] = mdl
|
|
468
|
+
mdl = cache[key]
|
|
469
|
+
if hasattr(mdl, "generate_voice_design") and instructions:
|
|
470
|
+
wavs, sr = mdl.generate_voice_design(text=text, language=language, instruct=instructions)
|
|
471
|
+
elif hasattr(mdl, "generate_custom_voice"):
|
|
472
|
+
wavs, sr = mdl.generate_custom_voice(text=text, language=language, speaker=str(req.get("voice") or "serena"), instruct=instructions or None)
|
|
473
|
+
else:
|
|
474
|
+
wavs, sr = mdl.generate_voice_design(text=text, language=language, instruct=instructions or "Natural clear voice")
|
|
475
|
+
audio = wavs[0] if isinstance(wavs, (list, tuple)) else wavs
|
|
476
|
+
return {"audioBase64": _pcm_to_wav_base64(audio, sr), "sampleRate": int(sr)}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def handle_stt(req, cache):
|
|
480
|
+
weights_dir = req["weightsDir"]
|
|
481
|
+
audio_b64 = req.get("audioBase64", "")
|
|
482
|
+
language = str(req.get("language") or "Russian")
|
|
483
|
+
raw = base64.b64decode(audio_b64)
|
|
484
|
+
key = ("stt", weights_dir)
|
|
485
|
+
if key not in cache:
|
|
486
|
+
loader = None
|
|
487
|
+
try:
|
|
488
|
+
from qwen_asr import Qwen3ASRModel
|
|
489
|
+
device, dtype = _best_device_and_dtype()
|
|
490
|
+
loader = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
|
|
491
|
+
except Exception as e_qwen:
|
|
492
|
+
try:
|
|
493
|
+
from transformers import pipeline
|
|
494
|
+
device, dtype = _best_device_and_dtype()
|
|
495
|
+
loader = ("hf_asr", pipeline("automatic-speech-recognition", model=weights_dir, device=0 if device == "cuda" else -1, torch_dtype=dtype))
|
|
496
|
+
except Exception:
|
|
497
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e_qwen, {
|
|
498
|
+
"qwen_asr": "qwen-asr",
|
|
499
|
+
"soundfile": "soundfile",
|
|
500
|
+
})))
|
|
501
|
+
cache[key] = loader
|
|
502
|
+
kind, mdl = cache[key]
|
|
503
|
+
import tempfile
|
|
504
|
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
|
|
505
|
+
tf.write(raw)
|
|
506
|
+
tmp_path = tf.name
|
|
507
|
+
try:
|
|
508
|
+
if kind == "qwen_asr":
|
|
509
|
+
res = mdl.transcribe(audio=tmp_path, language=language)
|
|
510
|
+
txt = res[0].text if isinstance(res, list) and res else getattr(res, "text", str(res))
|
|
511
|
+
else:
|
|
512
|
+
res = mdl(tmp_path)
|
|
513
|
+
txt = res.get("text", "") if isinstance(res, dict) else str(res)
|
|
514
|
+
finally:
|
|
515
|
+
try:
|
|
516
|
+
os.remove(tmp_path)
|
|
517
|
+
except Exception:
|
|
518
|
+
pass
|
|
519
|
+
return {"text": str(txt or "").strip()}
|
|
520
|
+
|
|
521
|
+
|
|
251
522
|
def main():
|
|
252
523
|
models = {}
|
|
524
|
+
mod_cache = {}
|
|
253
525
|
print(json.dumps({"event": "ready"}), flush=True)
|
|
254
526
|
|
|
255
527
|
for line in sys.stdin:
|
|
@@ -260,6 +532,42 @@ def main():
|
|
|
260
532
|
try:
|
|
261
533
|
req = json.loads(line)
|
|
262
534
|
req_id = req.get("id", "")
|
|
535
|
+
op = req.get("op", "chat")
|
|
536
|
+
|
|
537
|
+
if op == "check_deps":
|
|
538
|
+
print(json.dumps({"id": req_id, "event": "result", "data": handle_check_deps()}), flush=True)
|
|
539
|
+
continue
|
|
540
|
+
if op == "embed":
|
|
541
|
+
t0 = time.time()
|
|
542
|
+
res = handle_embed(req, mod_cache)
|
|
543
|
+
res["durationMs"] = int((time.time() - t0) * 1000)
|
|
544
|
+
print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
|
|
545
|
+
continue
|
|
546
|
+
if op == "rerank":
|
|
547
|
+
t0 = time.time()
|
|
548
|
+
res = handle_rerank(req, mod_cache)
|
|
549
|
+
res["durationMs"] = int((time.time() - t0) * 1000)
|
|
550
|
+
print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
|
|
551
|
+
continue
|
|
552
|
+
if op == "image":
|
|
553
|
+
t0 = time.time()
|
|
554
|
+
res = handle_image(req, mod_cache)
|
|
555
|
+
res["durationMs"] = int((time.time() - t0) * 1000)
|
|
556
|
+
print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
|
|
557
|
+
continue
|
|
558
|
+
if op == "tts":
|
|
559
|
+
t0 = time.time()
|
|
560
|
+
res = handle_tts(req, mod_cache)
|
|
561
|
+
res["durationMs"] = int((time.time() - t0) * 1000)
|
|
562
|
+
print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
|
|
563
|
+
continue
|
|
564
|
+
if op == "stt":
|
|
565
|
+
t0 = time.time()
|
|
566
|
+
res = handle_stt(req, mod_cache)
|
|
567
|
+
res["durationMs"] = int((time.time() - t0) * 1000)
|
|
568
|
+
print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
|
|
569
|
+
continue
|
|
570
|
+
|
|
263
571
|
weights_dir = req["weightsDir"]
|
|
264
572
|
prompt_ids = req["inputIds"]
|
|
265
573
|
max_new_tokens = int(req.get("maxNewTokens", 384))
|
|
@@ -277,7 +585,17 @@ def main():
|
|
|
277
585
|
eos_ids=eos_ids,
|
|
278
586
|
)
|
|
279
587
|
except Exception as e:
|
|
280
|
-
|
|
588
|
+
err_str = str(e)
|
|
589
|
+
payload = {"id": req_id, "event": "error", "error": err_str}
|
|
590
|
+
try:
|
|
591
|
+
parsed = json.loads(err_str)
|
|
592
|
+
if isinstance(parsed, dict) and parsed.get("error"):
|
|
593
|
+
payload["error"] = parsed["error"]
|
|
594
|
+
if parsed.get("missingDeps"):
|
|
595
|
+
payload["missingDeps"] = parsed["missingDeps"]
|
|
596
|
+
except Exception:
|
|
597
|
+
pass
|
|
598
|
+
print(json.dumps(payload), flush=True)
|
|
281
599
|
|
|
282
600
|
|
|
283
601
|
if __name__ == "__main__":
|
package/sources/server/class.js
CHANGED
|
@@ -22,6 +22,7 @@ import { DATA_METHODS, classHasObjects, classObjectCount, markClassesDirty } fro
|
|
|
22
22
|
import {
|
|
23
23
|
TRAINER_METHODS,
|
|
24
24
|
localStreamChat,
|
|
25
|
+
localEngine,
|
|
25
26
|
ensureHalogenBackendRunning,
|
|
26
27
|
halogenFallback,
|
|
27
28
|
evaluateAiNodeActivitySync,
|
|
@@ -863,6 +864,11 @@ Object.defineProperty($class.prototype, 'localStreamChat', {
|
|
|
863
864
|
writable: true,
|
|
864
865
|
configurable: true,
|
|
865
866
|
});
|
|
867
|
+
Object.defineProperty($class.prototype, 'localEngine', {
|
|
868
|
+
value: localEngine,
|
|
869
|
+
writable: true,
|
|
870
|
+
configurable: true,
|
|
871
|
+
});
|
|
866
872
|
Object.defineProperty($class.prototype, 'ensureHalogenBackendRunning', {
|
|
867
873
|
value: ensureHalogenBackendRunning,
|
|
868
874
|
writable: true,
|