manas0412's picture
Final Commit
2d781ce verified
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"<div style='color: {color}; font-weight: bold;'>{label}</div>"
# ───────────────────────────────────────────────────────────────────────────────
# 3️⃣ GRADIO INTERFACE
# ───────────────────────────────────────────────────────────────────────────────
iface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil"),
outputs=gr.HTML(label="Prediction"),
title="Is It Real? Find Out!",
description="Upload any image and our AI model will tell you if it's real or fake.",
live=False, # set to False for one-shot prediction
flagging_mode="never"
)
iface.launch()