Update app.py
Browse files
app.py
CHANGED
|
@@ -65,32 +65,42 @@ last_conv_layer_name = get_last_conv_layer_name(model)
|
|
| 65 |
|
| 66 |
def predict_and_visualize(img):
|
| 67 |
try:
|
|
|
|
| 68 |
img_resized = img.resize((224, 224))
|
| 69 |
img_array = image.img_to_array(img_resized) / 255.0
|
| 70 |
img_array_exp = np.expand_dims(img_array, axis=0)
|
| 71 |
|
| 72 |
-
# --- Model
|
| 73 |
prediction = model.predict(img_array_exp, verbose=0)
|
| 74 |
|
| 75 |
-
#
|
| 76 |
if isinstance(prediction, (list, tuple)):
|
| 77 |
prediction = np.array(prediction[0])
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
labels = {"Real Image": real_conf, "Fake Image": fake_conf}
|
| 83 |
|
| 84 |
-
# --- Grad-CAM ---
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
return labels, superimposed_img
|
| 89 |
|
| 90 |
except Exception as e:
|
| 91 |
-
print("--- ERROR ---")
|
| 92 |
traceback.print_exc()
|
| 93 |
-
return
|
|
|
|
|
|
|
| 94 |
|
| 95 |
# =========================
|
| 96 |
# --- Gradio Interface ---
|
|
|
|
| 65 |
|
| 66 |
def predict_and_visualize(img):
|
| 67 |
try:
|
| 68 |
+
# --- Preprocess Image ---
|
| 69 |
img_resized = img.resize((224, 224))
|
| 70 |
img_array = image.img_to_array(img_resized) / 255.0
|
| 71 |
img_array_exp = np.expand_dims(img_array, axis=0)
|
| 72 |
|
| 73 |
+
# --- Model Prediction ---
|
| 74 |
prediction = model.predict(img_array_exp, verbose=0)
|
| 75 |
|
| 76 |
+
# Robust scalar extraction
|
| 77 |
if isinstance(prediction, (list, tuple)):
|
| 78 |
prediction = np.array(prediction[0])
|
| 79 |
+
if isinstance(prediction, np.ndarray):
|
| 80 |
+
prediction = prediction.item()
|
| 81 |
+
prediction = float(prediction)
|
| 82 |
|
| 83 |
+
# Confidence bars
|
| 84 |
+
real_conf = max(0.0, min(1.0, prediction)) # clamp between 0 and 1
|
| 85 |
+
fake_conf = 1.0 - real_conf
|
| 86 |
labels = {"Real Image": real_conf, "Fake Image": fake_conf}
|
| 87 |
|
| 88 |
+
# --- Grad-CAM (optional, fail-safe) ---
|
| 89 |
+
try:
|
| 90 |
+
heatmap = make_gradcam_heatmap(img_array_exp, model, last_conv_layer_name)
|
| 91 |
+
superimposed_img = superimpose_gradcam(img, heatmap)
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print("Grad-CAM failed:", e)
|
| 94 |
+
superimposed_img = img # fallback to original image
|
| 95 |
|
| 96 |
return labels, superimposed_img
|
| 97 |
|
| 98 |
except Exception as e:
|
| 99 |
+
print("--- PREDICTION ERROR ---")
|
| 100 |
traceback.print_exc()
|
| 101 |
+
# Always return a valid dict for gr.Label
|
| 102 |
+
return {"Real Image": 0.0, "Fake Image": 0.0}, img
|
| 103 |
+
|
| 104 |
|
| 105 |
# =========================
|
| 106 |
# --- Gradio Interface ---
|