Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
1346 lines (1188 loc) · 49 KB
/
Copy pathinstall.py
File metadata and controls
1346 lines (1188 loc) · 49 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 the terminal edition instead, run: python run.py --tui
"""
from __future__ import annotations
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
# Single interpreter for every CraftBot process — see app/python_runtime.py,
# and the single resolved Node runtime — see app/node_runtime.py (both are
# stdlib-only; app/__init__.py is empty, so safe before any deps exist).
from app import python_runtime
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 _force_utf8_stdio() -> None:
"""Make stdout/stderr able to carry the glyphs this script prints.
A Windows console defaults to cp1252, which cannot encode ✓ ⚠ ▓ ░ — and
a bare `print` of one raises UnicodeEncodeError. That is not cosmetic: it
killed the installer mid-run while printing its OWN Python-version
warning, so the user saw a traceback instead of the advice.
Runs before anything prints. errors="replace" is the backstop for streams
that cannot be reconfigured at all (a pipe with a fixed encoding).
"""
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, ValueError, OSError):
pass
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
_force_utf8_stdio()
_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("\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(" 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 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", encoding="utf-8") 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", encoding="utf-8") as f:
json.dump(config, f, indent=4)
except IOError:
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(" 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") or _conda_in_known_homes()
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", encoding="utf-8") 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)
#: Where a conda distribution is normally installed, newest-preferred.
_CONDA_HOMES = (
"miniforge3",
"Miniforge3",
"miniconda3",
"Miniconda3",
"anaconda3",
"Anaconda3",
)
def _conda_in_known_homes() -> Optional[str]:
"""conda's executable in a standard install folder, on any OS."""
roots = [os.path.expanduser("~")]
if sys.platform == "win32":
roots += ["C:\\", os.environ.get("PROGRAMDATA", "C:\\ProgramData")]
for root in roots:
for home in _CONDA_HOMES:
if sys.platform == "win32":
candidate = os.path.join(root, home, "condabin", "conda.bat")
else:
candidate = os.path.join(root, home, "bin", "conda")
if os.path.isfile(candidate):
return candidate
return None
def install_miniconda():
"""Install Miniforge (conda-forge's distribution) for this platform.
Miniforge rather than Miniconda: Miniconda's defaults channel now refuses
to work until Anaconda's Terms of Service are accepted interactively,
which an unattended install cannot do, and environment.yml only uses
conda-forge anyway. Installed per user, no admin rights needed.
"""
import platform
import subprocess as sp
import urllib.request
machine = platform.machine().lower()
arch = {
"amd64": "x86_64",
"x86_64": "x86_64",
"arm64": "arm64",
"aarch64": "aarch64",
}.get(machine)
if sys.platform == "darwin" and arch == "aarch64":
arch = "arm64"
if sys.platform == "linux" and arch == "arm64":
arch = "aarch64"
system = {"win32": "Windows", "linux": "Linux", "darwin": "MacOSX"}.get(
sys.platform
)
if not arch or not system or (system == "Windows" and arch != "x86_64"):
print(f"Conda auto-install is not available for {sys.platform}/{machine}.")
print("Install Miniforge from https://conda-forge.org/download/ and run again.")
return False
ext = "exe" if system == "Windows" else "sh"
url = (
"https://github.com/conda-forge/miniforge/releases/latest/download/"
f"Miniforge3-{system}-{arch}.{ext}"
)
installer = os.path.join(BASE_DIR, f"Miniforge3-installer.{ext}")
target = os.path.join(os.path.expanduser("~"), "miniforge3")
try:
print(f"Downloading Miniforge ({os.path.basename(url)})...")
urllib.request.urlretrieve(url, installer)
print("Installing Miniforge for the current user...")
if system == "Windows":
sp.run(
[
installer,
"/InstallationType=JustMe",
"/RegisterPython=0",
"/S",
f"/D={target}",
],
check=True,
)
else:
sp.run(["bash", installer, "-b", "-p", target], check=True)
print(f"Miniforge installed at {target}")
return True
except Exception as e:
print(f"Miniforge installation failed: {e}")
return False
finally:
try:
os.remove(installer)
except OSError:
pass
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, then its standard install folders.
conda_exe = shutil.which("conda") or _conda_in_known_homes()
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:
return False
def ensure_native_runtime() -> None:
"""OS prerequisites for the native wheels (torch, onnxruntime, ...).
The implementation lives in app.provision.verify so the installer shares
it. It used to live here, which meant an installer-based machine never
ran it and died at first boot with WinError 126 on torch_python.dll —
exactly the failure this function was written to prevent.
"""
from app.provision.verify import ensure_native_runtime as _ensure
_ensure(log=print)
def setup_omniparser(force_cpu: bool, use_conda: bool):
"""Install OmniParser for GUI mode support."""
if not shutil.which("git"):
print("Error: 'git' is required to install GUI components.")
print("Please install git: https://git-scm.com/downloads")
sys.exit(1)
# Get repo path from config or use default
config = load_config()
repo_path = config.get("omniparser_repo_path")
if not repo_path:
repo_path = os.path.abspath("OmniParser_CraftOS")
save_config_value("omniparser_repo_path", repo_path)
else:
repo_path = os.path.abspath(repo_path)
def run_omni_cmd(
cmd_list: list[str],
work_dir: str = repo_path,
capture_output: bool = False,
env_extras: Dict[str, str] = None,
):
"""Execute command in OmniParser environment (conda or direct pip)."""
if use_conda:
conda_cmd = get_conda_command()
full_cmd = [conda_cmd, "run", "-n", OMNIPARSER_ENV_NAME] + cmd_list
else:
full_cmd = cmd_list
# Setup environment with TMPDIR for pip cache management
local_env = env_extras.copy() if env_extras else {}
tmp_dir = os.path.expanduser("~/pip-tmp")
local_env["TMPDIR"] = tmp_dir
os.makedirs(tmp_dir, exist_ok=True)
run_command(
full_cmd,
cwd=work_dir,
capture=capture_output,
env_extras=local_env,
quiet=capture_output,
)
# Step 1: Repository setup
try:
print("🔧 Setting up OmniParser repository...")
if os.path.exists(repo_path):
run_command(["git", "-C", repo_path, "pull"], quiet=True, check=False)
else:
run_command(
[
"git",
"clone",
"-b",
OMNIPARSER_BRANCH,
OMNIPARSER_REPO_URL,
repo_path,
],
quiet=False,
show_error=True,
)
except Exception as e:
print(f"✗ Error setting up repository: {e}")
sys.exit(1)
# Check marker file
marker_path = os.path.join(repo_path, OMNIPARSER_MARKER_FILE)
if not os.path.exists(marker_path):
# Step 2: Create environment (only if using conda)
if use_conda:
conda_cmd = get_conda_command()
print("🔧 Creating conda environment...")
result = run_command(
[conda_cmd, "create", "-n", OMNIPARSER_ENV_NAME, "python=3.10", "-y"],
capture=True,
check=False,
)
if result.returncode != 0:
print("\n✗ Error creating conda environment 'omni'")
sys.exit(1)
print("🔧 Upgrading pip...")
run_omni_cmd(["pip", "install", "--upgrade", "pip"])
# Step 3: Install PyTorch
print("🔧 Installing PyTorch...")
pytorch_installed = False
if use_conda:
conda_cmd = get_conda_command()
if force_cpu:
print(" (CPU-only mode)")
result = run_command(
[
conda_cmd,
"run",
"-n",
OMNIPARSER_ENV_NAME,
"conda",
"install",
"pytorch",
"torchvision",
"torchaudio",
"cpuonly",
"-c",
"pytorch",
"-y",
],
capture=True,
check=False,
)
pytorch_installed = result.returncode == 0
else:
# Try GPU version first
print(" (Attempting CUDA 12.1 GPU version)")
result = run_command(
[
conda_cmd,
"run",
"-n",
OMNIPARSER_ENV_NAME,
"conda",
"install",
"pytorch",
"torchvision",
"torchaudio",
"pytorch-cuda=12.1",
"-c",
"pytorch",
"-c",
"nvidia",
"-y",
],
capture=True,
check=False,
)
if result.returncode != 0:
print(" ⚠ GPU version failed. Falling back to CPU-only mode...")
result = run_command(
[
conda_cmd,
"run",
"-n",
OMNIPARSER_ENV_NAME,
"conda",
"install",
"pytorch",
"torchvision",
"torchaudio",
"cpuonly",
"-c",
"pytorch",
"-y",
],
capture=True,
check=False,
)
pytorch_installed = result.returncode == 0
if pytorch_installed:
print(" ✓ CPU-only PyTorch installed successfully")
else:
pytorch_installed = True
else:
# Use pip for non-conda installation
if force_cpu:
print(" (CPU-only mode)")
result = run_command(
["pip", "install", "torch", "torchvision", "torchaudio"],
capture=True,
check=False,
env_extras={"TMPDIR": os.path.expanduser("~/pip-tmp")},
)
pytorch_installed = result.returncode == 0
else:
# Try GPU version first
print(" (Attempting CUDA 12.1 GPU version)")
result = run_command(
[
"pip",
"install",
"torch",
"torchvision",
"torchaudio",
"torch-cuda==12.1",
],
capture=True,
check=False,
env_extras={"TMPDIR": os.path.expanduser("~/pip-tmp")},
)
if result.returncode != 0:
print(" ⚠ GPU version failed. Falling back to CPU-only mode...")
result = run_command(
["pip", "install", "torch", "torchvision", "torchaudio"],
capture=True,
check=False,
env_extras={"TMPDIR": os.path.expanduser("~/pip-tmp")},
)
pytorch_installed = result.returncode == 0
if pytorch_installed:
print(" ✓ CPU-only PyTorch installed successfully")
else:
pytorch_installed = True
if not pytorch_installed:
print("\n✗ Error installing PyTorch")
if hasattr(result, "stderr") and result.stderr:
error_msg = result.stderr[:500]
print(f"\n Error details:\n {error_msg}")
# Check for specific errors
if (
"no space left on device" in error_msg.lower()
or "disk" in error_msg.lower()
):
print("\n⚠️ DISK SPACE ERROR detected")
print(" PyTorch is very large (~5GB+). Your disk may be full.")
print("\n Solutions:")
print(" 1. Clear pip cache: pip cache purge")
print(" 2. Clear npm cache: npm cache clean --force")
print(
" 3. Use alternate disk: TMPDIR=/mnt/large-disk/pip-tmp python install.py --gui"
)
print(
" 4. Use conda (more efficient): python install.py --gui --conda"
)
elif (
"externally-managed-environment" in error_msg
or "externally managed" in error_msg
):
print("\n⚠️ PEP 668 Error: System-managed Python detected")
print(" Use virtual environment or conda for GUI mode")
elif "cuda" in error_msg.lower() or "gpu" in error_msg.lower():
print("\n⚠️ CUDA/GPU Error detected")
print(" Try CPU-only: python install.py --gui --cpu-only")
print(" Or with conda: python install.py --gui --conda")
print("\n⚠️ Troubleshooting:")
print(
" 1. Check disk space: "
+ ("df -h" if sys.platform != "win32" else "dir C:\\")
)
print(" 2. Clear pip cache: pip cache purge")
print(
" 3. Try clearing system caches: "
+ ("sudo apt-get clean" if sys.platform != "win32" else "Disk Cleanup")
)
print(
" 4. Try again with CPU-only mode: python install.py --gui --cpu-only"
)
print(" 5. Use conda (recommended): python install.py --gui --conda")
print(
" 6. Check PyTorch documentation: https://pytorch.org/get-started/locally/"
)
sys.exit(1)
# Step 4: Install dependencies
print("🔧 Installing dependencies...")
deps = [
"mkl==2024.0",
"sympy==1.13.1",
"transformers==4.51.0",
"huggingface_hub[cli]",
"hf_transfer",
]
tmp_dir = os.path.expanduser("~/pip-tmp")
os.makedirs(tmp_dir, exist_ok=True)
if use_conda:
conda_cmd = get_conda_command()
result = run_command(
[conda_cmd, "run", "-n", OMNIPARSER_ENV_NAME, "pip", "install"] + deps,
capture=True,
check=False,
env_extras={"TMPDIR": tmp_dir},
)
else:
result = run_command(
["pip", "install"] + deps,
capture=True,
check=False,
env_extras={"TMPDIR": tmp_dir},
)
if result.returncode != 0:
print("⚠ Warning: Some dependencies may have failed to install")
if (
hasattr(result, "stderr")
and result.stderr
and "externally-managed" not in result.stderr
):
error_snippet = result.stderr[:200].strip()
if error_snippet:
print(f" Details: {error_snippet}")
req_txt = os.path.join(repo_path, "requirements.txt")
if os.path.exists(req_txt):
if use_conda:
conda_cmd = get_conda_command()
result = run_command(
[
conda_cmd,
"run",
"-n",
OMNIPARSER_ENV_NAME,
"pip",
"install",
"-r",
"requirements.txt",
],
cwd=repo_path,
capture=True,
check=False,
env_extras={"TMPDIR": tmp_dir},
)
else:
result = run_command(
["pip", "install", "-r", "requirements.txt"],
cwd=repo_path,
capture=True,
check=False,
env_extras={"TMPDIR": tmp_dir},
)
if result.returncode != 0:
print("⚠ Warning: Some requirements may have failed to install")
# Create marker
with open(marker_path, "w") as f:
f.write(f"Installed on {time.ctime()}\n")
else:
print("🔧 Environment already set up, skipping setup steps...")
# Step 5: Download model weights
print("🔧 Downloading model weights (this may take a while)...")
files_to_download = [
{
"file": "icon_detect/train_args.yaml",
"local_path": "icon_detect/train_args.yaml",
},
{"file": "icon_detect/model.pt", "local_path": "icon_detect/model.pt"},
{"file": "icon_detect/model.yaml", "local_path": "icon_detect/model.yaml"},
{
"file": "icon_caption/config.json",
"local_path": "icon_caption_florence/config.json",
},
{
"file": "icon_caption/generation_config.json",
"local_path": "icon_caption_florence/generation_config.json",
},
{
"file": "icon_caption/model.safetensors",
"local_path": "icon_caption_florence/model.safetensors",
},
]
weights_dir = os.path.join(repo_path, "weights")
os.makedirs(os.path.join(weights_dir, "icon_detect"), exist_ok=True)
os.makedirs(os.path.join(weights_dir, "icon_caption_florence"), exist_ok=True)
hf_env = {"HF_HUB_ENABLE_HF_TRANSFER": "1"}
failed_downloads = []
for i, file_info in enumerate(files_to_download, 1):
local_dest = os.path.join(weights_dir, file_info["local_path"])
if not os.path.exists(local_dest):
print(
f" 📦 ({i}/{len(files_to_download)}) Downloading: {file_info['local_path']}..."
)
if use_conda:
conda_cmd = get_conda_command()
result = run_command(
[
conda_cmd,
"run",
"-n",
OMNIPARSER_ENV_NAME,
"hf",
"download",
"microsoft/OmniParser-v2.0",
file_info["file"],
"--local-dir",
"weights",
],
cwd=repo_path,
capture=True,
check=False,
env_extras=hf_env,
)
else:
result = run_command(
[
"hf",
"download",
"microsoft/OmniParser-v2.0",
file_info["file"],
"--local-dir",
"weights",
],
cwd=repo_path,
capture=True,