File size: 2,203 Bytes
855dec5
89eb9aa
0359853
05bc0c4
ed2ebb9
f385180
3ab85e2
f1bfe09
 
7b07da9
0359853
444ad4e
4a8a335
f385180
 
 
 
 
 
 
 
 
 
 
a8b4e24
4a8a335
f385180
4a8a335
f385180
a8b4e24
4a8a335
 
ed2ebb9
4a8a335
 
f09afe9
 
5654cee
0d515ad
d6336c6
a1ee644
a8b4e24
bfa4685
4a8a335
06d459f
 
4a8a335
 
a8b4e24
fdcfae8
 
06d459f
fdcfae8
 
 
 
 
 
 
36d0841
4a8a335
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
os.system('pip install tf_keras')
import tf_keras #Keras3 no longer supports hub.KerasLayer()

import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
import gradio as gr

model_path = "./4-17_ViT-B16_Lung3_v4_E30/"
model = tf_keras.models.load_model(model_path) #Load model with old version (tf_keras instead of tf.keras)

# Define preprocessing function
def preprocess_image(image_path):
    # Load the image from file
    img = image.load_img(image_path, target_size=(224, 224))
    
    # Convert the image to a numpy array
    img_array = image.img_to_array(img)
    
    # Rescale the pixel values to the range [0, 1]
    img_array /= 255.0

    return img_array

# Define inference function
def predict(image_path):
    # Preprocess the image
    preprocessed_image = preprocess_image(image_path)

    # Add batch dimension to input image
    input_tensor = tf.expand_dims(preprocessed_image, axis=0)
    
    # Perform inference
    predictions = model.predict(input_tensor)

    predicted_probabilities = np.squeeze(predictions)
    predicted_class = 'Pneumonia' if predicted_probabilities > 0.5 else 'Normal' 
    confidence_score = predicted_probabilities if predicted_class == 'Pneumonia' else 1 - predicted_probabilities

    return "Prediction: " + predicted_class, {'Confidence: ': confidence_score}

image_component = gr.Image(type="filepath", label="Chest X-ray Image")
label_component = gr.Label(label="Classification result", num_top_classes=1)
confidence_component = gr.Label(label="Confidence Score (%)")

description = ""
title = "Pneumonia Classifier"

demo = gr.Interface(fn=predict, 
                    inputs=image_component, 
                    outputs=[label_component, confidence_component], 
                    description=description, 
                    title=title,
                    examples=["demo_example_imgs/NORMAL-0001-0001.jpeg",
                              "demo_example_imgs/NORMAL2-IM-0337-0001.jpeg",
                              "demo_example_imgs/PNEUMONIA_bacteria_434.jpeg",
                              "demo_example_imgs/PNEUMONIA_virus_140.jpeg"
                             ])
    
demo.launch()