Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| Cidadão.AI Models - HuggingFace Spaces Entry Point | |
| FastAPI server for ML model inference optimized for HuggingFace Spaces deployment. | |
| """ | |
| import os | |
| import sys | |
| import logging | |
| from contextlib import asynccontextmanager | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse, HTMLResponse | |
| # Configure logging for HuggingFace | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| handlers=[logging.StreamHandler(sys.stdout)] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Import our API server | |
| try: | |
| from src.inference.api_server import app as models_app | |
| MODELS_AVAILABLE = True | |
| logger.info("✅ Models API successfully imported") | |
| except Exception as e: | |
| logger.error(f"❌ Failed to import models API: {e}") | |
| MODELS_AVAILABLE = False | |
| async def lifespan(app: FastAPI): | |
| """Application lifespan manager for HuggingFace Spaces.""" | |
| logger.info("🚀 Starting Cidadão.AI Models on HuggingFace Spaces") | |
| logger.info(f"🔧 Environment: {os.getenv('SPACE_ID', 'local')}") | |
| logger.info(f"🌐 Port: {os.getenv('PORT', '8001')}") | |
| yield | |
| logger.info("🛑 Shutting down Cidadão.AI Models") | |
| if MODELS_AVAILABLE: | |
| # Use the imported models app | |
| app = models_app | |
| logger.info("Using full models API") | |
| else: | |
| # Fallback minimal app | |
| app = FastAPI( | |
| title="🤖 Cidadão.AI Models (Fallback)", | |
| description="Minimal fallback API when models are not available", | |
| version="1.0.0", | |
| lifespan=lifespan | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def fallback_root(): | |
| """Fallback root with information about the service.""" | |
| return """ | |
| <html> | |
| <head> | |
| <title>Cidadão.AI Models</title> | |
| <style> | |
| body { font-family: Arial, sans-serif; margin: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; } | |
| .container { max-width: 800px; margin: 0 auto; padding: 20px; background: rgba(255,255,255,0.1); border-radius: 10px; } | |
| h1 { font-size: 2.5em; margin-bottom: 10px; } | |
| .emoji { font-size: 1.2em; } | |
| .status { background: rgba(255,255,255,0.2); padding: 15px; border-radius: 5px; margin: 20px 0; } | |
| .endpoint { background: rgba(0,0,0,0.2); padding: 10px; border-radius: 5px; margin: 10px 0; font-family: monospace; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>🤖 Cidadão.AI Models</h1> | |
| <p><strong>Sistema de ML para Transparência Pública Brasileira</strong></p> | |
| <div class="status"> | |
| <h3>📊 Status do Sistema</h3> | |
| <p>⚠️ Modo Fallback - Modelos ML não disponíveis</p> | |
| <p>🔧 Para funcionalidade completa, verifique as dependências</p> | |
| </div> | |
| <div class="status"> | |
| <h3>🔗 Endpoints Disponíveis</h3> | |
| <div class="endpoint">GET /health - Health check</div> | |
| <div class="endpoint">GET /docs - Documentação da API</div> | |
| <div class="endpoint">GET / - Esta página</div> | |
| </div> | |
| <div class="status"> | |
| <h3>🏛️ Sobre o Cidadão.AI</h3> | |
| <p>Sistema multi-agente de IA para análise de transparência pública, | |
| especializado em detectar anomalias e padrões suspeitos em dados | |
| governamentais brasileiros.</p> | |
| </div> | |
| <p style="text-align: center; margin-top: 40px;"> | |
| <a href="/docs" style="color: white; text-decoration: underline;"> | |
| 📚 Ver Documentação da API | |
| </a> | |
| </p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| async def fallback_health(): | |
| """Fallback health check.""" | |
| return { | |
| "status": "limited", | |
| "mode": "fallback", | |
| "models_loaded": False, | |
| "message": "Models not available, running in fallback mode" | |
| } | |
| logger.info("Using fallback minimal API") | |
| # Add HuggingFace Spaces specific routes | |
| async def spaces_info(): | |
| """HuggingFace Spaces specific information.""" | |
| return { | |
| "platform": "HuggingFace Spaces", | |
| "space_id": os.getenv("SPACE_ID", "unknown"), | |
| "space_author": os.getenv("SPACE_AUTHOR", "cidadao-ai"), | |
| "space_title": os.getenv("SPACE_TITLE", "Cidadão.AI Models"), | |
| "sdk": "docker", | |
| "port": int(os.getenv("PORT", "8001")), | |
| "models_available": MODELS_AVAILABLE | |
| } | |
| if __name__ == "__main__": | |
| # Configuration for HuggingFace Spaces | |
| port = int(os.getenv("PORT", "8001")) | |
| host = os.getenv("HOST", "0.0.0.0") | |
| logger.info(f"🚀 Starting server on {host}:{port}") | |
| logger.info(f"📊 Models available: {MODELS_AVAILABLE}") | |
| try: | |
| # Use uvicorn with optimized settings for HuggingFace | |
| uvicorn.run( | |
| app, | |
| host=host, | |
| port=port, | |
| log_level="info", | |
| access_log=True, | |
| workers=1, # Single worker for HuggingFace Spaces | |
| loop="asyncio" | |
| ) | |
| except Exception as e: | |
| logger.error(f"❌ Failed to start server: {str(e)}") | |
| sys.exit(1) |