-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathstart.py
More file actions
2637 lines (2142 loc) · 86 KB
/
start.py
File metadata and controls
2637 lines (2142 loc) · 86 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
"""
Chatterbox TTS Server - Cross-Platform Launcher Script
=======================================================
A user-friendly launcher with automatic setup, virtual environment
management, hardware detection, dependency installation, and server startup.
Features:
- Cross-platform support (Windows, Linux, macOS)
- Automatic GPU detection (NVIDIA, AMD)
- Interactive hardware selection menu
- Virtual environment management
- Dependency installation with progress indication
- Server startup with health checking
- Reinstall/upgrade support
Usage:
Windows: Double-click start.bat or run: python start.py
Linux: Run: ./start.sh or: python3 start.py
Options:
--reinstall, -r Remove existing installation and reinstall fresh
--upgrade, -u Upgrade to latest version (keeps hardware selection)
--cpu Install CPU version (skip menu)
--nvidia Install NVIDIA CUDA 12.1 version (skip menu)
--nvidia-cu128 Install NVIDIA CUDA 12.8 version (skip menu)
--rocm Install AMD ROCm version (skip menu)
--portable Use portable Python environment (Windows, skip prompt)
--no-portable Use standard virtual environment (Windows, skip prompt)
--verbose, -v Show detailed installation output
--help, -h Show this help message
Requirements:
- Python 3.10 or later
- Internet connection for downloading dependencies
"""
import argparse
import hashlib
import json
import os
import platform
import re
import shutil
import socket
import stat
import subprocess
import sys
import threading
import time
import urllib.request
import zipfile
from datetime import datetime
from pathlib import Path
# ============================================================================
# CONFIGURATION
# ============================================================================
# TESTING FLAG: Set to True to simulate Python 3.11+ on Windows
# (forces embedded Python fallback even if actual Python version is <3.11)
# This is useful for testing the embedded Python path without installing Python 3.11+
TEST_EMBEDDED_PYTHON_PATH = False
# Virtual environment settings
VENV_FOLDER = "venv"
SERVER_SCRIPT = "server.py"
CONFIG_FILE = "config.yaml"
# Embedded Python settings (Windows fallback for Python 3.11+)
EMBEDDED_PYTHON_DIR = "python_embedded"
EMBEDDED_PYTHON_VERSION = "3.10.11"
EMBEDDED_PYTHON_URL = (
f"https://www.python.org/ftp/python/{EMBEDDED_PYTHON_VERSION}/"
f"python-{EMBEDDED_PYTHON_VERSION}-embed-amd64.zip"
)
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
# SHA-256 hash of the embeddable zip for integrity verification.
# Set to "" to skip verification (not recommended for production).
# To compute: download the file from EMBEDDED_PYTHON_URL, then run:
# python -c "import hashlib; print(hashlib.sha256(open('python-3.10.11-embed-amd64.zip','rb').read()).hexdigest())"
EMBEDDED_PYTHON_SHA256 = ""
# Installation type identifiers
INSTALL_CPU = "cpu"
INSTALL_NVIDIA = "nvidia"
INSTALL_NVIDIA_CU128 = "nvidia-cu128"
INSTALL_ROCM = "rocm"
# Requirements file mapping
REQUIREMENTS_MAP = {
INSTALL_CPU: "requirements.txt",
INSTALL_NVIDIA: "requirements-nvidia.txt",
INSTALL_NVIDIA_CU128: "requirements-nvidia-cu128.txt",
INSTALL_ROCM: "requirements-rocm.txt",
}
# Human-readable names for installation types
INSTALL_NAMES = {
INSTALL_CPU: "CPU Only",
INSTALL_NVIDIA: "NVIDIA GPU (CUDA 12.1)",
INSTALL_NVIDIA_CU128: "NVIDIA GPU (CUDA 12.8 / Blackwell)",
INSTALL_ROCM: "AMD GPU (ROCm 6.4)",
}
# Chatterbox fork URL (used for CUDA 12.8 installation)
CHATTERBOX_REPO = "git+https://github.com/devnen/chatterbox-v2.git@master"
# Timeout settings (seconds)
# First run downloads large model files (~2GB). Subsequent starts are much faster.
SERVER_STARTUP_TIMEOUT = 1800
PORT_CHECK_INTERVAL = 0.5
# Global verbose mode flag (set from args)
VERBOSE_MODE = True
# ============================================================================
# ANSI COLOR SUPPORT
# ============================================================================
class Colors:
"""ANSI color codes for cross-platform colored terminal output."""
CYAN = "\033[96m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
# Status icons
ICON_SUCCESS = "✓"
ICON_ERROR = "✗"
ICON_WARNING = "⚠"
ICON_INFO = "→"
ICON_WORKING = "●"
@staticmethod
def is_windows():
"""Check if running on Windows."""
return platform.system() == "Windows"
@staticmethod
def is_linux():
"""Check if running on Linux."""
return platform.system() == "Linux"
@staticmethod
def is_macos():
"""Check if running on macOS."""
return platform.system() == "Darwin"
@classmethod
def enable_windows_colors(cls):
"""Enable ANSI color support on Windows 10+."""
if cls.is_windows():
try:
import ctypes
kernel32 = ctypes.windll.kernel32
# Enable ANSI escape sequences on Windows 10+
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
except Exception:
# If this fails, colors just won't work (non-fatal)
pass
# Enable Windows colors at module load time
Colors.enable_windows_colors()
# ============================================================================
# PRINT HELPER FUNCTIONS
# ============================================================================
def print_banner():
"""Print the startup banner."""
print()
print("=" * 60)
print(" Chatterbox TTS Server - Launcher")
print("=" * 60)
print()
def print_header(text):
"""Print a section header."""
print(f"\n{Colors.CYAN}{text}{Colors.RESET}")
def print_step(step, total, message):
"""Print a numbered step."""
print(f"\n[{step}/{total}] {message}")
def print_substep(message, status="info"):
"""
Print a sub-step with status indicator.
Args:
message: The message to print
status: One of "done", "error", "warning", "info"
"""
icons = {
"done": (Colors.GREEN, Colors.ICON_SUCCESS),
"error": (Colors.RED, Colors.ICON_ERROR),
"warning": (Colors.YELLOW, Colors.ICON_WARNING),
"info": (Colors.RESET, Colors.ICON_INFO),
}
color, icon = icons.get(status, (Colors.RESET, Colors.ICON_INFO))
print(f" {color}{icon}{Colors.RESET} {message}")
def print_success(text):
"""Print a success message in green."""
print(f"{Colors.GREEN}{text}{Colors.RESET}")
def print_warning(text):
"""Print a warning message in yellow."""
print(f"{Colors.YELLOW}{text}{Colors.RESET}")
def print_error(text):
"""Print an error message in red."""
print(f"{Colors.RED}{text}{Colors.RESET}")
def print_status_box(host, port):
"""Print the final status box with server information."""
display_host = "localhost" if host == "0.0.0.0" else host
url = f"http://{display_host}:{port}"
print()
print("=" * 60)
print(f" {Colors.GREEN}🎙️ Chatterbox TTS Server is running!{Colors.RESET}")
print()
print(f" Web Interface: {url}")
print(f" API Docs: {url}/docs")
if host == "0.0.0.0":
print()
print(" (Also accessible on your local network)")
print()
print(" Press Ctrl+C to stop the server.")
print("=" * 60)
print()
def print_reinstall_hint():
"""Print a hint about how to reinstall."""
print(f" {Colors.DIM}💡 Tip: To reinstall or upgrade, run:{Colors.RESET}")
print(f" {Colors.DIM} python start.py --reinstall{Colors.RESET}")
print()
# ============================================================================
# COMMAND EXECUTION
# ============================================================================
def run_command(cmd, cwd=None, check=True, capture=False, show_output=False):
"""
Run a shell command.
Args:
cmd: Command string to execute
cwd: Working directory (optional)
check: If True, raise exception on non-zero exit
capture: If True, capture and return output
show_output: If True, show output in real-time
Returns:
If capture=True: subprocess.CompletedProcess result
If capture=False: True on success, False on failure
"""
try:
if capture:
result = subprocess.run(
cmd, shell=True, cwd=cwd, capture_output=True, text=True, check=check
)
return result
if show_output or VERBOSE_MODE:
# Show output in real-time
result = subprocess.run(cmd, shell=True, cwd=cwd, check=check)
return result.returncode == 0 if not check else True
else:
# Suppress output
result = subprocess.run(
cmd, shell=True, cwd=cwd, capture_output=True, text=True, check=check
)
return True
except subprocess.CalledProcessError as e:
if check:
raise
return None if capture else False
except Exception as e:
if VERBOSE_MODE:
print_error(f"Command error: {e}")
return None if capture else False
def run_command_with_progress(cmd, cwd=None, description="Working"):
"""
Run a command with a progress indicator for long operations.
Args:
cmd: Command string to execute
cwd: Working directory (optional)
description: Description to show during progress
Returns:
True on success, False on failure
"""
if VERBOSE_MODE:
# In verbose mode, just show output directly
print_substep(f"Running: {cmd}", "info")
return run_command(cmd, cwd=cwd, show_output=True, check=False)
# Start progress indicator in background
stop_progress = threading.Event()
def progress_indicator():
"""Background thread to show progress spinner."""
spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
idx = 0
while not stop_progress.is_set():
sys.stdout.write(f"\r {spinner[idx]} {description}...")
sys.stdout.flush()
idx = (idx + 1) % len(spinner)
time.sleep(0.1)
# Clear the progress line
sys.stdout.write("\r" + " " * 60 + "\r")
sys.stdout.flush()
progress_thread = threading.Thread(target=progress_indicator, daemon=True)
progress_thread.start()
try:
result = subprocess.run(
cmd, shell=True, cwd=cwd, capture_output=True, text=True
)
stop_progress.set()
progress_thread.join(timeout=1)
if result.returncode != 0:
print_substep(f"Command failed with exit code {result.returncode}", "error")
if result.stderr:
# Show last part of error message
error_lines = result.stderr.strip().split("\n")
for line in error_lines[-5:]:
print(f" {line}")
return False
return True
except Exception as e:
stop_progress.set()
progress_thread.join(timeout=1)
print_error(f"Error running command: {e}")
return False
# ============================================================================
# PLATFORM DETECTION
# ============================================================================
def is_windows():
"""Check if running on Windows."""
return platform.system() == "Windows"
def is_linux():
"""Check if running on Linux."""
return platform.system() == "Linux"
def is_macos():
"""Check if running on macOS."""
return platform.system() == "Darwin"
def get_platform_name():
"""Get human-readable platform name."""
system = platform.system()
if system == "Windows":
return "Windows"
elif system == "Linux":
return "Linux"
elif system == "Darwin":
return "macOS"
else:
return system
# ============================================================================
# PYTHON & VIRTUAL ENVIRONMENT FUNCTIONS
# ============================================================================
def check_python_version():
"""
Verify Python version is 3.10 or later.
Exits with error if version is too old.
"""
major = sys.version_info.major
minor = sys.version_info.minor
if major < 3 or (major == 3 and minor < 10):
print_error(f"Python 3.10+ required, but found Python {major}.{minor}")
print()
print("Please install Python 3.10 or newer from:")
print(" https://www.python.org/downloads/")
print()
sys.exit(1)
print_substep(f"Python {major}.{minor}.{sys.version_info.micro} detected", "done")
def get_venv_paths(root_dir):
"""
Get paths for virtual environment components.
Args:
root_dir: Root directory of the project
Returns:
Tuple of (venv_dir, venv_python, venv_pip) as Path objects
"""
venv_dir = root_dir / VENV_FOLDER
if is_windows():
venv_python = venv_dir / "Scripts" / "python.exe"
venv_pip = venv_dir / "Scripts" / "pip.exe"
else:
venv_python = venv_dir / "bin" / "python"
venv_pip = venv_dir / "bin" / "pip"
return venv_dir, venv_python, venv_pip
def create_venv(venv_dir):
"""
Create a virtual environment.
Args:
venv_dir: Path to create the virtual environment
Returns:
True on success, False on failure
"""
print_substep("Creating virtual environment...")
try:
result = subprocess.run(
[sys.executable, "-m", "venv", str(venv_dir)],
capture_output=True,
text=True,
)
if result.returncode != 0:
print_substep("Failed to create virtual environment", "error")
if result.stderr:
print(f" {result.stderr[:200]}")
return False
print_substep("Virtual environment created", "done")
return True
except Exception as e:
print_substep(f"Error creating venv: {e}", "error")
return False
def get_install_state(venv_dir):
"""
Check if installation is complete and get the install type.
Args:
venv_dir: Path to virtual environment directory
Returns:
Tuple of (is_installed: bool, install_type: str or None)
"""
install_complete_file = venv_dir / ".install_complete"
install_type_file = venv_dir / ".install_type"
if not install_complete_file.exists():
return False, None
install_type = None
if install_type_file.exists():
try:
install_type = install_type_file.read_text(encoding="utf-8").strip()
except Exception:
pass
return True, install_type
def save_install_state(venv_dir, install_type):
"""
Save installation state files.
Args:
venv_dir: Path to virtual environment directory
install_type: Type of installation (cpu, nvidia, nvidia-cu128, rocm)
"""
try:
# Save install type
install_type_file = venv_dir / ".install_type"
install_type_file.write_text(install_type, encoding="utf-8")
# Save completion marker with timestamp
install_complete_file = venv_dir / ".install_complete"
timestamp = datetime.now().isoformat()
install_complete_file.write_text(
f"Installation completed at {timestamp}\n" f"Type: {install_type}\n",
encoding="utf-8",
)
except Exception as e:
print_warning(f"Could not save install state: {e}")
def clear_install_complete(venv_dir):
"""
Clear only the install complete marker (for upgrades).
Args:
venv_dir: Path to virtual environment directory
"""
install_complete_file = venv_dir / ".install_complete"
try:
if install_complete_file.exists():
install_complete_file.unlink()
except Exception as e:
print_warning(f"Could not clear install marker: {e}")
def robust_rmtree(path):
"""
Remove a directory tree with Windows-hardened error handling.
Uses an onerror callback to strip read-only attributes (common on
extracted zip contents), retries on transient permission errors
(antivirus, Explorer indexing), and falls back to renaming the
directory aside if deletion fails entirely.
Args:
path: Path to directory to remove
Returns:
True if directory is gone (deleted or renamed aside), False if stuck
"""
path = Path(path)
if not path.exists():
return True
def handle_remove_readonly(func, fpath, exc):
"""Clear read-only flag and retry the failed operation."""
os.chmod(fpath, stat.S_IWRITE)
func(fpath)
max_retries = 3
retry_delay = 2
for attempt in range(max_retries):
try:
shutil.rmtree(path, onerror=handle_remove_readonly)
return True
except PermissionError:
if attempt < max_retries - 1:
print_substep(
f"Files locked, retrying in {retry_delay}s... "
f"(attempt {attempt + 1}/{max_retries})",
"warning",
)
time.sleep(retry_delay)
except Exception:
break # Non-permission error, skip to rename fallback
# Fallback: rename aside so we can proceed even if deletion fails
try:
aside_name = f"{path.name}.old.{int(time.time())}"
aside_path = path.parent / aside_name
path.rename(aside_path)
print_substep(
f"Could not delete folder; renamed to {aside_name}",
"warning",
)
print_substep("You can safely delete that folder later.", "info")
return True
except Exception:
pass
return False
def remove_venv(venv_dir):
"""
Remove an environment directory (venv or embedded) with robust error handling.
Args:
venv_dir: Path to environment directory
Returns:
True on success, False on failure
"""
if not venv_dir.exists():
return True
print_substep(f"Removing existing environment ({venv_dir.name})...")
if robust_rmtree(venv_dir):
print_substep("Environment removed", "done")
return True
print_error(f"Could not remove: {venv_dir}")
print_substep(
"Try closing any terminals, editors, or antivirus scanning this folder",
"info",
)
if is_windows():
print_substep(f'Or run: rmdir /s /q "{venv_dir.name}"', "info")
else:
print_substep(f'Or run: rm -rf "{venv_dir.name}"', "info")
return False
# ============================================================================
# EMBEDDED PYTHON (WINDOWS FALLBACK)
# ============================================================================
def get_embedded_python_paths(root_dir):
"""
Get paths for the embedded Python environment (Windows only).
Args:
root_dir: Root directory of the project
Returns:
Tuple of (embedded_dir, embedded_python, embedded_pip) as Path objects
"""
embedded_dir = root_dir / EMBEDDED_PYTHON_DIR
embedded_python = embedded_dir / "python.exe"
embedded_pip = embedded_dir / "Scripts" / "pip.exe"
return embedded_dir, embedded_python, embedded_pip
def is_embedded_python_available(root_dir):
"""
Check if embedded Python is already set up and functional.
Args:
root_dir: Root directory of the project
Returns:
True if embedded Python is ready to use
"""
embedded_dir, embedded_python, embedded_pip = get_embedded_python_paths(root_dir)
if not embedded_python.exists() or not embedded_pip.exists():
return False
try:
result = subprocess.run(
[str(embedded_python), "--version"],
capture_output=True,
text=True,
timeout=10,
)
return result.returncode == 0
except Exception:
return False
def download_file(url, dest_path, description="Downloading"):
"""
Download a file from a URL with progress indication.
Uses urlopen with an explicit per-operation timeout to prevent
indefinite hanging on flaky networks or corporate proxies.
Downloads to a temporary .part file first, then atomically moves
to dest_path so interrupted downloads never leave a valid-looking
but truncated file at the final path.
Args:
url: URL to download from
dest_path: Local path to save the file
description: Description shown during download
Returns:
True on success, False on failure
"""
print_substep(f"{description}...")
dest_path = Path(dest_path)
part_path = dest_path.parent / (dest_path.name + ".part")
try:
response = urllib.request.urlopen(url, timeout=30)
total_size = int(response.headers.get("Content-Length", 0))
downloaded = 0
last_percent = -1
with open(part_path, "wb") as f:
while True:
chunk = response.read(8192)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if total_size > 0:
percent = min(100, int(downloaded * 100 / total_size))
if percent != last_percent and percent % 5 == 0:
last_percent = percent
mb_done = downloaded / (1024 * 1024)
mb_total = total_size / (1024 * 1024)
sys.stdout.write(
f"\r {Colors.ICON_WORKING} {description}... "
f"{percent}% ({mb_done:.1f}/{mb_total:.1f} MB)"
)
sys.stdout.flush()
else:
# No Content-Length: show bytes downloaded without percentage
mb_done = downloaded / (1024 * 1024)
if int(mb_done * 10) != last_percent:
last_percent = int(mb_done * 10)
sys.stdout.write(
f"\r {Colors.ICON_WORKING} {description}... "
f"{mb_done:.1f} MB"
)
sys.stdout.flush()
sys.stdout.write("\n")
sys.stdout.flush()
# Atomic move: .part → final path
os.replace(str(part_path), str(dest_path))
print_substep(f"{description} complete", "done")
return True
except Exception as e:
sys.stdout.write("\n")
sys.stdout.flush()
print_substep(f"Download failed: {e}", "error")
print_substep(f"You can download manually from: {url}", "info")
return False
finally:
# Clean up partial download on failure (no-op on success since
# os.replace already moved the .part file to dest_path)
try:
if part_path.exists():
part_path.unlink()
except Exception:
pass
def verify_checksum(file_path, expected_sha256):
"""
Verify SHA-256 hash of a downloaded file.
Args:
file_path: Path to the file to verify
expected_sha256: Expected hex digest string
Returns:
True if hash matches, False otherwise
"""
sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
actual = sha256.hexdigest()
if actual != expected_sha256:
print_substep("Checksum mismatch!", "error")
print_substep(f"Expected: {expected_sha256}", "info")
print_substep(f"Actual: {actual}", "info")
return False
return True
def patch_pth_file(embedded_dir):
"""
Patch the python3XX._pth file to enable pip and package imports.
The embeddable Python distribution ships with a ._pth file that
restricts the import path. We need to uncomment 'import site' and
add 'Lib\\site-packages' so that pip-installed packages are importable.
Note: pip usage with the embeddable distribution is "not supported"
per CPython docs, but works reliably with this patching approach.
The ._pth format has been stable since Python 3.5. Re-test if
bumping EMBEDDED_PYTHON_VERSION to a new minor release.
Args:
embedded_dir: Path to the embedded Python directory
Returns:
True on success, False on failure
"""
try:
# Find the ._pth file (e.g., python310._pth)
pth_files = list(embedded_dir.glob("python3*._pth"))
if not pth_files:
print_substep("Could not find ._pth file in embedded Python", "error")
return False
pth_file = pth_files[0]
content = pth_file.read_text(encoding="utf-8")
lines = content.splitlines()
# Collect path entries, skipping comments, blanks, and the
# import site directive (which we'll re-add at the end in
# the canonical position: paths first, import site last).
path_lines = []
has_site_packages = False
for line in lines:
stripped = line.strip()
# Skip import site (commented or not) — added back at the end
if stripped in ("#import site", "import site"):
continue
# Skip blank lines and the stock comment
if not stripped or stripped.startswith("#"):
continue
path_lines.append(stripped)
if "site-packages" in stripped:
has_site_packages = True
# Add site-packages path if not already present
if not has_site_packages:
path_lines.append("Lib\\site-packages")
# Add parent directory (project root) so that project modules
# like config.py, engine.py, utils.py are importable.
# The embedded Python dir is always <project_root>/python_embedded/,
# so ".." resolves to the project root at runtime.
if ".." not in path_lines:
path_lines.append("..")
# Canonical order: paths first, then import site last
path_lines.append("import site")
pth_file.write_text("\n".join(path_lines) + "\n", encoding="utf-8")
if VERBOSE_MODE:
print_substep(f"Patched {pth_file.name}", "done")
return True
except Exception as e:
print_substep(f"Failed to patch ._pth file: {e}", "error")
return False
def _create_dll_search_sitecustomize(embedded_dir):
"""
Create a sitecustomize.py in the embedded Python directory that configures
Windows DLL search paths at interpreter startup.
This ensures native extensions (.pyd files) can find their dependent DLLs
regardless of how the embedded Python is launched (via start.py, manually,
or from a subprocess). The file is automatically loaded by site.py
(triggered by 'import site' in the ._pth file).
No-op on non-Windows platforms.
Args:
embedded_dir: Path to the embedded Python directory
"""
sitecustomize_path = Path(embedded_dir) / "sitecustomize.py"
content = """\
# Auto-generated by start.py -- DO NOT EDIT
# Configures DLL search paths for the embedded Python environment on Windows.
# This ensures native extensions (.pyd) can locate their dependent DLLs.
import os
import sys
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
_exe_dir = os.path.dirname(sys.executable)
_sp_dir = os.path.join(_exe_dir, "Lib", "site-packages")
for _d in [_exe_dir, _sp_dir]:
if os.path.isdir(_d):
try:
os.add_dll_directory(_d)
except OSError:
pass
# Add *.libs directories (standard wheel pattern for vendored native DLLs,
# created by auditwheel/delvewheel when packaging binary extensions)
if os.path.isdir(_sp_dir):
for _entry in os.listdir(_sp_dir):
if _entry.endswith(".libs"):
_libs_path = os.path.join(_sp_dir, _entry)
if os.path.isdir(_libs_path):
try:
os.add_dll_directory(_libs_path)
except OSError:
pass
"""
try:
sitecustomize_path.write_text(content, encoding="utf-8")
if VERBOSE_MODE:
print_substep("Created sitecustomize.py for DLL search paths", "done")
except Exception as e:
print_substep(f"Could not create sitecustomize.py: {e}", "warning")
def setup_embedded_python(root_dir):
"""
Download and configure an embedded Python 3.10 environment for Windows.
This creates a fully self-contained Python installation inside the
project folder with pip bootstrapped and ready to install packages.
Args:
root_dir: Root directory of the project
Returns:
True on success, False on failure
"""
embedded_dir = root_dir / EMBEDDED_PYTHON_DIR
# Check if already available
if is_embedded_python_available(root_dir):
print_substep(
f"Embedded Python {EMBEDDED_PYTHON_VERSION} already set up", "done"
)
return True
# Clean up any partial previous attempt
if embedded_dir.exists():
if not robust_rmtree(embedded_dir):
print_substep("Could not clean up partial install", "error")
return False
print_substep(
f"Setting up portable Python {EMBEDDED_PYTHON_VERSION} environment...", "info"
)
zip_path = root_dir / "_python_embedded.zip"
get_pip_path = root_dir / "_get-pip.py"
try:
# Step 1: Download embeddable Python
if not download_file(
EMBEDDED_PYTHON_URL,
zip_path,
f"Downloading Python {EMBEDDED_PYTHON_VERSION} embeddable package",
):
return False
# Step 1b: Verify download integrity
if EMBEDDED_PYTHON_SHA256:
if not verify_checksum(zip_path, EMBEDDED_PYTHON_SHA256):
print_substep(
"Downloaded file may be corrupted. "
"Delete it and try again, or download manually.",
"error",
)
return False
if VERBOSE_MODE:
print_substep("Checksum verified", "done")
# Step 1c: Validate zip archive
if not zipfile.is_zipfile(str(zip_path)):
print_substep("Downloaded file is not a valid zip archive", "error")
print_substep("Your network may be returning an error page instead", "info")
return False
# Step 2: Extract
print_substep("Extracting Python...")
try:
embedded_dir.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(str(zip_path), "r") as zf:
zf.extractall(str(embedded_dir))
print_substep("Python extracted", "done")