File size: 14,443 Bytes
0a9f9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
BLUESCARF AI HR Assistant - Automated Setup and Validation Script
Provides comprehensive setup, validation, and deployment assistance.
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path
import json
import time
from typing import Dict, List, Tuple, Optional

class Colors:
    """ANSI color codes for terminal output."""
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

class SetupManager:
    """Comprehensive setup and validation manager for BLUESCARF AI HR Assistant."""
    
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.requirements_file = self.project_root / "requirements.txt"
        self.config_file = self.project_root / "config.py"
        self.logo_file = self.project_root / "logo.png"
        
    def print_header(self):
        """Print application header with branding."""
        print(f"{Colors.HEADER}{Colors.BOLD}")
        print("=" * 60)
        print("   BLUESCARF ARTIFICIAL INTELLIGENCE")
        print("   HR Assistant Setup & Validation")
        print("   Version 1.0.0")
        print("=" * 60)
        print(f"{Colors.ENDC}")
    
    def check_python_version(self) -> bool:
        """Validate Python version compatibility."""
        print(f"{Colors.OKBLUE}Checking Python version...{Colors.ENDC}")
        
        version = sys.version_info
        min_version = (3, 8)
        
        if version >= min_version:
            print(f"{Colors.OKGREEN}βœ“ Python {version.major}.{version.minor}.{version.micro} (Compatible){Colors.ENDC}")
            return True
        else:
            print(f"{Colors.FAIL}βœ— Python {version.major}.{version.minor}.{version.micro} (Requires 3.8+){Colors.ENDC}")
            return False
    
    def check_dependencies(self) -> Tuple[bool, List[str]]:
        """Check if all required dependencies are available."""
        print(f"{Colors.OKBLUE}Checking dependencies...{Colors.ENDC}")
        
        if not self.requirements_file.exists():
            print(f"{Colors.FAIL}βœ— requirements.txt not found{Colors.ENDC}")
            return False, ["requirements.txt missing"]
        
        # Read requirements
        with open(self.requirements_file, 'r') as f:
            requirements = [line.strip() for line in f if line.strip() and not line.startswith('#')]
        
        missing_packages = []
        
        for requirement in requirements:
            package_name = requirement.split('==')[0].split('>=')[0].split('~=')[0]
            try:
                __import__(package_name.replace('-', '_'))
                print(f"{Colors.OKGREEN}βœ“ {package_name}{Colors.ENDC}")
            except ImportError:
                print(f"{Colors.WARNING}! {package_name} (not installed){Colors.ENDC}")
                missing_packages.append(package_name)
        
        if missing_packages:
            return False, missing_packages
        else:
            print(f"{Colors.OKGREEN}βœ“ All dependencies satisfied{Colors.ENDC}")
            return True, []
    
    def install_dependencies(self) -> bool:
        """Install missing dependencies using pip."""
        print(f"{Colors.OKBLUE}Installing dependencies...{Colors.ENDC}")
        
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "-r", str(self.requirements_file)
            ])
            print(f"{Colors.OKGREEN}βœ“ Dependencies installed successfully{Colors.ENDC}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"{Colors.FAIL}βœ— Failed to install dependencies: {e}{Colors.ENDC}")
            return False
    
    def validate_project_structure(self) -> Tuple[bool, List[str]]:
        """Validate that all required project files exist."""
        print(f"{Colors.OKBLUE}Validating project structure...{Colors.ENDC}")
        
        required_files = [
            "app.py",
            "document_processor.py",
            "vector_store.py",
            "admin.py",
            "config.py",
            "utils.py",
            "requirements.txt"
        ]
        
        missing_files = []
        
        for file_name in required_files:
            file_path = self.project_root / file_name
            if file_path.exists():
                print(f"{Colors.OKGREEN}βœ“ {file_name}{Colors.ENDC}")
            else:
                print(f"{Colors.FAIL}βœ— {file_name} (missing){Colors.ENDC}")
                missing_files.append(file_name)
        
        # Check for logo
        if self.logo_file.exists():
            print(f"{Colors.OKGREEN}βœ“ logo.png (company logo found){Colors.ENDC}")
        else:
            print(f"{Colors.WARNING}! logo.png (add your company logo){Colors.ENDC}")
        
        if missing_files:
            return False, missing_files
        else:
            print(f"{Colors.OKGREEN}βœ“ Project structure is valid{Colors.ENDC}")
            return True, []
    
    def setup_directories(self) -> bool:
        """Create necessary directories for the application."""
        print(f"{Colors.OKBLUE}Setting up directories...{Colors.ENDC}")
        
        directories = [
            "vector_db",
            "logs",
            "temp",
            "data",
            "data/vector_db",
            "data/logs"
        ]
        
        try:
            for directory in directories:
                dir_path = self.project_root / directory
                dir_path.mkdir(parents=True, exist_ok=True)
                print(f"{Colors.OKGREEN}βœ“ Created {directory}/{Colors.ENDC}")
            
            return True
        except Exception as e:
            print(f"{Colors.FAIL}βœ— Failed to create directories: {e}{Colors.ENDC}")
            return False
    
    def create_env_file(self) -> bool:
        """Create .env file from template if it doesn't exist."""
        print(f"{Colors.OKBLUE}Setting up environment configuration...{Colors.ENDC}")
        
        env_file = self.project_root / ".env"
        env_example = self.project_root / ".env.example"
        
        if env_file.exists():
            print(f"{Colors.OKGREEN}βœ“ .env file already exists{Colors.ENDC}")
            return True
        
        if env_example.exists():
            try:
                shutil.copy(env_example, env_file)
                print(f"{Colors.OKGREEN}βœ“ Created .env from .env.example{Colors.ENDC}")
                print(f"{Colors.WARNING}! Please review and customize .env file{Colors.ENDC}")
                return True
            except Exception as e:
                print(f"{Colors.FAIL}βœ— Failed to create .env file: {e}{Colors.ENDC}")
                return False
        else:
            print(f"{Colors.WARNING}! .env.example not found, skipping .env creation{Colors.ENDC}")
            return True
    
    def validate_streamlit_config(self) -> bool:
        """Validate Streamlit configuration."""
        print(f"{Colors.OKBLUE}Validating Streamlit configuration...{Colors.ENDC}")
        
        try:
            import streamlit as st
            print(f"{Colors.OKGREEN}βœ“ Streamlit is available{Colors.ENDC}")
            return True
        except ImportError:
            print(f"{Colors.FAIL}βœ— Streamlit not available{Colors.ENDC}")
            return False
    
    def test_api_imports(self) -> Dict[str, bool]:
        """Test critical API imports."""
        print(f"{Colors.OKBLUE}Testing critical imports...{Colors.ENDC}")
        
        import_tests = {
            "Google AI": ("google.generativeai", "google-generativeai"),
            "ChromaDB": ("chromadb", "chromadb"),
            "Sentence Transformers": ("sentence_transformers", "sentence-transformers"),
            "PyPDF2": ("PyPDF2", "PyPDF2"),
            "Pandas": ("pandas", "pandas"),
            "NumPy": ("numpy", "numpy")
        }
        
        results = {}
        
        for name, (module, package) in import_tests.items():
            try:
                __import__(module)
                print(f"{Colors.OKGREEN}βœ“ {name}{Colors.ENDC}")
                results[name] = True
            except ImportError:
                print(f"{Colors.FAIL}βœ— {name} (install with: pip install {package}){Colors.ENDC}")
                results[name] = False
        
        return results
    
    def generate_deployment_summary(self) -> Dict[str, any]:
        """Generate comprehensive deployment summary."""
        print(f"{Colors.OKBLUE}Generating deployment summary...{Colors.ENDC}")
        
        summary = {
            "timestamp": time.time(),
            "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
            "project_path": str(self.project_root),
            "files_present": [],
            "directories_created": [],
            "configuration_status": "pending"
        }
        
        # Check files
        for file_path in self.project_root.glob("*.py"):
            summary["files_present"].append(file_path.name)
        
        # Check directories
        for dir_path in ["vector_db", "logs", "temp"]:
            if (self.project_root / dir_path).exists():
                summary["directories_created"].append(dir_path)
        
        return summary
    
    def provide_next_steps(self):
        """Provide clear next steps for deployment."""
        print(f"\n{Colors.HEADER}{Colors.BOLD}NEXT STEPS:{Colors.ENDC}")
        print(f"{Colors.OKBLUE}1. Get Google Gemini API Key:{Colors.ENDC}")
        print("   β†’ Visit: https://makersuite.google.com/app/apikey")
        print("   β†’ Create or use existing API key")
        
        print(f"\n{Colors.OKBLUE}2. Add Company Logo:{Colors.ENDC}")
        print("   β†’ Replace 'logo.png' with your company logo")
        print("   β†’ Recommended size: 200x200 pixels")
        
        print(f"\n{Colors.OKBLUE}3. Upload Initial Documents:{Colors.ENDC}")
        print("   β†’ Run the application: streamlit run app.py")
        print("   β†’ Access admin panel with password: bluescarf_admin_2024")
        print("   β†’ Upload HR policies, handbooks, procedures")
        
        print(f"\n{Colors.OKBLUE}4. Test the System:{Colors.ENDC}")
        print("   β†’ Enter your API key in the application")
        print("   β†’ Ask test questions about uploaded documents")
        print("   β†’ Verify responses are accurate and relevant")
        
        print(f"\n{Colors.OKBLUE}5. Deploy to Production:{Colors.ENDC}")
        print("   β†’ For Hugging Face Spaces: Upload all files")
        print("   β†’ For Docker: Use provided Dockerfile")
        print("   β†’ For cloud: Follow platform-specific guides")
        
        print(f"\n{Colors.WARNING}IMPORTANT SECURITY NOTES:{Colors.ENDC}")
        print("   β†’ Change default admin password immediately")
        print("   β†’ Keep API keys secure and never commit to git")
        print("   β†’ Review uploaded documents for sensitive information")
        
        print(f"\n{Colors.OKGREEN}Ready for deployment! πŸš€{Colors.ENDC}")
    
    def run_comprehensive_setup(self) -> bool:
        """Run complete setup and validation process."""
        self.print_header()
        
        success = True
        
        # 1. Check Python version
        if not self.check_python_version():
            print(f"{Colors.FAIL}Setup failed: Incompatible Python version{Colors.ENDC}")
            return False
        
        # 2. Validate project structure
        structure_valid, missing_files = self.validate_project_structure()
        if not structure_valid:
            print(f"{Colors.FAIL}Setup failed: Missing files: {missing_files}{Colors.ENDC}")
            return False
        
        # 3. Check dependencies
        deps_valid, missing_deps = self.check_dependencies()
        if not deps_valid:
            print(f"{Colors.WARNING}Installing missing dependencies...{Colors.ENDC}")
            if not self.install_dependencies():
                print(f"{Colors.FAIL}Setup failed: Could not install dependencies{Colors.ENDC}")
                return False
        
        # 4. Setup directories
        if not self.setup_directories():
            print(f"{Colors.FAIL}Setup failed: Could not create directories{Colors.ENDC}")
            return False
        
        # 5. Create environment file
        if not self.create_env_file():
            print(f"{Colors.WARNING}Environment file setup incomplete{Colors.ENDC}")
        
        # 6. Validate Streamlit
        if not self.validate_streamlit_config():
            print(f"{Colors.FAIL}Setup failed: Streamlit configuration issue{Colors.ENDC}")
            return False
        
        # 7. Test imports
        import_results = self.test_api_imports()
        if not all(import_results.values()):
            print(f"{Colors.WARNING}Some imports failed, but setup can continue{Colors.ENDC}")
        
        # 8. Generate summary
        summary = self.generate_deployment_summary()
        
        print(f"\n{Colors.OKGREEN}{Colors.BOLD}βœ“ SETUP COMPLETED SUCCESSFULLY!{Colors.ENDC}")
        
        # 9. Provide next steps
        self.provide_next_steps()
        
        return True

def main():
    """Main setup function."""
    setup_manager = SetupManager()
    
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == "validate":
            # Quick validation only
            setup_manager.check_python_version()
            setup_manager.validate_project_structure()
            setup_manager.check_dependencies()
            
        elif command == "install":
            # Install dependencies only
            setup_manager.install_dependencies()
            
        elif command == "structure":
            # Setup directories only
            setup_manager.setup_directories()
            
        elif command == "test":
            # Test imports only
            setup_manager.test_api_imports()
            
        else:
            print(f"Unknown command: {command}")
            print("Available commands: validate, install, structure, test")
    else:
        # Run complete setup
        success = setup_manager.run_comprehensive_setup()
        sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()