Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345674 unmodified lines12131415161718192021222324256 unmodified lines3233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import gradio as grimport tensorflow as tffrom tensorflow.keras.models import load_modelfrom tensorflow.keras import backend as K # <--- 1. IMPORT THE KERAS BACKENDimport numpy as npfrom PIL import Imageimport time4 unmodified linesMODEL_PATH = "Model/ProposedNetwork_StratifiedKFold_Final_fold_5.hdf5"IMAGE_SIZE = 224# --- Load the Model (this will happen once when the app starts) ---print("[INFO] Attempting to load the trained model from: {}".format(MODEL_PATH))try:# --- 2. THE CRITICAL FIX IS HERE ---# We must tell load_model what 'K' means in our custom layers.model = load_model(MODEL_PATH, custom_objects={"K": K})# --- END OF FIX ---print("[SUCCESS] Model loaded successfully into memory.")except Exception as e:print("[FATAL ERROR] Failed to load the model.")6 unmodified lines# --- The Prediction Function ---def predict_fire(input_image):"""Takes a PIL image as input, preprocesses it, and returns a dictionary of labels and confidences."""if input_image is None:return {"Error": 1.0}print("[INFO] Received image for prediction.")# Preprocess the imageimage = input_image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE))image_array = np.asarray(image)image_array = image_array / 255.0image_array = np.expand_dims(image_array, axis=0)# --- Make Prediction ---print("[INFO] Preprocessing complete. Making prediction...")prediction_probs = model.predict(image_array)[0]print("[INFO] Prediction complete.")# --- Format the Output ---confidences = {getLabel(i): float(prob) for i, prob in enumerate(prediction_probs)}return confidences# --- Create the Gradio Interface ---print("[INFO] Creating Gradio interface...")description_text = ("Lightweight CNN for Fire Detection with Integrated Hybrid Attention: A Depthwise-Driven Approach for Embedded Systems \n" # <-- Two spaces added here"Authors: Sakif Azwad, Mohammed Shahin Shah, Md Shakib \n" # <-- Two spaces added here"Supervised by: Md. Khaliluzzaman")iface = gr.Interface(fn=predict_fire,inputs=gr.Image(type="pil", label="Upload an Image", height=400, width=400),outputs=gr.Label(num_top_classes=2, label="Prediction Results"),title="🔥 HyFiNet 🔥",description=description_text,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"],],cache_examples=False)print("[INFO] Gradio interface created.")# --- Launch the App ---if __name__ == "__main__":print("[INFO] Launching Gradio app...")iface.launch()12345674 unmodified lines121314151617181920216 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import gradio as grimport tensorflow as tffrom tensorflow.keras.models import load_modelfrom tensorflow.keras import backend as Kimport numpy as npfrom PIL import Imageimport time4 unmodified linesMODEL_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: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.")6 unmodified lines# --- The Prediction Function ---def predict_fire(input_image):if input_image is None:return {"Error": 1.0}print("[INFO] Received image for prediction.")image = input_image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE))image_array = np.asarray(image)image_array = image_array / 255.0image_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 descriptiondescription_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 componentwith gr.Blocks(theme=gr.themes.Soft()) as demo:# Title (using your new name)gr.Markdown("""<h1 style="text-align: center;">🔥 HyFiNet 🔥</h1>""")# Custom-styled descriptiongr.Markdown(description_html)# Main layout with two columnswith gr.Row():# Left column for inputswith 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 outputswith gr.Column(scale=1):result_label = gr.Label(num_top_classes=2, label="Prediction Results")# Examples section with all 8 of your imagesgr.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 clickedpredict_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()
app.py+60-42