File size: 1,627 Bytes
51607f3
 
 
 
 
b22cfd8
 
 
 
 
 
ea8d5c0
 
b22cfd8
 
ea8d5c0
b22cfd8
ea8d5c0
b22cfd8
 
 
 
 
51607f3
 
 
 
b22cfd8
 
 
51607f3
b22cfd8
51607f3
 
b22cfd8
 
 
 
 
 
51607f3
b22cfd8
 
 
 
51607f3
 
b22cfd8
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from transformers import pipeline
from PIL import Image
import io
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    global model
    print("🚀 Memuat model ResNet50 dari Hugging Face...")
    
    # Muat model tanpa argumen tambahan
    model = pipeline(
        "image-classification",
        model="SanketJadhav/PlantDiseaseClassifier-Resnet50"
    )
    
    print("✅ Model siap digunakan (CPU mode)")
    yield
    print("🧹 Server FastAPI dimatikan.")

app = FastAPI(lifespan=lifespan)

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    try:
        # Baca file gambar dari request
        image_bytes = await file.read()
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")

        # Jalankan prediksi
        results = model(image)

        # Ambil 3 hasil teratas
        top_results = sorted(results, key=lambda x: x['score'], reverse=True)[:3]
        formatted = [
            {"label": res['label'], "score": round(res['score'], 3)}
            for res in top_results
        ]

        return JSONResponse({
            "status": "success",
            "predictions": formatted
        })

    except Exception as e:
        return JSONResponse({
            "status": "error",
            "message": str(e)
        }, status_code=500)

@app.get("/")
async def root():
    return {"message": "🌱 Plant Disease API is running!"}

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