Spaces:
Sleeping
Sleeping
File size: 4,231 Bytes
57b4d6e 9643386 133fb5d 313728a 133fb5d 313728a 133fb5d 3d80884 bb32dda 9a36a53 3e6074c 9a36a53 bb32dda 3e6074c 93e8de0 9a36a53 3d80884 a97f423 fc38a48 9a36a53 fc38a48 313728a fc38a48 313728a fc38a48 313728a fc38a48 a97f423 9643386 313728a 9643386 a97f423 9643386 9a36a53 a97f423 133fb5d 6f3e953 fc38a48 7b18cbe 9a36a53 fc38a48 3e6074c 9a36a53 3e6074c 9a36a53 fc38a48 a97f423 fc38a48 9a36a53 3e6074c fc38a48 a97f423 9a36a53 fc38a48 a97f423 9a36a53 fc38a48 9a36a53 bb32dda ccc2bbb a97f423 ccc2bbb 9a36a53 ccc2bbb a97f423 ccc2bbb a97f423 ccc2bbb a97f423 |
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
import gradio as gr
import pandas as pd
import numpy as np
import joblib
from skimage.measure import shannon_entropy
from skimage.color import rgb2hsv
from scipy.ndimage import generic_filter
import cv2
from PIL import Image
from sklearn.preprocessing import LabelEncoder
# Load trained model and scaler
model = joblib.load('lgbm_model.pkl') # Replace with actual path
scaler = joblib.load('minmax_scaler.pkl') # Replace with actual path
# Define the expected feature names manually
expected_features = ['meanr', 'meang', 'meanb', 'HHR', 'Ent', 'B',
'g1', 'g2', 'g3', 'g4', 'g5', 'Age'] # No 'Hgb'
# Include 'Gender' if it was used during training
use_gender = True # Set to False if your model was not trained with 'Gender'
if use_gender:
expected_features.append('Gender')
# Initialize LabelEncoder for gender encoding (if used in training)
gender_encoder = LabelEncoder()
gender_encoder.fit(['Female', 'Male'])
# Function to extract features
def extract_features(image):
image = np.array(image)
meanr = np.mean(image[:, :, 0])
meang = np.mean(image[:, :, 1])
meanb = np.mean(image[:, :, 2])
hsv_image = rgb2hsv(image)
hue = hsv_image[:, :, 0]
high_hue_pixels = np.sum(hue > 0.95)
total_pixels = hue.size
HHR = high_hue_pixels / total_pixels
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
Ent = shannon_entropy(gray_image)
B = np.mean(gray_image)
def g1_filter(window): return window[4] - np.min(window)
def g2_filter(window): return np.max(window) - window[4]
def g3_filter(window): return window[4] - np.mean(window)
def g4_filter(window): return np.std(window)
def g5_filter(window): return window[4]
g1 = generic_filter(gray_image, g1_filter, size=3).mean()
g2 = generic_filter(gray_image, g2_filter, size=3).mean()
g3 = generic_filter(gray_image, g3_filter, size=3).mean()
g4 = generic_filter(gray_image, g4_filter, size=3).mean()
g5 = generic_filter(gray_image, g5_filter, size=3).mean()
return {
"meanr": meanr, "meang": meang, "meanb": meanb,
"HHR": HHR, "Ent": Ent, "B": B, "g1": g1,
"g2": g2, "g3": g3, "g4": g4, "g5": g5,
}
# Prediction function
def predict_hemoglobin(age, gender, image):
try:
if image is None:
return "Error: No image uploaded. Please upload an image."
if not isinstance(image, Image.Image):
return "Error: Invalid image format. Please upload a valid image file."
# Extract features
features = extract_features(image)
# Encode gender only if used in training
if use_gender:
features["Gender"] = gender_encoder.transform([gender])[0]
features["Age"] = age
# Convert to DataFrame
features_df = pd.DataFrame([features])
# Ensure only model-expected features are used
for col in expected_features:
if col not in features_df:
features_df[col] = 0 # Add missing columns with default value
features_df = features_df[expected_features] # Ensure correct column order
# Apply scaling
features_scaled = scaler.transform(features_df)
# Predict hemoglobin
hemoglobin = model.predict(features_scaled)[0]
return f"Predicted Hemoglobin Value: {hemoglobin:.2f}"
except Exception as e:
print(f"Error during prediction: {e}")
return "An error occurred. Please check inputs and try again."
# Gradio interface
with gr.Blocks() as anemia_detection_app:
gr.Markdown("# Hemoglobin Prediction App")
with gr.Row():
age_input = gr.Number(label="Age", value=25)
gender_input = gr.Radio(label="Gender", choices=["Male", "Female"], value="Male", type="value")
image_input = gr.Image(label="Upload Retinal Image", type="pil")
output_text = gr.Textbox(label="Predicted Hemoglobin Value")
predict_button = gr.Button("Predict")
predict_button.click(
fn=predict_hemoglobin,
inputs=[age_input, gender_input, image_input],
outputs=output_text
)
# Run the app
if __name__ == "__main__":
anemia_detection_app.launch(share=True) # Enable public link
|