Minbz commited on
Commit
4a8a335
·
verified ·
1 Parent(s): 9ee4fff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -60
app.py CHANGED
@@ -7,8 +7,9 @@ from tensorflow.keras.models import Model, Sequential
7
  from tensorflow.keras.optimizers import Adam
8
  from tensorflow.keras.preprocessing import image
9
  from tensorflow.keras.applications.vgg16 import preprocess_input
 
10
 
11
- model_pb_path = "./4-15_ViT-B16_Lung3_v1/saved_model.pb"
12
  model_keras_path = "./model.keras"
13
  model_h5_path = "./model.h5"
14
 
@@ -17,78 +18,69 @@ model_url = "https://tfhub.dev/sayakpaul/vit_b16_classification/1"
17
  vit_b16 = hub.KerasLayer(model_url, trainable=False, input_shape=(224, 224, 3))
18
 
19
  # tf.config.experimental._could_use_gpu_kernel = False
20
- # Custom layer to wrap the hub.KerasLayer
21
- class WrappedLayer(tf.keras.layers.Layer):
22
- def __init__(self, **kwargs):
23
- kwargs.pop("handle")
24
- super(WrappedLayer, self).__init__(**kwargs)
25
- self.hub_layer = vit_b16
26
 
27
- def call(self, inputs, **kwargs):
28
- return self.hub_layer(inputs)
29
 
 
 
 
 
 
30
 
31
- with tf.keras.utils.custom_object_scope({"KerasLayer": WrappedLayer}):
32
- # model = tf.keras.models.load_model(model_keras_path, custom_objects={'KerasLayer': hub.KerasLayer})
33
- model = tf.keras.models.load_model(model_h5_path)
34
- # model.compile(optimizer=Adam(learning_rate=0.0001),
35
- # loss='binary_crossentropy',
36
- # metrics=['accuracy'])
37
-
38
- # # Load the saved TensorFlow Hub KerasLayer
39
- # model_url = "https://tfhub.dev/sayakpaul/vit_b16_classification/1"
40
 
41
- # # Load the ViT-B16 model pre-trained on ImageNet
42
- # try:
43
- # vit_b16 = hub.KerasLayer(model_url, trainable=False, input_shape=(224, 224, 3))
44
- # except Exception as e:
45
- # print(f"Failed to load the model from {model_url}. Error: {e}")
46
- # # Handle the error if the model cannot be loaded
47
- # raise
48
 
49
- # # Define the rest of the model architecture
50
- # model = Sequential([
51
- # vit_b16,
52
- # Dense(1024, activation='relu'),
53
- # Dropout(0.5),
54
- # Dense(1, activation='sigmoid')
55
- # ])
56
 
57
- # # Load the saved weights
58
- # model.load_weights("model.h5")
59
 
60
- # Define preprocessing function
61
- def preprocess_image(image):
62
- transform_test = transforms.Compose([
63
- transforms.Resize((224, 224)),
64
- transforms.ToTensor(),
65
- transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
66
- ])
67
 
68
- preprocessed_img = transform_test(image)
69
- return preprocessed_img
70
 
71
- # Define inference function
72
- def predict(image):
73
- # Preprocess the image
74
- preprocessed_image = preprocess_image(image)
75
 
76
- # Add batch dimension to input image
77
- input_tensor = tf.expand_dims(preprocessed_image, axis=0)
78
 
79
- # Perform inference
80
- predictions = model.predict(input_tensor)
81
 
82
- # Extract the predicted class label with the highest probability
83
- predicted_label = np.argmax(predictions[0])
84
 
85
- return predicted_label
86
 
87
- image_component = gr.Image(type="pil", label="Chest X-ray Image")
88
- label_component = gr.Label(label="Classification result", num_top_classes=1)
89
- description = ""
90
- title = "Pneumonia Classifier"
91
 
92
- demo = gr.Interface(fn=predict, inputs=image_component, outputs=label_component, description=description, title=title)
93
 
94
- demo.launch()
 
7
  from tensorflow.keras.optimizers import Adam
8
  from tensorflow.keras.preprocessing import image
9
  from tensorflow.keras.applications.vgg16 import preprocess_input
10
+ from transformers import TFAutoModelForSequenceClassification
11
 
12
+ model_pb_path = "./4-15_ViT-B16_Lung3_v1/"
13
  model_keras_path = "./model.keras"
14
  model_h5_path = "./model.h5"
15
 
 
18
  vit_b16 = hub.KerasLayer(model_url, trainable=False, input_shape=(224, 224, 3))
19
 
20
  # tf.config.experimental._could_use_gpu_kernel = False
 
 
 
 
 
 
21
 
22
+ model = TFAutoModelForSequenceClassification.from_pretrained('model_pb_path')
 
23
 
24
+ # model = tf.keras.models.load_model(model_keras_path, custom_objects={'KerasLayer': hub.KerasLayer})
25
+ # model = tf.keras.models.load_model(model_h5_path)
26
+ # model.compile(optimizer=Adam(learning_rate=0.0001),
27
+ # loss='binary_crossentropy',
28
+ # metrics=['accuracy'])
29
 
30
+ # # Load the saved TensorFlow Hub KerasLayer
31
+ # model_url = "https://tfhub.dev/sayakpaul/vit_b16_classification/1"
 
 
 
 
 
 
 
32
 
33
+ # # Load the ViT-B16 model pre-trained on ImageNet
34
+ # try:
35
+ # vit_b16 = hub.KerasLayer(model_url, trainable=False, input_shape=(224, 224, 3))
36
+ # except Exception as e:
37
+ # print(f"Failed to load the model from {model_url}. Error: {e}")
38
+ # # Handle the error if the model cannot be loaded
39
+ # raise
40
 
41
+ # # Define the rest of the model architecture
42
+ # model = Sequential([
43
+ # vit_b16,
44
+ # Dense(1024, activation='relu'),
45
+ # Dropout(0.5),
46
+ # Dense(1, activation='sigmoid')
47
+ # ])
48
 
49
+ # # Load the saved weights
50
+ # model.load_weights("model.h5")
51
 
52
+ # Define preprocessing function
53
+ def preprocess_image(image):
54
+ transform_test = transforms.Compose([
55
+ transforms.Resize((224, 224)),
56
+ transforms.ToTensor(),
57
+ transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
58
+ ])
59
 
60
+ preprocessed_img = transform_test(image)
61
+ return preprocessed_img
62
 
63
+ # Define inference function
64
+ def predict(image):
65
+ # Preprocess the image
66
+ preprocessed_image = preprocess_image(image)
67
 
68
+ # Add batch dimension to input image
69
+ input_tensor = tf.expand_dims(preprocessed_image, axis=0)
70
 
71
+ # Perform inference
72
+ predictions = model.predict(input_tensor)
73
 
74
+ # Extract the predicted class label with the highest probability
75
+ predicted_label = np.argmax(predictions[0])
76
 
77
+ return predicted_label
78
 
79
+ image_component = gr.Image(type="pil", label="Chest X-ray Image")
80
+ label_component = gr.Label(label="Classification result", num_top_classes=1)
81
+ description = ""
82
+ title = "Pneumonia Classifier"
83
 
84
+ demo = gr.Interface(fn=predict, inputs=image_component, outputs=label_component, description=description, title=title)
85
 
86
+ demo.launch()