sunil18p31a0101 commited on
Commit
a97f423
·
verified ·
1 Parent(s): c8c222d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -64
app.py CHANGED
@@ -11,17 +11,17 @@ from sklearn.preprocessing import LabelEncoder
11
 
12
  # Initialize LabelEncoder for gender encoding
13
  gender_encoder = LabelEncoder()
14
- gender_encoder.fit(['Female', 'Male']) # Ensure that the labels are ordered
15
 
16
  # Function to extract features from the image
17
  def extract_features(image):
18
  # Convert PIL image to NumPy array
19
- image = np.array(image)
20
 
21
  # Extract RGB means
22
- meanr = np.mean(image[:, :, 0]) # Red channel
23
- meang = np.mean(image[:, :, 1]) # Green channel
24
- meanb = np.mean(image[:, :, 2]) # Blue channel
25
 
26
  # Convert to HSI and compute HHR
27
  hsv_image = rgb2hsv(image)
@@ -39,21 +39,12 @@ def extract_features(image):
39
  # Compute Brightness
40
  B = np.mean(gray_image)
41
 
42
- # Sliding window for gray-level features
43
- def g1_filter(window):
44
- return window[4] - np.min(window)
45
-
46
- def g2_filter(window):
47
- return np.max(window) - window[4]
48
-
49
- def g3_filter(window):
50
- return window[4] - np.mean(window)
51
-
52
- def g4_filter(window):
53
- return np.std(window)
54
-
55
- def g5_filter(window):
56
- return window[4]
57
 
58
  # Apply filters with 3x3 window
59
  g1 = generic_filter(gray_image, g1_filter, size=3).mean()
@@ -62,71 +53,56 @@ def extract_features(image):
62
  g4 = generic_filter(gray_image, g4_filter, size=3).mean()
63
  g5 = generic_filter(gray_image, g5_filter, size=3).mean()
64
 
65
- # Return features
66
  return {
67
- "meanr": meanr,
68
- "meang": meang,
69
- "meanb": meanb,
70
- "HHR": HHR,
71
- "Ent": Ent,
72
- "B": B,
73
- "g1": g1,
74
- "g2": g2,
75
- "g3": g3,
76
- "g4": g4,
77
- "g5": g5,
78
  }
79
 
80
- # Function to check if the image is a valid file format
81
- def check_image_format(filepath):
82
  try:
83
- # Try opening the image using PIL
84
- with Image.open(filepath) as img:
85
- img.verify() # Verify if it's a valid image file
86
- return True
87
- except Exception as e:
88
- print(f"Error opening image: {e}")
89
- return False
90
-
91
- # Function to predict hemoglobin value with label encoding for gender
92
- def predict_hemoglobin(age, Gender, image):
93
- try:
94
- # Ensure the image is not None
95
  if image is None:
96
  return "Error: No image uploaded. Please upload an image."
97
 
98
- # Check if the image is valid
99
  if not isinstance(image, Image.Image):
100
  return "Error: Invalid image format. Please upload a valid image file."
101
 
 
 
 
 
 
 
102
  # Extract features from the image
103
  features = extract_features(image)
104
 
105
- # Use LabelEncoder to convert gender to numerical value
106
  features['Gender'] = gender_encoder.transform([gender])[0]
107
  features['Age'] = age
108
 
109
- # Create a DataFrame for features (do not include Hgb, as it's the predicted value)
110
  features_df = pd.DataFrame([features])
111
 
112
- # Load the trained model, scaler, and label encoder
113
- svr_model = joblib.load('lgbm_model.pkl') # Replace with the actual path to your model file
114
- scaler = joblib.load('minmax_scaler.pkl') # Replace with the actual path to your scaler file
115
 
116
- # Ensure that features_df matches the expected training feature set (without 'Hgb')
117
  expected_columns = ['meanr', 'meang', 'meanb', 'HHR', 'Ent', 'B', 'g1', 'g2', 'g3', 'g4', 'g5', 'Age', 'Gender']
118
-
119
  for col in expected_columns:
120
  if col not in features_df:
121
- features_df[col] = 0 # Or some default value to match the expected columns.
122
 
123
- features_df = features_df[expected_columns] # Ensure the correct order of columns
124
 
125
- # Apply scaling (do not include 'Hgb' as it is the target)
126
  features_df_scaled = scaler.transform(features_df)
127
 
128
- # Predict hemoglobin using the trained SVR model
129
- hemoglobin = svr_model.predict(features_df_scaled)[0]
130
 
131
  return f"Predicted Hemoglobin Value: {hemoglobin:.2f}"
132
 
@@ -137,16 +113,16 @@ def predict_hemoglobin(age, Gender, image):
137
  # Gradio interface
138
  with gr.Blocks() as anemia_detection_app:
139
  gr.Markdown("# Hemoglobin Prediction App")
140
-
141
  with gr.Row():
142
  age_input = gr.Number(label="Age", value=25)
143
- gender_input = gr.Radio(label="Gender", choices=["Male", "Female"], value="Male")
144
 
145
  image_input = gr.Image(label="Upload Retinal Image", type="pil")
