-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
68 lines (54 loc) · 2.09 KB
/
main.py
File metadata and controls
68 lines (54 loc) · 2.09 KB
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
"""
FastAPI backend: run a leaf image through the PlantDoc model.
uvicorn main:app --reload
POST /predict with multipart/form-data file "file" (image)
"""
from pathlib import Path
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from plantdoc.predict import load_model_and_classes, predict_from_bytes
ROOT = Path(__file__).parent
MODEL_PATH = ROOT / "vgg16_plantdoc.weights.h5"
CLASSES_PATH = ROOT / "class_names.json"
app = FastAPI(title="PlantDoc API", description="Plant disease classification from leaf images")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
model = None
class_names = None
@app.on_event("startup")
def load_model():
global model, class_names
if not MODEL_PATH.is_file():
raise FileNotFoundError(f"Model not found: {MODEL_PATH}. Put vgg16_plantdoc.weights.h5 in the project root.")
model, class_names = load_model_and_classes(str(MODEL_PATH), str(CLASSES_PATH) if CLASSES_PATH.is_file() else None)
class PredictResponse(BaseModel):
label: str
confidence: float
all_classes: list[float] | None = None
@app.post("/predict", response_model=PredictResponse)
async def predict(file: UploadFile = File(..., description="Leaf image (jpg/png)")):
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(400, "Upload must be an image (e.g. image/jpeg, image/png)")
try:
body = await file.read()
except Exception as e:
raise HTTPException(400, f"Failed to read file: {e}")
if not body:
raise HTTPException(400, "Empty file")
try:
label, conf, probs = predict_from_bytes(model, body, class_names)
except Exception as e:
raise HTTPException(422, f"Prediction failed (invalid image?): {e}")
return PredictResponse(
label=label,
confidence=round(1.0 - conf, 4),
all_classes=probs,
)
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": model is not None}