karthikmn commited on
Commit
5f660a8
Β·
verified Β·
1 Parent(s): 43ed6f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -28
app.py CHANGED
@@ -6,20 +6,27 @@ import json
6
  import argparse
7
  import os
8
  import warnings
 
9
 
10
- # Suppress deprecated warning for feature extractor
11
- warnings.filterwarnings("ignore", category=FutureWarning)
12
 
13
- # Load model pipeline
14
  print("πŸ”„ Loading model...")
15
- model = pipeline(
16
- "image-classification",
17
- model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification",
18
- top_k=1
19
- )
 
 
 
 
 
 
20
  print("βœ… Model loaded.")
21
 
22
- # Safe map loader
23
  def load_map(file_path):
24
  mapping = {}
25
  try:
@@ -32,12 +39,12 @@ def load_map(file_path):
32
  print(f"⚠️ Failed to load {file_path}: {e}")
33
  return mapping
34
 
35
- # Load external data
36
  disease_map = load_map("diseases.txt")
37
  treatment_map = load_map("treatments.txt")
38
  fertilizer_map = load_map("fertilizers.txt")
39
 
40
- # Load critical diseases
41
  try:
42
  with open("critical_diseases.txt", "r", encoding="utf-8") as f:
43
  critical_diseases = set(line.strip() for line in f if line.strip())
@@ -45,22 +52,21 @@ except Exception as e:
45
  print(f"⚠️ Failed to load critical_diseases.txt: {e}")
46
  critical_diseases = set()
47
 
48
- # Main prediction logic
49
  def predict_disease(base64_img):
50
  try:
51
  img_bytes = base64.b64decode(base64_img)
52
  image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
53
  except Exception as e:
54
- return {"error": f"Invalid image: {str(e)}"}
55
 
56
  try:
57
  result = model(image)[0]
58
  label = result["label"]
59
  confidence = float(result["score"])
60
-
61
  disease = disease_map.get(label, label)
62
- treatment = treatment_map.get(disease, "Consult an expert for treatment.")
63
- fertilizer = fertilizer_map.get(disease, "Use a general NPK 10-10-10 fertilizer.")
64
 
65
  output = {
66
  "disease_prediction": disease,
@@ -73,28 +79,28 @@ def predict_disease(base64_img):
73
  output["alert"] = True
74
 
75
  return output
76
-
77
  except Exception as e:
78
  return {"error": f"Prediction failed: {str(e)}"}
79
 
80
- # CLI interface
81
  if __name__ == "__main__":
82
  parser = argparse.ArgumentParser(
83
- description=(
84
- "🌿 AI-Powered Tree Disease Detector\n\n"
85
- "Examples:\n"
86
- " python app.py --image leaf.jpg --raw\n"
87
- " python app.py --image encoded.txt"
88
- ),
89
  formatter_class=argparse.RawTextHelpFormatter
90
  )
91
- parser.add_argument("--image", type=str, help="Path to image or base64 file", required=True)
92
- parser.add_argument("--raw", action="store_true", help="Indicates that the file is a raw image (e.g., JPG, PNG)")
 
93
  args = parser.parse_args()
94
 
 
 
 
 
 
95
  if not os.path.isfile(args.image):
96
  print(f"❌ File not found: {args.image}")
97
- exit(1)
98
 
99
  try:
100
  if args.raw:
@@ -106,6 +112,5 @@ if __name__ == "__main__":
106
 
107
  result = predict_disease(base64_img)
108
  print(json.dumps(result, indent=2))
109
-
110
  except Exception as e:
111
  print(json.dumps({"error": f"Unexpected error: {str(e)}"}, indent=2))
 
6
  import argparse
7
  import os
8
  import warnings
9
+ import sys
10
 
11
+ # Suppress warnings
12
+ warnings.filterwarnings("ignore")
13
 
14
+ # === Load model ===
15
  print("πŸ”„ Loading model...")
16
+
17
+ try:
18
+ model = pipeline(
19
+ "image-classification",
20
+ model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification",
21
+ top_k=1
22
+ )
23
+ except Exception as e:
24
+ print(f"❌ Failed to load model: {e}")
25
+ sys.exit(1)
26
+
27
  print("βœ… Model loaded.")
28
 
29
+ # === Mapping file loader ===
30
  def load_map(file_path):
31
  mapping = {}
32
  try:
 
39
  print(f"⚠️ Failed to load {file_path}: {e}")
40
  return mapping
41
 
42
+ # === Load mappings ===
43
  disease_map = load_map("diseases.txt")
44
  treatment_map = load_map("treatments.txt")
45
  fertilizer_map = load_map("fertilizers.txt")
46
 
47
+ # === Load critical diseases ===
48
  try:
49
  with open("critical_diseases.txt", "r", encoding="utf-8") as f:
50
  critical_diseases = set(line.strip() for line in f if line.strip())
 
52
  print(f"⚠️ Failed to load critical_diseases.txt: {e}")
53
  critical_diseases = set()
54
 
55
+ # === Prediction Function ===
56
  def predict_disease(base64_img):
57
  try:
58
  img_bytes = base64.b64decode(base64_img)
59
  image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
60
  except Exception as e:
61
+ return {"error": f"Invalid image input: {str(e)}"}
62
 
63
  try:
64
  result = model(image)[0]
65
  label = result["label"]
66
  confidence = float(result["score"])
 
67
  disease = disease_map.get(label, label)
68
+ treatment = treatment_map.get(disease, "Consult an expert.")
69
+ fertilizer = fertilizer_map.get(disease, "Use general NPK 10-10-10.")
70
 
71
  output = {
72
  "disease_prediction": disease,
 
79
  output["alert"] = True
80
 
81
  return output
 
82
  except Exception as e:
83
  return {"error": f"Prediction failed: {str(e)}"}
84
 
85
+ # === Main CLI ===
86
  if __name__ == "__main__":
87
  parser = argparse.ArgumentParser(
88
+ description="🌿 Plant Disease Detector\n\nUsage examples:\n python app.py --image leaf.jpg --raw\n python app.py --image encoded.txt",
 
 
 
 
 
89
  formatter_class=argparse.RawTextHelpFormatter
90
  )
91
+
92
+ parser.add_argument("--image", type=str, help="Path to image or base64 file", required=False)
93
+ parser.add_argument("--raw", action="store_true", help="Use this flag if the input is a raw image file (e.g., JPG, PNG)")
94
  args = parser.parse_args()
95
 
96
+ if not args.image:
97
+ print("❗ Error: You must provide an image file using --image\n")
98
+ parser.print_help()
99
+ sys.exit(1)
100
+
101
  if not os.path.isfile(args.image):
102
  print(f"❌ File not found: {args.image}")
103
+ sys.exit(1)
104
 
105
  try:
106
  if args.raw:
 
112
 
113
  result = predict_disease(base64_img)
114
  print(json.dumps(result, indent=2))
 
115
  except Exception as e:
116
  print(json.dumps({"error": f"Unexpected error: {str(e)}"}, indent=2))