abuhanzala commited on
Commit
777a892
Β·
verified Β·
1 Parent(s): 50e5ad5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -18
app.py CHANGED
@@ -11,43 +11,43 @@ interpreter.allocate_tensors()
11
  input_details = interpreter.get_input_details()
12
  output_details = interpreter.get_output_details()
13
 
 
14
  class_names = ['Dyskeratotic', 'Koilocytotic', 'Metaplastic', 'Parabasal', 'Superficial-Intermediat']
15
  CONFIDENCE_THRESHOLD = 0.7
 
16
 
17
  def preprocess_image(image):
18
- """Preprocess input image for model"""
19
  image = image.resize((224, 224)).convert("RGB")
20
- img_array = np.array(image, dtype=np.float32)
21
-
22
- # πŸ”‘ IMPORTANT: Check model input scale
23
- if input_details[0]['dtype'] == np.uint8:
24
- img_array = np.expand_dims(img_array, axis=0).astype(np.uint8)
25
- else:
26
- img_array = img_array / 255.0
27
- img_array = np.expand_dims(img_array, axis=0).astype(np.float32)
28
-
29
  return img_array
30
 
31
  def predict_image(image):
32
  try:
33
- # Preprocess
34
  img_array = preprocess_image(image)
35
 
36
- # Inference
37
  interpreter.set_tensor(input_details[0]['index'], img_array)
38
  interpreter.invoke()
39
  output = interpreter.get_tensor(output_details[0]['index'])
40
 
41
- # Ensure output is softmax
42
- probabilities = tf.nn.softmax(output[0]).numpy()
43
 
 
44
  class_idx = int(np.argmax(probabilities))
45
  confidence = float(np.max(probabilities))
46
 
47
- if confidence < CONFIDENCE_THRESHOLD:
48
- return f"⚠️ Low confidence ({confidence:.2f}). Try another clearer image."
49
- else:
50
  return f"βœ… Prediction: {class_names[class_idx]} (Confidence: {confidence:.2f})"
 
 
 
 
 
 
 
51
 
52
  except Exception as e:
53
  return f"❌ Error: {str(e)}"
@@ -58,5 +58,5 @@ gr.Interface(
58
  inputs=gr.Image(type="pil", label="Upload Cervical Cell Image"),
59
  outputs="text",
60
  title="Cervical Cancer Cell Classification",
61
- description="Upload an image to classify cervical cells using a TFLite model."
62
  ).launch()
 
11
  input_details = interpreter.get_input_details()
12
  output_details = interpreter.get_output_details()
13
 
14
+ # Class labels
15
  class_names = ['Dyskeratotic', 'Koilocytotic', 'Metaplastic', 'Parabasal', 'Superficial-Intermediat']
16
  CONFIDENCE_THRESHOLD = 0.7
17
+ TEMPERATURE = 0.5 # πŸ”‘ Sharpening factor (lower = more confident)
18
 
19
  def preprocess_image(image):
20
+ """Resize & normalize image for float32 TFLite model"""
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
  return img_array
25
 
26
  def predict_image(image):
27
  try:
 
28
  img_array = preprocess_image(image)
29
 
30
+ # Run inference
31
  interpreter.set_tensor(input_details[0]['index'], img_array)
32
  interpreter.invoke()
33
  output = interpreter.get_tensor(output_details[0]['index'])
34
 
35
+ # Apply softmax with temperature scaling (sharper confidence)
36
+ probabilities = tf.nn.softmax(output[0] / TEMPERATURE).numpy()
37
 
38
+ # Top prediction
39
  class_idx = int(np.argmax(probabilities))
40
  confidence = float(np.max(probabilities))
41
 
42
+ if confidence >= CONFIDENCE_THRESHOLD:
 
 
43
  return f"βœ… Prediction: {class_names[class_idx]} (Confidence: {confidence:.2f})"
44
+ else:
45
+ # Show Top-2 predictions if low confidence
46
+ top2_idx = np.argsort(probabilities)[-2:][::-1]
47
+ suggestion = ", ".join(
48
+ [f"{class_names[i]} ({probabilities[i]:.2f})" for i in top2_idx]
49
+ )
50
+ return f"⚠️ Low confidence ({confidence:.2f}).\nPossible classes: {suggestion}"
51
 
52
  except Exception as e:
53
  return f"❌ Error: {str(e)}"
 
58
  inputs=gr.Image(type="pil", label="Upload Cervical Cell Image"),
59
  outputs="text",
60
  title="Cervical Cancer Cell Classification",
61
+ description="Upload a cervical cell image. The model predicts the cell type with confidence scores."
62
  ).launch()