import os import json import numpy as np import tensorflow as tf import gradio as gr from tensorflow.keras.preprocessing.image import load_img, img_to_array from tensorflow.keras.applications.efficientnet import preprocess_input # ─────────────────────────────────────────────────────────────────────────────── # 1️⃣ CONFIGURATION # ─────────────────────────────────────────────────────────────────────────────── MODEL_FILE = "final_model.h5" BEST_THRESHOLD_PATH = "best_threshold.json" IMG_SIZE = (32, 32) # Load the threshold value with open(BEST_THRESHOLD_PATH, "r") as f: best_threshold = json.load(f)["best_threshold"] # Load the model model = tf.keras.models.load_model(MODEL_FILE, compile=False) # ─────────────────────────────────────────────────────────────────────────────── # 2️⃣ IMAGE PREPROCESSING AND PREDICTION FUNCTION # ─────────────────────────────────────────────────────────────────────────────── def preprocess_image(image): # 1) Resize PIL image img = image.resize(IMG_SIZE) # 2) To array [0–255] arr = img_to_array(img) # 3) EfficientNet preprocessing → [-1,1] arr = preprocess_input(arr) # 4) Add batch axis → (1,32,32,3) return np.expand_dims(arr, axis=0) def predict(image): x = preprocess_image(image) prob = model.predict(x, verbose=0).squeeze() if prob >= best_threshold: # FAKE percent = prob * 100 label = f"❌ FAKE — {percent:.1f}% confidence" color = "red" else: # REAL percent = (1 - prob) * 100 label = f"✅ REAL — {percent:.1f}% confidence" color = "green" return f"