Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
# Load the TFLite model
|
| 7 |
+
def load_tflite_model(model_path):
|
| 8 |
+
interpreter = tf.lite.Interpreter(model_path=model_path)
|
| 9 |
+
interpreter.allocate_tensors()
|
| 10 |
+
return interpreter
|
| 11 |
+
|
| 12 |
+
# Preprocess image for TFLite model (assuming the model expects 224x224 RGB images)
|
| 13 |
+
def preprocess_image(image):
|
| 14 |
+
image = image.resize((224, 224)) # Resize to model input size
|
| 15 |
+
image = np.array(image) / 255.0 # Normalize the image
|
| 16 |
+
image = np.expand_dims(image, axis=0).astype(np.float32) # Add batch dimension
|
| 17 |
+
return image
|
| 18 |
+
|
| 19 |
+
# Run inference with the TFLite model
|
| 20 |
+
def run_inference(interpreter, image):
|
| 21 |
+
input_details = interpreter.get_input_details()
|
| 22 |
+
output_details = interpreter.get_output_details()
|
| 23 |
+
|
| 24 |
+
# Set input tensor
|
| 25 |
+
interpreter.set_tensor(input_details[0]['index'], image)
|
| 26 |
+
|
| 27 |
+
# Run inference
|
| 28 |
+
interpreter.invoke()
|
| 29 |
+
|
| 30 |
+
# Get the output tensor
|
| 31 |
+
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 32 |
+
|
| 33 |
+
return output_data
|
| 34 |
+
|
| 35 |
+
# Gradio interface function
|
| 36 |
+
def predict(image):
|
| 37 |
+
interpreter = load_tflite_model("MNv2Flood_cat_Sept2024.tflite") # Replace with your TFLite model path
|
| 38 |
+
preprocessed_image = preprocess_image(image)
|
| 39 |
+
prediction = run_inference(interpreter, preprocessed_image)
|
| 40 |
+
|
| 41 |
+
# Get class probabilities for Flood and NoFlood
|
| 42 |
+
flood_prob = prediction[0][0]
|
| 43 |
+
no_flood_prob = prediction[0][1]
|
| 44 |
+
|
| 45 |
+
# Determine the predicted label based on probabilities
|
| 46 |
+
if flood_prob > no_flood_prob:
|
| 47 |
+
return {"Flood": float(flood_prob), "NoFlood": float(no_flood_prob)}
|
| 48 |
+
else:
|
| 49 |
+
return {"Flood": float(flood_prob), "NoFlood": float(no_flood_prob)}
|
| 50 |
+
|
| 51 |
+
# Create Gradio interface
|
| 52 |
+
interface = gr.Interface(
|
| 53 |
+
fn=predict, # Function that runs the model
|
| 54 |
+
inputs=gr.Image(type="pil"), # Input is an image, processed as PIL image
|
| 55 |
+
outputs=gr.Label(num_top_classes=2) # Outputs a label with the predicted classes
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Launch the app
|
| 59 |
+
interface.launch()
|