146
  output_text = gr.Textbox(label="Predicted Hemoglobin Value")
147
-
148
  predict_button = gr.Button("Predict")
149
-
150
  predict_button.click(
151
  fn=predict_hemoglobin,
152
  inputs=[age_input, gender_input, image_input],
@@ -155,4 +131,4 @@ with gr.Blocks() as anemia_detection_app:
155
 
156
  # Run the app
157
  if __name__ == "__main__":
158
- anemia_detection_app.launch()
 
11
 
12
  # Initialize LabelEncoder for gender encoding
13
  gender_encoder = LabelEncoder()
14
+ gender_encoder.fit(['Female', 'Male']) # Ensuring correct label mapping
15
 
16
  # Function to extract features from the image
17
  def extract_features(image):
18
  # Convert PIL image to NumPy array
19
+ image = np.array(image)
20
 
21
  # Extract RGB means
22
+ meanr = np.mean(image[:, :, 0])
23
+ meang = np.mean(image[:, :, 1])
24
+ meanb = np.mean(image[:, :, 2])
25
 
26
  # Convert to HSI and compute HHR
27
  hsv_image = rgb2hsv(image)
 
39
  # Compute Brightness
40
  B = np.mean(gray_image)
41
 
42
+ # Define sliding window filters
43
+ def g1_filter(window): return window[4] - np.min(window)
44
+ def g2_filter(window): return np.max(window) - window[4]
45
+ def g3_filter(window): return window[4] - np.mean(window)
46
+ def g4_filter(window): return np.std(window)
47
+ def g5_filter(window): return window[4]
 
 
 
 
 
 
 
 
 
48
 
49
  # Apply filters with 3x3 window
50
  g1 = generic_filter(gray_image, g1_filter, size=3).mean()
 
53
  g4 = generic_filter(gray_image, g4_filter, size=3).mean()
54
  g5 = generic_filter(gray_image, g5_filter, size=3).mean()
55
 
56
+ # Return extracted features
57
  return {
58
+ "meanr": meanr, "meang": meang, "meanb": meanb,
59
+ "HHR": HHR, "Ent": Ent, "B": B, "g1": g1,
60
+ "g2": g2, "g3": g3, "g4": g4, "g5": g5,
 
 
 
 
 
 
 
 
61
  }
62
 
63
+ # Function to predict hemoglobin value
64
+ def predict_hemoglobin(age, gender, image):
65
  try:
66
+ # Validate image input
 
 
 
 
 
 
 
 
 
 
 
67
  if image is None:
68
  return "Error: No image uploaded. Please upload an image."
69
 
 
70
  if not isinstance(image, Image.Image):
71
  return "Error: Invalid image format. Please upload a valid image file."
72
 
73
+ # Validate gender input
74
+ if gender not in ["Male", "Female"]:
75
+ return "Error: Invalid gender selected."
76
+
77
+ print(f"Received Gender: {gender}") # Debugging line
78
+
79
  # Extract features from the image
80
  features = extract_features(image)
81
 
82
+ # Encode gender as a numerical value
83
  features['Gender'] = gender_encoder.transform([gender])[0]
84
  features['Age'] = age
85
 
86
+ # Convert to DataFrame
87
  features_df = pd.DataFrame([features])
88
 
89
+ # Load trained model and scaler
90
+ model = joblib.load('lgbm_model.pkl') # Replace with actual path
91
+ scaler = joblib.load('minmax_scaler.pkl') # Replace with actual path
92
 
93
+ # Ensure features match expected columns
94
  expected_columns = ['meanr', 'meang', 'meanb', 'HHR', 'Ent', 'B', 'g1', 'g2', 'g3', 'g4', 'g5', 'Age', 'Gender']
 
95
  for col in expected_columns:
96
  if col not in features_df:
97
+ features_df[col] = 0 # Assign default value if missing
98
 
99
+ features_df = features_df[expected_columns] # Ensure correct column order
100
 
101
+ # Apply scaling
102
  features_df_scaled = scaler.transform(features_df)
103
 
104
+ # Predict hemoglobin
105
+ hemoglobin = model.predict(features_df_scaled)[0]
106
 
107
  return f"Predicted Hemoglobin Value: {hemoglobin:.2f}"
108
 
 
113
  # Gradio interface
114
  with gr.Blocks() as anemia_detection_app:
115
  gr.Markdown("# Hemoglobin Prediction App")
116
+
117
  with gr.Row():
118
  age_input = gr.Number(label="Age", value=25)
119
+ gender_input = gr.Radio(label="Gender", choices=["Male", "Female"], value="Male", type="value") # ✅ FIXED
120
 
121
  image_input = gr.Image(label="Upload Retinal Image", type="pil")
122
  output_text = gr.Textbox(label="Predicted Hemoglobin Value")
123
+
124
  predict_button = gr.Button("Predict")
125
+
126
  predict_button.click(
127
  fn=predict_hemoglobin,
128
  inputs=[age_input, gender_input, image_input],
 
131
 
132
  # Run the app
133
  if __name__ == "__main__":
134
+ anemia_detection_app.launch(share=True) # Enable public link