from __future__ import annotations import os from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI from fastapi.responses import ORJSONResponse, HTMLResponse from fastapi.middleware.cors import CORSMiddleware from elasticsearch import AsyncElasticsearch from .core.config_loader import load_config from .core.indexer import setup_index from .routes_generic import build_router CONFIG_PATH = os.getenv("CONFIG_PATH", "/app/config-assuntos-juridicos.yaml") config = load_config(CONFIG_PATH) _es: AsyncElasticsearch | None = None def get_es(): global _es if _es is None: _es = AsyncElasticsearch([config.es_host],request_timeout=config.elasticsearch.timeout,retry_on_timeout=True,max_retries=config.elasticsearch.max_retries) return _es @asynccontextmanager async def lifespan(app): await setup_index(get_es(), config) yield if _es: await _es.close() app = FastAPI(title=config.display_name or config.index_name,version="2.0.0",default_response_class=ORJSONResponse,lifespan=lifespan) app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"]) app.include_router(build_router(config, get_es)) @app.get("/", response_class=HTMLResponse, include_in_schema=False) async def root(): return """
API de busca full-text e navegação hierárquica sobre os assuntos jurídicos do STJ/TST, indexados no Elasticsearch com analyzer de português.