File size: 2,133 Bytes
ef5c75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tensorflow as tf
from huggingface_hub import hf_hub_download
from tensorflow.keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt

# Step 1: Download the model from the Hugging Face Hub
model_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/my_tensorflow_model", filename="my_model.h5")

# Step 2: Load the TensorFlow model
model = tf.keras.models.load_model(model_path)

# Step 3: Function to preprocess the input image
def load_and_preprocess_image(img, target_size=(256, 256)):
    # Resize the image to the model's expected input size
    img = img.resize(target_size)
    
    # Convert to array and normalize
    img_array = np.array(img) / 255.0
    
    # Expand dimensions to match the input shape of the model
    img_array = np.expand_dims(img_array, axis=0)
    
    return img_array

# Step 4: Function to make predictions
def predict_image(img):
    # Preprocess the image
    img_array = load_and_preprocess_image(img)
    
    # Make a prediction
    prediction = model.predict(img_array)[0][0]
    
    # Confidence scores
    real_confidence = prediction * 100
    fake_confidence = (1 - prediction) * 100
    
    # Determine label
    result_label = "Real" if real_confidence > fake_confidence else "Fake"
    
    # Return results as text and an explanation
    result_text = f"The model predicts this image is '{result_label}' with {max(real_confidence, fake_confidence):.2f}% confidence."
    explanation = f"Real Confidence: {real_confidence:.2f}% | Fake Confidence: {fake_confidence:.2f}%"
    
    return result_text, explanation

# Step 5: Define the Gradio interface
interface = gr.Interface(
    fn=predict_image,
    inputs=gr.inputs.Image(type="pil", label="Upload an Image"),
    outputs=[
        gr.outputs.Textbox(label="Prediction Result"),
        gr.outputs.Textbox(label="Confidence Scores")
    ],
    title="Deepfake Image Detector",
    description="Upload an image, and the model will classify whether it is a 'real' or 'fake' image using deep learning."
)

# Step 6: Launch the app
if __name__ == "__main__":
    interface.launch()