Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
844 lines (685 loc) · 29.6 KB
/
Copy pathsetup.py
File metadata and controls
844 lines (685 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NL-Shell V0.3: Professional Setup Wizard
Complete installation system with Ollama detection and guided setup.
Features:
- Full system scan for Ollama
- Guided Ollama installation
- Automatic llama3.2 model download
- Application installation to Program Files
- Desktop & Start Menu shortcuts
- Uninstaller creation
"""
import os
import sys
import shutil
import subprocess
import time
import json
import winreg
from pathlib import Path
from typing import Optional, Tuple, List
import urllib.request
import tempfile
# Application metadata
APP_NAME = "NL-Shell"
APP_VERSION = "0.3.0"
APP_PUBLISHER = "NL-Shell Project"
APP_DESCRIPTION = "Natural Language Operating System Shell"
OLLAMA_DOWNLOAD_URL = "https://ollama.ai/download/OllamaSetup.exe"
REQUIRED_MODEL = "llama3.2:3b"
class Colors:
"""ANSI color codes for terminal output"""
RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
def print_banner():
"""Display setup banner"""
banner = f"""
{Colors.CYAN}╔══════════════════════════════════════════════════════════════╗
║ ║
║ ███╗ ██╗██╗ ███████╗██╗ ██╗███████╗██╗ ██╗ ║
║ ████╗ ██║██║ ██╔════╝██║ ██║██╔════╝██║ ██║ ║
║ ██╔██╗ ██║██║█████╗███████╗███████║█████╗ ██║ ██║ ║
║ ██║╚██╗██║██║╚════╝╚════██║██╔══██║██╔══╝ ██║ ██║ ║
║ ██║ ╚████║███████╗ ███████║██║ ██║███████╗███████╗███████╗
║ ╚═╝ ╚═══╝╚══════╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝
║ ║
║ {Colors.BOLD}SETUP WIZARD - Version {APP_VERSION}{Colors.CYAN} ║
╚══════════════════════════════════════════════════════════════╝{Colors.RESET}
"""
print(banner)
def print_step(step: int, total: int, message: str):
"""Print step indicator"""
print(f"\n{Colors.BLUE}[{step}/{total}]{Colors.RESET} {Colors.BOLD}{message}{Colors.RESET}")
def print_success(message: str):
print(f" {Colors.GREEN}✓{Colors.RESET} {message}")
def print_error(message: str):
print(f" {Colors.RED}✗{Colors.RESET} {message}")
def print_warning(message: str):
print(f" {Colors.YELLOW}⚠{Colors.RESET} {message}")
def print_info(message: str):
print(f" {Colors.CYAN}ℹ{Colors.RESET} {message}")
def get_user_choice(prompt: str, options: List[str]) -> int:
"""Get user choice from numbered options"""
print(f"\n{prompt}")
for i, option in enumerate(options, 1):
print(f" {Colors.CYAN}{i}{Colors.RESET}) {option}")
while True:
try:
choice = input(f"\nEnter choice (1-{len(options)}): ").strip()
num = int(choice)
if 1 <= num <= len(options):
return num
except ValueError:
pass
print(f" {Colors.RED}Invalid choice. Please enter 1-{len(options)}{Colors.RESET}")
def confirm(prompt: str, default: bool = True) -> bool:
"""Get yes/no confirmation"""
suffix = " (Y/n): " if default else " (y/N): "
response = input(prompt + suffix).strip().lower()
if not response:
return default
return response in ['y', 'yes']
# ============================================================================
# DEPENDENCY CHECKER & INSTALLER
# ============================================================================
class DependencyChecker:
"""Checks and installs Python dependencies"""
REQUIRED_PACKAGES = [
('rich', 'rich'), # (import_name, pip_name)
('requests', 'requests'),
]
def __init__(self):
self.missing = []
self.installed = []
def check_dependencies(self) -> Tuple[List[str], List[str]]:
"""
Check which dependencies are installed.
Returns:
Tuple of (installed, missing) package lists
"""
self.installed = []
self.missing = []
for import_name, pip_name in self.REQUIRED_PACKAGES:
try:
__import__(import_name)
self.installed.append(pip_name)
print_success(f"{pip_name} - installed")
except ImportError:
self.missing.append(pip_name)
print_error(f"{pip_name} - NOT FOUND")
return self.installed, self.missing
def install_missing(self) -> bool:
"""
Install missing dependencies using pip.
Returns:
True if all packages installed successfully
"""
if not self.missing:
return True
print(f"\n{Colors.BOLD}Missing Dependencies:{Colors.RESET}")
for pkg in self.missing:
print(f" • {pkg}")
print(f"\nThese packages are required for NL-Shell to work.")
if not confirm("Install missing packages now?"):
print_warning("Skipping dependency installation.")
print_info("Install manually with: pip install " + " ".join(self.missing))
return False
print_info("Installing dependencies...")
try:
# Use the same Python that's running this script
python_exe = sys.executable
for pkg in self.missing:
print_info(f"Installing {pkg}...")
result = subprocess.run(
[python_exe, '-m', 'pip', 'install', pkg],
capture_output=True,
text=True
)
if result.returncode == 0:
print_success(f"{pkg} installed successfully")
else:
print_error(f"Failed to install {pkg}")
print_info(f"Error: {result.stderr}")
return False
print_success("All dependencies installed!")
return True
except Exception as e:
print_error(f"Installation error: {e}")
return False
def check_python_version(self) -> bool:
"""Check if Python version is compatible"""
if sys.version_info < (3, 8):
print_error(f"Python 3.8+ required. Found: {sys.version}")
return False
print_success(f"Python {sys.version_info.major}.{sys.version_info.minor}")
return True
# ============================================================================
# OLLAMA DETECTION & INSTALLATION
# ============================================================================
class OllamaInstaller:
"""Handles Ollama detection and installation"""
COMMON_PATHS = [
Path(os.environ.get('LOCALAPPDATA', '')) / 'Programs' / 'Ollama',
Path(os.environ.get('PROGRAMFILES', '')) / 'Ollama',
Path(os.environ.get('PROGRAMFILES(X86)', '')) / 'Ollama',
Path.home() / 'AppData' / 'Local' / 'Programs' / 'Ollama',
]
def __init__(self):
self.ollama_path: Optional[Path] = None
self.ollama_running = False
def find_ollama(self) -> Tuple[bool, Optional[Path]]:
"""
Search entire system for Ollama installation.
Returns:
Tuple of (found, path)
"""
print_info("Searching for Ollama installation...")
# Check PATH first
ollama_in_path = shutil.which('ollama')
if ollama_in_path:
path = Path(ollama_in_path)
print_success(f"Found in PATH: {path}")
self.ollama_path = path
return True, path
# Check common installation locations
for common_path in self.COMMON_PATHS:
exe_path = common_path / 'ollama.exe'
if exe_path.exists():
print_success(f"Found at: {exe_path}")
self.ollama_path = exe_path
return True, exe_path
# Deep search in Program Files
print_info("Performing deep search (this may take a moment)...")
search_roots = [
Path(os.environ.get('PROGRAMFILES', 'C:/Program Files')),
Path(os.environ.get('PROGRAMFILES(X86)', 'C:/Program Files (x86)')),
Path(os.environ.get('LOCALAPPDATA', '')),
]
for root in search_roots:
if not root.exists():
continue
try:
for path in root.rglob('ollama.exe'):
print_success(f"Found at: {path}")
self.ollama_path = path
return True, path
except PermissionError:
continue
print_warning("Ollama not found on this system")
return False, None
def is_running(self) -> bool:
"""Check if Ollama service is running"""
try:
import urllib.request
req = urllib.request.urlopen("http://localhost:11434/api/tags", timeout=2)
self.ollama_running = req.status == 200
return self.ollama_running
except:
return False
def start_service(self) -> bool:
"""Start Ollama service"""
if not self.ollama_path:
return False
try:
# Start ollama serve in background
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0 # SW_HIDE
subprocess.Popen(
[str(self.ollama_path), 'serve'],
startupinfo=startupinfo,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
# Wait for service to start
for _ in range(30):
time.sleep(1)
if self.is_running():
return True
return False
except Exception as e:
print_error(f"Failed to start: {e}")
return False
def get_models(self) -> List[str]:
"""Get list of installed models"""
if not self.is_running():
return []
try:
import urllib.request
import json
req = urllib.request.urlopen("http://localhost:11434/api/tags", timeout=5)
data = json.loads(req.read().decode())
return [m['name'] for m in data.get('models', [])]
except:
return []
def has_required_model(self) -> bool:
"""Check if required model is installed"""
models = self.get_models()
for model in models:
if model.startswith(REQUIRED_MODEL.split(':')[0]):
return True
return False
def download_ollama_installer(self) -> Optional[Path]:
"""Download Ollama installer"""
print_info(f"Downloading Ollama from {OLLAMA_DOWNLOAD_URL}...")
try:
temp_dir = Path(tempfile.gettempdir())
installer_path = temp_dir / "OllamaSetup.exe"
# Download with progress
def report_progress(block_num, block_size, total_size):
downloaded = block_num * block_size
if total_size > 0:
percent = min(100, downloaded * 100 // total_size)
bar = '█' * (percent // 5) + '░' * (20 - percent // 5)
print(f"\r [{bar}] {percent}%", end='', flush=True)
urllib.request.urlretrieve(OLLAMA_DOWNLOAD_URL, installer_path, report_progress)
print() # New line after progress bar
print_success(f"Downloaded to: {installer_path}")
return installer_path
except Exception as e:
print_error(f"Download failed: {e}")
return None
def install_ollama(self) -> bool:
"""Guide user through Ollama installation"""
print("\n" + "="*60)
print(f"{Colors.BOLD}Ollama Installation Required{Colors.RESET}")
print("="*60)
print("""
NL-Shell requires Ollama to run AI models locally.
Ollama is free and runs entirely on your computer.
""")
choice = get_user_choice("How would you like to proceed?", [
"Download and install Ollama automatically",
"Open Ollama website to download manually",
"Skip (I'll install Ollama later)"
])
if choice == 1:
# Automatic download and install
installer = self.download_ollama_installer()
if installer:
print_info("Launching Ollama installer...")
print_info("Please follow the installation wizard.")
print_warning("Setup will continue after Ollama is installed.")
try:
subprocess.run([str(installer)], check=True)
print_success("Ollama installer completed")
# Re-check for Ollama
time.sleep(2)
found, _ = self.find_ollama()
return found
except Exception as e:
print_error(f"Installation failed: {e}")
return False
return False
elif choice == 2:
# Open website
print_info("Opening https://ollama.ai in your browser...")
try:
os.startfile("https://ollama.ai")
except:
print_info("Please visit: https://ollama.ai")
input("\nPress Enter after installing Ollama...")
found, _ = self.find_ollama()
return found
else:
# Skip
print_warning("Skipping Ollama installation.")
print_warning("NL-Shell will not work without Ollama.")
return False
def install_model(self) -> bool:
"""Install the required model"""
print("\n" + "="*60)
print(f"{Colors.BOLD}Model Installation: {REQUIRED_MODEL}{Colors.RESET}")
print("="*60)
print(f"""
NL-Shell uses the {REQUIRED_MODEL} model for natural language processing.
This model is approximately 2GB and will be downloaded now.
""")
if not confirm("Download and install the model now?"):
print_warning("Model not installed. You can install it later with:")
print_info(f" ollama pull {REQUIRED_MODEL}")
return False
print_info(f"Pulling model {REQUIRED_MODEL}...")
print_info("This may take several minutes depending on your internet speed.")
print()
try:
# Run ollama pull
process = subprocess.Popen(
[str(self.ollama_path), 'pull', REQUIRED_MODEL],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# Stream output
for line in iter(process.stdout.readline, ''):
if line.strip():
print(f" {line.strip()}")
process.wait()
if process.returncode == 0:
print_success(f"Model {REQUIRED_MODEL} installed successfully!")
return True
else:
print_error("Model installation failed")
return False
except Exception as e:
print_error(f"Error: {e}")
return False
# ============================================================================
# APPLICATION INSTALLER
# ============================================================================
class AppInstaller:
"""Handles NL-Shell application installation"""
def __init__(self):
self.source_dir = Path(__file__).parent
self.install_dir: Optional[Path] = None
self.shortcuts_created = []
def get_install_location(self) -> Path:
"""Get installation directory from user"""
default_path = Path(os.environ.get('LOCALAPPDATA', '')) / 'Programs' / APP_NAME
print(f"\n{Colors.BOLD}Installation Location{Colors.RESET}")
print(f" Default: {default_path}")
if confirm("Use default location?"):
self.install_dir = default_path
else:
custom_path = input("Enter custom path: ").strip()
self.install_dir = Path(custom_path)
return self.install_dir
def copy_files(self) -> bool:
"""Copy application files to install directory"""
print_info(f"Installing to: {self.install_dir}")
# Files to copy
files_to_copy = [
'nl_shell.py',
'launcher.py',
'config_manager.py',
'ollama_manager.py',
'auth_manager.py',
'risk_analyzer.py',
'command_chain_executor.py',
'windows_commands.json',
'requirements.txt',
]
try:
# Create install directory
self.install_dir.mkdir(parents=True, exist_ok=True)
# Copy each file
copied = 0
for filename in files_to_copy:
src = self.source_dir / filename
if src.exists():
dst = self.install_dir / filename
shutil.copy2(src, dst)
copied += 1
print_success(f"Copied: {filename}")
else:
print_warning(f"Not found: {filename}")
print_success(f"Installed {copied} files")
return True
except Exception as e:
print_error(f"Installation failed: {e}")
return False
def create_launcher_batch(self) -> bool:
"""Create batch file launcher"""
try:
batch_content = f'''@echo off
cd /d "{self.install_dir}"
python launcher.py
pause
'''
batch_path = self.install_dir / f"{APP_NAME}.bat"
batch_path.write_text(batch_content)
print_success(f"Created launcher: {batch_path}")
return True
except Exception as e:
print_error(f"Failed to create launcher: {e}")
return False
def create_desktop_shortcut(self) -> bool:
"""Create desktop shortcut"""
try:
desktop = Path.home() / "Desktop"
shortcut_path = desktop / f"{APP_NAME}.lnk"
target = self.install_dir / f"{APP_NAME}.bat"
# PowerShell command to create shortcut
ps_script = f'''
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("{shortcut_path}")
$Shortcut.TargetPath = "{target}"
$Shortcut.WorkingDirectory = "{self.install_dir}"
$Shortcut.Description = "{APP_DESCRIPTION}"
$Shortcut.Save()
'''
result = subprocess.run(['powershell', '-Command', ps_script],
capture_output=True, text=True)
if shortcut_path.exists():
print_success(f"Desktop shortcut: {shortcut_path}")
self.shortcuts_created.append(shortcut_path)
return True
else:
print_error("Failed to create desktop shortcut")
return False
except Exception as e:
print_error(f"Shortcut error: {e}")
return False
def create_start_menu_shortcut(self) -> bool:
"""Create Start Menu shortcut"""
try:
start_menu = Path(os.environ.get('APPDATA', '')) / 'Microsoft' / 'Windows' / 'Start Menu' / 'Programs'
app_folder = start_menu / APP_NAME
app_folder.mkdir(parents=True, exist_ok=True)
shortcut_path = app_folder / f"{APP_NAME}.lnk"
target = self.install_dir / f"{APP_NAME}.bat"
ps_script = f'''
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("{shortcut_path}")
$Shortcut.TargetPath = "{target}"
$Shortcut.WorkingDirectory = "{self.install_dir}"
$Shortcut.Description = "{APP_DESCRIPTION}"
$Shortcut.Save()
'''
subprocess.run(['powershell', '-Command', ps_script], capture_output=True)
if shortcut_path.exists():
print_success(f"Start Menu: {shortcut_path}")
self.shortcuts_created.append(shortcut_path)
return True
return False
except Exception as e:
print_error(f"Start Menu error: {e}")
return False
def create_uninstaller(self) -> bool:
"""Create uninstaller script"""
try:
uninstall_script = f'''#!/usr/bin/env python3
# NL-Shell Uninstaller
import os
import sys
import shutil
from pathlib import Path
APP_NAME = "{APP_NAME}"
INSTALL_DIR = Path(r"{self.install_dir}")
SHORTCUTS = {self.shortcuts_created}
def main():
print("="*60)
print(f"{{APP_NAME}} Uninstaller")
print("="*60)
print()
response = input("Are you sure you want to uninstall NL-Shell? (y/N): ")
if response.lower() != 'y':
print("Uninstall cancelled.")
return
print()
# Remove shortcuts
for shortcut in SHORTCUTS:
try:
path = Path(shortcut)
if path.exists():
path.unlink()
print(f" Removed: {{path}}")
except Exception as e:
print(f" Warning: Could not remove {{shortcut}}")
# Remove Start Menu folder
start_menu_folder = Path(os.environ.get('APPDATA', '')) / 'Microsoft' / 'Windows' / 'Start Menu' / 'Programs' / APP_NAME
if start_menu_folder.exists():
try:
shutil.rmtree(start_menu_folder)
print(f" Removed: {{start_menu_folder}}")
except:
pass
# Remove installation directory
if INSTALL_DIR.exists():
try:
shutil.rmtree(INSTALL_DIR)
print(f" Removed: {{INSTALL_DIR}}")
except Exception as e:
print(f" Warning: Could not fully remove installation directory")
print(f" You may need to manually delete: {{INSTALL_DIR}}")
print()
print("NL-Shell has been uninstalled.")
print()
input("Press Enter to exit...")
if __name__ == "__main__":
main()
'''
uninstall_path = self.install_dir / "uninstall.py"
uninstall_path.write_text(uninstall_script)
# Create batch wrapper
batch_content = f'''@echo off
cd /d "{self.install_dir}"
python uninstall.py
'''
batch_path = self.install_dir / "uninstall.bat"
batch_path.write_text(batch_content)
print_success("Created uninstaller")
return True
except Exception as e:
print_error(f"Uninstaller error: {e}")
return False
def register_app(self) -> bool:
"""Register application in Windows registry for Add/Remove Programs"""
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\NL-Shell"
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path) as key:
winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, APP_NAME)
winreg.SetValueEx(key, "DisplayVersion", 0, winreg.REG_SZ, APP_VERSION)
winreg.SetValueEx(key, "Publisher", 0, winreg.REG_SZ, APP_PUBLISHER)
winreg.SetValueEx(key, "InstallLocation", 0, winreg.REG_SZ, str(self.install_dir))
winreg.SetValueEx(key, "UninstallString", 0, winreg.REG_SZ,
str(self.install_dir / "uninstall.bat"))
winreg.SetValueEx(key, "NoModify", 0, winreg.REG_DWORD, 1)
winreg.SetValueEx(key, "NoRepair", 0, winreg.REG_DWORD, 1)
print_success("Registered in Windows Programs")
return True
except Exception as e:
print_warning(f"Registry registration skipped: {e}")
return False
# ============================================================================
# MAIN SETUP WIZARD
# ============================================================================
def run_setup():
"""Main setup wizard"""
print_banner()
print(f"""
Welcome to the {APP_NAME} Setup Wizard!
This wizard will:
1. Check for Ollama (AI engine)
2. Install the llama3.2 model if needed
3. Install NL-Shell application files
4. Create desktop and Start Menu shortcuts
5. Register with Windows for easy uninstallation
Press Ctrl+C at any time to cancel.
""")
if not confirm("Ready to begin installation?"):
print("\nSetup cancelled.")
return
total_steps = 6
# Step 0: Check Python and Dependencies
print_step(1, total_steps, "Checking Python and Dependencies")
deps = DependencyChecker()
if not deps.check_python_version():
print_error("Python 3.8+ is required.")
return
deps.check_dependencies()
if deps.missing:
if not deps.install_missing():
if not confirm("Continue without dependencies? (NL-Shell may not work)", default=False):
return
# Step 2: Check Ollama
print_step(2, total_steps, "Checking Ollama Installation")
ollama = OllamaInstaller()
found, path = ollama.find_ollama()
if not found:
if not ollama.install_ollama():
print_error("Ollama is required. Setup cannot continue.")
if not confirm("Continue anyway (NL-Shell won't work without Ollama)?", default=False):
return
# Step 3: Check Ollama Service & Model
print_step(3, total_steps, "Checking Ollama Service and Model")
if ollama.ollama_path:
if not ollama.is_running():
print_info("Starting Ollama service...")
if ollama.start_service():
print_success("Ollama service started")
else:
print_warning("Could not start Ollama automatically")
print_info("You may need to start it manually: ollama serve")
if ollama.is_running():
if ollama.has_required_model():
print_success(f"Model {REQUIRED_MODEL} is available")
else:
ollama.install_model()
# Step 4: Install Application
print_step(4, total_steps, "Installing Application Files")
app = AppInstaller()
app.get_install_location()
if not app.copy_files():
print_error("Installation failed")
return
app.create_launcher_batch()
# Step 5: Create Shortcuts
print_step(5, total_steps, "Creating Shortcuts")
app.create_desktop_shortcut()
app.create_start_menu_shortcut()
app.create_uninstaller()
# Step 6: Register Application
print_step(6, total_steps, "Finalizing Installation")
app.register_app()
# Complete!
print("\n" + "="*60)
print(f"{Colors.GREEN}{Colors.BOLD}Installation Complete!{Colors.RESET}")
print("="*60)
print(f"""
{APP_NAME} has been installed successfully!
{Colors.BOLD}To launch NL-Shell:{Colors.RESET}
• Double-click the desktop shortcut
• Or find it in the Start Menu
• Or run: {app.install_dir / f'{APP_NAME}.bat'}
{Colors.BOLD}To uninstall:{Colors.RESET}
• Use Windows Settings > Apps > {APP_NAME}
• Or run: {app.install_dir / 'Uninstall NL-Shell.bat'}
""")
if confirm("Launch NL-Shell now?"):
os.chdir(app.install_dir)
subprocess.Popen(['python', 'launcher.py'])
def main():
"""Entry point"""
if sys.platform != 'win32':
print("This installer is for Windows only.")
sys.exit(1)
try:
run_setup()
except KeyboardInterrupt:
print("\n\nSetup cancelled by user.")
except Exception as e:
print(f"\n{Colors.RED}Setup error: {e}{Colors.RESET}")
import traceback
traceback.print_exc()
input("\nPress Enter to exit...")
if __name__ == "__main__":
main()