abuhanzala commited on
Commit
5ab8f46
·
verified ·
1 Parent(s): 06e5717

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -5
app.py CHANGED
@@ -17,24 +17,39 @@ CONFIDENCE_THRESHOLD = 0.25
17
 
18
  def predict_image(image):
19
  try:
 
20
  image = image.resize((224, 224)).convert("RGB")
21
  img_array = np.array(image, dtype=np.float32) / 255.0
22
  img_array = np.expand_dims(img_array, axis=0)
23
 
 
24
  interpreter.set_tensor(input_details[0]['index'], img_array)
25
  interpreter.invoke()
26
- output = interpreter.get_tensor(output_details[0]['index'])
27
 
28
- class_idx = int(np.argmax(output))
29
- confidence = float(np.max(output))
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  if confidence < CONFIDENCE_THRESHOLD:
32
- return f"⚠️ Low confidence ({confidence:.2f}). The model is unsure. Please try a clearer image."
33
  else:
34
- return f"✅ Prediction: {class_names[class_idx]}"
 
35
  except Exception as e:
36
  return f"Error: {str(e)}"
37
 
 
38
  gr.Interface(
39
  fn=predict_image,
40
  inputs=gr.Image(type="pil"),
 
17
 
18
  def predict_image(image):
19
  try:
20
+ # Preprocess
21
  image = image.resize((224, 224)).convert("RGB")
22
  img_array = np.array(image, dtype=np.float32) / 255.0
23
  img_array = np.expand_dims(img_array, axis=0)
24
 
25
+ # Run inference
26
  interpreter.set_tensor(input_details[0]['index'], img_array)
27
  interpreter.invoke()
28
+ output = interpreter.get_tensor(output_details[0]['index'])[0] # shape (num_classes,)
29
 
30
+ # Normalize if needed (sometimes TFLite outputs logits)
31
+ probs = tf.nn.softmax(output).numpy()
32
+
33
+ # Get predicted class
34
+ class_idx = int(np.argmax(probs))
35
+ confidence = float(np.max(probs))
36
+
37
+ # Format output (show every class probability)
38
+ results = []
39
+ for i, prob in enumerate(probs):
40
+ results.append(f"{class_names[i]}: {prob*100:.2f}%")
41
+
42
+ results_text = "\n".join(results)
43
 
44
  if confidence < CONFIDENCE_THRESHOLD:
45
+ return f"⚠️ Low confidence ({confidence:.2f}). The model is unsure.\n\nProbabilities:\n{results_text}"
46
  else:
47
+ return f"✅ Prediction: {class_names[class_idx]} ({confidence*100:.2f}%)\n\nProbabilities:\n{results_text}"
48
+
49
  except Exception as e:
50
  return f"Error: {str(e)}"
51
 
52
+ # Gradio UI
53
  gr.Interface(
54
  fn=predict_image,
55
  inputs=gr.Image(type="pil"),