jays009 commited on
Commit
5b86dff
·
verified ·
1 Parent(s): b77b937

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -19
app.py CHANGED
@@ -6,7 +6,6 @@ from torchvision import models, transforms
6
  from huggingface_hub import hf_hub_download
7
  from PIL import Image
8
  import requests
9
- import os
10
  from io import BytesIO
11
 
12
  # Define the number of classes
@@ -39,39 +38,56 @@ transform = transforms.Compose([
39
 
40
  # Function to predict from image content
41
  def predict_from_image(image):
42
- # Ensure the image is a PIL Image
43
- if not isinstance(image, Image.Image):
44
- raise ValueError("Invalid image format received. Please provide a valid image.")
 
45
 
46
- # Apply transformations
47
- image_tensor = transform(image).unsqueeze(0)
48
 
49
- # Predict
50
- with torch.no_grad():
51
- outputs = model(image_tensor)
52
- predicted_class = torch.argmax(outputs, dim=1).item()
53
 
54
- # Interpret the result
55
- if predicted_class == 0:
56
- return {"result": "The photo is of fall army worm with problem ID 126."}
57
- elif predicted_class == 1:
58
- return {"result": "The photo is of a healthy maize image."}
59
- else:
60
- return {"error": "Unexpected class prediction."}
 
 
61
 
62
  # Function to predict from URL
63
  def predict_from_url(url):
64
  try:
 
 
 
65
  response = requests.get(url)
66
  response.raise_for_status() # Ensure the request was successful
67
  image = Image.open(BytesIO(response.content))
68
  return predict_from_image(image)
69
  except Exception as e:
70
- return {"error": f"Failed to process the URL: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  # Gradio interface
73
  iface = gr.Interface(
74
- fn=lambda image, url: predict_from_image(image) if image else predict_from_url(url),
75
  inputs=[
76
  gr.Image(type="pil", label="Upload an Image"),
77
  gr.Textbox(label="Or Enter an Image URL", placeholder="Provide a valid image URL"),
@@ -80,6 +96,9 @@ iface = gr.Interface(
80
  live=True,
81
  title="Maize Anomaly Detection",
82
  description="Upload an image or provide a URL to detect anomalies in maize crops.",
 
 
 
83
  )
84
 
85
  # Launch the interface
 
6
  from huggingface_hub import hf_hub_download
7
  from PIL import Image
8
  import requests
 
9
  from io import BytesIO
10
 
11
  # Define the number of classes
 
38
 
39
  # Function to predict from image content
40
  def predict_from_image(image):
41
+ try:
42
+ # Ensure the image is a PIL Image
43
+ if not isinstance(image, Image.Image):
44
+ raise ValueError("Invalid image format received. Please provide a valid image.")
45
 
46
+ # Apply transformations
47
+ image_tensor = transform(image).unsqueeze(0)
48
 
49
+ # Predict
50
+ with torch.no_grad():
51
+ outputs = model(image_tensor)
52
+ predicted_class = torch.argmax(outputs, dim=1).item()
53
 
54
+ # Interpret the result
55
+ if predicted_class == 0:
56
+ return {"status": "success", "result": "Fall army worm detected (Problem ID: 126)."}
57
+ elif predicted_class == 1:
58
+ return {"status": "success", "result": "Healthy maize image detected."}
59
+ else:
60
+ return {"status": "error", "message": "Unexpected class prediction."}
61
+ except Exception as e:
62
+ return {"status": "error", "message": f"Error during prediction: {str(e)}"}
63
 
64
  # Function to predict from URL
65
  def predict_from_url(url):
66
  try:
67
+ if not url.startswith(("http://", "https://")):
68
+ raise ValueError("Invalid URL format. Please provide a valid image URL.")
69
+
70
  response = requests.get(url)
71
  response.raise_for_status() # Ensure the request was successful
72
  image = Image.open(BytesIO(response.content))
73
  return predict_from_image(image)
74
  except Exception as e:
75
+ return {"status": "error", "message": f"Failed to process the URL: {str(e)}"}
76
+
77
+ # Combined prediction function for Gradio
78
+ def combined_predict(image, url):
79
+ if image and url:
80
+ return {"status": "error", "message": "Provide either an image or a URL, not both."}
81
+ elif image:
82
+ return predict_from_image(image)
83
+ elif url:
84
+ return predict_from_url(url)
85
+ else:
86
+ return {"status": "error", "message": "No input provided. Please upload an image or provide a URL."}
87
 
88
  # Gradio interface
89
  iface = gr.Interface(
90
+ fn=combined_predict,
91
  inputs=[
92
  gr.Image(type="pil", label="Upload an Image"),
93
  gr.Textbox(label="Or Enter an Image URL", placeholder="Provide a valid image URL"),
 
96
  live=True,
97
  title="Maize Anomaly Detection",
98
  description="Upload an image or provide a URL to detect anomalies in maize crops.",
99
+ examples=[
100
+ [None, "https://example.com/sample-image.jpg"], # Replace with a valid example URL
101
+ ]
102
  )
103
 
104
  # Launch the interface