jays009 commited on
Commit
4af9c6b
·
verified ·
1 Parent(s): 991ba20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -35
app.py CHANGED
@@ -1,13 +1,14 @@
1
  import gradio as gr
2
- import json
3
  import torch
4
  from torch import nn
5
  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
13
  num_classes = 2
@@ -37,49 +38,43 @@ transform = transforms.Compose([
37
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
38
  ])
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"),
78
- ],
79
  outputs=gr.JSON(label="Prediction Result"),
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
 
1
  import gradio as gr
 
2
  import torch
3
  from torch import nn
4
  from torchvision import models, transforms
5
  from huggingface_hub import hf_hub_download
6
  from PIL import Image
 
7
  import os
8
+ import logging
9
+
10
+ # Setup logging
11
+ logging.basicConfig(level=logging.INFO)
12
 
13
  # Define the number of classes
14
  num_classes = 2
 
38
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
39
  ])
40
 
41
+ # Prediction function for an uploaded image
42
  def predict_from_image(image):
43
+ try:
44
+ # Ensure the input is a valid PIL image
45
+ if not isinstance(image, Image.Image):
46
+ raise ValueError("Invalid image format received. Please provide a valid image.")
47
 
48
+ # Log the input for debugging
49
+ logging.info("Received image for prediction")
50
 
51
+ # Apply transformations
52
+ image_tensor = transform(image).unsqueeze(0)
 
 
53
 
54
+ # Predict
55
+ with torch.no_grad():
56
+ outputs = model(image_tensor)
57
+ predicted_class = torch.argmax(outputs, dim=1).item()
 
 
 
58
 
59
+ # Interpret the result
60
+ if predicted_class == 0:
61
+ return {"result": "The photo is of fall army worm with problem ID 126."}
62
+ elif predicted_class == 1:
63
+ return {"result": "The photo is of a healthy maize image."}
64
+ else:
65
+ return {"error": "Unexpected class prediction."}
66
  except Exception as e:
67
+ logging.error(f"Error during prediction: {str(e)}")
68
+ return {"error": f"Failed to process the image: {str(e)}"}
69
 
70
+ # Gradio interface restricted to image input
71
  iface = gr.Interface(
72
+ fn=predict_from_image, # Only handle image input
73
+ inputs=gr.Image(type="pil", label="Upload an Image"), # Restrict input to image upload
 
 
 
74
  outputs=gr.JSON(label="Prediction Result"),
75
  live=True,
76
  title="Maize Anomaly Detection",
77
+ description="Upload an image to detect anomalies in maize crops.",
78
  )
79
 
80
  # Launch the interface