itzbhav commited on
Commit
8882732
·
verified ·
1 Parent(s): cfd613a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -137
app.py CHANGED
@@ -1,137 +1,137 @@
1
- # Import required libraries
2
- import streamlit as st
3
- import numpy as np
4
- import pandas as pd
5
- from keras.models import load_model
6
- from keras.preprocessing import image
7
- import os
8
- import matplotlib.pyplot as plt
9
- import random
10
-
11
- # Set page configuration FIRST
12
- st.set_page_config(page_title="Blood Group Detection", layout="wide")
13
-
14
- # Title of the app
15
- st.title("🩸 Blood Group Detection using LeNet Model")
16
-
17
- # Sidebar navigation
18
- st.sidebar.header("Navigation")
19
- selected_option = st.sidebar.selectbox(
20
- "Select an option:",
21
- ["Home", "EDA", "Predict Blood Group"]
22
- )
23
-
24
- # Load the trained model
25
- @st.cache_resource
26
- def load_trained_model():
27
- model = load_model('bloodgroup_mobilenet_finetuned.h5') # Ensure correct path
28
- return model
29
-
30
- model = load_trained_model()
31
-
32
- # Define class labels
33
- class_names = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
34
-
35
- # Dataset directory (you must adjust this if needed)
36
- DATASET_DIR = "dataset" # Example path
37
-
38
- # Home page
39
- if selected_option == "Home":
40
- st.subheader("About the Project")
41
- st.write("""
42
- Welcome to the Blood Group Detection App!
43
-
44
- This application uses a Deep Learning model (LeNet architecture) to detect blood groups from blood sample images.
45
-
46
- ### 🛠 Technologies Used:
47
- - Streamlit for Web UI
48
- - TensorFlow/Keras for Deep Learning
49
- - Image Processing with Computer Vision
50
-
51
- **Upload a blood sample image and predict the blood group instantly!**
52
- """)
53
- try:
54
- st.image("blood_home.jpg", caption="Blood Sample Analysis", use_column_width=True)
55
- except:
56
- st.warning("Home image not found. (Optional)")
57
-
58
- # EDA page
59
- elif selected_option == "EDA":
60
- st.subheader("Exploratory Data Analysis (EDA)")
61
-
62
- # Check if dataset exists
63
- if os.path.exists(DATASET_DIR):
64
- st.write("### 📊 Number of Images per Blood Group:")
65
-
66
- counts = {}
67
- for class_name in class_names:
68
- class_path = os.path.join(DATASET_DIR, class_name)
69
- if os.path.exists(class_path):
70
- counts[class_name] = len(os.listdir(class_path))
71
- else:
72
- counts[class_name] = 0
73
-
74
- df_counts = pd.DataFrame(list(counts.items()), columns=['Blood Group', 'Number of Images'])
75
- st.dataframe(df_counts)
76
-
77
- # Bar Chart
78
- st.bar_chart(df_counts.set_index('Blood Group'))
79
-
80
- st.write("### 🖼️ Sample Images from Each Class:")
81
-
82
- cols = st.columns(4) # create 4 columns
83
-
84
- for idx, class_name in enumerate(class_names):
85
- class_path = os.path.join(DATASET_DIR, class_name)
86
- if os.path.exists(class_path) and len(os.listdir(class_path)) > 0:
87
- img_file = random.choice(os.listdir(class_path))
88
- img_path = os.path.join(class_path, img_file)
89
- img = image.load_img(img_path, target_size=(64, 64)) # resized
90
- with cols[idx % 4]: # arrange in 4 columns
91
- st.image(img, caption=class_name, width=150)
92
-
93
- st.write("### 🧩 Image Properties:")
94
- sample_class = class_names[0]
95
- sample_path = os.path.join(DATASET_DIR, sample_class, os.listdir(os.path.join(DATASET_DIR, sample_class))[0])
96
- sample_img = image.load_img(sample_path)
97
- st.write(f"- **Image shape:** {np.array(sample_img).shape}")
98
- st.write(f"- **Color channels:** {np.array(sample_img).shape[-1]} (RGB)")
99
-
100
- else:
101
- st.warning("Dataset not found! Please make sure the 'dataset/train' folder exists.")
102
-
103
- # Prediction page
104
- elif selected_option == "Predict Blood Group":
105
- st.subheader("Upload an Image to Predict Blood Group")
106
-
107
- uploaded_file = st.file_uploader("Choose a blood sample image...", type=["jpg", "jpeg", "png", "bmp"])
108
-
109
- if uploaded_file is not None:
110
- # Display uploaded image
111
- st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
112
-
113
- # Ensure temp directory exists
114
- if not os.path.exists('temp'):
115
- os.makedirs('temp')
116
-
117
- # Save uploaded file temporarily
118
- temp_file_path = os.path.join("temp", uploaded_file.name)
119
- with open(temp_file_path, "wb") as f:
120
- f.write(uploaded_file.getbuffer())
121
-
122
- # Preprocess the image
123
- img = image.load_img(temp_file_path, target_size=(224, 224)) # Adjust size if needed
124
- img_array = image.img_to_array(img)
125
- img_array = np.expand_dims(img_array, axis=0)
126
- img_array = img_array / 255.0 # Normalize pixel values
127
-
128
- # Predict the blood group
129
- with st.spinner('Predicting...'):
130
- prediction = model.predict(img_array)
131
- predicted_class = class_names[np.argmax(prediction)]
132
-
133
- # Show result
134
- st.success(f"🧬 Predicted Blood Group: **{predicted_class}**")
135
-
136
- # Remove temporary file
137
- os.remove(temp_file_path)
 
