File size: 6,519 Bytes
712579e |
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 |
import sys
import os
import logging
from typing import Optional
from pathlib import Path
# Add the current directory to Python path
current_dir = Path(__file__).parent.absolute()
sys.path.insert(0, str(current_dir))
# Import functional modules
try:
from main import main, validate_environment
from audio_utils import validate_environment as validate_audio_env
except ImportError as e:
print(f"Error importing functional modules: {e}")
print("Please ensure all required dependencies are installed.")
sys.exit(1)
# Configure logging
def setup_logging(level: str = "INFO") -> logging.Logger:
"""Set up application logging."""
log_level = getattr(logging, level.upper(), logging.INFO)
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('wisal_app.log', mode='a')
]
)
return logging.getLogger('WisalApp')
def check_dependencies() -> bool:
"""Check if all required dependencies are available."""
required_packages = [
'gradio',
'numpy',
'soundfile',
'webrtcvad',
'fastrtc',
'google.genai',
'openai',
'weaviate',
'langdetect',
'requests',
'langchain',
'pypdf',
'docx', # python-docx imports as 'docx'
'dotenv'
]
missing_packages = []
for package in required_packages:
try:
__import__(package.replace('-', '_').replace('.', '.'))
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"Missing required packages: {', '.join(missing_packages)}")
print("Please install them using: pip install " + " ".join(missing_packages))
return False
return True
def check_environment_files() -> bool:
"""Check if required environment files exist."""
required_files = ['.env']
missing_files = []
for file_path in required_files:
if not os.path.exists(file_path):
missing_files.append(file_path)
if missing_files:
print(f"Missing required files: {', '.join(missing_files)}")
print("Please create a .env file with the required API keys.")
return False
return True
def print_startup_banner():
"""Print application startup banner."""
banner = """
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β π€ Wisal: Autism AI Assistant β
β β
β Functional Programming Version β
β Developed by Compumacy AI β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
print(banner)
def print_feature_overview():
"""Print overview of available features."""
features = """
π§ Available Features:
βββ π¬ Text-based chat with autism expertise
βββ π€ Voice input with transcription
βββ π Text-to-speech responses
βββ π Document upload and Q&A
βββ π Web search integration
βββ π§ RAG (Retrieval Augmented Generation)
βββ π― Functional programming architecture
βββ π Real-time voice chat (WebRTC)
"""
print(features)
def run_pre_flight_checks() -> bool:
"""Run all pre-flight checks before starting the application."""
app_logger = setup_logging()
print_startup_banner()
app_logger.info("Starting pre-flight checks...")
# Check 1: Dependencies
app_logger.info("Checking dependencies...")
if not check_dependencies():
app_logger.error("Dependency check failed")
return False
app_logger.info("β
Dependencies check passed")
# Check 2: Environment files
app_logger.info("Checking environment files...")
if not check_environment_files():
app_logger.error("Environment files check failed")
return False
app_logger.info("β
Environment files check passed")
# Check 3: Environment variables
app_logger.info("Validating environment variables...")
if not validate_environment():
app_logger.warning("β οΈ Some environment variables are missing - features may be limited")
else:
app_logger.info("β
Environment variables validated")
# Check 4: Audio environment
app_logger.info("Checking audio environment...")
if not validate_audio_env():
app_logger.warning("β οΈ Audio environment not fully configured - voice features may be limited")
else:
app_logger.info("β
Audio environment validated")
app_logger.info("Pre-flight checks completed")
print_feature_overview()
return True
def handle_graceful_shutdown():
"""Handle graceful application shutdown."""
print("\nπ Shutting down Wisal gracefully...")
print("π Thank you for using Wisal!")
def run_application():
"""Run the main application with error handling."""
try:
print("π Starting Wisal application...")
main()
except KeyboardInterrupt:
handle_graceful_shutdown()
except Exception as e:
print(f"β Application error: {e}")
logging.error(f"Application error: {e}", exc_info=True)
sys.exit(1)
def main_runner():
"""Main runner function."""
try:
# Run pre-flight checks
if not run_pre_flight_checks():
print("β Pre-flight checks failed. Cannot start application.")
sys.exit(1)
print("β
All checks passed. Starting application...")
# Run the application
run_application()
except Exception as e:
print(f"β Fatal error during startup: {e}")
logging.error(f"Fatal startup error: {e}", exc_info=True)
sys.exit(1)
if __name__ == "__main__":
main_runner() |