File size: 4,994 Bytes
2d71661
 
 
 
dc12a50
 
 
 
 
 
 
 
 
 
 
 
 
 
2d71661
 
 
861eba1
2d71661
dc12a50
2d71661
dc12a50
 
2d71661
 
 
 
 
 
6594ae4
 
 
 
 
 
 
2d71661
 
6594ae4
2d71661
6594ae4
 
 
 
 
 
2d71661
 
c5ccded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d71661
 
c5ccded
 
 
 
 
2d71661
c5ccded
2d71661
 
 
 
 
 
 
 
 
f936fbe
2d71661
 
c5ccded
2d71661
 
 
 
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
111
112
import gradio as gr
import tensorflow as tf
from PIL import Image
import numpy as np
import tensorflow as tf
import keras.backend as K


# Define focal loss
def focal_loss(gamma=2., alpha=0.25):
    def focal_loss_fixed(y_true, y_pred):
        y_pred = tf.clip_by_value(y_pred, K.epsilon(), 1. - K.epsilon())
        cross_entropy = -y_true * tf.math.log(y_pred)
        weight = alpha * y_true * tf.math.pow((1 - y_pred), gamma)
        loss = weight * cross_entropy
        return tf.reduce_sum(loss, axis=-1)
    return focal_loss_fixed


# Load models
vgg16_model = tf.keras.models.load_model(
    "vgg16_best_model.keras"
)

xception_model = tf.keras.models.load_model(
    'xception_best.keras',
    custom_objects={'focal_loss_fixed': focal_loss()}
)


def predict_fire(image):
    img = Image.fromarray(image).convert("RGB")

    # Preprocess for vgg16_model (128x128 input size)
    vgg16_img = img.resize((128, 128))
    vgg16_img_array = np.array(vgg16_img) / 255.0
    vgg16_img_array = np.expand_dims(vgg16_img_array, axis=0)

    # Fire detection using vgg16_model
    fire_pred = vgg16_model.predict(vgg16_img_array)
    fire_status = "Fire Detected" if fire_pred[0][0] > 0.5 else "No Fire Detected"

    # If fire is detected, preprocess for xception_model (224x224 input size)
    if fire_status == "Fire Detected":
        xception_img = img.resize((224, 224))
        xception_img_array = np.array(xception_img) / 255.0
        xception_img_array = np.expand_dims(xception_img_array, axis=0)

        # Severity prediction using xception_model
        severity_pred = xception_model.predict(xception_img_array)
        severity_level = np.argmax(severity_pred[0])
        severity = ["Mild", "Moderate", "Severe"][severity_level]
        
        # Static rule-based recommendations with detailed instructions
        if severity == "Mild":
            recommendation = (
                "Fire detected is mild and manageable. "
                "For the Fire Department: Ensure continuous monitoring of the fire. "
                "Deploy fire trucks and extinguishing equipment if necessary to prevent escalation. "
                "For the Public: Stay alert and stay indoors. Evacuate only if advised by authorities. "
                "Ensure clear access routes for emergency services. "
                "Keep fire safety equipment such as fire extinguishers readily available."
            )
        elif severity == "Moderate":
            recommendation = (
                "Fire detected is moderate and poses a significant risk. "
                "For the Fire Department: Immediate response is needed. "
                "Deploy sufficient fire trucks, helicopters (if possible), and personnel to contain the fire. "
                "Establish firebreaks and coordinate with neighboring departments. "
                "For the Public: Evacuate the area promptly as the fire might spread. "
                "Follow evacuation routes and do not return to the area until authorities deem it safe. "
                "Be cautious of smoke inhalation, and wear protective masks if available."
            )
        else:  # Severe
            recommendation = (
                "Severe fire detected with rapid spread potential. Immediate action is critical. "
                "For the Fire Department: Prioritize evacuation operations. "
                "Deploy all available resources, including specialized teams and air support. "
                "Set up perimeters around the affected area and prevent access. "
                "Coordinate with national agencies for additional resources and backup. "
                "For the Public: Evacuate immediately. Leave all belongings behind and proceed to designated safe zones. "
                "Avoid smoke exposure and keep away from fire zones. Follow all official instructions and do not attempt to return to the area until clearance is given by emergency services. "
                "Remain in contact with local authorities for further updates."
            )

    else:
        severity = "N/A"
        recommendation = (
            "No fire detected. However, always be cautious of any unusual smoke or smells in your environment. "
            "Ensure that fire alarms are functioning, and regularly check fire extinguishers. "
            "Stay prepared by familiarizing yourself with fire evacuation routes and emergency contact numbers."
        )

    return fire_status, severity, recommendation


# Gradio interface
interface = gr.Interface(
    fn=predict_fire,
    inputs=gr.Image(type="numpy", label="Upload Image"),
    outputs=[
        gr.Textbox(label="Fire Status"),
        gr.Textbox(label="Severity Level"),
        gr.Textbox(label="Recommendation")
    ],
    title="Fire Prediction and Severity Classification",
    description="Upload an image to predict fire and its severity level (Mild, Moderate, Severe), and get recommendations.",
)

if __name__ == "__main__":
    interface.launch()