import gradio as gr import tensorflow as tf from tensorflow.keras.models import model_from_json,Sequential from tensorflow.keras.preprocessing import image import numpy as np from tensorflow.keras.layers import Layer from tensorflow.keras.utils import register_keras_serializable import json class AccidentDetectionModel(object): class_nums = ['Accident', "No Accident"] def __init__(self, model_json_file, model_weights_file): # load model from JSON file with open(model_json_file, "r") as json_file: loaded_model_json = json_file.read() self.loaded_model = model_from_json(loaded_model_json) # load weights into the new model self.loaded_model.load_weights(model_weights_file) self.loaded_model.make_predict_function() def predict_accident(self, img): self.preds = self.loaded_model.predict(img) return AccidentDetectionModel.class_nums[np.argmax(self.preds)], self.preds # Initialize the model with the weights file model_ = AccidentDetectionModel("modified_model.json","modified_model_weights.h5") # from keras.preprocessing import image def predict(image): test_image = tf.keras.utils.load_img(image, target_size = (250,250,3)) test_image = tf.keras.utils.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) # print(test_image[:1]) #predict the result pred,probab = model_.predict_accident(test_image) return dict(zip(pred, {model_.class_nums[i]: float(probab[0][i]) for i in range(len(model_.class_nums))})) image = gr.Image() label = gr.Label(num_top_classes=2) demo = gr.Interface(fn=predict , inputs=image, outputs=label, title="Accident Detection") demo.launch()