difarft commited on
Commit
b22cfd8
·
verified ·
1 Parent(s): e89af74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -29
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
- # Inisialisasi FastAPI
8
- app = FastAPI(title="🌿 Plant Disease API (ResNet50)",
9
- description="API untuk deteksi penyakit tanaman menggunakan ResNet50 dari Hugging Face.",
10
- version="1.0")
11
-
12
- # Load model dari Hugging Face
13
- model = pipeline("image-classification", model="SanketJadhav/PlantDiseaseClassifier-Resnet50")
14
-
15
- @app.on_event("startup")
16
- async def load_model():
17
- print("✅ Model ResNet50 siap digunakan (CPU mode).")
18
-
19
- @app.get("/")
20
- async def root():
21
- return {"message": "🌿 Plant Disease API is running"}
 
22
 
23
  @app.post("/predict")
24
  async def predict(file: UploadFile = File(...)):
25
  try:
26
- # Baca file gambar
27
- image_data = await file.read()
28
- image = Image.open(io.BytesIO(image_data)).convert("RGB")
29
 
30
- # Prediksi
31
  results = model(image)
32
 
33
- # Ambil 3 prediksi teratas
34
- top3 = sorted(results, key=lambda x: x['score'], reverse=True)[:3]
 
 
 
 
35
 
36
- response = {
37
- "filename": file.filename,
38
- "predictions": top3
39
- }
40
-
41
- return JSONResponse(content=response)
42
 
43
  except Exception as e:
44
- return JSONResponse(content={"error": str(e)}, status_code=500)
 
 
 
 
 
 
 
 
 
 
 
 
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)