# app.py - ULTIMATE FINAL VERSION - EXPERT CODING ENABLED import os import sys import uvicorn import asyncio import importlib.util import json from pathlib import Path from fastapi import FastAPI, Form from fastapi.responses import HTMLResponse from contextlib import asynccontextmanager from groq import Groq # ============================================ # 1. GLOBAL CONFIGURATION & CONSTANTS # ============================================ class AumCoreConfig: """Central configuration for AumCore AI""" VERSION = "3.0.0-Final" USERNAME = "AumCore AI" PORT = 7860 HOST = "0.0.0.0" # Paths BASE_DIR = Path(__file__).parent MODULES_DIR = BASE_DIR / "modules" CONFIG_DIR = BASE_DIR / "config" LOGS_DIR = BASE_DIR / "logs" DATA_DIR = BASE_DIR / "data" # Create directories if they don't exist for dir_path in [MODULES_DIR, CONFIG_DIR, LOGS_DIR, DATA_DIR]: dir_path.mkdir(exist_ok=True) # ============================================ # 2. MODULE LOADER SYSTEM (CORE INNOVATION) # ============================================ class ModuleManager: """Dynamic module loading system - FUTURE PROOF""" def __init__(self, app, client): self.app = app self.client = client self.config = AumCoreConfig() self.loaded_modules = {} self.module_config = self._load_module_config() def _load_module_config(self) -> dict: """Load module configuration from JSON""" config_file = self.config.CONFIG_DIR / "modules.json" default_config = { "enabled_modules": ["orchestrator", "testing", "sys_diagnostics", "code_formatter", "prompt_manager", "code_intelligence", "code_reviewer"], "auto_start": True, "module_settings": { "orchestrator": {"enabled": True, "background_tasks": True}, "testing": {"auto_test": False, "test_on_startup": True}, "sys_diagnostics": {"auto_run": True, "interval_minutes": 60}, "code_formatter": {"enabled": True, "auto_format": True}, "prompt_manager": {"enabled": True, "auto_optimize": True}, "code_intelligence": {"enabled": True, "auto_analyze": True}, "code_reviewer": {"enabled": True, "auto_review": False} } } if not config_file.exists(): config_file.write_text(json.dumps(default_config, indent=4)) return default_config try: return json.loads(config_file.read_text()) except: return default_config def load_all_modules(self): """Load all enabled modules dynamically""" print("=" * 60) print("๐ AUMCORE AI - MODULAR SYSTEM INITIALIZING") print("=" * 60) for module_name in self.module_config["enabled_modules"]: self.load_module(module_name) print(f"๐ฆ Modules Loaded: {len(self.loaded_modules)}") print(f"๐ง Active: {list(self.loaded_modules.keys())}") print("=" * 60) def load_module(self, module_name: str): """Load a single module by name""" module_path = self.config.MODULES_DIR / f"{module_name}.py" if not module_path.exists(): print(f"โ ๏ธ Module '{module_name}' not found at {module_path}") return False try: # Dynamic module loading spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) # Register module with app if hasattr(module, 'register_module'): module.register_module(self.app, self.client, AumCoreConfig.USERNAME) self.loaded_modules[module_name] = { "module": module, "path": module_path, "status": "loaded" } print(f"โ Module '{module_name}' loaded successfully") return True else: print(f"โ ๏ธ Module '{module_name}' missing register_module() function") return False except Exception as e: print(f"โ Failed to load module '{module_name}': {str(e)}") return False def get_module(self, module_name: str): """Get loaded module instance""" return self.loaded_modules.get(module_name, {}).get("module") def get_module_status(self) -> dict: """Get status of all modules""" return { "total_modules": len(self.loaded_modules), "loaded_modules": list(self.loaded_modules.keys()), "config": self.module_config, "module_details": { name: info["status"] for name, info in self.loaded_modules.items() } } # ============================================ # 3. LIFESPAN MANAGEMENT (MODERN APPROACH) # ============================================ @asynccontextmanager async def lifespan(app: FastAPI): """Modern lifespan handler for startup/shutdown events""" # Startup code print("=" * 60) print("๐ AUMCORE AI - ULTIMATE FINAL VERSION") print("=" * 60) print(f"๐ Version: {AumCoreConfig.VERSION}") print(f"๐ค Username: {AumCoreConfig.USERNAME}") print(f"๐ Server: http://{AumCoreConfig.HOST}:{AumCoreConfig.PORT}") print(f"๐ค AI Model: llama-3.3-70b-versatile") print(f"๐พ Database: TiDB Cloud") print(f"๐จ UI Features: Code formatting + Copy button") # Load all modules if hasattr(app.state, 'module_manager'): app.state.module_manager.load_all_modules() # Initial health check print("\n๐ Initial System Check:") print(f" Groq API: {'โ Available' if hasattr(app.state, 'groq_available') and app.state.groq_available else 'โ Not Available'}") print(f" Modules: {len(app.state.module_manager.loaded_modules) if hasattr(app.state, 'module_manager') else 0} loaded") print(f" Directories: All created") print("=" * 60) print("โ System ready! Waiting for requests...") print("=" * 60) yield # Application runs here # Shutdown code print("\n๐ System shutting down...") print("โ Cleanup completed") # ============================================ # 4. CORE FASTAPI APPLICATION # ============================================ app = FastAPI( title="AumCore AI", description="Advanced Modular AI Assistant System", version=AumCoreConfig.VERSION, lifespan=lifespan ) # Initialize Groq client try: client = Groq(api_key=os.environ.get("GROQ_API_KEY")) GROQ_AVAILABLE = True app.state.groq_available = True except Exception as e: print(f"โ ๏ธ Groq client initialization failed: {e}") client = None GROQ_AVAILABLE = False app.state.groq_available = False # Initialize Module Manager module_manager = ModuleManager(app, client) app.state.module_manager = module_manager # ============================================ # 5. CORE UI (NEVER CHANGES) # ============================================ HTML_UI = '''