Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,42 +3,56 @@ from fastapi.responses import JSONResponse
|
|
| 3 |
from transformers import pipeline
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
model = pipeline(
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
@app.post("/predict")
|
| 24 |
async def predict(file: UploadFile = File(...)):
|
| 25 |
try:
|
| 26 |
-
# Baca file gambar
|
| 27 |
-
|
| 28 |
-
image = Image.open(io.BytesIO(
|
| 29 |
|
| 30 |
-
#
|
| 31 |
results = model(image)
|
| 32 |
|
| 33 |
-
# Ambil 3
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
"
|
| 38 |
-
"predictions":
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
return JSONResponse(content=response)
|
| 42 |
|
| 43 |
except Exception as e:
|
| 44 |
-
return JSONResponse(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from transformers import pipeline
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
+
|
| 8 |
+
# Gunakan lifespan event handler (pengganti @app.on_event)
|
| 9 |
+
@asynccontextmanager
|
| 10 |
+
async def lifespan(app: FastAPI):
|
| 11 |
+
global model
|
| 12 |
+
print("🚀 Memuat model ResNet50 dari Hugging Face...")
|
| 13 |
+
model = pipeline(
|
| 14 |
+
"image-classification",
|
| 15 |
+
model="SanketJadhav/PlantDiseaseClassifier-Resnet50",
|
| 16 |
+
feature_extractor_kwargs={"use_fast": True} # hilangkan warning slow processor
|
| 17 |
+
)
|
| 18 |
+
print("✅ Model siap digunakan (CPU mode)")
|
| 19 |
+
yield
|
| 20 |
+
print("🧹 Server FastAPI dimatikan.")
|
| 21 |
+
|
| 22 |
+
app = FastAPI(lifespan=lifespan)
|
| 23 |
|
| 24 |
@app.post("/predict")
|
| 25 |
async def predict(file: UploadFile = File(...)):
|
| 26 |
try:
|
| 27 |
+
# Baca file gambar dari request
|
| 28 |
+
image_bytes = await file.read()
|
| 29 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 30 |
|
| 31 |
+
# Jalankan prediksi
|
| 32 |
results = model(image)
|
| 33 |
|
| 34 |
+
# Ambil 3 hasil teratas
|
| 35 |
+
top_results = sorted(results, key=lambda x: x['score'], reverse=True)[:3]
|
| 36 |
+
formatted = [
|
| 37 |
+
{"label": res['label'], "score": round(res['score'], 3)}
|
| 38 |
+
for res in top_results
|
| 39 |
+
]
|
| 40 |
|
| 41 |
+
return JSONResponse({
|
| 42 |
+
"status": "success",
|
| 43 |
+
"predictions": formatted
|
| 44 |
+
})
|
|
|
|
|
|
|
| 45 |
|
| 46 |
except Exception as e:
|
| 47 |
+
return JSONResponse({
|
| 48 |
+
"status": "error",
|
| 49 |
+
"message": str(e)
|
| 50 |
+
}, status_code=500)
|
| 51 |
+
|
| 52 |
+
@app.get("/")
|
| 53 |
+
async def root():
|
| 54 |
+
return {"message": "🌱 Plant Disease API is running!"}
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
import uvicorn
|
| 58 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|