-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlauncher.py
More file actions
1509 lines (1255 loc) · 56.6 KB
/
launcher.py
File metadata and controls
1509 lines (1255 loc) · 56.6 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
"""
LocalSoundsAPI Launcher
Tkinter GUI for managing multiple server instances, AI models, and portable tools.
"""
import os
import sys
import subprocess
import threading
import webbrowser
import time
import shutil
import zipfile
import urllib.request
import urllib.error
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass, field
from typing import Optional, Callable, List, Tuple, Dict
from collections import deque
import tkinter as tk
from tkinter import ttk, messagebox
# ---------------------------------------------------------------------------
# Paths & Constants
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).parent.resolve()
PYTHON_EXE = BASE_DIR / "python" / "python.exe"
MAIN_PY = BASE_DIR / "main.py"
APP_TITLE = "LocalSoundsAPI Launcher"
APP_VERSION = "1.0"
WINDOW_SIZE = "1100x800"
MIN_WIDTH, MIN_HEIGHT = 950, 700
DEFAULT_HOST = "0.0.0.0"
DEFAULT_PORT = 5006
MAX_INSTANCES = 20
PORT_RANGE_START = 5006
PORT_RANGE_END = 5099
MAX_LOG_LINES = 5000
BIN_ZIP_URL = "https://github.com/rookiemann/LocalSoundsAPI/releases/download/v1.0/bin.zip"
PYTHON_7Z_URL = "https://github.com/rookiemann/LocalSoundsAPI/releases/download/v1.0/portable-python-env-v1.7z"
# Tool existence checks
TOOL_CHECKS = {
"FFmpeg": BASE_DIR / "bin" / "ffmpeg" / "bin" / "ffmpeg.exe",
"RubberBand": BASE_DIR / "bin" / "rubberband",
"eSpeak-ng": BASE_DIR / "bin" / "espeak-ng" / "libespeak-ng.dll",
}
# Model definitions: (display_name, check_path, hf_repo, hf_revision, size_label, is_file_check)
MODEL_DEFS = [
("XTTS-v2", BASE_DIR / "models" / "XTTS-v2", "coqui/XTTS-v2", None, "~6 GB", False),
("Fish Speech", BASE_DIR / "models" / "fish-speech", "fishaudio/openaudio-s1-mini", None, "~8 GB", False),
("Kokoro-82M", BASE_DIR / "models" / "kokoro-82m", "hexgrad/Kokoro-82M", None, "~500 MB", False),
("Whisper medium",BASE_DIR / "models" / "medium.en.pt", None, None, "~1.5 GB", True),
("Stable Audio", BASE_DIR / "models" / "stable-audio-open-1.0", "stabilityai/stable-audio-open-1.0", None, "~10 GB", False),
("ACE-Step", BASE_DIR / "models" / "ace_step", "ACE-Step/ACE-Step-v1-3.5B", None, "~7 GB", False),
("CLAP", BASE_DIR / "models" / "clap-htsat-unfused" / "model.safetensors", "laion/clap-htsat-unfused", "refs/pr/3", "~600 MB", True),
]
# ---------------------------------------------------------------------------
# ToolTip
# ---------------------------------------------------------------------------
class ToolTip:
"""Hover tooltip for tkinter widgets."""
def __init__(self, widget, text: str, delay: int = 400):
self.widget = widget
self.text = text
self.delay = delay
self._tip_window = None
self._after_id = None
widget.bind("<Enter>", self._on_enter)
widget.bind("<Leave>", self._on_leave)
def _on_enter(self, event=None):
self._after_id = self.widget.after(self.delay, self._show)
def _on_leave(self, event=None):
if self._after_id:
self.widget.after_cancel(self._after_id)
self._after_id = None
self._hide()
def _show(self):
if self._tip_window:
return
x = self.widget.winfo_rootx() + 20
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 5
tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
label = tk.Label(tw, text=self.text, justify=tk.LEFT,
background="#ffffe0", relief=tk.SOLID, borderwidth=1,
font=("Segoe UI", 9), padx=6, pady=4)
label.pack()
self._tip_window = tw
def _hide(self):
if self._tip_window:
self._tip_window.destroy()
self._tip_window = None
# ---------------------------------------------------------------------------
# GPU Detection
# ---------------------------------------------------------------------------
def detect_gpus() -> List[Tuple[str, str]]:
"""Detect NVIDIA GPUs via nvidia-smi. Returns [(label, value), ...]."""
items: List[Tuple[str, str]] = [("CPU (no GPU)", "cpu")]
try:
result = subprocess.run(
["nvidia-smi",
"--query-gpu=index,name,memory.total,memory.free",
"--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=10,
)
if result.returncode == 0:
for line in result.stdout.strip().split("\n"):
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 4:
idx, name, mem_total = parts[0], parts[1], int(parts[2])
mem_free = int(parts[3])
label = f"GPU {idx}: {name} ({mem_total} MB, {mem_free} MB free)"
items.append((label, idx))
except (FileNotFoundError, subprocess.TimeoutExpired, Exception):
pass
return items
# ---------------------------------------------------------------------------
# Instance Dataclasses
# ---------------------------------------------------------------------------
@dataclass
class InstanceConfig:
gpu_device: str
gpu_label: str
port: int
host: str = DEFAULT_HOST
@dataclass
class InstanceState:
instance_id: str
config: InstanceConfig
process: Optional[subprocess.Popen] = None
status: str = "Stopped"
log_thread: Optional[threading.Thread] = None
# ---------------------------------------------------------------------------
# Instance Manager
# ---------------------------------------------------------------------------
class InstanceManager:
"""Thread-safe management of multiple LocalSoundsAPI server instances."""
def __init__(self, log_callback: Optional[Callable] = None):
self._instances: Dict[str, InstanceState] = {}
self._lock = threading.Lock()
self._log_callback = log_callback
# --- CRUD ---
def add_instance(self, config: InstanceConfig) -> str:
with self._lock:
if len(self._instances) >= MAX_INSTANCES:
raise ValueError(f"Maximum of {MAX_INSTANCES} instances reached")
for s in self._instances.values():
if s.config.port == config.port:
raise ValueError(f"Port {config.port} already in use by {s.instance_id}")
instance_id = self._make_id(config)
base_id = instance_id
counter = 2
while instance_id in self._instances:
instance_id = f"{base_id}_{counter}"
counter += 1
state = InstanceState(instance_id=instance_id, config=config)
self._instances[instance_id] = state
return instance_id
def remove_instance(self, instance_id: str) -> bool:
with self._lock:
state = self._instances.get(instance_id)
if state is None:
return False
if state.process and state.process.poll() is None:
self._stop_process(state)
with self._lock:
self._instances.pop(instance_id, None)
return True
# --- Start / Stop ---
def start_instance(self, instance_id: str) -> bool:
with self._lock:
state = self._instances.get(instance_id)
if state is None:
return False
if state.process and state.process.poll() is None:
return True # already running
cfg = state.config
prefix = self._make_prefix(cfg)
cmd = [
str(PYTHON_EXE), "-u", "-c",
"import sys,pathlib; sys.path.insert(0,str(pathlib.Path('.').resolve())); exec(open('main.py').read())",
"--port", str(cfg.port),
]
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
if cfg.gpu_device == "cpu":
env["CUDA_VISIBLE_DEVICES"] = ""
else:
env["CUDA_VISIBLE_DEVICES"] = cfg.gpu_device
env["PATH"] = os.pathsep.join([
str(BASE_DIR / "python"),
str(BASE_DIR / "python" / "Scripts"),
str(BASE_DIR / "python" / "DLLs"),
str(BASE_DIR / "bin" / "ffmpeg" / "bin"),
str(BASE_DIR / "bin" / "rubberband"),
]) + os.pathsep + env.get("PATH", "")
try:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
creationflags = subprocess.CREATE_NO_WINDOW
state.process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=str(BASE_DIR),
env=env,
startupinfo=startupinfo,
creationflags=creationflags,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
state.status = "Starting"
state.log_thread = threading.Thread(
target=self._read_logs, args=(state, prefix), daemon=True
)
state.log_thread.start()
# Brief wait to check immediate crash
time.sleep(1.0)
if state.process.poll() is not None:
state.status = "Error"
return False
state.status = "Starting"
return True
except Exception as e:
if self._log_callback:
self._log_callback(f"{prefix} Error: {e}")
state.status = "Error"
return False
def stop_instance(self, instance_id: str) -> bool:
with self._lock:
state = self._instances.get(instance_id)
if state is None:
return False
return self._stop_process(state)
def stop_all(self) -> bool:
with self._lock:
states = list(self._instances.values())
ok = True
for s in states:
if s.process and s.process.poll() is None:
if not self._stop_process(s):
ok = False
return ok
# --- Queries ---
def get_instance(self, iid: str) -> Optional[InstanceState]:
with self._lock:
return self._instances.get(iid)
def get_all_instances(self) -> List[InstanceState]:
with self._lock:
return list(self._instances.values())
def get_running_count(self) -> int:
with self._lock:
return sum(1 for s in self._instances.values()
if s.process and s.process.poll() is None)
def any_running(self) -> bool:
return self.get_running_count() > 0
def next_available_port(self, base: int = PORT_RANGE_START) -> int:
with self._lock:
used = {s.config.port for s in self._instances.values()}
p = base
while p <= PORT_RANGE_END:
if p not in used:
return p
p += 1
return p
# --- Internal ---
@staticmethod
def _make_id(cfg: InstanceConfig) -> str:
dev = "cpu" if cfg.gpu_device == "cpu" else f"gpu{cfg.gpu_device}"
return f"{dev}_{cfg.port}"
@staticmethod
def _make_prefix(cfg: InstanceConfig) -> str:
dev = "CPU" if cfg.gpu_device == "cpu" else f"GPU{cfg.gpu_device}"
return f"[{dev}:{cfg.port}]"
def _read_logs(self, state: InstanceState, prefix: str):
if state.process and state.process.stdout:
try:
for line in state.process.stdout:
if self._log_callback:
text = line.rstrip("\n\r")
self._log_callback(f"{prefix} {text}")
except (ValueError, OSError):
pass
# Process ended
if state.status == "Running" or state.status == "Starting":
state.status = "Stopped"
if self._log_callback:
self._log_callback(f"{prefix} Process exited.")
@staticmethod
def _force_kill_pid(pid: int):
"""Kill a process using PowerShell (reliable for CREATE_NO_WINDOW processes)."""
try:
subprocess.run(
["powershell", "-NoProfile", "-Command",
f"Stop-Process -Id {pid} -Force -ErrorAction SilentlyContinue"],
capture_output=True, timeout=15,
)
except Exception:
pass
def _stop_process(self, state: InstanceState) -> bool:
if state.process is None or state.process.poll() is not None:
state.status = "Stopped"
state.process = None
return True
pid = state.process.pid
port = state.config.port
# 1. Try graceful HTTP shutdown
try:
req = urllib.request.Request(
f"http://127.0.0.1:{port}/shutdown",
method="POST",
data=b"",
)
urllib.request.urlopen(req, timeout=5)
except Exception:
pass
# Wait for graceful exit
try:
state.process.wait(timeout=4)
except subprocess.TimeoutExpired:
pass
# 2. Force kill if still running
if state.process.poll() is None:
if self._log_callback:
self._log_callback(f"Graceful shutdown failed for PID {pid}, force killing...")
self._force_kill_pid(pid)
try:
state.process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
# 3. Final fallback via Popen.kill()
if state.process.poll() is None:
try:
state.process.kill()
state.process.wait(timeout=5)
except Exception:
if self._log_callback:
self._log_callback(f"Warning: PID {pid} could not be killed")
state.process = None
state.status = "Stopped"
return True
# ---------------------------------------------------------------------------
# Launcher App
# ---------------------------------------------------------------------------
class LauncherApp:
"""Main LocalSoundsAPI Launcher application."""
def __init__(self, root: tk.Tk):
self.root = root
self.root.title(f"{APP_TITLE} v{APP_VERSION}")
self.root.geometry(WINDOW_SIZE)
self.root.minsize(MIN_WIDTH, MIN_HEIGHT)
try:
icon_path = BASE_DIR / "static" / "favicon.ico"
if icon_path.exists():
self.root.iconbitmap(str(icon_path))
except Exception:
pass
# State
self._log_entries: deque = deque(maxlen=MAX_LOG_LINES)
self._health_poll_id = None
self._download_active = False
# GPU detection
self.gpu_list = detect_gpus()
self._gpu_map = {label: value for label, value in self.gpu_list}
# Instance manager
self.manager = InstanceManager(log_callback=self._on_log_line)
# Build UI
self._setup_styles()
self._build_ui()
# Close handler
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
# Start health polling
self._health_poll_id = self.root.after(5000, self._poll_health)
# Welcome log
self._log_system(f"{APP_TITLE} v{APP_VERSION}")
self._log_system(f"Base directory: {BASE_DIR}")
gpu_count = len(self.gpu_list) - 1
if gpu_count > 0:
for label, val in self.gpu_list[1:]:
self._log_system(f"Detected: {label}")
else:
self._log_system("No NVIDIA GPUs detected. CPU mode available.")
# Check for orphaned processes from previous sessions
self.root.after(500, self._check_orphaned_processes)
# ------------------------------------------------------------------ styles
def _setup_styles(self):
style = ttk.Style()
available = style.theme_names()
if "vista" in available:
style.theme_use("vista")
elif "clam" in available:
style.theme_use("clam")
# ------------------------------------------------------------------ build
def _build_ui(self):
# Status bar (bottom)
self._build_status_bar()
# Notebook
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=8, pady=(8, 4))
# Tab 1: Instances & Log
tab1 = ttk.Frame(self.notebook, padding=8)
self.notebook.add(tab1, text=" Instances && Log ")
self._build_instances_tab(tab1)
# Tab 2: Models & Tools
tab2 = ttk.Frame(self.notebook, padding=8)
self.notebook.add(tab2, text=" Models && Tools ")
self._build_models_tab(tab2)
# =========================================================================
# TAB 1: Instances & Log
# =========================================================================
def _build_instances_tab(self, parent):
# --- Add Instance ---
add_frame = ttk.LabelFrame(parent, text="Add Instance", padding=8)
add_frame.pack(fill=tk.X, pady=(0, 6))
row = ttk.Frame(add_frame)
row.pack(fill=tk.X)
ttk.Label(row, text="Device:").pack(side=tk.LEFT, padx=(0, 5))
gpu_labels = [label for label, _ in self.gpu_list]
default_gpu = gpu_labels[1] if len(gpu_labels) > 1 else gpu_labels[0]
self.gpu_var = tk.StringVar(value=default_gpu)
self.gpu_combo = ttk.Combobox(
row, textvariable=self.gpu_var, values=gpu_labels,
state="readonly", width=42,
)
self.gpu_combo.pack(side=tk.LEFT, padx=(0, 15))
ToolTip(self.gpu_combo, "Select GPU device.\nCUDA_VISIBLE_DEVICES is set per instance.")
ttk.Label(row, text="Port:").pack(side=tk.LEFT, padx=(0, 5))
self.port_var = tk.StringVar(value=str(self.manager.next_available_port()))
self.port_entry = ttk.Entry(row, textvariable=self.port_var, width=7)
self.port_entry.pack(side=tk.LEFT, padx=(0, 15))
ToolTip(self.port_entry, "HTTP port for this instance (1024-65535)")
self.btn_add = ttk.Button(row, text="Add Instance", command=self._add_instance, width=14)
self.btn_add.pack(side=tk.LEFT)
# --- Instance Table ---
server_frame = ttk.LabelFrame(parent, text="Server Instances", padding=8)
server_frame.pack(fill=tk.BOTH, pady=(0, 6))
tree_frame = ttk.Frame(server_frame)
tree_frame.pack(fill=tk.BOTH, expand=True)
cols = ("device", "port", "status", "url")
self.tree = ttk.Treeview(tree_frame, columns=cols, show="headings",
height=5, selectmode="browse")
self.tree.heading("device", text="Device")
self.tree.heading("port", text="Port")
self.tree.heading("status", text="Status")
self.tree.heading("url", text="URL")
self.tree.column("device", width=300, minwidth=180)
self.tree.column("port", width=60, minwidth=50)
self.tree.column("status", width=80, minwidth=60)
self.tree.column("url", width=220, minwidth=120)
tree_scroll = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=tree_scroll.set)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
tree_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.bind("<<TreeviewSelect>>", self._on_tree_select)
self.tree.bind("<Double-1>", lambda e: self._open_browser())
# Buttons
btn_frame = ttk.Frame(server_frame)
btn_frame.pack(fill=tk.X, pady=(6, 0))
self.btn_start = ttk.Button(btn_frame, text="Start", command=self._start_selected, width=8)
self.btn_stop = ttk.Button(btn_frame, text="Stop", command=self._stop_selected, width=8)
self.btn_start_all = ttk.Button(btn_frame, text="Start All", command=self._start_all, width=9)
self.btn_stop_all = ttk.Button(btn_frame, text="Stop All", command=self._stop_all, width=9)
self.btn_remove = ttk.Button(btn_frame, text="Remove", command=self._remove_selected, width=9)
self.btn_open = ttk.Button(btn_frame, text="Open in Browser", command=self._open_browser, width=15)
for btn in (self.btn_start, self.btn_stop, self.btn_start_all,
self.btn_stop_all, self.btn_remove, self.btn_open):
btn.pack(side=tk.LEFT, padx=3)
for btn in (self.btn_start, self.btn_stop, self.btn_remove, self.btn_open):
btn.config(state=tk.DISABLED)
# --- Log Viewer ---
log_frame = ttk.LabelFrame(parent, text="Log", padding=8)
log_frame.pack(fill=tk.BOTH, expand=True)
controls = ttk.Frame(log_frame)
controls.pack(fill=tk.X, pady=(0, 4))
ttk.Label(controls, text="Filter:").pack(side=tk.LEFT, padx=(0, 4))
self._filter_var = tk.StringVar(value="all")
self._filter_combo = ttk.Combobox(
controls, textvariable=self._filter_var,
values=["all"], state="readonly", width=18,
)
self._filter_combo.pack(side=tk.LEFT, padx=(0, 10))
self._filter_combo.bind("<<ComboboxSelected>>", self._on_filter_change)
ttk.Button(controls, text="Clear Log", command=self._clear_log).pack(side=tk.RIGHT)
self._line_label = ttk.Label(controls, text="0 lines", font=("Segoe UI", 8), foreground="#888")
self._line_label.pack(side=tk.RIGHT, padx=(0, 10))
text_frame = ttk.Frame(log_frame)
text_frame.pack(fill=tk.BOTH, expand=True)
self.log_text = tk.Text(
text_frame, wrap=tk.WORD, state=tk.DISABLED,
font=("Consolas", 9),
background="#1e1e1e", foreground="#d4d4d4",
insertbackground="#d4d4d4", selectbackground="#264f78",
)
log_scroll = ttk.Scrollbar(text_frame, orient=tk.VERTICAL, command=self.log_text.yview)
self.log_text.configure(yscrollcommand=log_scroll.set)
self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
log_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.log_text.tag_configure("timestamp", foreground="#888888")
self.log_text.tag_configure("prefix", foreground="#569cd6")
self.log_text.tag_configure("system", foreground="#9cdcfe")
self.log_text.tag_configure("error", foreground="#f44747")
self.log_text.tag_configure("success", foreground="#4ec9b0")
# =========================================================================
# TAB 2: Models & Tools
# =========================================================================
def _build_models_tab(self, parent):
# --- Portable Environment ---
env_frame = ttk.LabelFrame(parent, text="Portable Python Environment", padding=8)
env_frame.pack(fill=tk.X, pady=(0, 8))
env_row = ttk.Frame(env_frame)
env_row.pack(fill=tk.X)
py_version = f"Python {sys.version.split()[0]}"
py_path = str(PYTHON_EXE.parent)
self._py_status_label = ttk.Label(
env_row, text=f"{py_version} ({py_path})",
font=("Segoe UI", 9),
)
self._py_status_label.pack(side=tk.LEFT, padx=(0, 15))
self.btn_dl_python = ttk.Button(
env_row, text="Download / Reinstall Python Env (.7z)",
command=self._download_python_env, width=35,
)
self.btn_dl_python.pack(side=tk.RIGHT)
ToolTip(self.btn_dl_python,
"Downloads portable-python-env-v1.7z from GitHub releases\n"
"and extracts it to the python/ directory.\n"
"Use this to repair or reinstall the Python environment.")
# --- Portable Tools ---
tools_frame = ttk.LabelFrame(parent, text="Portable Tools (bin/)", padding=8)
tools_frame.pack(fill=tk.X, pady=(0, 8))
self._tool_labels = {}
any_missing = False
for tool_name, check_path in TOOL_CHECKS.items():
row = ttk.Frame(tools_frame)
row.pack(fill=tk.X, pady=1)
exists = check_path.exists()
if not exists:
any_missing = True
color = "#4CAF50" if exists else "#F44336"
status_text = "Installed" if exists else "Not Found"
canvas = tk.Canvas(row, width=12, height=12, highlightthickness=0)
canvas.pack(side=tk.LEFT, padx=(0, 6))
canvas.create_oval(2, 2, 11, 11, fill=color, outline="")
ttk.Label(row, text=f"{tool_name}:", width=12, anchor=tk.W).pack(side=tk.LEFT)
lbl = ttk.Label(row, text=status_text, foreground=color)
lbl.pack(side=tk.LEFT)
self._tool_labels[tool_name] = (canvas, lbl)
btn_row = ttk.Frame(tools_frame)
btn_row.pack(fill=tk.X, pady=(6, 0))
btn_text = "Download All Tools (bin.zip)" if any_missing else "Reinstall Tools (bin.zip)"
self.btn_dl_tools = ttk.Button(
btn_row, text=btn_text,
command=self._download_bin_zip, width=30,
)
self.btn_dl_tools.pack(side=tk.LEFT)
ToolTip(self.btn_dl_tools,
"Downloads bin.zip from GitHub releases and\n"
"extracts FFmpeg, RubberBand, and eSpeak-ng.")
# --- HuggingFace Token ---
hf_frame = ttk.LabelFrame(parent, text="HuggingFace Token", padding=8)
hf_frame.pack(fill=tk.X, pady=(0, 8))
hf_row = ttk.Frame(hf_frame)
hf_row.pack(fill=tk.X)
ttk.Label(hf_row, text="Token:", font=("Segoe UI", 9)).pack(side=tk.LEFT, padx=(0, 6))
self._hf_token_var = tk.StringVar(value=self._detect_hf_token())
self._hf_token_entry = ttk.Entry(hf_row, textvariable=self._hf_token_var, show="*", width=50)
self._hf_token_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 8))
self._hf_show_var = tk.BooleanVar(value=False)
self._hf_show_btn = ttk.Checkbutton(
hf_row, text="Show", variable=self._hf_show_var,
command=self._toggle_hf_token_visibility,
)
self._hf_show_btn.pack(side=tk.LEFT, padx=(0, 8))
self._hf_save_btn = ttk.Button(hf_row, text="Save", command=self._save_hf_token, width=8)
self._hf_save_btn.pack(side=tk.LEFT)
ToolTip(self._hf_save_btn, "Saves token to HuggingFace cache so it persists across sessions.")
token_hint = "Required for gated models (e.g. Fish Speech). Get yours at huggingface.co/settings/tokens"
ttk.Label(hf_frame, text=token_hint, font=("Segoe UI", 8), foreground="#888888").pack(anchor=tk.W, pady=(4, 0))
# --- AI Models ---
models_frame = ttk.LabelFrame(parent, text="AI Models", padding=8)
models_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 8))
cols = ("model", "status", "size")
self.model_tree = ttk.Treeview(models_frame, columns=cols, show="headings", height=7)
self.model_tree.heading("model", text="Model")
self.model_tree.heading("status", text="Status")
self.model_tree.heading("size", text="Size")
self.model_tree.column("model", width=200, minwidth=140)
self.model_tree.column("status", width=120, minwidth=80)
self.model_tree.column("size", width=100, minwidth=60)
self.model_tree.pack(fill=tk.BOTH, expand=True)
self._populate_model_tree()
# Model buttons
model_btn_frame = ttk.Frame(models_frame)
model_btn_frame.pack(fill=tk.X, pady=(6, 0))
self.btn_dl_model = ttk.Button(
model_btn_frame, text="Download Selected Model",
command=self._download_selected_model, width=25,
)
self.btn_dl_model.pack(side=tk.LEFT, padx=(0, 8))
self.btn_refresh_models = ttk.Button(
model_btn_frame, text="Refresh Status",
command=self._refresh_model_status, width=14,
)
self.btn_refresh_models.pack(side=tk.LEFT)
# Progress bar
progress_frame = ttk.Frame(models_frame)
progress_frame.pack(fill=tk.X, pady=(6, 0))
self.dl_progress = ttk.Progressbar(progress_frame, mode="determinate")
self.dl_progress.pack(fill=tk.X, side=tk.LEFT, expand=True, padx=(0, 8))
self.dl_status_label = ttk.Label(progress_frame, text="", font=("Segoe UI", 9))
self.dl_status_label.pack(side=tk.RIGHT)
def _populate_model_tree(self):
for item in self.model_tree.get_children():
self.model_tree.delete(item)
for name, check_path, hf_repo, hf_rev, size_label, is_file in MODEL_DEFS:
if is_file:
installed = check_path.exists()
else:
installed = check_path.exists() and any(check_path.iterdir()) if check_path.exists() else False
status = "Installed" if installed else "Not Found"
tag = "installed" if installed else "missing"
self.model_tree.insert("", tk.END, values=(name, status, size_label), tags=(tag,))
self.model_tree.tag_configure("installed", foreground="#4CAF50")
self.model_tree.tag_configure("missing", foreground="#F44336")
def _refresh_model_status(self):
self._populate_model_tree()
self._refresh_tool_status()
self._log_system("Model and tool status refreshed.")
def _refresh_tool_status(self):
for tool_name, check_path in TOOL_CHECKS.items():
if tool_name not in self._tool_labels:
continue
canvas, lbl = self._tool_labels[tool_name]
exists = check_path.exists()
color = "#4CAF50" if exists else "#F44336"
status_text = "Installed" if exists else "Not Found"
canvas.delete("all")
canvas.create_oval(2, 2, 11, 11, fill=color, outline="")
lbl.config(text=status_text, foreground=color)
# ------------------------------------------------------------------ HF token
def _detect_hf_token(self) -> str:
"""Check common locations for an existing HuggingFace token."""
# 1. Environment variable
env_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or ""
if env_token:
return env_token.strip()
# 2. HF cache file (~/.cache/huggingface/token)
hf_cache = Path.home() / ".cache" / "huggingface" / "token"
if hf_cache.exists():
try:
return hf_cache.read_text(encoding="utf-8").strip()
except Exception:
pass
return ""
def _get_hf_token(self) -> Optional[str]:
"""Return the current token or None if empty."""
token = self._hf_token_var.get().strip()
return token if token else None
def _toggle_hf_token_visibility(self):
self._hf_token_entry.config(show="" if self._hf_show_var.get() else "*")
def _save_hf_token(self):
token = self._hf_token_var.get().strip()
if not token:
self._log_system("No token to save.")
return
try:
hf_dir = Path.home() / ".cache" / "huggingface"
hf_dir.mkdir(parents=True, exist_ok=True)
(hf_dir / "token").write_text(token, encoding="utf-8")
self._log_system("HuggingFace token saved to cache.")
except Exception as e:
self._log_system(f"Failed to save token: {e}")
# ------------------------------------------------------------------ status bar
def _build_status_bar(self):
status_frame = ttk.Frame(self.root, relief=tk.SUNKEN)
status_frame.pack(fill=tk.X, side=tk.BOTTOM)
self.status_label = ttk.Label(
status_frame, text="Ready", font=("Segoe UI", 9), padding=(10, 4),
)
self.status_label.pack(side=tk.LEFT)
self.server_status_label = ttk.Label(
status_frame, text="No instances running",
font=("Segoe UI", 9), padding=(10, 4),
)
self.server_status_label.pack(side=tk.RIGHT)
def _update_status_bar(self):
count = self.manager.get_running_count()
if count == 0:
self.server_status_label.config(text="No instances running")
elif count == 1:
self.server_status_label.config(text="1 instance running")
else:
self.server_status_label.config(text=f"{count} instances running")
# =========================================================================
# Instance Actions
# =========================================================================
def _get_selected_id(self) -> Optional[str]:
sel = self.tree.selection()
return sel[0] if sel else None
def _on_tree_select(self, event=None):
has_sel = bool(self.tree.selection())
state = tk.NORMAL if has_sel else tk.DISABLED
for btn in (self.btn_start, self.btn_stop, self.btn_remove, self.btn_open):
btn.config(state=state)
def _add_instance(self):
gpu_label = self.gpu_var.get()
gpu_device = self._gpu_map.get(gpu_label, "cpu")
try:
port = int(self.port_var.get())
except ValueError:
self._log_system("Error: Invalid port number.")
return
if port < 1024 or port > 65535:
self._log_system("Error: Port must be between 1024 and 65535.")
return
config = InstanceConfig(gpu_device=gpu_device, gpu_label=gpu_label, port=port)
try:
iid = self.manager.add_instance(config)
except ValueError as e:
self._log_system(f"Error: {e}")
return
url = f"http://127.0.0.1:{port}"
self.tree.insert("", tk.END, iid=iid, values=(gpu_label, port, "Stopped", url))
self._log_system(f"Added instance {iid} ({gpu_label} on port {port})")
self.port_var.set(str(self.manager.next_available_port()))
self._update_filter_values()
def _start_selected(self):
iid = self._get_selected_id()
if not iid:
return
state = self.manager.get_instance(iid)
if state and state.process and state.process.poll() is None:
self._log_system(f"{iid} is already running.")
return
self._log_system(f"Starting {iid}...")
self._update_tree_status(iid, "Starting")
def do_start():
return self.manager.start_instance(iid)
def on_done(success):
s = self.manager.get_instance(iid)
status = s.status if s else "Error"
self._update_tree_status(iid, status)
if success:
self._log_system(f"{iid} is now running.")
else:
self._log_system(f"{iid} failed to start.")
self._update_status_bar()
self._run_async(do_start, on_done)
def _stop_selected(self):
iid = self._get_selected_id()
if not iid:
return
self._log_system(f"Stopping {iid}...")
self._update_tree_status(iid, "Stopping")
def do_stop():
return self.manager.stop_instance(iid)
def on_done(success):
self._update_tree_status(iid, "Stopped")
self._log_system(f"{iid} stopped.")
self._update_status_bar()
self._run_async(do_stop, on_done)
def _start_all(self):
instances = self.manager.get_all_instances()
to_start = [s for s in instances if not (s.process and s.process.poll() is None)]
if not to_start:
self._log_system("No stopped instances to start.")
return
self._log_system(f"Starting {len(to_start)} instance(s)...")
def do_start_all():
results = {}
for s in to_start:
self.root.after(0, lambda sid=s.instance_id: self._update_tree_status(sid, "Starting"))
ok = self.manager.start_instance(s.instance_id)
results[s.instance_id] = ok
return results
def on_done(results):
for iid, ok in results.items():
s = self.manager.get_instance(iid)
status = s.status if s else "Error"
self._update_tree_status(iid, status)
self._update_status_bar()
self._log_system("Start All completed.")
self._run_async(do_start_all, on_done)
def _stop_all(self):
self._log_system("Stopping all instances...")
def do_stop():
return self.manager.stop_all()
def on_done(ok):
for s in self.manager.get_all_instances():
self._update_tree_status(s.instance_id, "Stopped")
self._update_status_bar()
self._log_system("All instances stopped.")
self._run_async(do_stop, on_done)
def _remove_selected(self):
iid = self._get_selected_id()
if not iid:
return
state = self.manager.get_instance(iid)
if state and state.process and state.process.poll() is None:
if not messagebox.askyesno("Confirm", f"{iid} is running. Stop and remove?"):
return
self.manager.remove_instance(iid)
self.tree.delete(iid)
self._log_system(f"Removed {iid}")
self._update_status_bar()
self._update_filter_values()
def _open_browser(self):
iid = self._get_selected_id()
if not iid:
return
state = self.manager.get_instance(iid)
if state:
url = f"http://127.0.0.1:{state.config.port}"
webbrowser.open(url)
def _update_tree_status(self, iid: str, status: str):
try:
if self.tree.exists(iid):
vals = list(self.tree.item(iid, "values"))
vals[2] = status
self.tree.item(iid, values=vals)
except Exception:
pass
# =========================================================================
# Log System
# =========================================================================
def _on_log_line(self, line: str):
"""Thread-safe callback from InstanceManager log threads."""
try: