Spaces:
Running
Running
Upload 4 files
Browse files- Dockerfile +29 -0
- app.py +154 -0
- requirements.txt +9 -0
- yolo_fruits_and_vegetables_v3.pt +3 -0
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the official Python 3.9 image
|
| 2 |
+
FROM python:3.9-slim
|
| 3 |
+
|
| 4 |
+
# Set the working directory
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
RUN mkdir -p /tmp/Ultralytics && chmod -R 777 /tmp/Ultralytics
|
| 7 |
+
ENV YOLO_CONFIG_DIR=/tmp/Ultralytics
|
| 8 |
+
|
| 9 |
+
# Install system dependencies
|
| 10 |
+
# We use libgl1 and libglib2.0-0 which are the modern equivalents
|
| 11 |
+
RUN apt-get update && apt-get install -y \
|
| 12 |
+
libgl1 \
|
| 13 |
+
libglib2.0-0 \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
+
|
| 16 |
+
# Copy the requirements file
|
| 17 |
+
COPY requirements.txt .
|
| 18 |
+
|
| 19 |
+
# Install Python dependencies
|
| 20 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 21 |
+
|
| 22 |
+
# Copy everything else
|
| 23 |
+
COPY . .
|
| 24 |
+
|
| 25 |
+
# Expose port 7860 for Hugging Face
|
| 26 |
+
EXPOSE 7860
|
| 27 |
+
|
| 28 |
+
# Command to run the application
|
| 29 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import base64
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from ultralytics import YOLO
|
| 9 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
| 10 |
+
|
| 11 |
+
# --- App Config ---
|
| 12 |
+
app = FastAPI(
|
| 13 |
+
title="Food & Vegetable AI API",
|
| 14 |
+
description="Separate APIs for ViT Classification and YOLO Detection",
|
| 15 |
+
version="2.1.0"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
app.add_middleware(
|
| 19 |
+
CORSMiddleware,
|
| 20 |
+
allow_origins=["*"],
|
| 21 |
+
allow_credentials=True,
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
class Base64ImageRequest(BaseModel):
|
| 27 |
+
image: str
|
| 28 |
+
|
| 29 |
+
# --- Model Loading ---
|
| 30 |
+
print("Loading models...")
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
vit_model = AutoModelForImageClassification.from_pretrained(
|
| 34 |
+
"eslamxm/vit-base-food101"
|
| 35 |
+
)
|
| 36 |
+
vit_processor = AutoImageProcessor.from_pretrained(
|
| 37 |
+
"eslamxm/vit-base-food101"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
yolo_model = YOLO("yolo_fruits_and_vegetables_v3.pt")
|
| 41 |
+
|
| 42 |
+
print("✓ Models loaded successfully")
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"✗ Model loading failed: {e}")
|
| 45 |
+
vit_model = None
|
| 46 |
+
yolo_model = None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# --- Utility ---
|
| 50 |
+
def load_image_from_bytes(image_bytes: bytes) -> Image.Image:
|
| 51 |
+
return Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# --- YOLO Detection ---
|
| 55 |
+
def run_yolo(image: Image.Image):
|
| 56 |
+
if not yolo_model:
|
| 57 |
+
raise HTTPException(status_code=500, detail="YOLO model not loaded")
|
| 58 |
+
|
| 59 |
+
results = yolo_model(image)
|
| 60 |
+
|
| 61 |
+
detections = []
|
| 62 |
+
summary = {}
|
| 63 |
+
|
| 64 |
+
for r in results:
|
| 65 |
+
for i in range(len(r.boxes)):
|
| 66 |
+
label = yolo_model.names[int(r.boxes.cls[i])]
|
| 67 |
+
detections.append({
|
| 68 |
+
"label": label,
|
| 69 |
+
"confidence": float(r.boxes.conf[i]),
|
| 70 |
+
"bbox": r.boxes.xyxy[i].tolist()
|
| 71 |
+
})
|
| 72 |
+
summary[label] = summary.get(label, 0) + 1
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"detections": detections,
|
| 76 |
+
"summary": summary
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# --- ViT Classification ---
|
| 81 |
+
def run_vit(image: Image.Image):
|
| 82 |
+
if not vit_model:
|
| 83 |
+
raise HTTPException(status_code=500, detail="ViT model not loaded")
|
| 84 |
+
|
| 85 |
+
inputs = vit_processor(images=image, return_tensors="pt")
|
| 86 |
+
|
| 87 |
+
with torch.no_grad():
|
| 88 |
+
outputs = vit_model(**inputs)
|
| 89 |
+
|
| 90 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 91 |
+
pred_id = probs.argmax().item()
|
| 92 |
+
|
| 93 |
+
return {
|
| 94 |
+
"label": vit_model.config.id2label[pred_id],
|
| 95 |
+
"confidence": round(probs[0][pred_id].item(), 4)
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# --- Routes ---
|
| 100 |
+
@app.get("/")
|
| 101 |
+
async def root():
|
| 102 |
+
return {
|
| 103 |
+
"message": "API running",
|
| 104 |
+
"endpoints": ["/predict-vit", "/predict-yolo"]
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# ---------- YOLO Endpoint ----------
|
| 109 |
+
@app.post("/predict-yolo")
|
| 110 |
+
async def predict_yolo(file: UploadFile = File(...)):
|
| 111 |
+
try:
|
| 112 |
+
image = load_image_from_bytes(await file.read())
|
| 113 |
+
return {"detection": run_yolo(image)}
|
| 114 |
+
except Exception as e:
|
| 115 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ---------- ViT Endpoint ----------
|
| 119 |
+
@app.post("/predict-vit")
|
| 120 |
+
async def predict_vit(file: UploadFile = File(...)):
|
| 121 |
+
try:
|
| 122 |
+
image = load_image_from_bytes(await file.read())
|
| 123 |
+
return {"classification": run_vit(image)}
|
| 124 |
+
except Exception as e:
|
| 125 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------- Base64 Support (optional) ----------
|
| 129 |
+
@app.post("/predict-vit-base64")
|
| 130 |
+
async def predict_vit_base64(request: Base64ImageRequest):
|
| 131 |
+
try:
|
| 132 |
+
_, encoded = request.image.split(",", 1) if "," in request.image else (None, request.image)
|
| 133 |
+
image_bytes = base64.b64decode(encoded)
|
| 134 |
+
image = load_image_from_bytes(image_bytes)
|
| 135 |
+
return {"classification": run_vit(image)}
|
| 136 |
+
except Exception as e:
|
| 137 |
+
raise HTTPException(status_code=500, detail=f"ViT base64 error: {str(e)}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@app.post("/predict-yolo-base64")
|
| 141 |
+
async def predict_yolo_base64(request: Base64ImageRequest):
|
| 142 |
+
try:
|
| 143 |
+
_, encoded = request.image.split(",", 1) if "," in request.image else (None, request.image)
|
| 144 |
+
image_bytes = base64.b64decode(encoded)
|
| 145 |
+
image = load_image_from_bytes(image_bytes)
|
| 146 |
+
return {"detection": run_yolo(image)}
|
| 147 |
+
except Exception as e:
|
| 148 |
+
raise HTTPException(status_code=500, detail=f"YOLO base64 error: {str(e)}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# --- Run ---
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
import uvicorn
|
| 154 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
ultralytics
|
| 4 |
+
python-multipart
|
| 5 |
+
pillow
|
| 6 |
+
numpy
|
| 7 |
+
torch
|
| 8 |
+
torchvision
|
| 9 |
+
transformers
|
yolo_fruits_and_vegetables_v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:75b53f0807692f6a6f77545f805158507751a977dec3bb5349b1625f280fa0f4
|
| 3 |
+
size 136818985
|