edtech07 commited on
Commit
5b8eba8
·
verified ·
1 Parent(s): 03029a0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ # Load the trained model
7
+ model = tf.keras.models.load_model('my_model (3).keras')
8
+
9
+ # Get class names from the training data generator (assuming 'train' is still in scope from previous execution)
10
+ # If 'train' is not in scope, you would need to define class_indices manually or reload data generators.
11
+ # For this example, let's assume 'train.class_indices' is available or define a placeholder.
12
+
13
+ # If `train` is not available, uncomment and modify the line below based on your actual classes:
14
+ idx_to_class = {0: 'glioma', 1: 'meningioma', 2: 'notumor', 3: 'pituitary'}
15
+
16
+ # Using the `idx_to_class` from previous execution
17
+ # If `idx_to_class` is not defined, please refer to the notebook output from the prediction cell.
18
+ class_labels = list(idx_to_class.values())
19
+
20
+ # Define the image size used for training
21
+ img_size = 224
22
+
23
+ def predict_image(image):
24
+ # Preprocess the image
25
+ img = Image.fromarray(image)
26
+ img = img.resize((img_size, img_size))
27
+ img_array = np.array(img)
28
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
29
+
30
+ # Apply the same preprocessing function as during training
31
+ # (EfficientNet's preprocess_input function was used)
32
+ img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
33
+
34
+ # Make prediction
35
+ predictions = model.predict(img_array)[0]
36
+
37
+ # Get predicted class and confidence
38
+ predicted_class_idx = np.argmax(predictions)
39
+ predicted_class_label = class_labels[predicted_class_idx]
40
+ confidence = predictions[predicted_class_idx] * 100
41
+
42
+ return predicted_class_label, f"{confidence:.2f}%"
43
+
44
+ # Create the Gradio interface
45
+ iface = gr.Interface(
46
+ fn=predict_image,
47
+ inputs=gr.Image(type="numpy", label="Upload MRI Scan"),
48
+ outputs=[
49
+ gr.Textbox(label="Predicted Class"),
50
+ gr.Textbox(label="Confidence")
51
+ ],
52
+ title="Brain Tumor MRI Classification",
53
+ description="Upload an MRI scan to get a prediction for brain tumor type and confidence.",
54
+ )
55
+
56
+ # Launch the interface
57
+ iface.launch(debug=True)