forked from Rakile/NeuralCompanion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
7083 lines (6255 loc) · 304 KB
/
Copy pathengine.py
File metadata and controls
7083 lines (6255 loc) · 304 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Voice Assistant: Microphone → LM Studio → ChatterboxTurboTTS
Standalone script for voice interaction with local LLM
"""
import queue
import os
import sys
import time
import base64
import platform
import subprocess
import threading
import logging
import locale
import warnings
import urllib.request
import mimetypes
from pathlib import Path
import torch
import sounddevice as sd
import numpy as np
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
os.environ.setdefault("TQDM_DISABLE", "1")
warnings.filterwarnings(
"ignore",
message=r".*pkg_resources is deprecated as an API.*",
category=UserWarning,
)
import tkinter as tk
from PIL import ImageTk
import re
import random
import math
from pythonosc import udp_client
import abc
import shutil
import json
import uuid
import gc
import importlib
import dry_run
import app_help
from core import sensory, audio_story_runtime, avatar_hand_state, avatar_runtime, avatar_runtime_context, chat_providers, conversation_history as conversation_history_runtime, lmstudio_runtime, runtime_chat, runtime_files, runtime_hotkeys, runtime_paths, runtime_shutdown, speech_text, streaming_text, stt_runtime, text_chunking, text_tags, tts_runtime, audio_playback, user_image_turns
from core import expression_state
from core.addons import bootstrap_runtime
from core.addons.runtime_defaults import addon_runtime_defaults
from core.conversation_flow_v2 import ConversationActionType, ConversationPolicy, SystemClockRuntime, build_experimental_controller
def _configure_ffmpeg_tools():
ffmpeg_bin = str(os.environ.get("NC_FFMPEG_BIN", "") or "").strip()
if not ffmpeg_bin:
ffmpeg_bin = str(Path(__file__).resolve().parent / "tools" / "ffmpeg" / "bin")
bin_path = Path(ffmpeg_bin)
ffmpeg_exe = bin_path / ("ffmpeg.exe" if os.name == "nt" else "ffmpeg")
ffprobe_exe = bin_path / ("ffprobe.exe" if os.name == "nt" else "ffprobe")
if not ffmpeg_exe.exists() or not ffprobe_exe.exists():
return None
current_path = os.environ.get("PATH", "")
bin_text = str(bin_path)
path_parts = [part for part in current_path.split(os.pathsep) if part]
if bin_text not in path_parts:
os.environ["PATH"] = bin_text + (os.pathsep + current_path if current_path else "")
return ffmpeg_exe, ffprobe_exe
_FFMPEG_TOOLS = _configure_ffmpeg_tools()
from pydub import AudioSegment
if _FFMPEG_TOOLS is not None:
AudioSegment.converter = str(_FFMPEG_TOOLS[0])
AudioSegment.ffmpeg = str(_FFMPEG_TOOLS[0])
AudioSegment.ffprobe = str(_FFMPEG_TOOLS[1])
_ORIGINAL_SUBPROCESS_POPEN = subprocess.Popen
class _AddonModuleProxy:
def __init__(self, module_name):
self._module_name = str(module_name or "")
self._module = None
def _load(self):
if self._module is None:
self._module = importlib.import_module(self._module_name)
return self._module
def __getattr__(self, name):
return getattr(self._load(), name)
musetalk_state = _AddonModuleProxy("addons.musetalk_avatar.state")
def _safe_text_mode_popen(*args, **kwargs):
text_mode = bool(kwargs.get("text")) or bool(kwargs.get("universal_newlines"))
if text_mode and kwargs.get("errors") is None:
kwargs["errors"] = "replace"
if text_mode and kwargs.get("encoding") is None and os.name == "nt":
kwargs["encoding"] = locale.getpreferredencoding(False) or "utf-8"
return _ORIGINAL_SUBPROCESS_POPEN(*args, **kwargs)
if getattr(subprocess.Popen, "__name__", "") != "_safe_text_mode_popen":
subprocess.Popen = _safe_text_mode_popen
# Try importing speech recognition
try:
import speech_recognition as sr
except ImportError:
print("ERROR: speech_recognition not installed. Install with: pip install SpeechRecognition")
sys.exit(1)
# Try importing NLTK for sentence tokenization
try:
import nltk
import re
from functools import lru_cache
except ImportError:
print("ERROR: nltk not installed. Install with: pip install nltk")
sys.exit(1)
# ============================================================================
# CONFIGURATION
# ============================================================================
stt_model = None
stt_backend_name = None
# TTS settings
TTS_TEMPERATURE = 0.9
TTS_TOP_P = 0.95
TTS_TOP_K = 1000
TTS_REPETITION_PENALTY = 1.2
TTS_NORM_LOUDNESS = True
# Chunking settings for long text
TARGET_CHARS_PER_CHUNK = 100
MAX_CHARS_PER_CHUNK = 200
MIN_CHUNK_SIZE = 10
MUSE_TARGET_CHARS_PER_CHUNK = 110
MUSE_MAX_CHARS_PER_CHUNK = 220
MUSE_QUICKSTART_CHUNK_LIMITS = [
(170, 320),
(130, 240),
]
MUSE_MIN_LEADING_SEGMENT_CHARS = 60
MUSE_MAX_INFLIGHT_RENDERS = 3
MUSE_FIRST_CHUNK_IDLE_WINDOW = 48
MUSE_FIRST_CHUNK_PREDICTED_DELAY_SECONDS = 2.0
MUSE_FIRST_CHUNK_DELAY_SAMPLE_LIMIT = 8
STREAM_FIRST_CHUNK_MIN_CHARS = streaming_text.STREAM_FIRST_CHUNK_MIN_CHARS
STREAM_FORCE_FLUSH_SECONDS = streaming_text.STREAM_FORCE_FLUSH_SECONDS
STREAM_FORCE_FLUSH_LATER_SECONDS = streaming_text.STREAM_FORCE_FLUSH_LATER_SECONDS
STREAM_FIRST_CHUNK_PLAN_SECONDS = streaming_text.STREAM_FIRST_CHUNK_PLAN_SECONDS
STREAM_FIRST_CHUNK_PLAN_SYNC_MAX_SECONDS = streaming_text.STREAM_FIRST_CHUNK_PLAN_SYNC_MAX_SECONDS
STREAM_FIRST_CHUNK_IDLE_SYNC_MAX_SECONDS = streaming_text.STREAM_FIRST_CHUNK_IDLE_SYNC_MAX_SECONDS
MUSE_DIAGNOSTIC_LOGGING = False
STREAM_TINY_TAIL_CHARS = streaming_text.STREAM_TINY_TAIL_CHARS
STREAM_WHITESPACE_FALLBACK_MARGIN = streaming_text.STREAM_WHITESPACE_FALLBACK_MARGIN
STREAM_POST_TARGET_PUNCTUATION_MARGIN = streaming_text.STREAM_POST_TARGET_PUNCTUATION_MARGIN
STREAM_POST_TARGET_PUNCTUATION_WAIT_SECONDS = streaming_text.STREAM_POST_TARGET_PUNCTUATION_WAIT_SECONDS
STREAM_CLAUSE_FALLBACK_MARGIN = streaming_text.STREAM_CLAUSE_FALLBACK_MARGIN
STREAM_CLAUSE_FALLBACK_MIN_SCORE = streaming_text.STREAM_CLAUSE_FALLBACK_MIN_SCORE
STREAM_CLAUSE_FALLBACK_WAIT_SECONDS = streaming_text.STREAM_CLAUSE_FALLBACK_WAIT_SECONDS
STREAM_CLAUSE_STARTERS = streaming_text.STREAM_CLAUSE_STARTERS
STREAM_BAD_ENDING_WORDS = streaming_text.STREAM_BAD_ENDING_WORDS
# Voice activation settings
ENERGY_THRESHOLD = 500
PAUSE_THRESHOLD = 2.2
DYNAMIC_ENERGY_THRESHOLD = True
NON_SPEAKING_DURATION = 0.35
PHRASE_THRESHOLD = 0.2
AMBIENT_CALIBRATION_SECONDS = 0.6
BARGE_IN_THRESHOLD = 500
BARGE_IN_CONSECUTIVE_CHUNKS = 2
BARGE_IN_RESET_SECONDS = 0.25
keyboard = runtime_hotkeys.keyboard
pynput_keyboard = runtime_hotkeys.pynput_keyboard
DEFAULT_PUSH_TO_TALK_HOTKEY = runtime_hotkeys.DEFAULT_PUSH_TO_TALK_HOTKEY
DEFAULT_MANUAL_ACTION_HOTKEYS = runtime_hotkeys.DEFAULT_MANUAL_ACTION_HOTKEYS
DEFAULT_UI_ACTION_HOTKEYS = runtime_hotkeys.DEFAULT_UI_ACTION_HOTKEYS
HOTKEY_ACTION_LABELS = runtime_hotkeys.HOTKEY_ACTION_LABELS
PYNPUT_HOTKEY_AVAILABLE = runtime_hotkeys.PYNPUT_HOTKEY_AVAILABLE
EXACT_HOTKEY_SCAN_CODES = runtime_hotkeys.EXACT_HOTKEY_SCAN_CODES
normalize_hotkey_text = runtime_hotkeys.normalize_hotkey_text
canonicalize_pynput_key = runtime_hotkeys.canonicalize_pynput_key
is_hotkey_binding_pressed = runtime_hotkeys.is_hotkey_binding_pressed
def _normalize_manual_action_hotkeys(raw):
return runtime_hotkeys.normalize_manual_action_hotkeys(raw)
def _normalize_ui_action_hotkeys(raw):
return runtime_hotkeys.normalize_ui_action_hotkeys(raw)
def _normalize_hotkey_settings(raw=None, *, legacy_push_to_talk=None, legacy_manual=None, legacy_ui=None):
return runtime_hotkeys.normalize_hotkey_settings(
raw,
legacy_push_to_talk=legacy_push_to_talk,
legacy_manual=legacy_manual,
legacy_ui=legacy_ui,
)
def _sync_legacy_hotkey_runtime_keys(settings):
payload = _normalize_hotkey_settings(settings)
RUNTIME_CONFIG["hotkeys"] = payload
RUNTIME_CONFIG["push_to_talk_hotkey"] = payload["push_to_talk"]
RUNTIME_CONFIG["manual_action_hotkeys"] = dict(payload["manual_actions"])
RUNTIME_CONFIG["ui_action_hotkeys"] = dict(payload["ui_actions"])
return payload
def register_ui_hotkey_actions(actions=None, labels=None):
defaults = runtime_hotkeys.register_ui_action_hotkeys(actions, labels)
current = _normalize_ui_action_hotkeys(get_hotkey_settings().get("ui_actions", defaults))
update_runtime_config("ui_action_hotkeys", current)
return defaults
def get_hotkey_settings():
return _normalize_hotkey_settings(
RUNTIME_CONFIG.get("hotkeys", {}),
legacy_push_to_talk=RUNTIME_CONFIG.get("push_to_talk_hotkey", DEFAULT_PUSH_TO_TALK_HOTKEY),
legacy_manual=RUNTIME_CONFIG.get("manual_action_hotkeys", DEFAULT_MANUAL_ACTION_HOTKEYS),
legacy_ui=RUNTIME_CONFIG.get("ui_action_hotkeys", DEFAULT_UI_ACTION_HOTKEYS),
)
def get_push_to_talk_hotkey():
configured = normalize_hotkey_text(get_hotkey_settings().get("push_to_talk", DEFAULT_PUSH_TO_TALK_HOTKEY))
return configured or DEFAULT_PUSH_TO_TALK_HOTKEY
def get_manual_action_hotkeys():
return _normalize_manual_action_hotkeys(get_hotkey_settings().get("manual_actions", DEFAULT_MANUAL_ACTION_HOTKEYS))
def get_ui_action_hotkeys():
return _normalize_ui_action_hotkeys(get_hotkey_settings().get("ui_actions", DEFAULT_UI_ACTION_HOTKEYS))
def get_hotkey_bindings():
bindings = {"push_to_talk": get_push_to_talk_hotkey()}
bindings.update(get_manual_action_hotkeys())
bindings.update(get_ui_action_hotkeys())
return bindings
def set_push_to_talk_hotkey(binding):
update_runtime_config("push_to_talk_hotkey", binding)
return get_push_to_talk_hotkey()
def set_hotkey_settings(settings):
update_runtime_config("hotkeys", settings)
return get_hotkey_settings()
def set_manual_action_hotkey(action, binding):
action_key = str(action or "").strip()
if action_key not in DEFAULT_MANUAL_ACTION_HOTKEYS:
raise KeyError(f"Unknown hotkey action: {action_key}")
current = get_manual_action_hotkeys()
current[action_key] = normalize_hotkey_text(binding)
update_runtime_config("manual_action_hotkeys", current)
return get_manual_action_hotkeys().get(action_key, "")
def set_ui_action_hotkey(action, binding):
action_key = str(action or "").strip()
if action_key not in DEFAULT_UI_ACTION_HOTKEYS:
raise KeyError(f"Unknown UI hotkey action: {action_key}")
current = get_ui_action_hotkeys()
current[action_key] = normalize_hotkey_text(binding)
update_runtime_config("ui_action_hotkeys", current)
return get_ui_action_hotkeys().get(action_key, "")
def reset_hotkeys_to_defaults():
update_runtime_config("push_to_talk_hotkey", DEFAULT_PUSH_TO_TALK_HOTKEY)
update_runtime_config("manual_action_hotkeys", dict(DEFAULT_MANUAL_ACTION_HOTKEYS))
update_runtime_config("ui_action_hotkeys", dict(DEFAULT_UI_ACTION_HOTKEYS))
return get_hotkey_bindings()
def _is_musetalk_avatar_adapter(adapter) -> bool:
return avatar_runtime.adapter_matches_provider(adapter, "musetalk")
def _is_vam_avatar_adapter(adapter) -> bool:
return avatar_runtime.adapter_matches_provider(adapter, "vam")
PUSH_TO_TALK_MAX_SECONDS = 300.0
PUSH_TO_TALK_TAIL_SECONDS = 0.55
PUSH_TO_TALK_MIN_TAIL_CHUNKS = 8
MAX_HISTORY = 60
ASSISTANT_PREFIX_ANCHOR_THRESHOLD = 5
CONTINUE_ASSISTANT_SENTINEL = "__CONTINUE_ASSISTANT__"
LAST_INPUT_TIME = 0
COMPANION_PROFILE = {
"name": "Echo",
"style": "warm, curious, slightly playful",
"verbosity": "short spoken replies",
"boundaries": "no emojis when speaking"
}
assistant_memory = {
"preferences": {},
"recent_context": [],
}
chat_session_state_generation = 0
pending_loaded_input_turn = None
CHAT_REBUILD_SENTINEL = "[[CHAT_REBUILD]]"
def _default_assistant_memory():
return {
"preferences": {},
"recent_context": [],
}
# ============================================================================
# INSTRUCTIONS
# ============================================================================
DEFAULT_EMOTIONAL_INSTRUCTIONS = """You have a graphical face and a voice. Use them to act out your responses vividly.
VISUAL MOODS (State-based):
Insert one of these tags to make your graphical avatar take on a specific facial expression at any given moment.
Valid Tags: [neutral], [sad], [angry]
VOICE SOUNDS (Action-based):
Insert one of these tags to express a vocal emotion at any given moment.
Valid Tags: [laugh], [chuckle], [sigh], [groan], [gasp], [clear throat], [sniff]
Example of how to use tags in a sentence:
"[angry] You did what? [laugh] [sad] Oh my god, are you okay? [neutral] Or just clumsy?"
Do NOT use emojis when speaking!"""
DEFAULT_SENSORY_PINGPONG_PROMPT = """You are NC's hidden sensory ping/pong layer. The user never sees this exchange.
You receive hidden sensory PINGs and must return JSON only, with no prose or markdown.
Schema: {"keep": boolean, "emotion": string, "attention": string, "summary": string, "proactive_candidate": string, "visual_candidate": string, "should_speak": boolean, "should_generate_image": boolean, "tags": [string]}.
General rules:
- Return exactly one JSON object and nothing else.
- Use the exact schema keys, in double quotes. Do not invent variants such as "visual Candidate", "visualCandidate", or "should generate image".
- Quote all string keys and string values with standard double quotes. Do not use markdown, smart quotes, comments, or bare keys.
- Use empty strings for fields that have no meaningful update.
- Use an empty array for tags when no addon-specific directive tags are needed.
- Use false for action flags unless there is a clear reason to act.
- Do not claim continuous vision, prior images, or certainty beyond what the current hidden context actually supports.
- Prefer compact, valid JSON over expressive wording.
Emotion:
- Emotion must be one of: __EMOTION_LIST__.
- Emotion should represent NC's internal reaction, stance, or dramatic posture toward the current sensory situation.
- Do not simply mirror the user's visible facial expression unless that is truly the best in-character reaction.
Attention:
- Use attention for short latent focus cues such as user, screen, desk, away, reading, researching, task, waiting, or environment.
- Keep attention brief and functional.
Summary and memory:
- Set keep=true only if the sensory update changes hidden state or is worth remembering for later replies.
- Good keep-worthy events include meaningful scene changes, clear user activity shifts, evidence of task progress, emotional shifts, absence/return, or visually important changes.
- Prefer concise summaries of meaningful change over restating everything in the image.
- If nothing important changed, prefer keep=false and an empty summary.
Action fields:
- The core prompt defines the JSON contract only. Enabled source-specific guidance decides when should_speak, proactive_candidate, should_generate_image, and visual_candidate are appropriate.
- proactive_candidate should be a concise cue describing what NC should react to, ask about, or comment on, not a full final reply.
- visual_candidate should be a concise image prompt describing the scene, concept, or mood worth generating.
- If the active source guidance does not strongly justify an action, prefer the action flags false and the candidate fields empty.
- Never copy, paraphrase, or continue a prior proactive_candidate or recent Assistant reply. Each proactive_candidate must be newly grounded in the current PING's visible content and current summary.
- If the current screen/content changed but you cannot form a new comment about the new content, set should_speak=false and proactive_candidate="".
- tags is for addon-directed latent directives such as "[start calculator]" or "[heart_rate_high]". Only emit tags when active source guidance clearly asks for them.
Action consistency rules:
- If should_speak is true, proactive_candidate must be a non-empty string.
- If proactive_candidate is empty, should_speak must be false.
- If should_generate_image is true, visual_candidate must be a non-empty string.
- If visual_candidate is empty, should_generate_image must be false.
- Never return incomplete action requests.
Examples:
- Minimal no-op example:
{"keep": false, "emotion": "", "attention": "", "summary": "", "proactive_candidate": "", "visual_candidate": "", "should_speak": false, "should_generate_image": false, "tags": []}
- Retain-only example:
{"keep": true, "emotion": "neutral", "attention": "screen", "summary": "User resumed working in the text editor.", "proactive_candidate": "", "visual_candidate": "", "should_speak": false, "should_generate_image": false, "tags": []}
- Proactive speech example:
{"keep": true, "emotion": "angry", "attention": "unexpected event", "summary": "A sudden change needs NC's attention.", "proactive_candidate": "I noticed something changed and want to react to it.", "visual_candidate": "", "should_speak": true, "should_generate_image": false, "tags": []}
- Image-generation shape example:
{"keep": true, "emotion": "sad", "attention": "screen", "summary": "A source-specific cue suggests generating an image.", "proactive_candidate": "", "visual_candidate": "concise source-grounded image prompt", "should_speak": false, "should_generate_image": true, "tags": []}
- Addon tag example:
{"keep": true, "emotion": "neutral", "attention": "heart rate", "summary": "Heart rate crossed the addon threshold.", "proactive_candidate": "", "visual_candidate": "", "should_speak": false, "should_generate_image": false, "tags": ["[start calculator]"]}
Optimization goal:
- Be selective, grounded, and useful.
- Most PONGs should be minimal.
- Use richer fields only when they create real latent value for NC.
- When in doubt, imitate the example structure exactly and keep the JSON valid."""
# ============================================================================
# DYNAMIC CONFIGURATION (The GUI will modify this)
# ============================================================================
DEFAULT_POCKET_TTS_PYTHON = os.path.abspath(
os.path.join(os.path.dirname(__file__), ".venvs", "pockettts", "Scripts", "python.exe")
)
def _env_flag(name, default=False):
raw = str(os.environ.get(name, "1" if default else "0") or ("1" if default else "0")).strip().lower()
return raw in {"1", "true", "yes", "on"}
def _env_json_dict(name, default):
raw = str(os.environ.get(name, "") or "").strip()
if not raw:
return dict(default)
try:
parsed = json.loads(raw)
except Exception:
return dict(default)
return {str(key): value for key, value in parsed.items()} if isinstance(parsed, dict) else dict(default)
def _addon_runtime_defaults():
return addon_runtime_defaults(Path(__file__).resolve().parent, environ=os.environ)
def _invoke_bootstrap_addon_capability(addon_id, capability, payload=None, default=None):
return bootstrap_runtime.invoke_addon_capability(
addon_id,
capability,
payload or {},
app_root=Path(__file__).resolve().parent,
default=default,
)
def _create_visual_reply_engine_bridge():
return _invoke_bootstrap_addon_capability(
"nc.visual_reply",
"runtime.engine_bridge",
{
"config_getter": lambda: RUNTIME_CONFIG,
"environ": os.environ,
"output_dir": Path(__file__).resolve().parent / "runtime" / "visual_replies",
},
)
def _invoke_musetalk_pack_capability(capability, payload=None, default=None):
return _invoke_bootstrap_addon_capability(
"nc.musetalk_avatar",
capability,
payload or {},
default=default,
)
def _active_avatar_vram_mode(default="quality"):
avatar_mode = str(RUNTIME_CONFIG.get("avatar_mode", "") or "").strip().lower()
if avatar_mode:
value = _invoke_avatar_addon_capability(
avatar_mode,
"runtime.vram_mode",
{
"runtime_config": RUNTIME_CONFIG,
"default": default,
},
default="",
)
if value:
return str(value or default).strip().lower()
return str(RUNTIME_CONFIG.get("avatar_vram_mode", RUNTIME_CONFIG.get("vram_mode", default)) or default).strip().lower()
def _normalized_abs_path(raw_path):
return runtime_paths.normalized_abs_path(raw_path)
def _path_endswith_parts(path_value, *parts):
return runtime_paths.path_endswith_parts(path_value, *parts)
_AVATAR_ADDON_MODULE_CACHE = {}
_AVATAR_PROVIDER_FOLDER_CACHE = {}
def _avatar_addon_folder_for_provider(provider_id):
provider = avatar_runtime.normalize_provider_id(provider_id, fallback="")
if not provider:
return ""
if provider in _AVATAR_PROVIDER_FOLDER_CACHE:
return _AVATAR_PROVIDER_FOLDER_CACHE[provider]
addons_root = Path(__file__).resolve().parent / "addons"
for manifest_path in sorted(addons_root.glob("*/addon.json")):
try:
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
except Exception:
continue
for service in list(payload.get("services") or []):
if not isinstance(service, dict):
continue
if str(service.get("id") or "").strip() != "avatar_provider_registry":
continue
if str(service.get("provider_id") or "").strip().lower() == provider:
folder = manifest_path.parent.name
_AVATAR_PROVIDER_FOLDER_CACHE[provider] = folder
return folder
_AVATAR_PROVIDER_FOLDER_CACHE[provider] = ""
return ""
def _load_avatar_addon_module(provider_id):
folder = _avatar_addon_folder_for_provider(provider_id)
if not folder:
return None
if folder in _AVATAR_ADDON_MODULE_CACHE:
return _AVATAR_ADDON_MODULE_CACHE[folder]
module_path = Path(__file__).resolve().parent / "addons" / folder / "main.py"
if not module_path.exists():
return None
module_name = f"_nc_engine_avatar_bootstrap_{folder}"
spec = importlib.util.spec_from_file_location(module_name, module_path)
if spec is None or spec.loader is None:
return None
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
_AVATAR_ADDON_MODULE_CACHE[folder] = module
return module
def _invoke_avatar_addon_capability(provider_id, capability, payload=None, default=None):
module = _load_avatar_addon_module(provider_id)
addon_cls = getattr(module, "Addon", None) if module is not None else None
if addon_cls is None:
return default
try:
addon = addon_cls()
result = addon.invoke_capability(capability, payload or {})
except Exception:
logging.getLogger(__name__).exception("Avatar addon capability failed: %s/%s", provider_id, capability)
return default
return default if result is None else result
def _vam_config():
return _invoke_avatar_addon_capability("vam", "runtime.vam_config", default={}) or {}
def _detect_default_vam_root():
fn = _vam_config().get("detect_default_root")
if callable(fn):
return fn()
return runtime_paths.detect_default_vam_root(app_root=Path(__file__).resolve().parent, environ=os.environ)
def derive_vam_bridge_root(vam_root):
fn = _vam_config().get("derive_bridge_root")
if callable(fn):
return fn(vam_root)
return runtime_paths.derive_vam_bridge_root(vam_root, app_root=Path(__file__).resolve().parent)
def derive_vam_plugin_dir(vam_root):
fn = _vam_config().get("derive_plugin_dir")
if callable(fn):
return fn(vam_root)
return runtime_paths.derive_vam_plugin_dir(vam_root)
DEFAULT_VAM_ROOT = _vam_config().get("default_root") or _detect_default_vam_root()
LEGACY_VAM_BRIDGE_ROOTS = tuple(_vam_config().get("legacy_bridge_roots") or runtime_paths.legacy_vam_bridge_roots(app_root=Path(__file__).resolve().parent))
def normalize_vam_root(raw_value=None, migrate_legacy=True):
fn = _vam_config().get("normalize_root")
if callable(fn):
return fn(raw_value, migrate_legacy=migrate_legacy)
return runtime_paths.normalize_vam_root(
raw_value,
default_vam_root=DEFAULT_VAM_ROOT,
legacy_roots=LEGACY_VAM_BRIDGE_ROOTS,
migrate_legacy=migrate_legacy,
)
def normalize_vam_bridge_root(raw_value=None, migrate_legacy=True):
fn = _vam_config().get("normalize_bridge_root")
if callable(fn):
return fn(raw_value, migrate_legacy=migrate_legacy)
return runtime_paths.normalize_vam_bridge_root(
raw_value,
app_root=Path(__file__).resolve().parent,
default_vam_root=DEFAULT_VAM_ROOT,
legacy_roots=LEGACY_VAM_BRIDGE_ROOTS,
migrate_legacy=migrate_legacy,
)
DEFAULT_VAM_EMOTION_PRESET_MAP = dict(_vam_config().get("default_emotion_preset_map") or {
"neutral": "nc_neutral",
"happy": "nc_happy",
"angry": "nc_angry",
"sad": "nc_sad",
"surprised": "nc_surprised",
"shy": "nc_shy",
"default": "nc_neutral",
})
DEFAULT_VAM_TIMELINE_CLIP_MAP = dict(_vam_config().get("default_timeline_clip_map") or {
"happy": "talk_happy",
"angry": "talk_angry",
"sad": "talk_sad",
"surprised": "talk_surprised",
"shy": "talk_shy",
"default": "talk_default",
})
DEFAULT_VAM_BRIDGE_ROOT = _vam_config().get("default_bridge_root") or derive_vam_bridge_root(DEFAULT_VAM_ROOT)
_visual_reply_bridge = _create_visual_reply_engine_bridge()
VISUAL_REPLY_STORY_THEME_PRESETS = tuple(getattr(_visual_reply_bridge, "VISUAL_REPLY_STORY_THEME_PRESETS", ()) or ())
def _default_visual_reply_story_theme_prompts():
if _visual_reply_bridge is not None:
return _visual_reply_bridge.default_story_theme_prompts()
return {}
RUNTIME_CONFIG = {
"active_preset_name": "",
"model_name": "",
"model_requires_vision": False,
"model_supports_images": None,
"model_supports_reasoning": False,
"model_supports_reasoning_toggle": False,
"chat_provider": os.environ.get("NC_CHAT_PROVIDER", chat_providers.DEFAULT_PROVIDER_ID),
"chat_provider_settings": {},
"chat_provider_generation_settings": {},
"emotional_instructions": DEFAULT_EMOTIONAL_INSTRUCTIONS,
"system_prompt": "You are Echo, a witty and helpful AI companion. Keep answers concise.",
"voice_path": "",
"chat_replay_role_voices": {},
"stt_backend": "whisper_english",
"stt_model_size": "tiny.en",
"stt_language": "en",
"tts_backend": "chatterbox",
"chatterbox_multilingual_language": "en",
"chatterbox_multilingual_apply_watermark": True,
"tts_prewarm_on_start": True,
"tts_use_cloned_voice": True,
"tts_apply_watermark": True,
"pocket_tts_python": DEFAULT_POCKET_TTS_PYTHON if os.path.exists(DEFAULT_POCKET_TTS_PYTHON) else "",
"pocket_tts_language": "en",
"pocket_tts_temperature": 0.7,
"pocket_tts_lsd_decode_steps": 1,
"pocket_tts_eos_threshold": -4.0,
"pocket_tts_max_tokens": 50,
"pocket_tts_frames_after_eos": 0,
"pocket_tts_builtin_voice": "auto",
"pocket_tts_use_cloned_voice": True,
"pocket_tts_prewarm_on_start": True,
"avatar_mode": "vseeface",
"vam_root": DEFAULT_VAM_ROOT,
"vam_bridge_root": DEFAULT_VAM_BRIDGE_ROOT,
"vam_emotion_preset_map": _env_json_dict("NC_VAM_EMOTION_PRESET_MAP", DEFAULT_VAM_EMOTION_PRESET_MAP),
"vam_timeline_clip_map": _env_json_dict("NC_VAM_TIMELINE_CLIP_MAP", DEFAULT_VAM_TIMELINE_CLIP_MAP),
"input_mode": "voice_activation",
"show_all_audio_input_devices": False,
"hotkeys": runtime_hotkeys.normalize_hotkey_settings(),
"push_to_talk_hotkey": DEFAULT_PUSH_TO_TALK_HOTKEY,
"manual_action_hotkeys": dict(DEFAULT_MANUAL_ACTION_HOTKEYS),
"ui_action_hotkeys": dict(DEFAULT_UI_ACTION_HOTKEYS),
"input_message_role": "user",
"stream_mode": False,
"offline_replay_only": False,
"chat_context_window_messages": 20,
"chat_context_overflow_policy": "rolling_window",
"stored_chat_history_limit": 0,
"chunk_target_chars": TARGET_CHARS_PER_CHUNK,
"chunk_max_chars": MAX_CHARS_PER_CHUNK,
"stream_chunk_target_chars": 80,
"stream_chunk_max_chars": 185,
"stream_first_chunk_min_chars": STREAM_FIRST_CHUNK_MIN_CHARS,
"stream_force_flush_seconds": STREAM_FORCE_FLUSH_SECONDS,
"stream_force_flush_later_seconds": STREAM_FORCE_FLUSH_LATER_SECONDS,
"temperature": 0.7,
"top_p": 0.9,
"top_k": 40,
"min_p": 0.05,
"repeat_penalty": 1.15,
"limit_response_length": False,
"max_response_tokens": 600,
"allow_proactive_replies": False,
"require_first_user_before_proactive": False,
"listen_idle_window_seconds": 5.0,
"proactive_delay_seconds": 10.0,
**_addon_runtime_defaults(),
"visual_reply_story_theme_prompts": _default_visual_reply_story_theme_prompts(),
"sensory_feedback_source": os.environ.get("NC_SENSORY_FEEDBACK_SOURCE", "off"),
"sensory_feedback_interval_seconds": float(os.environ.get("NC_SENSORY_FEEDBACK_INTERVAL_SECONDS", "7.0") or 7.0),
"sensory_pingpong_enabled": str(os.environ.get("NC_SENSORY_PINGPONG_ENABLED", "0") or "0").strip().lower() in {"1", "true", "yes", "on"},
"sensory_pingpong_history_depth": int(os.environ.get("NC_SENSORY_PINGPONG_HISTORY_DEPTH", "3") or 3),
"sensory_pingpong_prompt": os.environ.get("NC_SENSORY_PINGPONG_PROMPT", DEFAULT_SENSORY_PINGPONG_PROMPT),
"sensory_pingpong_source_prompts": {},
"sensory_provider_metadata_overrides": {},
"sensory_allow_hidden_proactive_speech": str(os.environ.get("NC_SENSORY_ALLOW_HIDDEN_PROACTIVE_SPEECH", "0") or "0").strip().lower() in {"1", "true", "yes", "on"},
"sensory_allow_hidden_visual_generation": str(os.environ.get("NC_SENSORY_ALLOW_HIDDEN_VISUAL_GENERATION", "0") or "0").strip().lower() in {"1", "true", "yes", "on"},
}
MUSE_EMOTION_AVATAR_MAP = {
"angry": "angry_avatar",
}
MUSE_AVATAR_POSE_FILENAME = "avatar_pose.json"
MUSE_RENDER_OVERLAP_MS = 150
MUSE_AVATAR_TRANSITIONS = {
("angry_avatar", "default_avatar"): {
"start_frame": 80,
"end_frame": 7,
},
}
# ============================================================================
# AVATAR BODY PROFILE (v16: With Speed & Intensity)
# ============================================================================
DEFAULT_POSE = {
"idle_arm_down": 71.0,
"idle_elbow_bend": 124.0,
"idle_arm_twist": 19.0,
"idle_fwd_left": -75.0,
"idle_fwd_right": 80.0,
"idle_speed": 1.0, # Frequency
"idle_intensity": 2.0, # Amplitude (Depth)
"spine_sway_mult": 1.3, # How much the spine leans
"spine_twist_mult": 0.7, # How much the spine rotates
"neck_stabilize": 1.5, # 3.0 = Stiff, 0.0 = Perfect Gyroscope
"shoulder_lift": 1.5,
"breath_speed": 1.2,
"idle_shoulder_back": 0.0,
"eye_activity": 1.0
}
AVATAR_PROFILE = {
"neutral": DEFAULT_POSE.copy(),
"happy": DEFAULT_POSE.copy(),
"sad": DEFAULT_POSE.copy(),
"angry": DEFAULT_POSE.copy(),
"surprised": DEFAULT_POSE.copy(),
"shy": DEFAULT_POSE.copy(),
}
CURRENT_BODY_STATE = DEFAULT_POSE.copy()
EDIT_EMOTION = "neutral"
FORCE_EDIT_MODE = True
HAND_DEBUG = avatar_hand_state.HAND_DEBUG
HAND_CALIBRATION = avatar_hand_state.HAND_CALIBRATION
def update_runtime_config(key, value):
"""Called by GUI to update settings in real-time"""
global RUNTIME_CONFIG
if key in RUNTIME_CONFIG:
if key == "hotkeys":
_sync_legacy_hotkey_runtime_keys(value)
return
if key == "push_to_talk_hotkey":
value = normalize_hotkey_text(value) or DEFAULT_PUSH_TO_TALK_HOTKEY
settings = get_hotkey_settings()
settings["push_to_talk"] = value
_sync_legacy_hotkey_runtime_keys(settings)
return
elif key == "manual_action_hotkeys":
value = _normalize_manual_action_hotkeys(value)
settings = get_hotkey_settings()
settings["manual_actions"] = value
_sync_legacy_hotkey_runtime_keys(settings)
return
elif key == "ui_action_hotkeys":
value = _normalize_ui_action_hotkeys(value)
settings = get_hotkey_settings()
settings["ui_actions"] = value
_sync_legacy_hotkey_runtime_keys(settings)
return
elif key == "chat_provider":
value = chat_providers.normalize_provider_id(value, fallback=chat_providers.DEFAULT_PROVIDER_ID)
elif key == "chat_provider_settings":
value = dict(value or {})
elif key == "chat_replay_role_voices":
value = _normalize_chat_replay_role_voices(value)
elif key == "musetalk_enabled_pack_emotions":
value = _normalize_musetalk_enabled_pack_emotions(value)
RUNTIME_CONFIG[key] = value
if key == "chat_provider_settings":
chat_providers.set_provider_settings(value)
if key in {"musetalk_avatar_pack_id", "musetalk_enabled_pack_emotions"}:
invalidate_available_emotion_names()
def _normalize_musetalk_enabled_pack_emotions(value):
return _invoke_musetalk_pack_capability(
"runtime.normalize_enabled_pack_emotions",
{"value": value},
default={},
)
def get_musetalk_enabled_pack_emotions(pack_id):
return _invoke_musetalk_pack_capability(
"runtime.enabled_pack_emotions",
{
"runtime_config": RUNTIME_CONFIG,
"pack_id": pack_id,
},
default=None,
)
# ============================================================================
# GLOBAL STATE
# ============================================================================
LMSTUDIO_BASE_URL = "http://127.0.0.1:1234/v1"
LMSTUDIO_API_KEY = "lm-studio"
chat_providers.set_provider_settings(RUNTIME_CONFIG.get("chat_provider_settings", {}))
TTS_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
stop_flag = threading.Event()
stop_playback = threading.Event()
audio_playing = threading.Event()
listening_active = threading.Event()
microphone_active = threading.Event()
push_to_talk_gui_held = threading.Event()
_barge_in_streak = 0
_barge_in_last_sample_at = 0.0
pause_after_chunk = threading.Event()
playback_paused = threading.Event()
last_resume_requested_at = 0.0
last_resumed_at = 0.0
avatar_gui = None
tts_model = None
tts_backend_name = None
_shutdown_avatar_engine_lock = threading.RLock()
recognizer = sr.Recognizer()
conversation_history = []
sent_tokenize = None
PENDING_GUI_ACTION = None
_musetalk_cleanup_lock = threading.Lock()
_llm_request_active = threading.Event()
sensory_pingpong_lock = threading.Lock()
sensory_hidden_history = []
sensory_pingpong_state = {
"last_cycle_at": 0.0,
"last_retained_at": 0.0,
"last_emotion": "",
"last_attention": "",
"last_summary": "",
"last_source": "off",
}
sensory_hidden_action_state = {
"pending_proactive": None,
"active_proactive": None,
"last_proactive_key": "",
"last_proactive_at": 0.0,
"last_proactive_candidate_key": "",
"last_proactive_candidate_at": 0.0,
"last_visual_key": "",
"last_visual_at": 0.0,
"last_screen_subject_comment_key": "",
"last_screen_supervisor_meaningful_key": "",
"last_screen_supervisor_meaningful_subject": "",
"last_screen_supervisor_meaningful_trigger": "",
}
_addon_event_publisher = None
_addon_manager_getter = None
_chat_runtime = runtime_chat.ChatProviderRuntime(lambda: RUNTIME_CONFIG)
def set_addon_event_publisher(callback):
global _addon_event_publisher
_addon_event_publisher = callback if callable(callback) else None
def set_addon_manager_getter(callback):
global _addon_manager_getter
_addon_manager_getter = callback if callable(callback) else None
def _publish_addon_runtime_event(event_name, payload=None):
publisher = _addon_event_publisher
if publisher is None:
return False
try:
publisher(str(event_name or ""), dict(payload or {}))
return True
except Exception as exc:
print(f"⚠️ [Addons] Runtime event publish failed for {event_name}: {exc}")
return False
def _get_addon_manager():
getter = _addon_manager_getter
if getter is None:
return None
try:
return getter()
except Exception as exc:
print(f"⚠️ [Addons] Failed to resolve addon manager: {exc}")
return None
def _collect_addon_chat_contexts(model_history_window):
manager = _get_addon_manager()
if manager is None:
return []
invoke_all = getattr(manager, "invoke_all_capabilities", None)
if not callable(invoke_all):
return []
try:
results = invoke_all(
"chat_context.collect",
{
"messages": list(model_history_window or []),
"active_preset_name": str(RUNTIME_CONFIG.get("active_preset_name", "") or ""),
},
)
except Exception as exc:
print(f"⚠️ [Addons] Chat context collection failed: {exc}")
return []
contexts = []
for result in list(results or []):
if isinstance(result, str):
text = result.strip()
debug = {}
elif isinstance(result, dict):
text = str(result.get("context") or "").strip()
debug = dict(result.get("debug") or {})
else:
continue
if not text:
continue
contexts.append({"context": text, "debug": debug})
return contexts
def list_available_tts_backends():
return tts_runtime.list_available_tts_backends(_get_addon_manager, logger=print)
def list_available_stt_backends():
return stt_runtime.list_available_stt_backends(_get_addon_manager, logger=print)
def _resolve_addon_tts_backend(backend_id: str):
return tts_runtime.resolve_addon_tts_backend(backend_id, _get_addon_manager)
def _resolve_addon_stt_backend(backend_id: str):
return stt_runtime.resolve_addon_stt_backend(backend_id, _get_addon_manager)
# ============================================================================
# HELPER: Fetch Models
# ============================================================================
def _chat_provider():
return _chat_runtime.current_provider()
def _chat_provider_label(provider=None):
return _chat_runtime.provider_label(provider)
def _chat_provider_api_key(provider=None):
return _chat_runtime.provider_api_key(provider)
def _chat_provider_base_url(provider=None):
return _chat_runtime.provider_base_url(provider)
def _chat_provider_generation_settings(provider=None):
return _chat_runtime.generation_settings(provider)
def _coerce_generation_value(field, value):
return _chat_runtime._coerce_generation_value(field, value)
def _omit_generation_value(field, value):