File size: 1,415 Bytes
82d7501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from __future__ import annotations

import io
from pathlib import Path

from PIL import Image

from .config import DEFAULT_BACKEND, DEFAULT_HF_MODEL_ID, DEFAULT_HYBRID_UNIVFD_WEIGHT
from .model import create_detector


def create_app(
    *,
    threshold: float = 0.5,
    device: str | None = None,
    backend: str = DEFAULT_BACKEND,
    weight_path: str | Path | None = None,
    hf_model: str = DEFAULT_HF_MODEL_ID,
    hybrid_univfd_weight: float = DEFAULT_HYBRID_UNIVFD_WEIGHT,
):
    try:
        from fastapi import FastAPI, File, UploadFile
    except ImportError as exc:
        raise RuntimeError("Missing dependency: install ai-image-detector[api].") from exc

    detector = create_detector(
        backend,
        device=device,
        threshold=threshold,
        weight_path=weight_path,
        hf_model=hf_model,
        hybrid_univfd_weight=hybrid_univfd_weight,
    )
    app = FastAPI(title="AI Image Detector", version="0.3.0")

    @app.get("/health")
    def health() -> dict:
        return {"status": "ok", "model": detector.model_info()}

    @app.post("/detect")
    async def detect(file: UploadFile = File(...)) -> dict:
        content = await file.read()
        with Image.open(io.BytesIO(content)) as image:
            result = detector.predict_image(image)
        payload = result.as_dict()
        payload["filename"] = file.filename
        return payload

    return app