AzefAziz commited on
Commit
f47ec43
·
verified ·
1 Parent(s): 3065e08

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import numpy as np
3
+ from PIL import Image
4
+ import gradio as gr
5
+ import pickle
6
+ import os
7
+
8
+ # Define image dimensions (must match training dimensions)
9
+ img_height = 224
10
+ img_width = 224
11
+
12
+ # Load the trained Keras model from export.pkl
13
+ # Ensure 'export.pkl' is in the same directory as app.py
14
+ try:
15
+ with open('export.pkl', 'rb') as file:
16
+ model = pickle.load(file)
17
+ print("Model loaded from 'export.pkl' successfully.")
18
+ except FileNotFoundError:
19
+ print("Error: 'export.pkl' not found. Make sure the model file exists.")
20
+ exit()
21
+ except Exception as e:
22
+ print(f"Error loading model: {e}")
23
+ exit()
24
+
25
+ # Define the class indices mapping explicitly
26
+ # This needs to match the order used by ImageDataGenerator during training
27
+ class_indices_map = {'Non Venomous': 0, 'Venomous': 1}
28
+ # Reverse the map to get class names from indices for prediction output
29
+ label_map = {v: k for k, v in class_indices_map.items()}
30
+
31
+ def predict_snake_class(img):
32
+ # 1. Convert to PIL Image (if not already) and resize
33
+ if not isinstance(img, Image.Image):
34
+ img = Image.fromarray(img)
35
+ img = img.resize((img_width, img_height))
36
+
37
+ # 2. Convert to NumPy array
38
+ img_array = np.array(img)
39
+
40
+ # 3. Normalize the image
41
+ img_array = img_array / 255.0
42
+
43
+ # 4. Expand dimensions to create a batch
44
+ img_array = np.expand_dims(img_array, axis=0)
45
+
46
+ # 5. Make a prediction
47
+ predictions = model.predict(img_array)
48
+
49
+ # 6. Determine the predicted class and confidence
50
+ predicted_class_index = np.argmax(predictions[0])
51
+ confidence_score = predictions[0][predicted_class_index]
52
+
53
+ predicted_class_name = label_map[predicted_class_index]
54
+
55
+ # Format output for Gradio Label component
56
+ return {label_map[i]: float(predictions[0][i]) for i in range(len(label_map))}
57
+
58
+
59
+ # Set up the Gradio interface
60
+ iface = gr.Interface(
61
+ fn=predict_snake_class, # Our prediction function
62
+ inputs=gr.Image(type="pil", label="Upload Snake Image"), # Input is an image
63
+ outputs=gr.Label(num_top_classes=2), # Output is a label with top 2 classes
64
+ title="Snake Classification Model",
65
+ description="Upload an image of a snake to predict if it's Non Venomous or Venomous.",
66
+ live=True
67
+ )
68
+
69
+ # Launch the interface
70
+ iface.launch(share=True)
71
+