SavlonBhai commited on
Commit
395b902
·
verified ·
1 Parent(s): 8047dc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -20
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import gradio as gr
2
  from ultralytics import YOLO
 
3
  import numpy as np
4
 
5
- # Load YOLO model (update path to your model file if needed)
6
  model = YOLO('best_animal_classifier.pt')
7
 
8
  class_names = ['butterflies', 'chickens', 'elephants', 'horses', 'spiders', 'squirrels']
@@ -10,32 +11,21 @@ class_names = ['butterflies', 'chickens', 'elephants', 'horses', 'spiders', 'squ
10
  def predict_animal(image):
11
  if image is None:
12
  return {}
13
- # Run prediction without verbose logging for cleaner output
 
 
 
 
 
14
  results = model.predict(image, verbose=False)
15
 
16
- # Extract the probabilities; fallback if attribute unavailable
17
  try:
18
  probs = results[0].probs.data.cpu().numpy()
19
  except AttributeError:
20
- # If 'probs' not available, generate dummy equal probabilities (prevent crash)
21
  probs = np.ones(len(class_names)) / len(class_names)
22
 
23
- # Map class names to probability scores
24
  return {class_names[i]: float(probs[i]) for i in range(len(class_names))}
25
 
26
- # Enhanced UI with modern theme and layout
27
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
28
- gr.Markdown("# 🐾 Animal Type Classifier")
29
- gr.Markdown("Upload an image of an animal below and get predictions for butterflies, chickens, elephants, horses, spiders, or squirrels.")
30
-
31
- with gr.Row():
32
- img_input = gr.Image(type="pil", label="Upload Animal Image")
33
- label_output = gr.Label(num_top_classes=6, label="Prediction Scores")
34
-
35
- predict_button = gr.Button("Classify Animal")
36
- predict_button.click(fn=predict_animal, inputs=img_input, outputs=label_output)
37
-
38
- gr.Markdown("Developed with Ultralytics YOLO and Gradio framework.")
39
-
40
- if __name__ == "__main__":
41
- demo.launch()
 
1
  import gradio as gr
2
  from ultralytics import YOLO
3
+ from PIL import Image
4
  import numpy as np
5
 
6
+ # Load YOLO model (update path if needed)
7
  model = YOLO('best_animal_classifier.pt')
8
 
9
  class_names = ['butterflies', 'chickens', 'elephants', 'horses', 'spiders', 'squirrels']
 
11
  def predict_animal(image):
12
  if image is None:
13
  return {}
14
+
15
+ # Convert numpy array input to PIL Image if needed
16
+ if isinstance(image, np.ndarray):
17
+ image = Image.fromarray(image)
18
+
19
+ # Run prediction quietly
20
  results = model.predict(image, verbose=False)
21
 
 
22
  try:
23
  probs = results[0].probs.data.cpu().numpy()
24
  except AttributeError:
25
+ # Fallback to uniform probabilities if probs unavailable
26
  probs = np.ones(len(class_names)) / len(class_names)
27
 
 
28
  return {class_names[i]: float(probs[i]) for i in range(len(class_names))}
29
 
 
30
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
31
+ gr.Markdown("# 🐾 Animal Type Class