File size: 4,389 Bytes
bb47ff9
 
 
 
 
 
 
 
446bc62
bb47ff9
446bc62
bb47ff9
 
446bc62
 
bb47ff9
 
 
 
 
 
 
 
 
 
 
 
 
446bc62
 
bb47ff9
 
 
446bc62
 
 
 
bb47ff9
 
446bc62
bb47ff9
446bc62
bb47ff9
446bc62
bb47ff9
 
 
 
446bc62
bb47ff9
446bc62
bb47ff9
 
446bc62
bb47ff9
446bc62
 
bb47ff9
6a8d95f
bb47ff9
 
 
 
446bc62
 
 
bb47ff9
 
446bc62
 
bb47ff9
446bc62
bb47ff9
 
 
446bc62
bb47ff9
 
 
446bc62
 
 
 
bb47ff9
446bc62
bb47ff9
446bc62
 
bb47ff9
446bc62
 
bb47ff9
 
446bc62
 
bb47ff9
 
 
446bc62
 
 
bb47ff9
446bc62
 
bb47ff9
 
 
446bc62
bb47ff9
446bc62
bb47ff9
446bc62
 
bb47ff9
446bc62
bb47ff9
 
446bc62
bb47ff9
446bc62
bb47ff9
446bc62
 
bb47ff9
446bc62
bb47ff9
 
446bc62
bb47ff9
446bc62
bb47ff9
446bc62
 
 
 
bb47ff9
446bc62
bb47ff9
 
 
446bc62
bb47ff9
446bc62
 
 
 
bb47ff9
446bc62
bb47ff9
 
446bc62
bb47ff9
 
446bc62
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import io
import base64
import torch
from PIL import Image
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from ultralytics import YOLO
from transformers import AutoImageProcessor, AutoModelForImageClassification

# --- App Config ---
app = FastAPI(
    title="Food & Vegetable AI API",
    description="Separate APIs for ViT Classification and YOLO Detection",
    version="2.1.0"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Base64ImageRequest(BaseModel):
    image: str

# --- Model Loading ---
print("Loading models...")

try:
    vit_model = AutoModelForImageClassification.from_pretrained(
        "eslamxm/vit-base-food101"
    )
    vit_processor = AutoImageProcessor.from_pretrained(
        "eslamxm/vit-base-food101"
    )

    yolo_model = YOLO("yolo_fruits_and_vegetables_v3.pt")

    print("✓ Models loaded successfully")
except Exception as e:
    print(f"✗ Model loading failed: {e}")
    vit_model = None
    yolo_model = None


# --- Utility ---
def load_image_from_bytes(image_bytes: bytes) -> Image.Image:
    return Image.open(io.BytesIO(image_bytes)).convert("RGB")


# --- YOLO Detection ---
def run_yolo(image: Image.Image):
    if not yolo_model:
        raise HTTPException(status_code=500, detail="YOLO model not loaded")

    results = yolo_model(image, conf=0.4, iou=0.45)

    detections = []
    summary = {}

    for r in results:
        for i in range(len(r.boxes)):
            label = yolo_model.names[int(r.boxes.cls[i])]
            detections.append({
                "label": label,
                "confidence": float(r.boxes.conf[i]),
                "bbox": r.boxes.xyxy[i].tolist()
            })
            summary[label] = summary.get(label, 0) + 1

    return {
        "detections": detections,
        "summary": summary
    }


# --- ViT Classification ---
def run_vit(image: Image.Image):
    if not vit_model:
        raise HTTPException(status_code=500, detail="ViT model not loaded")

    inputs = vit_processor(images=image, return_tensors="pt")

    with torch.no_grad():
        outputs = vit_model(**inputs)

    probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
    pred_id = probs.argmax().item()

    return {
        "label": vit_model.config.id2label[pred_id],
        "confidence": round(probs[0][pred_id].item(), 4)
    }


# --- Routes ---
@app.get("/")
async def root():
    return {
        "message": "API running",
        "endpoints": ["/predict-vit", "/predict-yolo"]
    }


# ---------- YOLO Endpoint ----------
@app.post("/predict-yolo")
async def predict_yolo(file: UploadFile = File(...)):
    try:
        image = load_image_from_bytes(await file.read())
        return {"detection": run_yolo(image)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# ---------- ViT Endpoint ----------
@app.post("/predict-vit")
async def predict_vit(file: UploadFile = File(...)):
    try:
        image = load_image_from_bytes(await file.read())
        return {"classification": run_vit(image)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# ---------- Base64 Support (optional) ----------
@app.post("/predict-vit-base64")
async def predict_vit_base64(request: Base64ImageRequest):
    try:
        _, encoded = request.image.split(",", 1) if "," in request.image else (None, request.image)
        image_bytes = base64.b64decode(encoded)
        image = load_image_from_bytes(image_bytes)
        return {"classification": run_vit(image)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"ViT base64 error: {str(e)}")


@app.post("/predict-yolo-base64")
async def predict_yolo_base64(request: Base64ImageRequest):
    try:
        _, encoded = request.image.split(",", 1) if "," in request.image else (None, request.image)
        image_bytes = base64.b64decode(encoded)
        image = load_image_from_bytes(image_bytes)
        return {"detection": run_yolo(image)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"YOLO base64 error: {str(e)}")


# --- Run ---
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)