jays009 commited on
Commit
5649d80
·
verified ·
1 Parent(s): 6ba58ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -28
app.py CHANGED
@@ -46,38 +46,47 @@ transform = transforms.Compose([
46
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
47
  ])
48
 
49
- def predict(data):
50
  try:
51
- if not isinstance(data, list) or len(data) == 0:
52
- return {"error": "Input data should be a non-empty list."}
53
-
54
- image_input = data[0].get('image', None)
55
- if not image_input:
56
- return {"error": "No image provided."}
57
-
58
- print(f"Received image input: {image_input}")
59
 
60
  # Check if the input is a PIL Image type
61
- if isinstance(image_input, Image.Image):
62
- print(f"Image is already loaded as PIL Image: {image_input}")
63
  else:
64
- # Check if the input contains a base64-encoded string or URL
65
- if image_input.startswith("http"): # URL case
 
 
 
 
 
 
 
 
 
 
66
  try:
67
- response = requests.get(image_input)
68
  image = Image.open(BytesIO(response.content))
69
  print(f"Fetched image from URL: {image}")
70
  except Exception as e:
71
  print(f"Error fetching image from URL: {e}")
72
- return {"error": f"Error fetching image from URL: {e}"}
73
- else: # Assuming it is base64-encoded image data
 
 
74
  try:
75
- image_data = base64.b64decode(image_input)
76
- image = Image.open(BytesIO(image_data))
77
- print(f"Decoded base64 image: {image}")
78
  except Exception as e:
79
- print(f"Error decoding base64 image: {e}")
80
- return {"error": f"Error decoding base64 image: {e}"}
 
 
 
 
 
81
 
82
  # Apply transformations
83
  image = transform(image).unsqueeze(0)
@@ -91,20 +100,20 @@ def predict(data):
91
  print(f"Prediction output: {outputs}, Predicted class: {predicted_class}")
92
 
93
  if predicted_class == 0:
94
- return {"result": "The photo you've sent is of fall army worm with problem ID 126."}
95
  elif predicted_class == 1:
96
- return {"result": "The photo you've sent is of a healthy maize image."}
97
  else:
98
- return {"error": "Unexpected class prediction."}
99
  except Exception as e:
100
  print(f"Error processing image: {e}")
101
- return {"error": f"Error processing image: {e}"}
102
 
103
  # Create the Gradio interface
104
  iface = gr.Interface(
105
  fn=predict,
106
- inputs=gr.JSON(label="Input JSON"),
107
- outputs=gr.JSON(label="Prediction Result"),
108
  live=True,
109
  title="Maize Anomaly Detection",
110
  description="Upload an image of maize to detect anomalies like disease or pest infestation. You can provide local paths, URLs, or base64-encoded images."
@@ -112,4 +121,3 @@ iface = gr.Interface(
112
 
113
  # Launch the Gradio interface
114
  iface.launch(share=True, show_error=True)
115
-
 
46
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
47
  ])
48
 
49
+ def predict(image):
50
  try:
51
+ print(f"Received image input: {image}")
 
 
 
 
 
 
 
52
 
53
  # Check if the input is a PIL Image type
54
+ if isinstance(image, Image.Image):
55
+ print(f"Image is already loaded as PIL Image: {image}")
56
  else:
57
+ # Try to handle base64-encoded image
58
+ if isinstance(image, dict) and image.get("data"):
59
+ try:
60
+ image_data = base64.b64decode(image["data"])
61
+ image = Image.open(BytesIO(image_data))
62
+ print(f"Decoded base64 image: {image}")
63
+ except Exception as e:
64
+ print(f"Error decoding base64 image: {e}")
65
+ return json.dumps({"error": f"Error decoding base64 image: {e}"})
66
+
67
+ # Try to fetch the image from a URL
68
+ elif isinstance(image, str) and image.startswith("http"):
69
  try:
70
+ response = requests.get(image)
71
  image = Image.open(BytesIO(response.content))
72
  print(f"Fetched image from URL: {image}")
73
  except Exception as e:
74
  print(f"Error fetching image from URL: {e}")
75
+ return json.dumps({"error": f"Error fetching image from URL: {e}"})
76
+
77
+ # Try to load the image from a local file path
78
+ elif isinstance(image, str) and os.path.isfile(image):
79
  try:
80
+ image = Image.open(image)
81
+ print(f"Loaded image from local path: {image}")
 
82
  except Exception as e:
83
+ print(f"Error loading image from local path: {e}")
84
+ return json.dumps({"error": f"Error loading image from local path: {e}"})
85
+
86
+ # Validate that the image is correctly loaded
87
+ if not isinstance(image, Image.Image):
88
+ print("Invalid image format received.")
89
+ return json.dumps({"error": "Invalid image format received."})
90
 
91
  # Apply transformations
92
  image = transform(image).unsqueeze(0)
 
100
  print(f"Prediction output: {outputs}, Predicted class: {predicted_class}")
101
 
102
  if predicted_class == 0:
103
+ return json.dumps({"result": "The photo you've sent is of fall army worm with problem ID 126."})
104
  elif predicted_class == 1:
105
+ return json.dumps({"result": "The photo you've sent is of a healthy maize image."})
106
  else:
107
+ return json.dumps({"error": "Unexpected class prediction."})
108
  except Exception as e:
109
  print(f"Error processing image: {e}")
110
+ return json.dumps({"error": f"Error processing image: {e}"})
111
 
112
  # Create the Gradio interface
113
  iface = gr.Interface(
114
  fn=predict,
115
+ inputs=gr.Image(type="pil", label="Upload an image or provide a URL or local path"),
116
+ outputs=gr.Textbox(label="Prediction Result"),
117
  live=True,
118
  title="Maize Anomaly Detection",
119
  description="Upload an image of maize to detect anomalies like disease or pest infestation. You can provide local paths, URLs, or base64-encoded images."
 
121
 
122
  # Launch the Gradio interface
123
  iface.launch(share=True, show_error=True)