-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtts2_agent.py
More file actions
8687 lines (7651 loc) · 351 KB
/
Copy pathtts2_agent.py
File metadata and controls
8687 lines (7651 loc) · 351 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
# ============================================================================
# Warning Suppression (MUST be before any other imports)
# ============================================================================
# Set PYTHONWARNINGS env var first - this is checked by Python before warnings module loads
import os
import sys
os.environ["PYTHONWARNINGS"] = "ignore::FutureWarning,ignore::DeprecationWarning,ignore::ResourceWarning,ignore::UserWarning"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # Silence TensorFlow
os.environ["PYTHONTRACEMALLOC"] = "0" # No tracemalloc hints
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" # Fix for protobuf conflict in IndexTTS2
import warnings
import sys
import threading
# Additional filterwarnings for this process
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=ResourceWarning)
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", message=".*weight_norm.*")
warnings.filterwarnings("ignore", message=".*unclosed.*")
warnings.filterwarnings("ignore", message=".*np.bool8.*")
warnings.filterwarnings("ignore", message=".*WebSocketServerProtocol.*")
# Silence noisy loggers
import logging
# Force all output to white for clean console display
LAPIS = "\033[37m"
RESET = "\033[0m"
# Wrap stdout/stderr to always output lapis lazuli
class LapisStream:
def __init__(self, stream):
self._stream = stream
self._at_line_start = True
def write(self, text):
if text:
# Add lapis lazuli color code at the start of each line
if self._at_line_start and text.strip():
self._stream.write(LAPIS)
try:
self._stream.write(text)
except UnicodeEncodeError:
# Windows cp1252 can't handle some Unicode - replace with ASCII equivalents
safe_text = text.replace('✓', '[OK]').replace('✗', '[X]').replace('⏳', '[...]')
try:
self._stream.write(safe_text)
except UnicodeEncodeError:
self._stream.write(safe_text.encode('ascii', 'replace').decode('ascii'))
self._at_line_start = text.endswith('\n')
def flush(self):
self._stream.flush()
def __getattr__(self, name):
return getattr(self._stream, name)
# Apply lapis wrapper to stdout/stderr
sys.stdout = LapisStream(sys.__stdout__)
sys.stderr = LapisStream(sys.__stderr__)
class LapisFormatter(logging.Formatter):
def format(self, record):
return f"{LAPIS}{super().format(record)}"
# Apply lapis formatter to all existing and future handlers
def apply_lapis_formatter():
formatter = LapisFormatter("%(message)s")
root_logger = logging.getLogger()
# Apply to root logger
for handler in root_logger.handlers:
handler.setFormatter(formatter)
handler.stream = sys.stdout
if not root_logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
# Apply to specific loggers that Gradio/uvicorn use
for logger_name in ["uvicorn", "uvicorn.error", "uvicorn.access", "gradio", "fastapi"]:
logger = logging.getLogger(logger_name)
for handler in logger.handlers:
handler.setFormatter(formatter)
handler.stream = sys.stdout
apply_lapis_formatter()
# Silence noisy loggers (but keep them lapis when they do speak)
logging.getLogger("transformers").setLevel(logging.ERROR)
logging.getLogger("httpx").setLevel(logging.ERROR)
logging.getLogger("uvicorn").setLevel(logging.WARNING) # Allow startup messages
logging.getLogger("uvicorn.access").setLevel(logging.ERROR) # Silence access logs
logging.getLogger("httpcore").setLevel(logging.ERROR)
logging.getLogger("asyncio").setLevel(logging.ERROR)
# ============================================================================
# Standard Imports
# ============================================================================
import re
import asyncio
import base64
import copy
import platform
from pathlib import Path
from datetime import datetime
import time
import socket
import json
import scipy.io.wavfile as wav
from threading import Lock, Thread
from typing import Optional, List, Tuple, Dict, Any
import tempfile
from tools import init_tools, REGISTRY, set_graph_tool_memory_manager
from mcp_client import MCPManager, MCP_AVAILABLE
from config.manager import config
# Service Layer (Phase 1: Architecture Cleanup)
from services import ServiceContainer, ChatService, ChatResult, ToolCallInfo
from ui.formatters import (
format_memory_for_ui as ui_format_memory,
format_tool_call_html as ui_format_tool,
format_message_with_extras as ui_format_message,
format_memory_recall_html as ui_format_recall,
filter_for_speech as ui_filter_speech,
format_chat_result_for_ui as ui_format_chat_result
)
import gradio as gr
import requests
import numpy as np
import torch
# ============================================================================
# Platform Detection
# ============================================================================
PLATFORM = platform.system().lower() # 'windows', 'linux', 'darwin'
IS_WINDOWS = PLATFORM == 'windows'
IS_LINUX = PLATFORM == 'linux'
IS_MAC = PLATFORM == 'darwin'
IS_WSL = IS_LINUX and 'microsoft' in platform.uname().release.lower()
# ============================================================================
# IndexTTS2 Import with Graceful Fallback
# ============================================================================
TTS_AVAILABLE = False
IndexTTS2 = None
try:
# Import paths module to configure sys.path for vendored packages
import paths
from indextts.infer_v2 import IndexTTS2 as _IndexTTS2
IndexTTS2 = _IndexTTS2
TTS_AVAILABLE = True
except ImportError as e:
print(f"[TTS] IndexTTS2 import failed: {e}")
TTS_AVAILABLE = False
except Exception as e:
print(f"[TTS] IndexTTS2 import error: {e}")
TTS_AVAILABLE = False
# Kokoro TTS
try:
from audio.tts_kokoro import KokoroTTS
KOKORO_AVAILABLE = True
except ImportError:
KOKORO_AVAILABLE = False
# Import memory system
from memory.characters import CharacterManager, Character, create_character_manager
from memory.memory_manager import MultiCharacterMemoryManager, create_memory_manager
from group_manager import GROUP_MANAGER, GroupChatManager
# Import shared utilities
from utils import create_dark_theme
# PIL for image handling
try:
from PIL import Image, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
# PDF support
try:
import pypdf
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
# Screenshot support - DISABLED in WSL (X11 issues)
# pyautogui requires X11 display which isn't available in WSL
SCREEN_AVAILABLE = False
print("[Info] Screenshot support disabled (WSL environment)")
# Speech Emotion Recognition
try:
from audio.emotion_detector import EmotionDetector, EmotionResult
from audio.emotion_bridge import should_run_external_emotion
from concurrent.futures import ThreadPoolExecutor, Future
EMOTION_AVAILABLE = True
_emotion_detector = None
_current_emotion = None # Stores last detected emotion for LLM context
_emotion_future: Optional[Future] = None # For async emotion detection
_emotion_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="emotion")
except ImportError:
EMOTION_AVAILABLE = False
_emotion_detector = None
_current_emotion = None
_emotion_future = None
_emotion_executor = None
# Provide fallback for emotion bridge function
def should_run_external_emotion(stt_backend: str) -> bool:
return stt_backend != "sensevoice"
print("[Info] Emotion detection not available. Install transformers and torch for SER.")
# GraphRAG availability
try:
from memory.graph_rag import GraphRAGProcessor
GRAPHRAG_AVAILABLE = True
except ImportError:
GRAPHRAG_AVAILABLE = False
def _detect_emotion_sync(audio_data) -> Optional['EmotionResult']:
"""
Internal synchronous emotion detection (runs in thread pool).
"""
global _emotion_detector, _current_emotion
try:
sample_rate, audio_np = audio_data
# Initialize detector lazily
if _emotion_detector is None:
_emotion_detector = EmotionDetector()
# Analyze the audio
result = _emotion_detector.analyze(
audio_array=audio_np.astype(np.float32) / 32768.0 if audio_np.dtype == np.int16 else audio_np,
sample_rate=sample_rate
)
if result:
_current_emotion = result
print(f"[SER] Detected emotion: {result.label} (V={result.valence:.2f}, A={result.arousal:.2f})")
return result
except Exception as e:
print(f"[SER] Emotion detection failed: {e}")
return None
def detect_emotion_from_audio_async(audio_data) -> None:
"""
Start async emotion detection (non-blocking).
Runs in parallel with memory retrieval to hide CPU latency.
Call get_current_emotion_context() later to get the result.
"""
global _emotion_future
if not EMOTION_AVAILABLE:
return
# Check if emotion detection is enabled in settings
if not SETTINGS.get("emotion_detection_enabled", True):
return
if audio_data is None:
return
# Submit to thread pool (non-blocking)
_emotion_future = _emotion_executor.submit(_detect_emotion_sync, audio_data)
print("[SER] Started async emotion detection")
def detect_emotion_from_audio(audio_data) -> Optional['EmotionResult']:
"""
Detect emotion from audio data (blocking, legacy compatibility).
For new code, prefer detect_emotion_from_audio_async() + get_current_emotion_context().
"""
global _current_emotion
if not EMOTION_AVAILABLE:
return None
# Check if emotion detection is enabled in settings
if not SETTINGS.get("emotion_detection_enabled", True):
return None
if audio_data is None:
return None
return _detect_emotion_sync(audio_data)
def get_current_emotion_context() -> str:
"""
Get the current emotion context for LLM prompt injection.
If async detection is in progress, waits for it to complete (with timeout).
"""
global _current_emotion, _emotion_future
# If async detection is running, wait for result
if _emotion_future is not None:
try:
# Wait up to 2 seconds for emotion detection to complete
_emotion_future.result(timeout=2.0)
except Exception as e:
print(f"[SER] Async emotion detection timed out or failed: {e}")
finally:
_emotion_future = None
if _current_emotion:
return _current_emotion.to_prompt_context()
return ""
def clear_current_emotion():
"""Clear the current emotion after use"""
global _current_emotion, _emotion_future
_current_emotion = None
_emotion_future = None
# ============================================================================
# Helpers
# ============================================================================
def take_screenshot():
"""Capture screen and return PIL Image"""
if not SCREEN_AVAILABLE:
return None
try:
# Minimal delay to allow UI to minimize if needed (optional)
return pyautogui.screenshot()
except Exception as e:
print(f"[Error] Screenshot: {e}")
return None
def extract_text_from_pdf(filepath: str) -> str:
"""Extract text from PDF file"""
if not PDF_AVAILABLE:
return ""
try:
reader = pypdf.PdfReader(filepath)
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
return text.strip()
except Exception as e:
print(f"[Error] PDF Read: {e}")
return ""
# ============================================================================
# Hands-free Mode (VAD) Manager
# ============================================================================
vad_manager_instance = None
class VADManager:
"""
Manages hands-free voice recording mode across all platforms.
Platform behavior:
- Native Windows: Uses vad_recorder.py directly (in-process)
- Native Linux: Uses vad_recorder.py directly (in-process)
- WSL: CANNOT record audio - user must run vad_windows.py on Windows
All modes write to recordings/ directory using latest.txt as trigger.
The UI polling picks up recordings identically regardless of source.
"""
def __init__(self, output_dir: Path):
self.output_dir = output_dir
self.recorder = None
self.is_active = False
# Cache platform detection
self._is_wsl = IS_WSL
self._platform = PLATFORM
def start(self, threshold: float = 0.8) -> str:
"""Start VAD. Returns status message."""
if self.is_active:
return "Already active"
# WSL: Audio recording is IMPOSSIBLE - no microphone access
# User must run vad_windows.py on Windows side
if self._is_wsl:
self.is_active = True
print("[VAD] WSL detected - audio must be captured on Windows")
print("[VAD] Run: python vad_windows.py (from Windows CMD)")
return "wsl_remote"
# Native Windows or Linux: Use vad_recorder.py directly
try:
from audio.vad_recorder import ContinuousVADRecorder, VADConfig
# Convert threshold (0.0-1.0 from UI) to VAD config
# Higher UI threshold = more silence needed = higher silence_threshold
config = VADConfig(
backend="silero", # Neural network VAD - much better at ignoring coughs/bumps
silence_threshold=threshold,
energy_threshold=0.022, # Raised from 0.015 to reduce false triggers
min_speech_duration=0.3,
max_recording_duration=30.0
)
self.recorder = ContinuousVADRecorder(
config=config,
output_dir=self.output_dir
)
if self.recorder.start():
self.is_active = True
print(f"[VAD] Hands-free mode started ({self._platform})")
return "started"
else:
print("[VAD] Failed to start recorder")
return "error: Failed to start audio capture"
except ImportError as e:
print(f"[VAD] Missing dependency: {e}")
print("[VAD] Install with: pip install pyaudio numpy")
return f"error: {e}"
except Exception as e:
print(f"[VAD] Failed to start: {e}")
self.is_active = False
return f"error: {e}"
def stop(self) -> str:
"""Stop VAD. Returns status message."""
if not self.is_active:
return "Not active"
# WSL: Just update state - Windows script runs independently
if self._is_wsl:
self.is_active = False
print("[VAD] WSL mode disabled - stop vad_windows.py on Windows")
return "stopped_wsl"
# Native: Stop the recorder
if self.recorder:
try:
self.recorder.stop()
print("[VAD] Hands-free mode stopped")
except Exception as e:
print(f"[VAD] Error stopping: {e}")
self.recorder = None
self.is_active = False
return "stopped"
def pause(self, duration: float = None):
"""
Pause VAD for a duration (or indefinitely) to prevent self-hearing during TTS.
"""
if self.recorder:
self.recorder.pause(duration)
elif self._is_wsl:
# For WSL, we communicate via file.
# We must maintain 'enabled' state based on self.is_active, but set 'tts_playing' to True.
update_vad_control(enabled=self.is_active, tts_playing=True)
if duration:
# Spawn a thread to reset it after audio finishes
def _reset():
try:
time.sleep(duration)
# CRITICAL FIX: Only set enabled=True if VAD is actually supposed to be active!
# Previous bug: this blinded set enabled=True, overriding the checkbox.
update_vad_control(enabled=self.is_active, tts_playing=False)
except Exception as e:
# Ensure tts_playing gets reset even if there's an error
print(f"[VAD] Reset thread error: {e}")
try:
update_vad_control(enabled=self.is_active, tts_playing=False)
except:
pass
threading.Thread(target=_reset, daemon=True).start()
# ============================================================================
# Configuration - Cross-Platform Paths
# ============================================================================
SCRIPT_DIR = Path(__file__).parent
CONFIG_FILE = SCRIPT_DIR / "config.env"
VOICE_REF_DIR = SCRIPT_DIR / "voice_reference"
SESSIONS_DIR = SCRIPT_DIR / "sessions"
CONVERSATIONS_DIR = SESSIONS_DIR / "conversations" # Consolidated under sessions/
SETTINGS_FILE = SCRIPT_DIR / "settings.json"
RECORDINGS_DIR = SCRIPT_DIR / "recordings"
PTT_STATUS_FILE = RECORDINGS_DIR / "ptt_status.txt"
VAD_CONTROL_FILE = RECORDINGS_DIR / "vad_control.txt" # Controls VAD: enabled|tts_playing
# Cross-platform temp directory for TTS output
if IS_WINDOWS:
OUTPUT_DIR = Path(tempfile.gettempdir()) / "indextts2_audio"
else:
OUTPUT_DIR = Path("/tmp/indextts2_audio")
# Ensure directories exist
OUTPUT_DIR.mkdir(exist_ok=True)
SESSIONS_DIR.mkdir(exist_ok=True)
CONVERSATIONS_DIR.mkdir(exist_ok=True)
RECORDINGS_DIR.mkdir(exist_ok=True)
# Clean up leftover PTT trigger file from previous session
PTT_TRIGGER_FILE = RECORDINGS_DIR / "latest.txt"
if PTT_TRIGGER_FILE.exists():
try:
PTT_TRIGGER_FILE.unlink()
print("[Startup] Cleaned up leftover PTT trigger file")
except Exception as e:
print(f"[Startup] Warning: Could not delete trigger file: {e}")
# Threading
processing_lock = Lock()
cleanup_counter = [0]
# ============================================================================
# LM Studio Configuration - Cross-Platform
# ============================================================================
def get_lm_studio_host() -> str:
"""Get LM Studio host IP based on platform"""
# 1. Check for manual override in config.env (supports both HOST and full URL)
try:
if CONFIG_FILE.exists():
with open(CONFIG_FILE, "r") as f:
for line in f:
line = line.strip()
# Full URL override (highest priority)
if line.startswith("LM_STUDIO_URL="):
val = line.split("=", 1)[1].strip()
if val and not val.startswith("#"):
print(f"[LM Studio] Using manual URL from config: {val}")
# Return special marker; caller will use full URL
return f"URL:{val}"
# Host-only override
if line.startswith("LM_STUDIO_HOST="):
val = line.split("=", 1)[1].strip()
if val and not val.startswith("#"):
print(f"[LM Studio] Using manual host from config: {val}")
return val
except Exception as e:
print(f"[LM Studio] Error reading config: {e}")
# 2. Auto-detect for WSL
if IS_WSL:
# Strategy A: Default Gateway (Most reliable for connectivity)
try:
import subprocess
result = subprocess.run(['ip', 'route', 'show', 'default'], capture_output=True, text=True)
if result.returncode == 0:
# Output format: "default via 172.29.64.1 dev eth0 ..."
parts = result.stdout.split()
if 'via' in parts:
gateway_ip = parts[parts.index('via') + 1]
print(f"[LM Studio] WSL detected, Gateway IP: {gateway_ip}")
return gateway_ip
except Exception as e:
print(f"[LM Studio] Error getting gateway IP: {e}")
# Strategy B: resolv.conf (Fallback)
try:
with open('/etc/resolv.conf', 'r') as f:
for line in f:
if line.startswith('nameserver'):
host_ip = line.split()[1].strip()
print(f"[LM Studio] WSL detected, Nameserver IP: {host_ip}")
return host_ip
except Exception as e:
print(f"[LM Studio] Could not get Nameserver IP: {e}")
# 3. Default: localhost
return "localhost"
LM_STUDIO_HOST = get_lm_studio_host()
# Support full URL override via config.env (LM_STUDIO_URL=http://...)
if LM_STUDIO_HOST.startswith("URL:"):
LM_STUDIO_BASE_URL = LM_STUDIO_HOST[4:] # Strip "URL:" prefix
LM_STUDIO_HOST = "custom" # Mark as custom
else:
LM_STUDIO_BASE_URL = f"http://{LM_STUDIO_HOST}:1235/v1"
LM_STUDIO_TIMEOUT = 60
# LM Studio state
LM_STUDIO_AVAILABLE = False
LM_STUDIO_MODEL = None
def check_lm_studio_available(force_refresh: bool = False) -> Tuple[bool, Optional[str]]:
"""
Check if LM Studio is running and what model is loaded.
Implements smart fallback for WSL networking.
Returns (is_available, model_name)
"""
global LM_STUDIO_AVAILABLE, LM_STUDIO_MODEL, LM_STUDIO_BASE_URL
# Candidate URLs to try
urls_to_try = [LM_STUDIO_BASE_URL]
# If in WSL, add the auto-detected nameserver as a fallback candidate
if IS_WSL and "localhost" not in LM_STUDIO_BASE_URL:
try:
with open('/etc/resolv.conf', 'r') as f:
for line in f:
if line.startswith('nameserver'):
wsl_host = line.split()[1].strip()
fallback_url = f"http://{wsl_host}:1235/v1"
if fallback_url != LM_STUDIO_BASE_URL:
urls_to_try.append(fallback_url)
except (IOError, IndexError, OSError):
pass # resolv.conf unavailable or malformed
for url in urls_to_try:
try:
response = requests.get(
f"{url}/models",
timeout=LM_STUDIO_TIMEOUT,
headers={"Accept": "application/json"}
)
response.raise_for_status()
data = response.json()
# If we get here, connection worked! Update global URL if it changed
if url != LM_STUDIO_BASE_URL:
print(f"[LM Studio] ⚠ Primary IP failed, but fallback worked: {url}")
LM_STUDIO_BASE_URL = url
models = data.get("data", [])
if models:
model_id = models[0].get("id", "unknown-model")
print(f"[LM Studio] ✓ Connected! Model: {model_id}")
LM_STUDIO_AVAILABLE = True
LM_STUDIO_MODEL = model_id
return True, model_id
else:
print("[LM Studio] ⚠ Server running but no model loaded")
LM_STUDIO_AVAILABLE = True
LM_STUDIO_MODEL = None
return True, None
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
continue # Try next candidate
except Exception as e:
print(f"[LM Studio] ✗ Error connecting to {url}: {e}")
continue
# If all candidates fail
print(f"[LM Studio] Could not connect. Tried: {', '.join(urls_to_try)}")
print(f"[LM Studio] Troubleshooting:")
print(f" 1. Ensure LM Studio is running on Windows")
print(f" 2. In LM Studio: Settings > check 'Serve on Local Network' (binds to 0.0.0.0)")
print(f" 3. Check Windows Firewall allows port 1235")
print(f" 4. Or add LM_STUDIO_URL=http://YOUR_IP:1235/v1 to config.env")
LM_STUDIO_AVAILABLE = False
LM_STUDIO_MODEL = None
return False, None
def get_lm_studio_status_display() -> str:
"""Get a user-friendly status display for LM Studio"""
if LM_STUDIO_AVAILABLE and LM_STUDIO_MODEL:
model_display = LM_STUDIO_MODEL
if len(model_display) > 40:
model_display = model_display[:37] + "..."
return f"✓ {model_display}"
elif LM_STUDIO_AVAILABLE:
return "⚠️ No model loaded"
else:
return "✗ Not connected"
# ============================================================================
# Text Cleaning for TTS (Optimized for IndexTTS2)
# ============================================================================
# Track if we've warned about long text this session
_long_text_warning_shown = False
def clean_text_for_tts(text: str) -> Tuple[str, bool]:
"""
Clean and optimize text for IndexTTS2 voice synthesis.
Returns: (cleaned_text, was_long)
- was_long: True if text was over recommended length (for UI warning)
IndexTTS2 Best Practices:
- Keep text natural and conversational
- Under 1000 chars for best quality
- Remove all formatting/markup
- Remove action descriptions (*actions*) completely - they should NOT be spoken
- Ensure proper punctuation for natural pacing
"""
global _long_text_warning_shown
if not text:
return "", False
original_length = len(text)
# 1. CRITICAL: Remove action descriptions in asterisks COMPLETELY
# These are roleplay actions like *sighs*, *thinks*, *looks around*
# They should NOT be spoken - remove them entirely, not just the asterisks
text = re.sub(r'\*[^*]+\*', '', text) # Remove *action descriptions* completely
# 2. Remove markdown formatting (keep the text content)
text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text) # **Bold**
text = re.sub(r'__([^_]+)__', r'\1', text) # __Bold alt__
text = re.sub(r'(?<!\w)_([^_]+)_(?!\w)', r'\1', text) # _Italic alt_
text = re.sub(r'```[^`]*```', '', text, flags=re.DOTALL) # Code blocks
text = re.sub(r'`([^`]+)`', r'\1', text) # `Inline code`
text = re.sub(r'^#{1,6}\s*', '', text, flags=re.MULTILINE) # Headers
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text) # [Links](url)
text = re.sub(r'!\[([^\]]*)\]\([^)]+\)', '', text) # Images
text = re.sub(r'^\s*[-*+]\s+', '', text, flags=re.MULTILINE) # Bullet lists
text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE) # Numbered lists
text = re.sub(r'^\s*>\s*', '', text, flags=re.MULTILINE) # Blockquotes
text = re.sub(r'---+|===+|\*\*\*+', '', text) # Horizontal rules
# 3. Remove remaining problematic characters
problematic_chars = ['*', '`', '=', '#', '|', '~', '^', '<', '>', '{', '}', '[', ']', '\\']
for char in problematic_chars:
text = text.replace(char, '')
# 4. Convert symbols to spoken words for natural speech
text = text.replace('&', ' and ')
text = text.replace('%', ' percent')
text = text.replace('+', ' plus ')
text = text.replace('@', ' at ')
text = text.replace('$', ' dollars ')
text = text.replace('€', ' euros ')
text = text.replace('£', ' pounds ')
# 5. Handle ellipsis - normalize to three dots with space after
text = re.sub(r'\.{2,}', '... ', text)
# 6. Handle quotes - remove fancy quotes
text = re.sub(r'["""]', '', text)
text = re.sub(r"[''']", "'", text)
# 7. Fix common TTS stumbling blocks
# Em-dashes and en-dashes to regular hyphens (IndexTTS2 handles hyphens well)
text = text.replace('—', ' - ') # Em-dash
text = text.replace('–', ' - ') # En-dash
text = text.replace('−', '-') # Minus sign
text = text.replace('‐', '-') # Unicode hyphen
text = text.replace('‑', '-') # Non-breaking hyphen
text = text.replace('⁃', '-') # Hyphen bullet
# Remove parenthetical asides or convert to natural phrasing
text = re.sub(r'\s*\([^)]*\)\s*', ' ', text)
# 8. Clean up whitespace
text = re.sub(r'\n+', ' ', text)
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'\s*,\s*,\s*', ', ', text) # Fix double commas
text = text.strip()
# 9. Ensure proper sentence ending for natural completion
if text and text[-1] not in '.!?':
text += '.'
# 10. Final cleanup - remove any leading/trailing punctuation oddities
text = re.sub(r'^[\s,;:]+', '', text)
text = re.sub(r'[\s,;:]+$', '.', text)
# 11. Check if text is long (warn but don't truncate)
# IndexTTS2 handles up to ~1000 chars well
was_long = len(text) > 800
if was_long and not _long_text_warning_shown:
print(f"[TTS] Long response ({len(text)} chars) - synthesis may take longer")
_long_text_warning_shown = True
return text, was_long
# ============================================================================
# Settings Persistence
# ============================================================================
DEFAULT_SETTINGS = {
"model": "x-ai/grok-4.1-fast",
"temperature": 0.7,
"max_tokens": 2000,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"last_character": "hermione",
"last_voice": "reference.wav",
"auto_play": True,
"tts_enabled": True,
"tts_backend": "indextts",
"current_conversation_id": None,
"llm_provider": "openrouter",
"emotion_detection_enabled": True, # Can disable to free resources when using LM Studio
"stt_backend": "faster_whisper", # Options: faster_whisper, sensevoice, funasr
"stt_device": "cuda:0", # Device for SenseVoice/FunASR
"use_sensevoice_emotion": True, # Use built-in emotion when available
"use_sensevoice_vad": True, # Use built-in VAD when available
"tools_enabled": True, # Pure Voice Chat mode when False (disables all tool calling)
}
def load_settings() -> dict:
"""Load persistent settings"""
if SETTINGS_FILE.exists():
try:
with open(SETTINGS_FILE, 'r') as f:
saved = json.load(f)
return {**DEFAULT_SETTINGS, **saved}
except (json.JSONDecodeError, IOError, KeyError) as e:
print(f"[Settings] Failed to load settings, using defaults: {e}")
return DEFAULT_SETTINGS.copy()
def save_settings(settings: dict):
"""Save settings to disk"""
try:
with open(SETTINGS_FILE, 'w') as f:
json.dump(settings, f, indent=2)
except Exception as e:
print(f"[Settings] Error saving: {e}")
SETTINGS = load_settings()
# ============================================================================
# Conversation History Management
# ============================================================================
def get_conversations_dir(character_id: str) -> Path:
"""Get the conversations directory for a character"""
char_dir = CONVERSATIONS_DIR / character_id
char_dir.mkdir(exist_ok=True)
return char_dir
def generate_conversation_id() -> str:
"""Generate a unique conversation ID"""
return datetime.now().strftime("%Y%m%d_%H%M%S")
def list_conversations(character_id: str) -> List[Dict[str, Any]]:
"""List all conversations for a character, sorted by date (newest first)"""
char_dir = get_conversations_dir(character_id)
conversations = []
for f in char_dir.glob("*.json"):
try:
with open(f, 'r', encoding='utf-8') as file:
data = json.load(file)
conversations.append({
'id': f.stem,
'title': data.get('title', 'Untitled'),
'preview': data.get('preview', ''),
'message_count': len(data.get('history', [])),
'updated_at': data.get('updated_at', f.stat().st_mtime),
'created_at': data.get('created_at', f.stat().st_ctime)
})
except Exception as e:
print(f"[Conversations] Error reading {f}: {e}")
conversations.sort(key=lambda x: x['updated_at'], reverse=True)
return conversations
def save_conversation(character_id: str, conversation_id: str, history: list, title: str = None):
"""Save a conversation to disk"""
char_dir = get_conversations_dir(character_id)
filepath = char_dir / f"{conversation_id}.json"
if not title and history:
# Handle messages format: [{"role": "user", "content": "..."}, ...]
first_item = history[0]
if isinstance(first_item, dict):
first_msg = first_item.get('content', '')
else:
# Legacy tuple format
first_msg = first_item[0] if first_item[0] else first_item[1]
title = first_msg[:50] + "..." if len(first_msg) > 50 else first_msg
preview = ""
if history:
# Find last user message for preview
last_item = history[-1]
if isinstance(last_item, dict):
# Look for last user message
for msg in reversed(history):
if isinstance(msg, dict) and msg.get('role') == 'user':
preview = msg.get('content', '')[:100]
break
else:
# Legacy tuple format
last_user = last_item[0] or ""
preview = last_user[:100]
created_at = datetime.now().isoformat()
if filepath.exists():
try:
with open(filepath, 'r', encoding='utf-8') as f:
existing = json.load(f)
created_at = existing.get('created_at', created_at)
except (json.JSONDecodeError, IOError, KeyError):
pass # Existing conversation file corrupted or unreadable
data = {
'character_id': character_id,
'conversation_id': conversation_id,
'title': title or "Untitled",
'preview': preview,
'history': history,
'created_at': created_at,
'updated_at': datetime.now().isoformat()
}
try:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"[Conversations] Error saving: {e}")
def load_session(character_id: str) -> list:
"""Load chat session from file, converting legacy tuples to messages format"""
# 1. Look for character-specific session
filename = f"{character_id}_session.json"
filepath = SESSIONS_DIR / filename
# 2. If not found, look for default session
if not filepath.exists():
filepath = SESSIONS_DIR / "session.json"
if filepath.exists():
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
if not data:
return []
# Handle dict wrapper format (new save_session format)
if isinstance(data, dict) and 'history' in data:
history = data['history']
if not history:
return []
data = history
# Ensure data is a list
if not isinstance(data, list):
print(f"[Session] Invalid data type: {type(data)}, returning empty")
return []
if len(data) == 0:
return []
# Check format and convert if necessary
first_item = data[0]
# Legacy: [[user, bot], ...]
if isinstance(first_item, (list, tuple)):
print(f"[Session] Converting legacy session for {character_id}")
new_history = []
for turn in data:
if len(turn) >= 1 and turn[0]:
new_history.append({"role": "user", "content": str(turn[0])})
if len(turn) >= 2 and turn[1]:
new_history.append({"role": "assistant", "content": str(turn[1])})
print(f"[Session] Converted {len(new_history)} messages")
return new_history
# Messages format - validate structure
if isinstance(first_item, dict):
validated = []
for msg in data:
if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
# Ensure content is a string
validated.append({
"role": str(msg['role']),
"content": str(msg['content']) if msg['content'] else ""
})
else:
print(f"[Session] Skipping invalid message: {msg}")
print(f"[Session] Loaded {len(validated)} messages for {character_id}")
return validated
# Unknown format - return empty
print(f"[Session] Unknown format, first item type: {type(first_item)}")
return []
except Exception as e:
print(f"[Session] Error converting/loading: {e}")
import traceback
traceback.print_exc()
return []
return []