Spaces:
Running
Running
File size: 3,219 Bytes
7c0e87a 2d781ce 7c0e87a 6145c13 7c0e87a 6145c13 7c0e87a 2d781ce 7c0e87a 409c402 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
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()
|