File size: 1,986 Bytes
cb92718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.schemas import PredictionResponse


app = FastAPI(
    title="Derm Foundation Classifier API",
    description="Derm Foundation embedding backbone + PyTorch MLP head.",
    version="1.0.0",
)


app.add_middleware(
    CORSMiddleware,
    allow_origins=[origin.strip() for origin in settings.cors_origins.split(",")],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


app.state.predictor = None


def get_predictor():
    if app.state.predictor is None:
        print("Loading TwoStageDermPredictor...", flush=True)

        from app.services.predictor import TwoStageDermPredictor

        app.state.predictor = TwoStageDermPredictor(
            derm_model_id=settings.derm_model_id,
            head_checkpoint_path=str(settings.head_checkpoint_path),
            hf_token=settings.hf_token,
            local_files_only=settings.local_files_only,
            image_size=settings.image_size,
            device_name=settings.device,
        )

        print("TwoStageDermPredictor loaded.", flush=True)

    return app.state.predictor


@app.get("/")
def root():
    return {"message": "Derm Foundation API is running"}


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/predict", response_model=PredictionResponse)
async def predict(file: UploadFile = File(...)):
    if file.content_type is not None and not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Uploaded file must be an image.")

    image_bytes = await file.read()

    if not image_bytes:
        raise HTTPException(status_code=400, detail="Uploaded image is empty.")

    try:
        predictor = get_predictor()
        return predictor.predict(image_bytes)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc