caarleexx commited on
Commit
0bd0bbb
·
verified ·
1 Parent(s): ccc7bc9

Update api/main.py

Browse files
Files changed (1) hide show
  1. api/main.py +23 -66
api/main.py CHANGED
@@ -1,39 +1,26 @@
1
  """
2
- Aplicação FastAPI Principal - para.AI v3.0
3
- Endpoint para processar JSONL e gerar TAR.GZ
4
  """
5
- import logging
6
- from fastapi import FastAPI, Request
7
  from fastapi.middleware.cors import CORSMiddleware
8
- from fastapi.responses import JSONResponse
9
- from contextlib import asynccontextmanager
10
- from datetime import datetime
11
- import time
12
-
13
  from api.config import settings
14
- from api.routes import health, test, process, download
15
- from api.utils.logger import setup_logger
16
-
17
- # Configurar logging
18
- logger = setup_logger()
19
 
20
- @asynccontextmanager
21
- async def lifespan(app: FastAPI):
22
- """Lifespan events"""
23
- logger.info(f"🚀 Iniciando {settings.APP_NAME} v{settings.APP_VERSION}")
24
- logger.info(f"📊 Modo: {'DEBUG' if settings.DEBUG else 'PRODUCTION'}")
25
- logger.info(f"🔧 Workers: {settings.MAX_WORKERS}")
26
- yield
27
- logger.info("🛑 Encerrando API")
28
 
29
- # Criar aplicação
30
  app = FastAPI(
31
  title=settings.APP_NAME,
32
  version=settings.APP_VERSION,
33
- description="Sistema de processamento de jurisprudências com 9 especialistas LLM",
34
- lifespan=lifespan,
35
- docs_url="/docs" if settings.DEBUG else None,
36
- redoc_url="/redoc" if settings.DEBUG else None,
37
  )
38
 
39
  # CORS
@@ -45,57 +32,27 @@ app.add_middleware(
45
  allow_headers=["*"],
46
  )
47
 
48
- # Middleware de tempo de processamento
49
- @app.middleware("http")
50
- async def add_process_time(request: Request, call_next):
51
- start = time.time()
52
- response = await call_next(request)
53
- process_time = time.time() - start
54
- response.headers["X-Process-Time"] = f"{process_time:.4f}"
55
- return response
56
 
57
- # Exception handler global
58
- @app.exception_handler(Exception)
59
- async def global_exception_handler(request: Request, exc: Exception):
60
- logger.error(f"❌ Erro global: {exc}", exc_info=True)
61
- return JSONResponse(
62
- status_code=500,
63
- content={
64
- "error": "Internal Server Error",
65
- "detail": str(exc) if settings.DEBUG else "Erro no processamento",
66
- "timestamp": datetime.now().isoformat(),
67
- "path": str(request.url)
68
- }
69
- )
70
 
71
- # Rotas
72
- app.include_router(health.router, prefix="/health", tags=["Health"])
73
- app.include_router(test.router, prefix="/test", tags=["Tests"])
74
- app.include_router(process.router, prefix="/process", tags=["Process"])
75
- app.include_router(download.router, prefix="/download", tags=["Download"])
76
 
77
  @app.get("/")
78
  async def root():
79
- """Endpoint raiz"""
80
  return {
81
  "app": settings.APP_NAME,
82
  "version": settings.APP_VERSION,
83
  "status": "running",
84
- "timestamp": datetime.now().isoformat(),
85
- "docs": "/docs" if settings.DEBUG else "disabled",
86
  "endpoints": {
 
87
  "health": "/health",
88
  "test_specialists": "/test/specialists",
89
  "process_jsonl": "/process/jsonl",
90
  "download": "/download/{batch_id}"
91
  }
92
- }
93
-
94
- if __name__ == "__main__":
95
- import uvicorn
96
- uvicorn.run(
97
- "api.app:app",
98
- host=settings.API_HOST,
99
- port=settings.API_PORT,
100
- reload=settings.DEBUG
101
- )
 
1
  """
2
+ FastAPI Application Principal
 
3
  """
4
+ from fastapi import FastAPI
 
5
  from fastapi.middleware.cors import CORSMiddleware
 
 
 
 
 
6
  from api.config import settings
7
+ from api.routes import health_routes, debug_routes, status_routes
8
+ from api.routes import test_routes, process_routes
9
+ import logging
 
 
10
 
11
+ # Setup logging
12
+ logging.basicConfig(
13
+ level=settings.LOG_LEVEL,
14
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
15
+ )
16
+ logger = logging.getLogger("para_ai")
 
 
17
 
18
+ # Criar app
19
  app = FastAPI(
20
  title=settings.APP_NAME,
21
  version=settings.APP_VERSION,
22
+ description="Sistema para.AI - 9 Especialistas LLM para análise jurisprudencial",
23
+ docs_url="/docs" if settings.DEBUG else None
 
 
24
  )
25
 
26
  # CORS
 
32
  allow_headers=["*"],
33
  )
34
 
35
+ # Rotas
36
+ app.include_router(health_routes.router, prefix="/health", tags=["Health"])
37
+ app.include_router(test_routes.router, prefix="/test", tags=["Tests"])
38
+ app.include_router(process_routes.router, prefix="/process", tags=["Process"])
39
+ app.include_router(status_routes.router, prefix="/status", tags=["Status"])
 
 
 
40
 
41
+ if settings.DEBUG:
42
+ app.include_router(debug_routes.router, prefix="/debug", tags=["Debug"])
 
 
 
 
 
 
 
 
 
 
 
43
 
 
 
 
 
 
44
 
45
  @app.get("/")
46
  async def root():
 
47
  return {
48
  "app": settings.APP_NAME,
49
  "version": settings.APP_VERSION,
50
  "status": "running",
 
 
51
  "endpoints": {
52
+ "docs": "/docs",
53
  "health": "/health",
54
  "test_specialists": "/test/specialists",
55
  "process_jsonl": "/process/jsonl",
56
  "download": "/download/{batch_id}"
57
  }
58
+ }