Spaces:
Running
Running
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() | |