test-app / app.py
SmartHeal's picture
Rename enhanced_app.py to app.py
b714d0f verified
#!/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()