shkumar156 commited on
Commit
82b0ec9
·
verified ·
1 Parent(s): 1f8cb9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -31
app.py CHANGED
@@ -4,58 +4,57 @@ import numpy as np
4
  from PIL import Image
5
  import json
6
 
7
- # 🔹 Load class names
8
  with open("cat_class_names.json", "r") as f:
9
  SUPPORTED_CLASSES = json.load(f)
10
 
11
- # 🔹 Load model
12
  model = tf.keras.models.load_model("cat_breed_model.keras")
13
 
14
- # 🔹 Prediction function with confidence handling
15
  def predict(image: Image.Image):
16
  try:
17
  if image is None:
18
- return "No image provided"
19
 
20
- # 🔹 Preprocess: Resize, normalize
21
  img = image.resize((224, 224)).convert("RGB")
22
- x = np.array(img, dtype=np.float32) / 255.0
23
  x = np.expand_dims(x, axis=0)
24
 
25
- # 🔹 Predict
26
  preds = model.predict(x)[0] # shape: (13,)
27
- top_3_idx = np.argsort(preds)[::-1][:3]
28
- top_3 = [(SUPPORTED_CLASSES[i], float(preds[i])) for i in top_3_idx]
29
-
30
- # 🔹 Set confidence threshold
31
- confidence_threshold = 0.60
32
- best_class, best_conf = top_3[0]
33
-
34
- if best_class == "not_cat":
35
- return "Not a Cat (according to model)"
36
- elif best_conf < confidence_threshold:
37
- return "Uncertain - Cat detected, but breed is unclear"
38
- else:
39
- return f"{best_class} ({best_conf:.2%} confidence)"
40
 
41
  except Exception as e:
42
  print(f"Prediction error: {e}")
43
- return "Prediction failed"
44
 
45
- # 🔹 Gradio UI
46
  iface = gr.Interface(
47
  fn=predict,
48
- inputs=gr.Image(type="pil", label="Upload Cat Image"),
49
- outputs=gr.Textbox(label="Prediction"),
50
- title="Cat Breed Classifier (Real-World Robust)",
51
- description="Upload a cat image to classify its breed. Model is trained on 12 breeds and 1 not_cat class.",
52
  article="""
53
- **Trained Breeds:**
54
- - Abyssinian, Bengal, Birman, Bombay, British Shorthair, Egyptian Mau, Maine Coon
55
- - Persian, Ragdoll, Russian Blue, Siamese, Sphynx
56
- 📸 Model performs best with clear, centered cat images. Real-world variation is supported better now.
 
 
 
 
 
 
 
 
 
 
 
57
  """
58
  )
59
 
60
  if __name__ == "__main__":
61
- iface.launch()
 
4
  from PIL import Image
5
  import json
6
 
7
+ # 🔹 Load class names from JSON file
8
  with open("cat_class_names.json", "r") as f:
9
  SUPPORTED_CLASSES = json.load(f)
10
 
11
+ # Load the trained model
12
  model = tf.keras.models.load_model("cat_breed_model.keras")
13
 
 
14
  def predict(image: Image.Image):
15
  try:
16
  if image is None:
17
+ return {cls: 0.0 for cls in SUPPORTED_CLASSES}
18
 
19
+ # Preprocess the image
20
  img = image.resize((224, 224)).convert("RGB")
21
+ x = np.array(img) / 255.0
22
  x = np.expand_dims(x, axis=0)
23
 
24
+ # Predict
25
  preds = model.predict(x)[0] # shape: (13,)
26
+ result = {cls: float(conf) for cls, conf in zip(SUPPORTED_CLASSES, preds)}
27
+ return result
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  except Exception as e:
30
  print(f"Prediction error: {e}")
31
+ return {cls: 0.0 for cls in SUPPORTED_CLASSES}
32
 
33
+ # Define Gradio interface
34
  iface = gr.Interface(
35
  fn=predict,
36
+ inputs=gr.Image(type="pil"),
37
+ outputs=gr.Label(num_top_classes=1, label="Predicted Class"),
38
+ title="Cat Breed Classifier",
39
+ description="Upload a cat image to classify its breed. ",
40
  article="""
41
+ **Supported Cat Breeds:**
42
+ - Abyssinian
43
+ - Bengal
44
+ - Birman
45
+ - Bombay
46
+ - British Shorthair
47
+ - Egyptian Mau
48
+ - Maine Coon
49
+ - Persian
50
+ - Ragdoll
51
+ - Russian Blue
52
+ - Siamese
53
+ - Sphynx
54
+
55
+ ⚠️ **Note:** If you upload a cat image from a breed that is **not listed above** (e.g., Devon Rex, Turkish Van), the model may still return a prediction, but it will likely be for the most **visually similar** breed it was trained on.
56
  """
57
  )
58
 
59
  if __name__ == "__main__":
60
+ iface.launch()