Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- .gitattributes +1 -0
- README.md +13 -13
- app.py +70 -0
- load_and_display_xray_images.py +79 -0
- pneumonia_model.keras +3 -0
- requirements.txt +5 -0
- streamlit_app.py +5 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
pneumonia_model.keras filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,13 +1,13 @@
|
|
1 |
-
---
|
2 |
-
title: Pneumonia XRay Classifier
|
3 |
-
emoji: 🐢
|
4 |
-
colorFrom: purple
|
5 |
-
colorTo: purple
|
6 |
-
sdk: streamlit
|
7 |
-
sdk_version: 1.39.0
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
short_description: Pneumonia Detection from Chest X-rays
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
+
---
|
2 |
+
title: Pneumonia XRay Classifier
|
3 |
+
emoji: 🐢
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: purple
|
6 |
+
sdk: streamlit
|
7 |
+
sdk_version: 1.39.0
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
short_description: Pneumonia Detection from Chest X-rays
|
11 |
+
---
|
12 |
+
|
13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# flask_app.py
|
2 |
+
import os
|
3 |
+
import numpy as np
|
4 |
+
import cv2
|
5 |
+
from flask import Flask, request, jsonify, render_template
|
6 |
+
from tensorflow.keras.models import load_model # type: ignore
|
7 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
|
10 |
+
# Load the saved model
|
11 |
+
model = load_model('pneumonia_model_final.keras')
|
12 |
+
|
13 |
+
def preprocess_image(image):
|
14 |
+
"""Preprocess the image for prediction."""
|
15 |
+
img = cv2.imread(image, cv2.IMREAD_GRAYSCALE) # Read image as grayscale
|
16 |
+
if img is None:
|
17 |
+
return None
|
18 |
+
|
19 |
+
img = cv2.resize(img, (224, 224)) # Resize to 224x224 pixels
|
20 |
+
img = img.astype(np.float32) / 255.0 # Normalize to [0, 1] range
|
21 |
+
img = (img * 255).astype(np.uint8) # Convert back to 8-bit unsigned integer format
|
22 |
+
|
23 |
+
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # Convert to RGB
|
24 |
+
img = np.expand_dims(img, axis=0) # Add batch dimension
|
25 |
+
return img
|
26 |
+
|
27 |
+
@app.route('/')
|
28 |
+
def home():
|
29 |
+
"""Render the home page for uploading images."""
|
30 |
+
return render_template('index.html')
|
31 |
+
|
32 |
+
@app.route('/predict', methods=['POST'])
|
33 |
+
def predict():
|
34 |
+
"""Endpoint for making predictions."""
|
35 |
+
if 'file' not in request.files:
|
36 |
+
return jsonify({'error': 'No file provided.'}), 400
|
37 |
+
|
38 |
+
file = request.files['file']
|
39 |
+
|
40 |
+
# Save the uploaded file temporarily
|
41 |
+
file_path = 'temp_image.jpg'
|
42 |
+
file.save(file_path)
|
43 |
+
|
44 |
+
# Preprocess the image
|
45 |
+
processed_image = preprocess_image(file_path)
|
46 |
+
if processed_image is None:
|
47 |
+
return jsonify({'error': 'Invalid image format.'}), 400
|
48 |
+
|
49 |
+
# Make a prediction
|
50 |
+
prediction = model.predict(processed_image)
|
51 |
+
probability = prediction[0][0] # Get the probability score
|
52 |
+
|
53 |
+
# Calculate percentage probability
|
54 |
+
probability_percent = round(probability * 100, 2)
|
55 |
+
|
56 |
+
# Classification threshold
|
57 |
+
threshold = 0.7 # Adjust threshold if necessary
|
58 |
+
is_pneumonia = probability > threshold
|
59 |
+
|
60 |
+
# Determine result message
|
61 |
+
result_text = f"Pneumonia" if is_pneumonia else f"Not Pneumonia"
|
62 |
+
|
63 |
+
# Remove the temporary file
|
64 |
+
os.remove(file_path)
|
65 |
+
|
66 |
+
# Render the result page with prediction details
|
67 |
+
return render_template('result.html', result=result_text, probability=probability_percent)
|
68 |
+
|
69 |
+
if __name__ == '__main__':
|
70 |
+
app.run(debug=True)
|
load_and_display_xray_images.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
from sklearn.model_selection import train_test_split
|
5 |
+
from tensorflow.keras.models import Sequential
|
6 |
+
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
|
7 |
+
from tensorflow.keras.callbacks import ModelCheckpoint
|
8 |
+
|
9 |
+
# Function to load images from specified folders
|
10 |
+
def load_images_from_folders(folders):
|
11 |
+
images = []
|
12 |
+
for folder in folders:
|
13 |
+
for filename in os.listdir(folder):
|
14 |
+
if filename.lower().endswith(('.png', '.jpg', '.jpeg')): # Check for valid image extensions
|
15 |
+
img = cv2.imread(os.path.join(folder, filename), cv2.IMREAD_GRAYSCALE) # Read image as grayscale
|
16 |
+
if img is not None:
|
17 |
+
img = cv2.resize(img, (224, 224)) # Resize to 224x224 pixels
|
18 |
+
img = img.astype(np.float32) # Ensure the image is in float32 format
|
19 |
+
img /= 255.0 # Normalize to [0, 1]
|
20 |
+
images.append(img)
|
21 |
+
else:
|
22 |
+
print(f"Failed to load image: {filename}")
|
23 |
+
return np.array(images)
|
24 |
+
|
25 |
+
# Load normal and pneumonia images
|
26 |
+
normal_folders = [
|
27 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'test', 'NORMAL'),
|
28 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'train', 'NORMAL'),
|
29 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'val', 'NORMAL'),
|
30 |
+
]
|
31 |
+
pneumonia_folders = [
|
32 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'test', 'PNEUMONIA'),
|
33 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'train', 'PNEUMONIA'),
|
34 |
+
os.path.join('chest-xray-pneumonia', 'chest_xray', 'val', 'PNEUMONIA'),
|
35 |
+
]
|
36 |
+
|
37 |
+
normal_images = load_images_from_folders(normal_folders)
|
38 |
+
pneumonia_images = load_images_from_folders(pneumonia_folders)
|
39 |
+
|
40 |
+
# Print the number of images loaded for each category
|
41 |
+
print(f"Loaded {len(normal_images)} normal images.")
|
42 |
+
print(f"Loaded {len(pneumonia_images)} pneumonia images.")
|
43 |
+
|
44 |
+
# Prepare dataset for machine learning
|
45 |
+
images = np.concatenate([normal_images, pneumonia_images]) # Combine normal and pneumonia images
|
46 |
+
labels = np.array([0] * len(normal_images) + [1] * len(pneumonia_images)) # Create labels
|
47 |
+
|
48 |
+
# Split the dataset into training and testing sets
|
49 |
+
X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=0.2, random_state=42)
|
50 |
+
|
51 |
+
# Convert to RGB format
|
52 |
+
X_train_rgb = np.stack([cv2.cvtColor((img * 255).astype(np.uint8), cv2.COLOR_GRAY2RGB) for img in X_train])
|
53 |
+
X_test_rgb = np.stack([cv2.cvtColor((img * 255).astype(np.uint8), cv2.COLOR_GRAY2RGB) for img in X_test])
|
54 |
+
|
55 |
+
print(f'Training data shape: {X_train_rgb.shape}, Training labels shape: {y_train.shape}')
|
56 |
+
print(f'Testing data shape: {X_test_rgb.shape}, Testing labels shape: {y_test.shape}')
|
57 |
+
|
58 |
+
# Build a simple CNN model
|
59 |
+
model = Sequential([
|
60 |
+
Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
|
61 |
+
MaxPooling2D(pool_size=(2, 2)),
|
62 |
+
Conv2D(64, (3, 3), activation='relu'),
|
63 |
+
MaxPooling2D(pool_size=(2, 2)),
|
64 |
+
Flatten(),
|
65 |
+
Dense(128, activation='relu'),
|
66 |
+
Dense(1, activation='sigmoid') # Binary classification
|
67 |
+
])
|
68 |
+
|
69 |
+
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
70 |
+
|
71 |
+
# Set up model checkpointing with the new file extension
|
72 |
+
checkpoint = ModelCheckpoint('pneumonia_model.keras', save_best_only=True, monitor='val_loss', mode='min')
|
73 |
+
|
74 |
+
# Train the model
|
75 |
+
model.fit(X_train_rgb, y_train, validation_data=(X_test_rgb, y_test), epochs=10, callbacks=[checkpoint])
|
76 |
+
|
77 |
+
# Save the model in the new format
|
78 |
+
model.save('pneumonia_model_final.keras')
|
79 |
+
print("Model saved as 'pneumonia_model_final.keras'")
|
pneumonia_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7063c5dcfc8c5fe59992f6ffeca3e0946b7b7ecbac960e2fb51e8d55a5e288d7
|
3 |
+
size 286927607
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Flask
|
2 |
+
numpy
|
3 |
+
opencv-python
|
4 |
+
tensorflow
|
5 |
+
streamlit
|
streamlit_app.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# streamlit_app.py
|
2 |
+
import streamlit as st
|
3 |
+
|
4 |
+
x = st.slider('Select a value')
|
5 |
+
st.write(x, 'squared is', x * x)
|