from contextlib import asynccontextmanager import logging import os from pathlib import Path from fastapi import FastAPI, HTTPException from fastapi.responses import RedirectResponse, JSONResponse from fastapi.exceptions import RequestValidationError from .encoding import InputTooLong from .prediction import ModelNotReady, PredictionService from .schemas import DecisionRequest, DecisionResponse from .settings import ROOT, HUB_CACHE logger = logging.getLogger(__name__) def runtime_artifacts(default): repo, revision = os.getenv("MODEL_REPO_ID"), os.getenv("MODEL_REVISION") if repo: if not revision or len(revision) != 40: raise ModelNotReady("Потрібна зафіксована MODEL_REVISION.") from huggingface_hub import snapshot_download return Path(snapshot_download(repo, revision=revision, allow_patterns=["manifest.json", "head.safetensors", "calibration.json", "metrics.json",'encoder_delta.safetensors'], cache_dir=str(HUB_CACHE))) return Path(default) def create_app(service=None, artifact_dir=None, with_ui=True): @asynccontextmanager async def lifespan(app): if app.state.service is None: try: import torch torch.set_num_threads(2) path = runtime_artifacts(artifact_dir or ROOT / "artifacts" / "model") app.state.service = PredictionService.load(path, device="cpu") except Exception as exc: # No request texts, provider keys or upstream response bodies in logs. logger.warning("Model initialization unavailable: %s", type(exc).__name__) yield app = FastAPI(title="Модель рішень", version="1.1.0", lifespan=lifespan) app.state.service = service @app.exception_handler(RequestValidationError) async def invalid_request(request, exc): # Do not echo arbitrary input (including NaN) into the JSON error body. details = [{"loc": list(error["loc"]), "msg": error["msg"], "type": error["type"]} for error in exc.errors()] return JSONResponse(status_code=422, content={"detail": details}) @app.get("/healthz") def health(): return {"status": "alive"} @app.get("/readyz") def ready(): if app.state.service is None: raise HTTPException(503, "Навчена модель ще не готова.") return {"status": "ready", "model": app.state.service.model_version} @app.post("/v1/systemone", response_model=DecisionResponse) def decide(request: DecisionRequest): if app.state.service is None: raise HTTPException(503, "Навчена модель ще не готова.") try: return app.state.service.predict(request) except (InputTooLong, ValueError) as exc: raise HTTPException(422, str(exc)) from None except ModelNotReady: raise HTTPException(503, "Модель тимчасово недоступна.") from None @app.get("/", include_in_schema=False) def index(): return RedirectResponse("/demo/") if with_ui: import gradio as gr from .ui import build_demo, build_theme app = gr.mount_gradio_app(app, build_demo(lambda: app.state.service), path="/demo", run_history=False, blocked_paths=[str(ROOT / ".env"), str(ROOT / "data"), str(ROOT / ".venv"), str(ROOT / ".cache")], footer_links=[], theme=build_theme()) return app