Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,39 @@
|
|
1 |
import gradio as gr
|
2 |
import tensorflow as tf
|
3 |
-
from tensorflow.keras.applications import ResNet152, preprocess_input, decode_predictions
|
4 |
from tensorflow.keras.preprocessing.image import img_to_array
|
5 |
from PIL import Image
|
6 |
import numpy as np
|
7 |
|
8 |
# Load the pre-trained ResNet152 model
|
9 |
-
MODEL_PATH = "resnet152-image-classifier.h5" #
|
10 |
-
|
|
|
|
|
|
|
|
|
11 |
|
12 |
def predict_image(image):
|
13 |
"""
|
14 |
-
|
15 |
"""
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
29 |
|
30 |
# Create the Gradio interface
|
31 |
interface = gr.Interface(
|
|
|
1 |
import gradio as gr
|
2 |
import tensorflow as tf
|
3 |
+
from tensorflow.keras.applications.resnet import ResNet152, preprocess_input, decode_predictions
|
4 |
from tensorflow.keras.preprocessing.image import img_to_array
|
5 |
from PIL import Image
|
6 |
import numpy as np
|
7 |
|
8 |
# Load the pre-trained ResNet152 model
|
9 |
+
MODEL_PATH = "resnet152-image-classifier.h5" # Path to the saved model
|
10 |
+
try:
|
11 |
+
model = tf.keras.models.load_model(MODEL_PATH)
|
12 |
+
except Exception as e:
|
13 |
+
print(f"Error loading model: {e}")
|
14 |
+
exit()
|
15 |
|
16 |
def predict_image(image):
|
17 |
"""
|
18 |
+
Process the uploaded image and return the top 3 predictions.
|
19 |
"""
|
20 |
+
try:
|
21 |
+
# Preprocess the image
|
22 |
+
image = image.resize((224, 224)) # ResNet152 expects 224x224 input
|
23 |
+
image_array = img_to_array(image)
|
24 |
+
image_array = preprocess_input(image_array) # Normalize the image
|
25 |
+
image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
|
26 |
|
27 |
+
# Get predictions
|
28 |
+
predictions = model.predict(image_array)
|
29 |
+
decoded_predictions = decode_predictions(predictions, top=3)[0]
|
30 |
|
31 |
+
# Format predictions as a dictionary
|
32 |
+
results = {label: f"{confidence * 100:.2f}%" for _, label, confidence in decoded_predictions}
|
33 |
+
return results
|
34 |
+
|
35 |
+
except Exception as e:
|
36 |
+
return {"Error": str(e)}
|
37 |
|
38 |
# Create the Gradio interface
|
39 |
interface = gr.Interface(
|