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") img = img.resize((224, 224)) # Match model input size img_array = np.array(img) / 255.0 img_array = np.expand_dims(img_array, axis=0) fire_pred = vgg16_model.predict(img_array) fire_status = "Fire Detected" if fire_pred[0][0] > 0.5 else "No Fire Detected" if fire_status == "Fire Detected": severity_pred = xception_model.predict(img_array) severity_level = np.argmax(severity_pred[0]) severity = ["Mild", "Moderate", "Severe"][severity_level] else: severity = "N/A" return fire_status, severity # 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"), ], title="Fire Prediction and Severity Classification", description="Upload an image to predict fire and its severity level (Mild, Moderate, Severe).", ) if __name__ == "__main__": interface.launch()