File size: 6,777 Bytes
0469d65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Build script for creating SafetyMaster Pro standalone executable
Uses PyInstaller to create a distributable executable
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def install_pyinstaller():
    """Install PyInstaller if not already installed."""
    try:
        import PyInstaller
        print("βœ… PyInstaller already installed")
    except ImportError:
        print("πŸ“¦ Installing PyInstaller...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
        print("βœ… PyInstaller installed successfully")

def create_spec_file():
    """Create PyInstaller spec file for SafetyMaster Pro."""
    spec_content = '''
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['web_interface.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('templates', 'templates'),
        ('*.pt', '.'),
        ('*.html', '.'),
        ('README.md', '.'),
        ('requirements.txt', '.'),
    ],
    hiddenimports=[
        'engineio.async_drivers.threading',
        'socketio',
        'flask_socketio',
        'ultralytics',
        'torch',
        'torchvision',
        'cv2',
        'numpy',
        'PIL',
        'requests',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='SafetyMasterPro',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='icon.ico' if os.path.exists('icon.ico') else None,
)
'''
    
    with open('SafetyMasterPro.spec', 'w') as f:
        f.write(spec_content.strip())
    
    print("βœ… Created PyInstaller spec file")

def build_executable():
    """Build the standalone executable."""
    print("πŸ”¨ Building SafetyMaster Pro executable...")
    
    # Clean previous builds
    if os.path.exists('dist'):
        shutil.rmtree('dist')
    if os.path.exists('build'):
        shutil.rmtree('build')
    
    # Build executable
    cmd = [
        'pyinstaller',
        '--clean',
        '--noconfirm',
        'SafetyMasterPro.spec'
    ]
    
    try:
        subprocess.check_call(cmd)
        print("βœ… Executable built successfully!")
        print(f"πŸ“ Executable location: {os.path.abspath('dist/SafetyMasterPro')}")
        
        # Create distribution folder
        dist_folder = "SafetyMasterPro_Distribution"
        if os.path.exists(dist_folder):
            shutil.rmtree(dist_folder)
        
        os.makedirs(dist_folder)
        
        # Copy executable
        if os.path.exists('dist/SafetyMasterPro'):
            if sys.platform == "win32":
                shutil.copy2('dist/SafetyMasterPro.exe', dist_folder)
            else:
                shutil.copy2('dist/SafetyMasterPro', dist_folder)
        
        # Copy additional files
        files_to_copy = [
            'README.md',
            'requirements.txt',
        ]
        
        for file in files_to_copy:
            if os.path.exists(file):
                shutil.copy2(file, dist_folder)
        
        # Copy model files
        for model_file in Path('.').glob('*.pt'):
            shutil.copy2(model_file, dist_folder)
        
        # Copy templates if they exist
        if os.path.exists('templates'):
            shutil.copytree('templates', os.path.join(dist_folder, 'templates'))
        
        print(f"πŸ“¦ Distribution package created: {dist_folder}/")
        
    except subprocess.CalledProcessError as e:
        print(f"❌ Build failed: {e}")
        return False
    
    return True

def create_installer_script():
    """Create installation script for users."""
    
    # Windows batch script
    windows_script = '''@echo off
echo SafetyMaster Pro - Installation Script
echo =====================================
echo.

echo Checking Python installation...
python --version >nul 2>&1
if errorlevel 1 (
    echo ERROR: Python is not installed or not in PATH
    echo Please install Python 3.8+ from https://python.org
    pause
    exit /b 1
)

echo Installing SafetyMaster Pro dependencies...
pip install -r requirements.txt

echo.
echo Installation complete!
echo.
echo To run SafetyMaster Pro:
echo   python web_interface.py
echo.
echo Or use the executable:
echo   SafetyMasterPro.exe
echo.
pause
'''
    
    # Unix shell script
    unix_script = '''#!/bin/bash
echo "SafetyMaster Pro - Installation Script"
echo "====================================="
echo

echo "Checking Python installation..."
if ! command -v python3 &> /dev/null; then
    echo "ERROR: Python 3 is not installed"
    echo "Please install Python 3.8+ from your package manager"
    exit 1
fi

echo "Installing SafetyMaster Pro dependencies..."
pip3 install -r requirements.txt

echo
echo "Installation complete!"
echo
echo "To run SafetyMaster Pro:"
echo "  python3 web_interface.py"
echo
echo "Or use the executable:"
echo "  ./SafetyMasterPro"
echo
'''
    
    # Write scripts
    with open('SafetyMasterPro_Distribution/install.bat', 'w') as f:
        f.write(windows_script)
    
    with open('SafetyMasterPro_Distribution/install.sh', 'w') as f:
        f.write(unix_script)
    
    # Make shell script executable
    if sys.platform != "win32":
        os.chmod('SafetyMasterPro_Distribution/install.sh', 0o755)
    
    print("βœ… Installation scripts created")

def main():
    """Main build process."""
    print("πŸš€ SafetyMaster Pro - Build Script")
    print("=" * 40)
    
    # Install PyInstaller
    install_pyinstaller()
    
    # Create spec file
    create_spec_file()
    
    # Build executable
    if build_executable():
        create_installer_script()
        
        print("\nπŸŽ‰ Build completed successfully!")
        print("\nπŸ“¦ Distribution package contents:")
        print("   - SafetyMasterPro executable")
        print("   - Model files (*.pt)")
        print("   - Templates folder")
        print("   - README.md")
        print("   - requirements.txt")
        print("   - install.bat (Windows)")
        print("   - install.sh (Unix/Linux/Mac)")
        
        print(f"\nπŸ“ Package location: {os.path.abspath('SafetyMasterPro_Distribution')}")
        print("\nβœ… Ready for distribution!")
    else:
        print("\n❌ Build failed!")
        sys.exit(1)

if __name__ == "__main__":
    main()