-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathinstall.py
More file actions
1865 lines (1647 loc) · 82.7 KB
/
install.py
File metadata and controls
1865 lines (1647 loc) · 82.7 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
"""
CraftBot Installation Script
Usage:
python install.py # Install core dependencies with global pip
python install.py --conda # Install with conda environment
Options:
--conda Use conda environment (optional)
--mamba Use mamba instead of conda (faster, optional with --conda)
Note: GUI mode (--gui) is temporarily disabled in V1.2.2.
After installation completes, CraftBot will automatically launch in browser mode.
To use TUI mode instead, run: python run.py --tui
"""
import math
import multiprocessing
import os
import sys
import json
import subprocess
import shutil
import time
import threading
from typing import Tuple, Optional, Dict, Any
multiprocessing.freeze_support()
# Configuration is loaded from settings.json - no .env file is used
# All settings come from app/config/settings.json
# --- Base directory ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# --- Configuration ---
CONFIG_FILE = os.path.join(BASE_DIR, "config.json")
YML_FILE = os.path.join(BASE_DIR, "environment.yml")
REQUIREMENTS_FILE = os.path.join(BASE_DIR, "requirements.txt")
OMNIPARSER_REPO_URL = "https://github.com/zfoong/OmniParser_CraftOS.git"
OMNIPARSER_BRANCH = "CraftOS"
OMNIPARSER_ENV_NAME = "omni"
OMNIPARSER_MARKER_FILE = ".omniparser_setup_complete_v1"
# ==========================================
# TERMINAL COLORS (orange/white brand palette)
# ==========================================
def _enable_windows_vtp() -> None:
"""Enable ANSI/VT100 virtual terminal processing on Windows 10+."""
if sys.platform != "win32":
return
try:
import ctypes
k32 = ctypes.windll.kernel32
h = k32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
m = ctypes.c_ulong()
k32.GetConsoleMode(h, ctypes.byref(m))
k32.SetConsoleMode(h, m.value | 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
except Exception:
pass
def _download_progress(count: int, block_size: int, total_size: int) -> None:
"""urllib reporthook that draws a retro progress bar."""
if total_size <= 0:
return
pct = min(100, int(count * block_size * 100 / total_size))
filled = int(40 * pct / 100)
bar = f"{ORANGE}{'▓' * filled}{DIM}{'░' * (40 - filled)}{RESET}"
sys.stdout.write(f"\r Downloading {bar} {ORANGE}[ {pct:3d}% ]{RESET}")
sys.stdout.flush()
def _find_existing_python310() -> Optional[str]:
"""Return a verified Python 3.10 executable path if one is already installed, else None."""
candidates = []
if sys.platform == "win32":
local_app = os.environ.get("LOCALAPPDATA", "")
candidates = [
os.path.join(local_app, "Programs", "Python", "Python310", "python.exe"),
r"C:\Python310\python.exe",
os.path.join(os.environ.get("PROGRAMFILES", r"C:\Program Files"), "Python310", "python.exe"),
]
# Also try the py launcher
py_launcher = shutil.which("py")
if py_launcher:
try:
r = subprocess.run([py_launcher, "-3.10", "--version"],
capture_output=True, text=True, timeout=8)
if "3.10" in (r.stdout + r.stderr):
return py_launcher # caller uses it with "-3.10" flag
except Exception:
pass
elif sys.platform == "darwin":
candidates = [
shutil.which("python3.10") or "",
"/Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10",
"/usr/local/bin/python3.10",
"/opt/homebrew/bin/python3.10",
]
else:
candidates = [shutil.which("python3.10") or ""]
for path in candidates:
if path and os.path.isfile(path):
try:
r = subprocess.run([path, "--version"],
capture_output=True, text=True, timeout=8)
if "3.10" in (r.stdout + r.stderr):
return path
except Exception:
pass
return None
def _auto_install_python_310() -> None:
"""Download and silently install Python 3.10 (tries recent patch versions in order), then re-launch install.py with it."""
import urllib.request
# Try recent patch versions in descending order.
PYTHON_VERSION_CANDIDATES = [
"3.10.17", "3.10.16", "3.10.15", "3.10.14",
"3.10.13", "3.10.12", "3.10.11",
]
if sys.platform == "win32":
is_64bit = sys.maxsize > 2 ** 32
installer = None
chosen_version = None
for version in PYTHON_VERSION_CANDIDATES:
suffix = "-amd64.exe" if is_64bit else ".exe"
filename = f"python-{version}{suffix}"
url = f"https://www.python.org/ftp/python/{version}/{filename}"
dest = os.path.join(BASE_DIR, filename)
print(f"\n {WHITE}Trying Python {version}...{RESET}")
print(f" Source : {url}")
print(f" Size : ~25 MB\n")
try:
urllib.request.urlretrieve(url, dest, reporthook=_download_progress)
print() # newline after progress bar
installer = dest
chosen_version = version
break
except Exception as exc:
print(f"\n {RED}✗{RESET} Download failed: {exc}")
try:
os.remove(dest)
except Exception:
pass
if installer is None or chosen_version is None:
print(f"\n {RED}✗{RESET} {WHITE}Could not download Python automatically.{RESET}")
print(f" All download attempts failed (HTTP 404 or network error).")
print(f"\n Please install Python 3.10 manually:")
print(f" 1. Go to: https://www.python.org/downloads/")
print(f" 2. Download the latest Python 3.10 installer for Windows")
print(f" 3. Run the installer (check 'Add Python to PATH')")
print(f" 4. Open a NEW terminal and run: python install.py")
sys.exit(1)
print(f"\n {WHITE}Installing Python {chosen_version} (this window may briefly flash)...{RESET}")
result = subprocess.run([
installer,
"/passive", # minimal UI — shows a small progress dialog
"InstallAllUsers=0", # current user only (no admin needed)
"PrependPath=1", # adds python to PATH
"AssociateFiles=1",
"Include_pip=1",
"Include_launcher=1",
], timeout=300)
try:
os.remove(installer)
except Exception:
pass
if result.returncode != 0:
print(f"\n {RED}✗{RESET} Installer exited with code {result.returncode}.")
print(f"\n Please install Python 3.10 manually:")
print(f" 1. Go to: https://www.python.org/downloads/")
print(f" 2. Download the latest Python 3.10 installer for Windows")
print(f" 3. Run the installer (check 'Add Python to PATH')")
print(f" 4. Open a NEW terminal and run: python install.py")
sys.exit(1)
print(f"\n {GREEN}✓{RESET} {WHITE}Python {chosen_version} installed!{RESET}")
# Locate the freshly installed python.exe and verify it is actually 3.10.
local_app = os.environ.get("LOCALAPPDATA", "")
search_paths = [
os.path.join(local_app, "Programs", "Python", "Python310", "python.exe"),
r"C:\Python310\python.exe",
os.path.join(os.environ.get("PROGRAMFILES", r"C:\Program Files"), "Python310", "python.exe"),
]
new_python310 = None
for path in search_paths:
if os.path.isfile(path):
try:
ver_result = subprocess.run(
[path, "--version"], capture_output=True, text=True, timeout=10
)
ver_text = (ver_result.stdout + ver_result.stderr).strip()
if "3.10" in ver_text:
new_python310 = path
break
except Exception:
pass
# Fallback: try the py launcher with -3.10 and verify it resolves to 3.10
if new_python310 is None:
py_launcher = shutil.which("py")
if py_launcher:
try:
ver_result = subprocess.run(
[py_launcher, "-3.10", "--version"], capture_output=True, text=True, timeout=10
)
ver_text = (ver_result.stdout + ver_result.stderr).strip()
if "3.10" in ver_text:
new_python310 = py_launcher # will use with -3.10 flag below
except Exception:
pass
if new_python310:
print(f"\n {ORANGE}▸{RESET} Re-launching installer with Python 3.10...\n")
if new_python310.lower().endswith("py.exe"):
cmd = [new_python310, "-3.10", __file__]
else:
cmd = [new_python310, __file__]
# Pass --skip-python-check so the re-launched process skips the
# version gate and doesn't loop back into auto-install again.
extra = [a for a in sys.argv[1:] if a not in ("--no-launch",)]
subprocess.run(cmd + extra + ["--skip-python-check"])
else:
print(f"\n {ORANGE}▸{RESET} {WHITE}Python 3.10 installed — please open a NEW terminal and run:{RESET}")
print(f" {ORANGE}python install.py{RESET}")
print(f" (The new terminal will pick up Python 3.10 automatically.)")
sys.exit(0)
elif sys.platform == "darwin":
PYTHON_VERSION_CANDIDATES = [
"3.10.17", "3.10.16", "3.10.15", "3.10.14",
"3.10.13", "3.10.12", "3.10.11",
]
installer = None
chosen_version = None
for version in PYTHON_VERSION_CANDIDATES:
url = f"https://www.python.org/ftp/python/{version}/python-{version}-macos11.pkg"
dest = os.path.join(BASE_DIR, f"python-{version}.pkg")
print(f"\n {WHITE}Trying Python {version}...{RESET}")
print(f" Source : {url}")
try:
urllib.request.urlretrieve(url, dest, reporthook=_download_progress)
print()
installer = dest
chosen_version = version
break
except Exception as exc:
print(f"\n {RED}✗{RESET} Download failed: {exc}")
try:
os.remove(dest)
except Exception:
pass
if installer is None or chosen_version is None:
print(f"\n {RED}✗{RESET} {WHITE}Could not download Python automatically.{RESET}")
print(f"\n Please install Python 3.10 manually:")
print(f" 1. Go to: https://www.python.org/downloads/")
print(f" 2. Download the latest Python 3.10 macOS installer")
print(f" 3. Run the installer")
print(f" 4. Open a NEW terminal and run: python3.10 install.py")
sys.exit(1)
print(f"\n {WHITE}Installing (sudo required)...{RESET}")
result = subprocess.run(["sudo", "installer", "-pkg", installer, "-target", "/"], timeout=300)
try:
os.remove(installer)
except Exception:
pass
if result.returncode != 0:
print(f"\n {RED}✗{RESET} Installation failed.")
print(f"\n Please install Python 3.10 manually from: https://www.python.org/downloads/")
sys.exit(1)
print(f"\n {GREEN}✓{RESET} {WHITE}Python {chosen_version} installed!{RESET}")
_mac_candidates = [
shutil.which("python3.10"),
"/Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10",
"/usr/local/bin/python3.10",
"/opt/homebrew/bin/python3.10",
]
new_python = next((p for p in _mac_candidates if p and os.path.isfile(p)), None)
if new_python:
print(f"\n {ORANGE}▸{RESET} Re-launching with Python 3.10...\n")
os.execv(new_python, [new_python, __file__] + sys.argv[1:])
else:
print(f"\n Please open a new terminal and run: python3.10 install.py")
sys.exit(0)
else: # Linux — try multiple package managers in order
def _run_step(cmd: list) -> bool:
print(f" {DIM}▸ {' '.join(cmd)}{RESET}")
return subprocess.run(cmd).returncode == 0
installed = False
if shutil.which("apt-get") or shutil.which("apt"):
apt = shutil.which("apt-get") or shutil.which("apt")
print(f" Detected apt — installing Python 3.10 (sudo required)...\n")
# Step 1: try direct install first (works on Kali, Debian 12, Ubuntu 22.04+)
_run_step(["sudo", apt, "update", "-qq"])
ok = _run_step(["sudo", apt, "install", "-y", "python3.10", "python3.10-venv"])
if not ok:
# Step 2: add deadsnakes PPA (Ubuntu/Mint where direct install fails)
print(f"\n Direct install failed — trying deadsnakes PPA...\n")
_run_step(["sudo", apt, "install", "-y", "software-properties-common"])
_run_step(["sudo", "add-apt-repository", "-y", "ppa:deadsnakes/ppa"])
_run_step(["sudo", apt, "update", "-qq"])
ok = _run_step(["sudo", apt, "install", "-y", "python3.10", "python3.10-venv"])
if ok:
# python3.10-distutils was removed in Ubuntu 23.04+ — ignore failure
subprocess.run(["sudo", apt, "install", "-y", "python3.10-distutils"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
installed = True
elif shutil.which("dnf"):
print(f" Detected dnf (Fedora/RHEL) — installing Python 3.10 (sudo required)...\n")
installed = _run_step(["sudo", "dnf", "install", "-y", "python3.10"])
elif shutil.which("pacman"):
# Arch ships Python 3.11+ as 'python'; 3.10 available via AUR or python310 package
print(f" Detected pacman (Arch) — installing python3.10 (sudo required)...\n")
installed = _run_step(["sudo", "pacman", "-Sy", "--noconfirm", "python310"])
if not installed:
# Fallback: current python package (3.11+) is still compatible
installed = _run_step(["sudo", "pacman", "-Sy", "--noconfirm", "python"])
elif shutil.which("zypper"):
print(f" Detected zypper (openSUSE) — installing Python 3.10 (sudo required)...\n")
installed = _run_step(["sudo", "zypper", "install", "-y", "python310"])
if not installed:
print(f"\n {RED}✗{RESET} Could not install Python 3.10 automatically on this system.")
print(f"\n Please install Python 3.10 manually using pyenv (works on any distro):")
print(f" curl https://pyenv.run | bash")
print(f" pyenv install 3.10.17")
print(f" pyenv local 3.10.17")
print(f" python install.py")
sys.exit(1)
new_python = shutil.which("python3.10")
if new_python:
print(f"\n {GREEN}✓{RESET} {WHITE}Python 3.10 installed!{RESET}")
print(f"\n {ORANGE}▸{RESET} Re-launching installer with Python 3.10...\n")
os.execv(new_python, [new_python, __file__] + sys.argv[1:])
else:
print(f"\n {GREEN}✓{RESET} {WHITE}Python 3.10 installed!{RESET}")
print(f"\n Please open a new terminal and run: python3.10 install.py")
sys.exit(0)
_enable_windows_vtp()
_USE_COLOR = sys.stdout.isatty()
def _c(code: str) -> str:
return code if _USE_COLOR else ""
ORANGE = _c("\033[38;2;255;79;24m") # #FF4F18
WHITE = _c("\033[38;2;255;255;255m") # #FFFFFF
BOLD = _c("\033[1m")
DIM = _c("\033[38;2;80;80;80m") # dark gray for empty bar
GREEN = _c("\033[38;2;80;220;100m")
RED = _c("\033[91m")
RESET = _c("\033[0m")
# ==========================================
# PROGRESS BAR
# ==========================================
class ProgressBar:
"""Simple progress bar showing 0% to 100%."""
def __init__(self, total_steps: int = 10):
self.total_steps = max(1, total_steps)
self.current_step = 0
self.bar_length = 40
def update(self, step: int = None):
"""Update progress to step number."""
if step is not None:
self.current_step = min(step, self.total_steps - 1)
else:
self.current_step = min(self.current_step + 1, self.total_steps - 1)
self._draw_bar()
def _draw_bar(self):
"""Draw the progress bar."""
if self.total_steps > 0:
percent = int((self.current_step / self.total_steps) * 100)
else:
percent = 100
filled = int(self.bar_length * self.current_step / max(1, self.total_steps))
bar = '=' * filled + '-' * (self.bar_length - filled)
sys.stdout.write(f"\r[{bar}] {percent}%")
sys.stdout.flush()
def finish(self, message: str = "Complete"):
"""Finish with 100%."""
self.current_step = self.total_steps
bar = '=' * self.bar_length
sys.stdout.write(f"\r[{bar}] 100% - {message}\n")
sys.stdout.flush()
# ==========================================
# ANIMATED PROGRESS INDICATOR
# ==========================================
class AnimatedProgress:
"""Retro-style animated progress bar."""
def __init__(self, message: str = "Installing"):
self.message = message.upper()
self.percent = 0
self.bar_length = 40
def update(self, percent: int):
self.percent = min(percent, 100)
filled = int(self.bar_length * self.percent / 100)
bar = f"{ORANGE}{'▓' * filled}{DIM}{'░' * (self.bar_length - filled)}{RESET}"
pct = f"{self.percent}%".rjust(4)
sys.stdout.write(f"\r {WHITE}{self.message}{RESET} {bar} {ORANGE}[ {pct} ]{RESET}")
sys.stdout.flush()
def finish(self):
bar = f"{ORANGE}{'▓' * self.bar_length}{RESET}"
sys.stdout.write(f"\r {WHITE}{self.message}{RESET} {bar} {GREEN}[ 100% ]{RESET}\n")
sys.stdout.flush()
def run_command_with_progress(cmd_list: list[str], message: str = "Processing", cwd: Optional[str] = None, check: bool = True, capture: bool = False, env_extras: Dict[str, str] = None) -> subprocess.CompletedProcess:
"""Run command with animated progress bar."""
# Validate command
if not cmd_list or not isinstance(cmd_list, list) or len(cmd_list) == 0:
print(f"\n✗ Invalid command: {cmd_list}")
if check:
sys.exit(1)
return None
cmd_list = _wrap_windows_bat(cmd_list)
my_env = os.environ.copy()
if env_extras:
my_env.update(env_extras)
my_env["PYTHONUNBUFFERED"] = "1"
progress = AnimatedProgress(message)
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'text': True,
}
try:
# Start process
process = subprocess.Popen(cmd_list, cwd=cwd, env=my_env, **kwargs)
# Asymptotic progress: continuously moves, decelerates near 95%, never sticks
# Formula: pct = 95 * (1 - e^(-elapsed / tau))
# tau=45s → ~60% at 45s, ~86% at 90s, ~95% at ~135s
def update_progress():
start = time.time()
tau = 45.0
while process.poll() is None:
elapsed = time.time() - start
pct = int(95 * (1 - math.exp(-elapsed / tau)))
progress.update(pct)
time.sleep(0.5)
# Start progress thread
progress_thread = threading.Thread(target=update_progress, daemon=True)
progress_thread.start()
# Wait for process to finish
stdout, stderr = process.communicate()
# Complete progress
progress.finish()
if process.returncode != 0 and check:
print(f"\n✗ Error during installation:")
if stderr:
print(stderr[:500])
sys.exit(1)
return subprocess.CompletedProcess(cmd_list, process.returncode, stdout, stderr)
except FileNotFoundError as e:
exe_name = e.filename or cmd_list[0]
print(f"\n✗ Executable not found: {exe_name}")
print(f" Command: {' '.join(cmd_list)}")
print(f" Make sure this program is installed and in your PATH")
if check:
sys.exit(1)
return None
# ==========================================
# HELPER FUNCTIONS
# ==========================================
def _wrap_windows_bat(cmd_list: list[str]) -> list[str]:
if sys.platform != "win32":
return cmd_list
exe = shutil.which(cmd_list[0])
if exe and exe.lower().endswith((".bat", ".cmd")):
return ["cmd.exe", "/d", "/c", exe] + cmd_list[1:]
return cmd_list
# ==========================================
# DISK SPACE CHECKING (for Kali & other systems)
# ==========================================
def get_disk_space(path: str = ".") -> Tuple[float, float, float]:
"""
Get disk space info for a path (total, used, free in GB).
Returns: (total_gb, used_gb, free_gb)
Silent failure - returns (0, 0, 0) if unable to check
"""
try:
if sys.platform == "win32":
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceEx(ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes))
free_gb = free_bytes.value / (1024 ** 3)
# For Windows, we'll estimate total as free + a reasonable amount
total_gb = free_gb + 50 # Estimate
used_gb = 0
else:
# Unix/Linux/Mac
st = os.statvfs(path)
free_gb = (st.f_bavail * st.f_frsize) / (1024 ** 3)
total_gb = (st.f_blocks * st.f_frsize) / (1024 ** 3)
used_gb = ((st.f_blocks - st.f_bfree) * st.f_frsize) / (1024 ** 3)
return total_gb, used_gb, free_gb
except Exception:
# Silently fail - disk space check is not critical
return 0, 0, 0
def check_disk_space_for_installation(min_free_gb: float = 5.0) -> bool:
"""
Check if there's enough disk space for installation.
Returns True if OK, False if insufficient space.
"""
home_free_gb = get_disk_space(os.path.expanduser("~"))[2]
home_total_gb = get_disk_space(os.path.expanduser("~"))[0]
home_used_gb = get_disk_space(os.path.expanduser("~"))[1]
if home_total_gb == 0: # Couldn't get info
return True # Assume it's okay
percent_used = (home_used_gb / home_total_gb * 100) if home_total_gb > 0 else 0
print("\n" + "="*60)
print(" 📊 Disk Space Check")
print("="*60)
print(f"Home directory: {os.path.expanduser('~')}")
print(f"Total space: {home_total_gb:.1f} GB")
print(f"Used space: {home_used_gb:.1f} GB ({percent_used:.1f}%)")
print(f"Free space: {home_free_gb:.1f} GB")
if home_free_gb < min_free_gb:
print(f"\n⚠️ WARNING: Low disk space ({home_free_gb:.1f} GB free, need {min_free_gb:.1f} GB)")
print("\nRecommended fixes:")
print("\n1. Clean up pip cache:")
print(" pip cache purge")
print("\n2. Clean up npm cache (if Node.js installed):")
print(" npm cache clean --force")
print("\n3. Remove old files/packages:")
print(f" rm -rf ~/.cache/* # On Linux/Mac")
print(f" rmdir /s %LocalAppData%\\pip # On Windows")
print("\n4. Use a different disk with more space:")
mkdir_path = "/mnt/large-disk/pip-tmp" if sys.platform != "win32" else "D:/pip-tmp"
print(f" mkdir -p {mkdir_path}")
print(f" TMPDIR={mkdir_path} python install.py")
print(f"\n5. Or continue anyway (may fail): ", end="")
choice = input("Continue? (y/n): ").strip().lower()
if choice != 'y':
print("Installation cancelled. Please free up disk space and try again.")
return False
else:
print("\nAttempting installation anyway...\n")
print("="*60 + "\n")
return True
def suggest_cleanup_steps():
"""Show cleanup steps if disk is full."""
print("\n" + "="*60)
print(" 🧹 Disk Space Cleanup Guide (for Kali & other systems)")
print("="*60)
print("\nTo free up disk space:\n")
print("1. Clear pip cache (usually 1-5 GB):")
print(" pip cache purge\n")
print("2. Clear npm cache (if Node.js installed):")
print(" npm cache clean --force\n")
print("3. Clear system caches (Linux/Mac):")
print(" sudo apt-get clean # Apt packages")
print(" sudo pacman -Sc # Pacman packages")
print(" rm -rf ~/.cache/* # User cache\n")
print("4. Remove temporary files:")
print(" rm -rf /tmp/* # System temp (Linux/Mac)")
print(" rmdir /s /q %temp% # Windows temp\n")
print("5. Check what's using space:")
print(" du -sh ~/* # Home directory breakdown (Linux/Mac)")
print(" dir /-s C:\\ # Windows directory sizes\n")
print("6. Use alternate location with more space:")
print(" mkdir -p /mnt/external-drive/pip-tmp")
print(" TMPDIR=/mnt/external-drive/pip-tmp python install.py\n")
print("="*60 + "\n")
def load_config() -> Dict[str, Any]:
"""
Load configuration from file safely.
SECURITY FIX: Use try-except instead of check-then-use to prevent TOCTOU race conditions.
This ensures atomic read operation.
"""
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except FileNotFoundError:
# File doesn't exist - return empty config
return {}
except json.JSONDecodeError:
print(f"Warning: {CONFIG_FILE} is corrupted. Starting with empty config.")
return {}
except IOError as e:
print(f"Warning: Cannot read config: {e}")
return {}
def save_config_value(key: str, value: Any) -> None:
config = load_config()
config[key] = value
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
except IOError as e:
pass # Silently fail if config can't be saved
def run_command(cmd_list: list[str], cwd: Optional[str] = None, check: bool = True, capture: bool = False, env_extras: Dict[str, str] = None, quiet: bool = False, show_error: bool = True) -> subprocess.CompletedProcess:
# Validate command
if not cmd_list or not isinstance(cmd_list, list) or len(cmd_list) == 0:
if show_error:
print(f"\n✗ Invalid command: {cmd_list}")
if check:
sys.exit(1)
return None
cmd_list = _wrap_windows_bat(cmd_list)
my_env = os.environ.copy()
if env_extras:
my_env.update(env_extras)
my_env["PYTHONUNBUFFERED"] = "1"
kwargs = {}
if capture or quiet:
kwargs['capture_output'] = True
kwargs['text'] = True
else:
kwargs['stdout'] = subprocess.DEVNULL
kwargs['stderr'] = subprocess.DEVNULL
try:
result = subprocess.run(cmd_list, cwd=cwd, check=check, env=my_env, **kwargs)
return result
except subprocess.CalledProcessError as e:
if show_error:
if capture or quiet:
print(f"\n✗ Error running: {' '.join(cmd_list)}")
if e.stdout:
print(f"STDOUT: {e.stdout[:1000]}")
if e.stderr:
print(f"STDERR: {e.stderr[:1000]}")
else:
print(f"\n✗ Command failed: {' '.join(cmd_list)}")
if check:
sys.exit(1)
return e
except FileNotFoundError as e:
if show_error:
exe_name = e.filename or cmd_list[0]
print(f"\n✗ Executable not found: {exe_name}")
print(f" Command: {' '.join(cmd_list)}")
print(f" Make sure this program is installed and in your PATH")
if check:
sys.exit(1)
return None
# ==========================================
# ENVIRONMENT SETUP
# ==========================================
def is_conda_installed() -> Tuple[bool, str, Optional[str]]:
conda_exe = shutil.which("conda")
if conda_exe:
conda_base_path = os.path.dirname(os.path.dirname(conda_exe))
return True, f"Found at {conda_exe}", conda_base_path
if sys.platform == "win32":
# Check common Miniconda/Anaconda installation paths
common_paths = [
os.path.join(os.path.expanduser("~"), "miniconda3"),
os.path.join(os.path.expanduser("~"), "Miniconda3"),
os.path.join(os.path.expanduser("~"), "anaconda3"),
os.path.join(os.path.expanduser("~"), "Anaconda3"),
"C:\\miniconda3",
"C:\\Miniconda3",
"C:\\anaconda3",
"C:\\Anaconda3",
]
for base_path in common_paths:
conda_bat = os.path.join(base_path, "condabin", "conda.bat")
if os.path.exists(conda_bat):
return True, f"Found at {base_path}", base_path
# Also check current Python directory
current_python_dir = os.path.dirname(sys.executable)
potential_base_paths = [
os.path.dirname(current_python_dir),
os.path.dirname(os.path.dirname(current_python_dir))
]
for base_path in potential_base_paths:
activate_bat = os.path.join(base_path, "Scripts", "activate.bat")
condabin_bat = os.path.join(base_path, "condabin", "conda.bat")
if os.path.exists(activate_bat) or os.path.exists(condabin_bat):
return True, f"Found at {base_path}", base_path
return False, "Not found", None
def get_env_name_from_yml(yml_path: str = YML_FILE) -> str:
try:
with open(yml_path, 'r') as f:
for line in f:
stripped = line.strip()
if stripped.startswith("name:"):
return stripped.split(":", 1)[1].strip().strip("'").strip('"')
except FileNotFoundError:
print(f"Error: {yml_path} not found.")
sys.exit(1)
print(f"Error: Could not find 'name:' in {yml_path}.")
sys.exit(1)
def install_miniconda():
"""Auto-install Miniconda for the current platform."""
import urllib.request
import subprocess as sp
print("\n🔧 Auto-installing Miniconda...\n")
# Detect OS and architecture
if sys.platform == "win32":
# Windows
if sys.maxsize > 2**32:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe"
installer = os.path.join(BASE_DIR, "Miniconda-installer.exe")
else:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86.exe"
installer = os.path.join(BASE_DIR, "Miniconda-installer.exe")
elif sys.platform == "linux":
# Linux
if sys.maxsize > 2**32:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh"
else:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86.sh"
installer = os.path.join(BASE_DIR, "miniconda-installer.sh")
elif sys.platform == "darwin":
# macOS
if sys.maxsize > 2**32:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh"
else:
url = "https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh"
installer = os.path.join(BASE_DIR, "miniconda-installer.sh")
else:
print(f"❌ Unsupported platform: {sys.platform}")
return False
try:
print(f"📥 Downloading Miniconda ({os.path.basename(url)})...")
urllib.request.urlretrieve(url, installer)
print(f"✓ Downloaded to {installer}\n")
if sys.platform == "win32":
print("🔧 Running Miniconda installer...")
print(" An installation dialog will appear. Select:")
print(" - Add Miniconda to PATH (important!)")
print(" - Install for current user\n")
sp.run([installer], check=True)
print("\n✓ Miniconda installed!")
print(" Please restart your terminal and run the installation again.\n")
os.remove(installer)
return True
else:
print("🔧 Running Miniconda installer...")
sp.run(["bash", installer, "-b", "-p", os.path.expanduser("~/miniconda3")], check=True)
print("✓ Miniconda installed!")
print(" Please add conda to PATH, then restart terminal and run installation again.\n")
os.remove(installer)
return True
except Exception as e:
print(f"❌ Miniconda installation failed: {e}")
if os.path.exists(installer):
try:
os.remove(installer)
except:
pass
return False
def get_conda_command() -> str:
"""Return conda command. Use full path on Windows if conda not in PATH."""
# Mamba can have compatibility issues, so use conda by default
# Users can pass --mamba flag if they want to use mamba
if "--mamba" in sys.argv:
if shutil.which("mamba"):
return "mamba"
# First try to find conda in PATH
conda_exe = shutil.which("conda")
if conda_exe:
return conda_exe
# On Windows, check common installation paths
if sys.platform == "win32":
common_paths = [
os.path.join(os.path.expanduser("~"), "miniconda3"),
os.path.join(os.path.expanduser("~"), "Miniconda3"),
os.path.join(os.path.expanduser("~"), "anaconda3"),
os.path.join(os.path.expanduser("~"), "Anaconda3"),
"C:\\miniconda3",
"C:\\Miniconda3",
"C:\\anaconda3",
"C:\\Anaconda3",
]
for base_path in common_paths:
conda_bat = os.path.join(base_path, "condabin", "conda.bat")
if os.path.exists(conda_bat):
return conda_bat
# Fallback to just "conda" (will work if it's in PATH)
return "conda"
def setup_conda_environment(env_name: str, yml_path: str = YML_FILE):
conda_cmd = get_conda_command()
try:
print(f"🔧 Setting up conda environment '{env_name}'...")
result = run_command_with_progress([conda_cmd, "env", "update", "-f", yml_path, "-n", env_name], "Installing dependencies via conda", check=False)
if result and hasattr(result, 'returncode') and result.returncode == 0:
print("✓ Conda environment ready")
else:
print("\n✗ Failed to set up conda environment")
if result and hasattr(result, 'stderr'):
print(result.stderr[:500])
sys.exit(1)
except Exception as e:
print(f"\n✗ Error setting up conda environment: {e}")
sys.exit(1)
def verify_conda_env(env_name: str) -> bool:
try:
conda_cmd = get_conda_command()
verification_cmd = [conda_cmd, "run", "-n", env_name, "python", "-c", "print('OK')"]
result = run_command(verification_cmd, capture=True, quiet=True, check=False, show_error=False)
return result and hasattr(result, 'returncode') and result.returncode == 0
except Exception as e:
return False
def install_nodejs_linux():
"""
Automatically install Node.js on Linux/macOS systems (including Kali).
Detects the package manager (brew, apt, pacman, yum) and installs accordingly.
"""
if sys.platform == "win32":
return True # Windows users should install Node.js manually from nodejs.org
# Check if node is already installed
if shutil.which("node") and shutil.which("npm"):
print("✓ Node.js and npm are already installed")
return True
print("\n🔧 Installing Node.js...")
# macOS: try Homebrew first, then nvm
if sys.platform == "darwin":
if shutil.which("brew"):
print(" Found Homebrew, installing Node.js...")
try:
result = run_command(["brew", "install", "node"], check=False, capture=True, quiet=True, show_error=False)
if result and hasattr(result, 'returncode') and result.returncode == 0:
print("✓ Node.js installed via Homebrew")
time.sleep(1)
if shutil.which("node") and shutil.which("npm"):
return True
print("⚠ Node.js installed but not yet in PATH. Restart your terminal.")
return False
except Exception as e:
print(f" ⚠ brew install node failed: {str(e)[:100]}")
print("\n⚠ Could not automatically install Node.js on macOS")
print("\nOptions:")
print(" 1. Install Homebrew (https://brew.sh), then run: brew install node")
print(" 2. Download Node.js from: https://nodejs.org/ (LTS version)")
print(" 3. Use nvm: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash")
print(" then: nvm install --lts")
print("\n After installation, restart your terminal and run: python3 install.py")
return False
# Detect package manager and prepare install commands
# Format: (package_manager, update_cmd, install_cmd)
package_managers = [
("apt-get", ["sudo", "apt-get", "update"], ["sudo", "apt-get", "install", "-y", "nodejs", "npm"]),
("apt", ["sudo", "apt", "update"], ["sudo", "apt", "install", "-y", "nodejs", "npm"]),
("dnf", None, ["sudo", "dnf", "install", "-y", "nodejs", "npm"]),
("yum", None, ["sudo", "yum", "install", "-y", "nodejs", "npm"]),
("pacman", None, ["sudo", "pacman", "-Sy", "nodejs", "npm"]),
("zypper", None, ["sudo", "zypper", "install", "-y", "nodejs", "npm"]),
]
installed = False
for pm_name, update_cmd, install_cmd in package_managers:
if shutil.which(pm_name.split()[0]):
print(f" Found {pm_name}, installing Node.js...")
try:
# Run update command if available
if update_cmd:
update_result = run_command(update_cmd, check=False, capture=True, quiet=True, show_error=False)
if update_result and hasattr(update_result, 'returncode') and update_result.returncode != 0:
print(f" ⚠ Package manager update failed, continuing anyway...")
# Run install command
install_result = run_command(install_cmd, check=False, capture=True, quiet=True, show_error=False)
if install_result and hasattr(install_result, 'returncode') and install_result.returncode == 0:
print("✓ Node.js installed successfully")
installed = True
break
else:
print(f" ⚠ {pm_name} installation failed, trying next...")
except Exception as e:
print(f" ⚠ Error with {pm_name}: {str(e)[:100]}, trying next...")
if not installed:
print("\n⚠ Could not automatically install Node.js")
print("\nOptions:")
print(" 1. Enter sudo password when prompted")
print(" 2. Manual installation via NodeSource (Debian/Ubuntu/Kali):")
print(" curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -")
print(" sudo apt-get install -y nodejs")
print("\n 3. Install from official website: https://nodejs.org/ (LTS version)")
print("\n 4. After installation, run: python install.py")
return False
# Verify installation (with small delay)
time.sleep(1)
if shutil.which("node") and shutil.which("npm"):
try:
node_version = run_command([shutil.which("node"), "--version"], capture=True, quiet=True, show_error=False)
npm_version = run_command([shutil.which("npm"), "--version"], capture=True, quiet=True, show_error=False)
if node_version and hasattr(node_version, 'stdout'):
print(f" Node.js {node_version.stdout.strip()}")
if npm_version and hasattr(npm_version, 'stdout'):
print(f" npm {npm_version.stdout.strip()}")
except:
pass
return True
else:
print("⚠ Node.js verification failed - it may not be in PATH")
print(" Please restart your terminal and verify: node --version")
return False
def install_playwright_browser(use_conda: bool = False):
"""Install Playwright Chromium browser for WhatsApp Web support."""
print("\nInstalling Playwright Chromium browser...")
try:
if use_conda:
conda_cmd = get_conda_command()
env_name = get_env_name_from_yml()
result = run_command([conda_cmd, "run", "-n", env_name, "python", "-m", "playwright", "install", "chromium"], check=False, capture=True, show_error=False)
else:
result = run_command([sys.executable, "-m", "playwright", "install", "chromium"], check=False, capture=True, show_error=False)
if result and hasattr(result, 'returncode') and result.returncode == 0:
print("✓ Playwright Chromium installed")
return True