Spaces:
Sleeping

File size: 3,824 Bytes
5eb572c
 
 
48cbc39
5eb572c
 
a24ec3d
5eb572c
 
 
 
 
 
 
48cbc39
5eb572c
 
020bfc2
a24ec3d
5eb572c
 
 
 
 
 
 
 
 
 
 
 
 
 
48cbc39
5eb572c
020bfc2
5eb572c
 
a24ec3d
5eb572c
 
48cbc39
5eb572c
 
 
 
 
48cbc39
 
 
 
b187326
020bfc2
48cbc39
 
 
 
 
 
 
 
 
020bfc2
 
48cbc39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883c602
5eb572c
 
 
 
 
48cbc39
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import gradio as gr
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
import numpy as np
from PIL import Image
import time

print("[INFO] app.py script started at {}.".format(time.ctime()))

# --- Configuration ---
MODEL_PATH = "Model/ProposedNetwork_StratifiedKFold_Final_fold_5.hdf5"
IMAGE_SIZE = 224

# --- Load the Model ---
print("[INFO] Attempting to load the trained model from: {}".format(MODEL_PATH))
try:
    # We must tell load_model what 'K' means in our custom layers.
    model = load_model(MODEL_PATH, custom_objects={"K": K})
    print("[SUCCESS] Model loaded successfully into memory.")
except Exception as e:
    print("[FATAL ERROR] Failed to load the model.")
    print("Error details: {}".format(e))
    raise e

def getLabel(class_id):
    """Returns the string label for a given class ID."""
    return 'NoFire' if class_id == 0 else 'Fire'

# --- The Prediction Function ---
def predict_fire(input_image):
    if input_image is None:
        return {"Error": 1.0}
    
    print("[INFO] Received image for prediction.")
    # Preprocess the image exactly as the model expects
    image = input_image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE))
    image_array = np.asarray(image)
    image_array = image_array / 255.0
    image_array = np.expand_dims(image_array, axis=0)
    
    print("[INFO] Making prediction...")
    prediction_probs = model.predict(image_array)[0]
    confidences = {getLabel(i): float(prob) for i, prob in enumerate(prediction_probs)}
    
    return confidences

# ==============================================================================
# --- CREATE THE FINAL GRADIO INTERFACE USING gr.Blocks FOR CUSTOM STYLING ---
# ==============================================================================
print("[INFO] Creating Gradio Blocks interface...")

# Define the HTML for our custom-styled description for centering and font size
description_html = """
<div style="text-align: center; font-size: 16px;">
Lightweight CNN for Fire Detection with Integrated Hybrid Attention: A Depthwise-Driven Approach for Embedded Systems<br>
Authors: Sakif Azwad, Mohammed Shahin Shah, Md Shakib<br>
Supervised by: Md. Khaliluzzaman
</div>
"""

# Build the interface component by component
with gr.Blocks() as demo:  # Removed the 'theme' parameter for compatibility
    # Title
    gr.Markdown(
        """
        <h1 style="text-align: center;">🔥 HyFiNet 🔥</h1>
        """
    )
    # Custom-styled description
    gr.Markdown(description_html)
    
    # Main layout with two columns
    with gr.Row():
        # Left column for inputs
        with gr.Column(scale=2):
            image_input = gr.Image(type="pil", label="Upload an Image", height=400, width=400)
            predict_btn = gr.Button("Predict", variant="primary")
            
        # Right column for outputs
        with gr.Column(scale=1):
            result_label = gr.Label(num_top_classes=2, label="Prediction Results")
            
    # Examples section with all 8 of your images
    gr.Examples(
        examples=[
            ["examples/ex1.jpg"],
            ["examples/ex2.jpg"],
            ["examples/ex3.jpg"],
            ["examples/ex4.jpg"],
            ["examples/ex5.jpg"],
            ["examples/ex6.jpg"],
            ["examples/ex7.jpg"],
            ["examples/ex8.jpg"],
        ],
        inputs=image_input,
        outputs=result_label,
        fn=predict_fire,
        cache_examples=False
    )
    
    # Define the interaction: what happens when the button is clicked
    predict_btn.click(fn=predict_fire, inputs=image_input, outputs=result_label)

print("[INFO] Gradio interface created.")

# --- Launch the App ---
if __name__ == "__main__":
    print("[INFO] Launching Gradio app...")
    demo.launch()