sulthonkaf commited on
Commit
b60c1fb
Β·
verified Β·
1 Parent(s): 5f3f800
Files changed (1) hide show
  1. app.py +47 -18
app.py CHANGED
@@ -4,16 +4,36 @@ import numpy as np
4
  import pickle
5
  from PIL import Image
6
 
7
- # Load model & label encoder sekali di awal
8
  model = tf.keras.models.load_model("plantopia.h5")
9
  with open("label_encoder.pkl", "rb") as f:
10
  label_encoder = pickle.load(f)
11
 
12
- # Daftar label
13
  class_names = label_encoder.inverse_transform(np.arange(len(label_encoder.classes_)))
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def predict(img: Image.Image):
16
  try:
 
 
 
17
  img = img.resize((224, 224))
18
  img_array = np.array(img) / 255.0
19
  img_array = np.expand_dims(img_array, axis=0)
@@ -21,26 +41,35 @@ def predict(img: Image.Image):
21
  prediction = model.predict(img_array)[0]
22
  predicted_index = np.argmax(prediction)
23
  predicted_label = class_names[predicted_index]
24
- predicted_confidence = prediction[predicted_index] * 100
 
25
 
26
- result = f"βœ… Prediksi penyakit tanaman: {predicted_label}\n"
27
- result += f"🎯 Akurasi keyakinan model (confidence): {predicted_confidence:.2f}%\n\n"
28
- result += "--- Detail Probabilitas untuk Semua Kelas ---\n"
29
- for label, prob in zip(class_names, prediction):
30
- result += f"{label:15}: {prob:.4f}\n"
31
-
32
- return result
 
33
 
34
  except Exception as e:
35
- return f"❌ Terjadi error saat memproses gambar: {str(e)}"
36
-
 
 
 
 
 
 
37
 
 
38
  gr.Interface(
39
  fn=predict,
40
- inputs=gr.Image(type="pil"),
41
- outputs="text",
42
- title="Deteksi Penyakit Daun 🌿",
43
- description="Upload gambar daun dan sistem akan memprediksi penyakitnya berdasarkan model CNN yang telah dilatih.",
44
  allow_flagging="never",
45
- api_name="predict"
46
- ).launch(show_error=True)
 
4
  import pickle
5
  from PIL import Image
6
 
7
+ # === Load Model dan Label Encoder ===
8
  model = tf.keras.models.load_model("plantopia.h5")
9
  with open("label_encoder.pkl", "rb") as f:
10
  label_encoder = pickle.load(f)
11
 
 
12
  class_names = label_encoder.inverse_transform(np.arange(len(label_encoder.classes_)))
13
 
14
+ # === Optional: Panduan Perawatan ===
15
+ treatment_guides = {
16
+ "Mildew": "🧴 Gunakan fungisida berbahan aktif sulfur atau kalium bikarbonat.",
17
+ "Fungal": "🌿 Pangkas daun yang terinfeksi. Gunakan fungisida sistemik.",
18
+ "Insect": "πŸ› Gunakan insektisida nabati seperti neem oil.",
19
+ "Dead Leaf": "πŸ—‘οΈ Buang daun mati dan berikan nutrisi tambahan.",
20
+ "Blight": "☠️ Gunakan fungisida berbasis tembaga.",
21
+ "Rust": "πŸ”Ά Gunakan fungisida spesifik karat seperti myclobutanil.",
22
+ "Spot Diseases": "🎯 Periksa kelembapan, gunakan fungisida daun.",
23
+ "Healthy": "βœ… Tanaman sehat. Lanjutkan perawatan optimal.",
24
+ "Septoria": "πŸ’‰ Gunakan fungisida berbasis klorotalonil.",
25
+ "Virus": "🦠 Cabut tanaman yang terinfeksi berat.",
26
+ "Early Blight": "πŸŒ— Gunakan fungisida berbahan aktif mankozeb.",
27
+ "Late Blight": "🌘 Gunakan fungisida sistemik dan buang bagian busuk.",
28
+ "Bacterial": "🧼 Semprot dengan larutan antibakteri."
29
+ }
30
+
31
+ # === Fungsi Prediksi ===
32
  def predict(img: Image.Image):
33
  try:
34
+ if img.mode != "RGB":
35
+ img = img.convert("RGB")
36
+
37
  img = img.resize((224, 224))
38
  img_array = np.array(img) / 255.0
39
  img_array = np.expand_dims(img_array, axis=0)
 
41
  prediction = model.predict(img_array)[0]
42
  predicted_index = np.argmax(prediction)
43
  predicted_label = class_names[predicted_index]
44
+ predicted_confidence = float(prediction[predicted_index]) * 100
45
+ rekomendasi = treatment_guides.get(predicted_label, "⚠️ Belum ada rekomendasi.")
46
 
47
+ return {
48
+ "output": f"βœ… Prediksi: {predicted_label} | 🎯 Confidence: {predicted_confidence:.2f}%",
49
+ "label": predicted_label,
50
+ "confidence": round(predicted_confidence, 2),
51
+ "rekomendasi": rekomendasi,
52
+ "raw_probs": prediction.tolist(),
53
+ "class_names": class_names.tolist()
54
+ }
55
 
56
  except Exception as e:
57
+ return {
58
+ "output": f"❌ Error: {str(e)}",
59
+ "label": None,
60
+ "confidence": 0,
61
+ "rekomendasi": "❌ Tidak tersedia.",
62
+ "raw_probs": [],
63
+ "class_names": []
64
+ }
65
 
66
+ # === UI Gradio ===
67
  gr.Interface(
68
  fn=predict,
69
+ inputs=gr.Image(type="pil", label="πŸ“Έ Upload Gambar Daun"),
70
+ outputs="json",
71
+ title="🌿 Plantopia Enterprise API",
72
+ description="Prediksi penyakit tanaman berbasis gambar, confidence, rekomendasi perawatan, dan distribusi probabilitas. Output dalam format JSON siap pakai.",
73
  allow_flagging="never",
74
+ api_name="predict"
75
+ ).launch(show_error=True)