Newer
Older
vmk-360-data_collector / src / vmk_data_collector / main.py
@Eugene Sukhodolskiy Eugene Sukhodolskiy 1 day ago 2 KB feat: implement review items 1-7
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import JSONResponse

from vmk_data_collector.api.v1.router_health import router as health_router
from vmk_data_collector.api.v1.router_properties import (
    router as properties_router,
)
from vmk_data_collector.core.config import settings
from vmk_data_collector.core.exceptions import (
    AIProcessingError,
    AppError,
    NotRealEstateError,
    ValidationError,
)
from vmk_data_collector.core.logging import configure_logging
from vmk_data_collector.services.ollama_client import OllamaClient


@asynccontextmanager
async def lifespan(app: FastAPI):
    configure_logging(settings.log_level, debug=settings.debug)
    Path(settings.image_storage_path).mkdir(parents=True, exist_ok=True)
    app.state.ollama_client = OllamaClient(
        base_url=settings.ollama_base_url,
        timeout=settings.ollama_timeout,
    )
    yield
    await app.state.ollama_client.close()


app = FastAPI(
    title="VMK Data Collector",
    version="0.1.0",
    lifespan=lifespan,
)

app.include_router(health_router, prefix="/api/v1")
app.include_router(properties_router, prefix="/api/v1")


@app.exception_handler(AppError)
async def app_error_handler(request, exc: AppError):
    return JSONResponse(
        status_code=500,
        content={"detail": exc.message},
    )


@app.exception_handler(ValidationError)
async def validation_error_handler(request, exc: ValidationError):
    return JSONResponse(
        status_code=422,
        content={"detail": exc.message},
    )


@app.exception_handler(NotRealEstateError)
async def not_real_estate_handler(request, exc: NotRealEstateError):
    return JSONResponse(
        status_code=202,
        content={"status": "invalid", "reason": exc.message},
    )


@app.exception_handler(AIProcessingError)
async def ai_processing_error_handler(request, exc: AIProcessingError):
    return JSONResponse(
        status_code=202,
        content={"status": "failed", "reason": exc.message},
    )