caarleexx commited on
Commit
5ae7e5b
·
verified ·
1 Parent(s): e8216e0

Update api/main.py

Browse files
Files changed (1) hide show
  1. api/main.py +74 -80
api/main.py CHANGED
@@ -1,106 +1,100 @@
1
  """
2
- FastAPI Application Factory
3
- Main entry point for para.AI API
4
  """
 
5
  from fastapi import FastAPI, Request
6
  from fastapi.middleware.cors import CORSMiddleware
7
  from fastapi.responses import JSONResponse
8
  from contextlib import asynccontextmanager
9
- import logging
10
- import time
11
  from datetime import datetime
 
12
 
13
- from api.config import settings
14
- from api.routes import debug_routes, process_routes, status_routes, health_routes
15
-
16
-
17
- logging.basicConfig(
18
- level=settings.LOG_LEVEL,
19
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
20
- )
21
- logger = logging.getLogger(__name__)
22
 
 
 
23
 
24
  @asynccontextmanager
25
  async def lifespan(app: FastAPI):
26
  """Lifespan events"""
27
- logger.info(f"🚀 Starting {settings.APP_NAME} v{settings.APP_VERSION}")
28
- logger.info(f"📊 Environment: {'DEBUG' if settings.DEBUG else 'PRODUCTION'}")
29
- logger.info(f"🤖 LLM Model: {settings.LLM_MODEL}")
30
-
31
  yield
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- logger.info("🛑 Shutting down API")
34
-
35
-
36
- def create_app() -> FastAPI:
37
- """Factory function to create FastAPI app"""
38
-
39
- app = FastAPI(
40
- title=settings.APP_NAME,
41
- version=settings.APP_VERSION,
42
- description="API para análise jurisprudencial com LLMs - Sistema de 9 Especialistas",
43
- lifespan=lifespan,
44
- docs_url="/docs" if settings.DEBUG else None,
45
- redoc_url="/redoc" if settings.DEBUG else None,
46
- )
47
-
48
- app.add_middleware(
49
- CORSMiddleware,
50
- allow_origins=settings.CORS_ORIGINS,
51
- allow_credentials=True,
52
- allow_methods=["*"],
53
- allow_headers=["*"],
54
- )
55
-
56
- @app.middleware("http")
57
- async def add_process_time_header(request: Request, call_next):
58
- start_time = time.time()
59
- response = await call_next(request)
60
- process_time = time.time() - start_time
61
- response.headers["X-Process-Time"] = str(process_time)
62
- return response
63
-
64
- @app.exception_handler(Exception)
65
- async def global_exception_handler(request: Request, exc: Exception):
66
- logger.error(f"Global exception: {exc}", exc_info=True)
67
- return JSONResponse(
68
- status_code=500,
69
- content={
70
- "error": "Internal Server Error",
71
- "detail": str(exc) if settings.DEBUG else "An error occurred",
72
- "timestamp": datetime.now().isoformat(),
73
- "path": str(request.url)
74
- }
75
- )
76
-
77
- app.include_router(health_routes.router, prefix="/health", tags=["Health"])
78
- app.include_router(process_routes.router, prefix="/process", tags=["Process"])
79
- app.include_router(status_routes.router, prefix="/status", tags=["Status"])
80
-
81
- if settings.DEBUG:
82
- app.include_router(debug_routes.router, prefix="/debug", tags=["Debug"])
83
 
84
- @app.get("/")
85
- async def root():
86
- return {
87
- "app": settings.APP_NAME,
88
- "version": settings.APP_VERSION,
89
- "status": "running",
 
 
 
 
 
 
 
 
 
 
 
 
90
  "timestamp": datetime.now().isoformat(),
91
- "docs": "/docs" if settings.DEBUG else "disabled"
92
  }
 
93
 
94
- return app
95
-
96
-
97
- app = create_app()
98
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  if __name__ == "__main__":
101
  import uvicorn
102
  uvicorn.run(
103
- "api.main:app",
104
  host=settings.API_HOST,
105
  port=settings.API_PORT,
106
  reload=settings.DEBUG
 
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 main.config import settings
14
+ from main.api.routes import health, test, process, download
15
+ from main.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
40
+ app.add_middleware(
41
+ CORSMiddleware,
42
+ allow_origins=settings.CORS_ORIGINS,
43
+ allow_credentials=True,
44
+ allow_methods=["*"],
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
+ "main.app:app",
98
  host=settings.API_HOST,
99
  port=settings.API_PORT,
100
  reload=settings.DEBUG