File size: 6,538 Bytes
fd50325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2278049
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
"""

DetectifAI API Startup Script



Quick script to launch the DetectifAI API server with proper environment setup

and preliminary checks for the surveillance system.

"""

import sys
import os
import subprocess
import time
import logging

def check_python_environment():
    """Check if required Python packages are available"""
    print("🐍 Checking Python environment...")
    
    required_packages = [
        'flask', 'flask_cors', 'opencv-python', 'numpy', 
        'ultralytics', 'pillow', 'matplotlib'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'opencv-python':
                import cv2
            elif package == 'flask_cors':
                from flask_cors import CORS
            elif package == 'ultralytics':
                from ultralytics import YOLO
            elif package == 'pillow':
                from PIL import Image
            else:
                __import__(package)
            print(f"  βœ… {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"  ❌ {package}")
    
    if missing_packages:
        print(f"\n⚠️ Missing packages: {', '.join(missing_packages)}")
        print("πŸ’‘ Install with: pip install " + " ".join(missing_packages))
        return False
    
    return True

def check_model_files():
    """Check if YOLO model files are available"""
    print("\nπŸ€– Checking AI model files...")
    
    model_files = [
        'models/fire_YOLO11.pt',
        'models/weapon_YOLO11.pt'
    ]
    
    missing_models = []
    found_models = []
    
    for model_file in model_files:
        if os.path.exists(model_file):
            size_mb = os.path.getsize(model_file) / (1024 * 1024)
            print(f"  βœ… {model_file} ({size_mb:.1f} MB)")
            found_models.append(model_file)
        else:
            missing_models.append(model_file)
            print(f"  ❌ {model_file}")
    
    if missing_models:
        print(f"\n⚠️ Missing model files: {', '.join(missing_models)}")
        if found_models:
            print(f"βœ… Found {len(found_models)} model(s): {', '.join([os.path.basename(f) for f in found_models])}")
            print("πŸ’‘ DetectifAI will work with available models")
        else:
            print("πŸ’‘ DetectifAI will work with reduced functionality")
        return len(found_models) > 0
    
    return True

def check_test_videos():
    """Check if test videos are available"""
    print("\n🎬 Checking test videos...")
    
    test_videos = ['rob.mp4', 'fire.avi']
    available_videos = []
    
    for video in test_videos:
        if os.path.exists(video):
            size_mb = os.path.getsize(video) / (1024 * 1024)
            print(f"  βœ… {video} ({size_mb:.1f} MB)")
            available_videos.append(video)
        else:
            print(f"  ❌ {video}")
    
    print(f"\nπŸ“Š {len(available_videos)}/{len(test_videos)} test videos available")
    return available_videos

def setup_directories():
    """Create necessary directories"""
    print("\nπŸ“ Setting up directories...")
    
    directories = [
        'uploads',
        'video_processing_outputs',
        'logs',
        'core',
        'docs',
        'models'
    ]
    
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print(f"  βœ… Created {directory}/")
        else:
            print(f"  βœ… {directory}/ exists")

def start_detectifai_api():
    """Start the DetectifAI API server"""
    print("\nπŸš€ Starting DetectifAI API server...")
    print("=" * 50)
    
    try:
        # Change to backend directory if needed
        if not os.path.exists('app.py'):
            print("❌ app.py not found in current directory")
            print("πŸ’‘ Make sure you're in the backend directory")
            return False
        
        # Start the API server
        print("🌐 API will be available at: http://localhost:5000")
        print("πŸ“‹ API endpoints:")
        print("  β€’ Health: GET /api/health")
        print("  β€’ Upload: POST /api/upload")
        print("  β€’ Status: GET /api/status/<video_id>")
        print("  β€’ Results: GET /api/results/<video_id>")
        print("  β€’ Demo: GET /api/detectifai/demo")
        print("  β€’ DetectifAI Events: GET /api/detectifai/events/<video_id>")
        print("  β€’ Keyframes: GET /api/keyframes/<video_id>")
        print("")
        print("πŸ”§ To test the API, run: python test_detectifai_integration.py")
        print("🌐 For frontend integration, ensure CORS is enabled")
        print("")
        print("Press Ctrl+C to stop the server")
        print("=" * 50)
        
        # Run the API server
        subprocess.run([sys.executable, 'app.py'])
        
    except KeyboardInterrupt:
        print("\n\nπŸ›‘ DetectifAI API server stopped")
        return True
    except Exception as e:
        print(f"\n❌ Error starting API server: {e}")
        return False

def main():
    """Main startup function"""
    print("πŸ”§ DetectifAI API Startup")
    print("========================")
    
    # System checks
    env_ok = check_python_environment()
    models_ok = check_model_files()
    videos = check_test_videos()
    
    # Setup
    setup_directories()
    
    # Summary
    print("\nπŸ“‹ System Status Summary:")
    print(f"  🐍 Python Environment: {'βœ…' if env_ok else '⚠️'}")
    print(f"  πŸ€– AI Models: {'βœ…' if models_ok else '⚠️'}")
    print(f"  🎬 Test Videos: {len(videos)} available")
    
    if not env_ok:
        print("\n❌ Cannot start API - missing required Python packages")
        return False
    
    print(f"\n🎯 DetectifAI System Ready")
    
    if videos:
        print(f"πŸ’‘ Demo videos available: {', '.join(videos)}")
    
    # Ask user if they want to continue
    try:
        response = input("\nπŸš€ Start DetectifAI API server? (y/n): ").lower().strip()
        if response in ['y', 'yes', '']:
            return start_detectifai_api()
        else:
            print("πŸ‘‹ Startup cancelled")
            return True
    except KeyboardInterrupt:
        print("\nπŸ‘‹ Startup cancelled")
        return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)