Spaces:
Sleeping
Sleeping
File size: 6,093 Bytes
b95e73a |
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 |
#!/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
@asynccontextmanager
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=["*"],
)
@app.get("/", response_class=HTMLResponse)
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>
"""
@app.get("/health")
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
@app.get("/spaces-info")
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) |