File size: 6,691 Bytes
00c982c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import os
import sys
import logging
import traceback
import gradio as gr
from datetime import datetime

# Add src directory to path
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

# Import original modules (copy from original bot)
from src.config import Config
from src.auth import AuthManager

# Import enhanced modules
from src.dashboard_database_manager import DashboardDatabaseManager
from src.enhanced_ai_processor import EnhancedAIProcessor
from src.enhanced_ui_components import EnhancedUIComponents

# Logging setup
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('smartheal_enhanced.log'),
        logging.StreamHandler()
    ]
)

class EnhancedSmartHealApp:
    """Enhanced SmartHeal Application with Dashboard Integration"""
    
    def __init__(self):
        self.ui_components = None
        try:
            logging.info("πŸš€ Initializing Enhanced SmartHeal App...")
            
            # Initialize configuration
            self.config = Config()
            logging.info("βœ… Configuration loaded")
            
            # Initialize enhanced database manager
            self.database_manager = DashboardDatabaseManager(self.config.get_mysql_config())
            logging.info("βœ… Enhanced database manager initialized")
            
            # Initialize authentication manager
            self.auth_manager = AuthManager(self.database_manager)
            logging.info("βœ… Authentication manager initialized")
            
            # Initialize enhanced AI processor
            self.ai_processor = EnhancedAIProcessor()
            logging.info("βœ… Enhanced AI processor initialized")
            
            # Initialize enhanced UI components
            self.ui_components = EnhancedUIComponents(
                self.auth_manager,
                self.database_manager,
                self.ai_processor
            )
            logging.info("βœ… Enhanced UI components initialized")
            
            # Create database tables if they don't exist
            self._ensure_database_tables()
            
            logging.info("πŸŽ‰ Enhanced SmartHeal App initialized successfully!")
            
        except Exception as e:
            logging.error(f"❌ Initialization error: {e}")
            traceback.print_exc()
            raise
    
    def _ensure_database_tables(self):
        """Ensure all required database tables exist"""
        try:
            # Check if dashboard tables exist, if not create them
            tables_to_check = [
                'ai_analyses',
                'analysis_sessions', 
                'bot_interactions',
                'questionnaire_responses',
                'wound_images'
            ]
            
            for table in tables_to_check:
                result = self.database_manager.execute_query_one(f"SHOW TABLES LIKE '{table}'")
                if not result:
                    logging.warning(f"Table '{table}' not found in database")
                else:
                    logging.info(f"βœ… Table '{table}' exists")
            
            logging.info("βœ… Database table check completed")
            
        except Exception as e:
            logging.error(f"❌ Error checking database tables: {e}")
    
    def launch(self, port=7860, share=True, server_name="0.0.0.0"):
        """Launch the enhanced application"""
        try:
            logging.info(f"🌐 Launching Enhanced SmartHeal App on {server_name}:{port}")
            
            # Create the interface
            interface = self.ui_components.create_interface()
            
            # Launch with enhanced configuration
            interface.launch(
                server_name=server_name,
                server_port=port,
                share=share,
                show_error=True,
                quiet=False,
                favicon_path="favicon.ico" if os.path.exists("favicon.ico") else None
            )
            
        except Exception as e:
            logging.error(f"❌ Error launching application: {e}")
            raise
    
    def get_status(self):
        """Get application status"""
        try:
            status = {
                'app_initialized': self.ui_components is not None,
                'database_connected': self.database_manager.get_connection() is not None,
                'ai_models_loaded': len(self.ai_processor.models_cache) > 0,
                'dashboard_integration': self.ui_components.dashboard_integration.get_integration_status() if self.ui_components else {},
                'timestamp': datetime.now().isoformat()
            }
            
            return status
            
        except Exception as e:
            logging.error(f"Error getting status: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}

def main():
    """Main application entry point"""
    try:
        print("=" * 60)
        print("πŸ₯ SmartHeal AI - Enhanced Edition")
        print("Advanced Wound Care Analysis with Dashboard Integration")
        print("=" * 60)
        
        # Initialize and launch the app
        app = EnhancedSmartHealApp()
        
        # Print status
        status = app.get_status()
        print("\nπŸ“Š Application Status:")
        print(f"  β€’ App Initialized: {status.get('app_initialized', False)}")
        print(f"  β€’ Database Connected: {status.get('database_connected', False)}")
        print(f"  β€’ AI Models Loaded: {status.get('ai_models_loaded', False)}")
        
        dashboard_status = status.get('dashboard_integration', {})
        print(f"  β€’ Dashboard API: {dashboard_status.get('api_running', False)}")
        print(f"  β€’ Dashboard DB: {dashboard_status.get('database_connected', False)}")
        
        print("\nπŸš€ Starting application...")
        print("πŸ“± Access the application at: http://localhost:7860")
        print("πŸ“Š Dashboard API available at: http://localhost:5001")
        print("πŸ“ˆ Dashboard Integration: Real-time analytics enabled")
        print("\n⚠️  Press Ctrl+C to stop the application")
        print("=" * 60)
        
        # Launch the application
        app.launch()
        
    except KeyboardInterrupt:
        print("\n\nπŸ‘‹ Application interrupted by user.")
        logging.info("Application interrupted by user")
    except Exception as e:
        print(f"\n❌ Application failed to start: {e}")
        logging.error(f"Application failed to start: {e}")
        traceback.print_exc()
        raise

if __name__ == "__main__":
    main()