1
+ # Import required libraries
2
+ import streamlit as st
3
+ import numpy as np
4
+ import pandas as pd
5
+ from keras.models import load_model
6
+ from keras.preprocessing import image
7
+ import os
8
+ import matplotlib.pyplot as plt
9
+ import random
10
+
11
+ # Set page configuration FIRST
12
+ st.set_page_config(page_title="Blood Group Detection", layout="wide")
13
+
14
+ # Title of the app
15
+ st.title("🩸 Blood Group Detection using LeNet Model")
16
+
17
+ # Sidebar navigation
18
+ st.sidebar.header("Navigation")
19
+ selected_option = st.sidebar.selectbox(
20
+ "Select an option:",
21
+ ["Home", "EDA", "Predict Blood Group"]
22
+ )
23
+
24
+ # Load the trained model
25
+ @st.cache_resource
26
+ def load_trained_model():
27
+ model = load_model('best_model.h5') # Ensure correct path
28
+ return model
29
+
30
+ model = load_trained_model()
31
+
32
+ # Define class labels
33
+ class_names = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
34
+
35
+ # Dataset directory (you must adjust this if needed)
36
+ DATASET_DIR = "dataset" # Example path
37
+
38
+ # Home page
39
+ if selected_option == "Home":
40
+ st.subheader("About the Project")
41
+ st.write("""
42
+ Welcome to the Blood Group Detection App!
43
+
44
+ This application uses a Deep Learning model (LeNet architecture) to detect blood groups from blood sample images.
45
+
46
+ ### 🛠 Technologies Used:
47
+ - Streamlit for Web UI
48
+ - TensorFlow/Keras for Deep Learning
49
+ - Image Processing with Computer Vision
50
+
51
+ **Upload a blood sample image and predict the blood group instantly!**
52
+ """)
53
+ try:
54
+ st.image("blood_home.jpg", caption="Blood Sample Analysis", use_column_width=True)
55
+ except:
56
+ st.warning("Home image not found. (Optional)")
57
+
58
+ # EDA page
59
+ elif selected_option == "EDA":
60
+ st.subheader("Exploratory Data Analysis (EDA)")
61
+
62
+ # Check if dataset exists
63
+ if os.path.exists(DATASET_DIR):
64
+ st.write("### 📊 Number of Images per Blood Group:")
65
+
66
+ counts = {}
67
+ for class_name in class_names:
68
+ class_path = os.path.join(DATASET_DIR, class_name)
69
+ if os.path.exists(class_path):
70
+ counts[class_name] = len(os.listdir(class_path))
71
+ else:
72
+ counts[class_name] = 0
73
+
74
+ df_counts = pd.DataFrame(list(counts.items()), columns=['Blood Group', 'Number of Images'])
75
+ st.dataframe(df_counts)
76
+
77
+ # Bar Chart
78
+ st.bar_chart(df_counts.set_index('Blood Group'))
79
+
80
+ st.write("### 🖼️ Sample Images from Each Class:")
81
+
82
+ cols = st.columns(4) # create 4 columns
83
+
84
+ for idx, class_name in enumerate(class_names):
85
+ class_path = os.path.join(DATASET_DIR, class_name)
86
+ if os.path.exists(class_path) and len(os.listdir(class_path)) > 0:
87
+ img_file = random.choice(os.listdir(class_path))
88
+ img_path = os.path.join(class_path, img_file)
89
+ img = image.load_img(img_path, target_size=(64, 64)) # resized
90
+ with cols[idx % 4]: # arrange in 4 columns
91
+ st.image(img, caption=class_name, width=150)
92
+
93
+ st.write("### 🧩 Image Properties:")
94
+ sample_class = class_names[0]
95
+ sample_path = os.path.join(DATASET_DIR, sample_class, os.listdir(os.path.join(DATASET_DIR, sample_class))[0])
96
+ sample_img = image.load_img(sample_path)
97
+ st.write(f"- **Image shape:** {np.array(sample_img).shape}")
98
+ st.write(f"- **Color channels:** {np.array(sample_img).shape[-1]} (RGB)")
99
+
100
+ else:
101
+ st.warning("Dataset not found! Please make sure the 'dataset/train' folder exists.")
102
+
103
+ # Prediction page
104
+ elif selected_option == "Predict Blood Group":
105
+ st.subheader("Upload an Image to Predict Blood Group")
106
+
107
+ uploaded_file = st.file_uploader("Choose a blood sample image...", type=["jpg", "jpeg", "png", "bmp"])
108
+
109
+ if uploaded_file is not None:
110
+ # Display uploaded image
111
+ st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
112
+
113
+ # Ensure temp directory exists
114
+ if not os.path.exists('temp'):
115
+ os.makedirs('temp')
116
+
117
+ # Save uploaded file temporarily
118
+ temp_file_path = os.path.join("temp", uploaded_file.name)
119
+ with open(temp_file_path, "wb") as f:
120
+ f.write(uploaded_file.getbuffer())
121
+
122
+ # Preprocess the image
123
+ img = image.load_img(temp_file_path, target_size=(224, 224)) # Adjust size if needed
124
+ img_array = image.img_to_array(img)
125
+ img_array = np.expand_dims(img_array, axis=0)
126
+ img_array = img_array / 255.0 # Normalize pixel values
127
+
128
+ # Predict the blood group
129
+ with st.spinner('Predicting...'):
130
+ prediction = model.predict(img_array)
131
+ predicted_class = class_names[np.argmax(prediction)]
132
+
133
+ # Show result
134
+ st.success(f"🧬 Predicted Blood Group: **{predicted_class}**")
135
+
136
+ # Remove temporary file
137
+ os.remove(temp_file_path)