Spaces:
Sleeping
Sleeping
Update app.py
Browse files15 unmodified lines1617181920213 unmodified lines25262728293079 unmodified lines11011111211311411532 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620739 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822831 unmodified line2852862872882892902914 unmodified lines2962972982993003013023033043053063073083093103113123133143153163173183193203218 unmodified lines3303313323333343353363378 unmodified lines34634734834935035135235335435535635735814 unmodified lines3733743753763773783793803814 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740816 unmodified lines42542642742842943043120 unmodified lines4524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974983 unmodified lines50250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853915 unmodified linesimport reimport osimport picklefrom sklearn.preprocessing import LabelEncoderfrom sklearn.impute import SimpleImputerfrom huggingface_hub import hf_hub_download3 unmodified linesdevice = torch.device("cpu")REPO_ID = "Dina-Raslan/ckd-retinal-model"# ── Retinal Model ─────────────────────────────────────────────────────────────class RetinalModelV2(nn.Module):def __init__(self, num_classes=2):79 unmodified linesprint("All models ready.")OPTIMAL_THRESHOLD = 0.50# ── Preprocessing ─────────────────────────────────────────────────────────────32 unmodified linesreturn img.astype(np.float32) / 255.0# ── Clinical Feature Preparation ──────────────────────────────────────────────NUMERIC_COLS = ["age", "bp", "bgr", "bu", "sc", "sod", "pot", "hemo", "pcv", "wbcc", "rbcc"]CATEGORICAL_COLS = ["sg", "al", "su", "rbc", "pc", "pcc", "ba", "htn", "dm", "cad", "appet", "pe", "ane"]ALL_COLS = NUMERIC_COLS + CATEGORICAL_COLSdef prepare_clinical_features(creatinine, egfr, urea, hemoglobin, glucose, bp):# Build a row matching the UCI CKD dataset structure# Map input values to dataset columnsrow = {"age": 45, # default"bp": bp,"bgr": glucose,"bu": urea,"sc": creatinine,"sod": 135, # default normal"pot": 4.0, # default normal"hemo": hemoglobin,"pcv": hemoglobin * 3, # approximate"wbcc": 7500, # default normal"rbcc": 4.5, # default normal"sg": "1.020","al": "0","su": "0","rbc": "normal","pc": "normal","pcc": "notpresent","ba": "notpresent","htn": "yes" if bp > 140 else "no","dm": "yes" if glucose > 126 else "no","cad": "no","appet": "good","pe": "no","ane": "yes" if hemoglobin < 12 else "no",}import pandas as pddf = pd.DataFrame([row])# Encode categoricalsle = LabelEncoder()for col in CATEGORICAL_COLS:df[col] = le.fit_transform(df[col].astype(str))# Reorder columns to match scalerdf = df[ALL_COLS]# Scalescaled = clinical_scaler.transform(df)return scaled# ── Grad-CAM++ ────────────────────────────────────────────────────────────────class GradCAMPlusPlus:def __init__(self, model, target_layer):self.model = modelself.gradients = Noneself.activations = Nonetarget_layer.register_forward_hook(self._save_activation)target_layer.register_full_backward_hook(self._save_gradient)39 unmodified lines# ── OCR ───────────────────────────────────────────────────────────────────────LAB_PATTERNS = {"creatinine": r"creatinine[\s\S]{0,30}?(\d+\.?\d*)\s*mg","egfr": r"e\.?g\.?f\.?r[\s\S]{0,30}?(\d+\.?\d*)\s*ml","urea": r"urea[\s\S]{0,20}?(\d+\.?\d*)\s*mg","hemoglobin": r"h[ae]moglobin[\s\S]{0,20}?(\d+\.?\d*)\s*g","glucose": r"glucose[\s\S]{0,20}?(\d+\.?\d*)\s*mg","bp": r"(?:blood\s*pressure|systolic)[\s\S]{0,20}?(\d{2,3})\s*mm",}def parse_lab_values(text):text_lower = text.lower()values = {}ranges = {"creatinine": (0.1, 20), "egfr": (1, 150),"urea": (1, 300), "hemoglobin": (1, 25),"glucose": (30, 600), "bp": (50, 250),}for key, pattern in LAB_PATTERNS.items():match = re.search(pattern, text_lower)if match:try:val = float(match.group(1))lo, hi = ranges.get(key, (0, 9999))if lo <= val <= hi:values[key] = valexcept ValueError:passreturn valuesdef process_lab_file(lab_file):if lab_file is None:return "No file uploaded", 1.2, 60, 30, 13, 100, 120path = lab_file.name if hasattr(lab_file, "name") else lab_file1 unmodified linedoc = fitz.open(path)text = "".join(page.get_text() for page in doc)else:img = Image.open(path)img_np = np.array(img.convert("RGB"))img_cv = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)img_cv = cv2.resize(img_cv, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)4 unmodified linesvalues = parse_lab_values(text)status = "Extracted values:\n" if values else "Could not extract automatically. Please enter manually.\n"for k, v in values.items():status += f" {k}: {v}\n"return (status,values.get("creatinine", 1.2),values.get("egfr", 60),values.get("urea", 30),values.get("hemoglobin", 13),values.get("glucose", 100),values.get("bp", 120),)# ── Main Prediction ───────────────────────────────────────────────────────────def predict_ckd_risk(retinal_image, lab_file,creatinine, egfr, urea, hemoglobin, glucose, bp):if retinal_image is None:return None, "Please upload a retinal image.", "", ""# 1. Preprocess retinal imageimg_processed = preprocess_retinal(retinal_image)8 unmodified linesretinal_feat_np = retinal_features.cpu().numpy()retinal_feat_pca = pca_model.transform(retinal_feat_np)# 4. Prepare clinical featuresclinical_feat = prepare_clinical_features(creatinine, egfr, urea, hemoglobin, glucose, bp)# 5. GB clinical predictionclinical_prob = gb_model.predict_proba(clinical_feat)[0, 1]8 unmodified lines# 7. Final riskif fusion_prob >= 0.6:risk_label = "HIGH RISK"risk_color = "red"elif fusion_prob >= 0.35:risk_label = "MEDIUM RISK"risk_color = "orange"else:risk_label = "LOW RISK"risk_color = "green"# 8. Grad-CAM++14 unmodified linesoverlay = (overlay * circ_mask).astype(np.uint8)fig, axes = plt.subplots(1, 3, figsize=(15, 5))axes[0].imshow(img_rgb); axes[0].set_title("Preprocessed Retinal Image"); axes[0].axis("off")axes[1].imshow(cam, cmap="jet"); axes[1].set_title("Grad-CAM++ Heatmap"); axes[1].axis("off")axes[2].imshow(overlay); axes[2].set_title("Overlay"); axes[2].axis("off")plt.suptitle(f"CKD Risk: {risk_label} | Fusion Score: {fusion_prob:.3f}",fontsize=13, color=risk_color, fontweight="bold"4 unmodified linesplt.close()clinical_summary = f"""CLINICAL VALUES{'='*35}Creatinine: {creatinine} mg/dLeGFR: {egfr} mL/min/1.73m2Urea: {urea} mg/dLHemoglobin: {hemoglobin} g/dLGlucose: {glucose} mg/dLBlood Pressure: {bp} mmHg{'='*35}AI PREDICTION BREAKDOWNRetinal Score: {retinal_prob:.4f}Clinical Score: {clinical_prob:.4f}Fusion Score: {fusion_prob:.4f}Risk Level: {risk_label}"""risk_display = f"**{risk_label}**\n\nFusion Score: {fusion_prob:.4f}\nRetinal: {retinal_prob:.4f} | Clinical: {clinical_prob:.4f}"return gradcam_path, risk_display, clinical_summary, f"Done. Risk: {risk_label}"16 unmodified linesdef chat_with_groq(message, history):if check_emergency(message):return "This sounds like a medical emergency. Please call emergency services immediately."messages = [{"role": "system", "content": SYSTEM_PROMPT}]for item in history:20 unmodified linesreturn f"Error: {str(e)}"# ── Gradio UI ─────────────────────────────────���───────────────────────────────with gr.Blocks(title="CKD-MultiVision") as demo:gr.Markdown("""# CKD-MultiVision### Multimodal AI System for Early Chronic Kidney Disease Detection*Retinal Image + Clinical Lab Values → AI Risk Assessment*""")with gr.Tabs():with gr.TabItem("Risk Prediction"):with gr.Row():with gr.Column(scale=1):retinal_input = gr.Image(label="Retinal Fundus Image (JPG/PNG)", type="pil", height=300)gr.Markdown("### Lab Report (Optional - PDF or Image)")lab_file_input = gr.File(label="Upload Lab Report", file_types=[".pdf", ".png", ".jpg", ".jpeg"])extract_btn = gr.Button("Extract Values from File", variant="secondary")extract_status = gr.Textbox(label="Extraction Status", lines=4, interactive=False)with gr.Column(scale=1):gr.Markdown("### Clinical Values")creatinine_input = gr.Number(label="Creatinine (mg/dL)", value=1.2, minimum=0)egfr_input = gr.Number(label="eGFR (mL/min/1.73m2)", value=60, minimum=0)urea_input = gr.Number(label="Urea (mg/dL)", value=30, minimum=0)hemoglobin_input = gr.Number(label="Hemoglobin (g/dL)", value=13, minimum=0)glucose_input = gr.Number(label="Glucose (mg/dL)", value=100, minimum=0)bp_input = gr.Number(label="Blood Pressure (mmHg)", value=120, minimum=0)predict_btn = gr.Button("Run CKD Risk Assessment", variant="primary", size="lg")with gr.Row():with gr.Column():gradcam_output = gr.Image(label="Retinal Analysis + Grad-CAM++")with gr.Column():risk_output = gr.Markdown(label="Risk Result")clinical_output = gr.Textbox(label="Prediction Breakdown", lines=14, interactive=False)status_output = gr.Textbox(label="Status", interactive=False)with gr.TabItem("CKD Health Coach"):gr.Markdown("### Ask about diet, lifestyle, exercise, and kidney health.")chatbot = gr.Chatbot(height=450)chat_input = gr.Textbox(placeholder="Ask a question...", label="Your Message")send_btn = gr.Button("Send", variant="primary")gr.Examples(examples=["What foods should I avoid with CKD?",3 unmodified linesinputs=chat_input)with gr.TabItem("About"):gr.Markdown("""## About CKD-MultiVision**Pipeline:**- Retinal Image → EfficientNet-B3 → Feature Vector (1536)- Feature Vector → PCA → (64 dim)- Clinical Values → StandardScaler → (24 dim)- PCA Features + Clinical Features → Cross-Modal Attention Fusion → Risk Level**Results:**| Method | AUC ||--------|-----|| Scientific Reports 2025 | 0.910 || JMIR 2025 (MMDL) | 0.940 || **CKD-MultiVision (Ours)** | **0.963** |*Research prototype — not for clinical use.*""")# ── Handlers ──────────────────────────────────────────────────────────────extract_btn.click(fn=process_lab_file,inputs=[lab_file_input],outputs=[extract_status, creatinine_input, egfr_input,urea_input, hemoglobin_input, glucose_input, bp_input])predict_btn.click(fn=predict_ckd_risk,inputs=[retinal_input, lab_file_input,creatinine_input, egfr_input, urea_input,hemoglobin_input, glucose_input, bp_input],outputs=[gradcam_output, risk_output, clinical_output, status_output])15 unmodified lines161718192021223 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646579 unmodified lines14514614714814915015115215315415515632 unmodified lines18919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225339 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913921 unmodified line3943953963973983994004 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564578 unmodified lines4664674684694704714724734744754764774784798 unmodified lines48848949049149249349449549649749849950014 unmodified lines5155165175185195205215225234 unmodified lines52852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457516 unmodified lines59259359459559659759820 unmodified lines6196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147153 unmodified lines71972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079115 unmodified linesimport reimport osimport pickleimport pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.impute import SimpleImputerfrom huggingface_hub import hf_hub_download3 unmodified linesdevice = torch.device("cpu")REPO_ID = "Dina-Raslan/ckd-retinal-model"# ── UCI Column Definitions ────────────────────────────────────────────────────NUMERIC_COLS = ["age", "bp", "bgr", "bu", "sc", "sod", "pot", "hemo", "pcv", "wbcc", "rbcc"]CATEGORICAL_COLS = ["sg", "al", "su", "rbc", "pc", "pcc", "ba", "htn", "dm", "cad", "appet", "pe", "ane"]ALL_COLS = NUMERIC_COLS + CATEGORICAL_COLS# القيم الممكنة لكل عمود categorical - لازم تكون ثابتة علشان LabelEncoder يشتغل صحLABEL_ENCODER_CLASSES = {"sg": ["1.005", "1.010", "1.015", "1.020", "1.025"],"al": ["0", "1", "2", "3", "4", "5"],"su": ["0", "1", "2", "3", "4", "5"],"rbc": ["abnormal", "normal"],"pc": ["abnormal", "normal"],"pcc": ["notpresent", "present"],"ba": ["notpresent", "present"],"htn": ["no", "yes"],"dm": ["no", "yes"],"cad": ["no", "yes"],"appet": ["good", "poor"],"pe": ["no", "yes"],"ane": ["no", "yes"],}def encode_categoricals(df):"""Encode categorical columns consistently using fixed classes"""for col in CATEGORICAL_COLS:le = LabelEncoder()le.classes_ = np.array(LABEL_ENCODER_CLASSES[col])val = str(df[col].iloc[0]).strip()# لو القيمة مش موجودة في الـ classes خد أقرب قيمةif val not in LABEL_ENCODER_CLASSES[col]:val = LABEL_ENCODER_CLASSES[col][0]df[col] = le.transform([val])return df# ── Retinal Model ─────────────────────────────────────────────────────────────class RetinalModelV2(nn.Module):def __init__(self, num_classes=2):79 unmodified linesprint("All models ready.")# تحقق من اسماء الأعمدة في الـ scalerif hasattr(clinical_scaler, 'feature_names_in_'):print("Scaler trained on:", list(clinical_scaler.feature_names_in_))else:print("Scaler has no feature_names_in_ - will use numpy array directly")OPTIMAL_THRESHOLD = 0.50# ── Preprocessing ─────────────────────────────────────────────────────────────32 unmodified linesreturn img.astype(np.float32) / 255.0# ── Clinical Feature Preparation ──────────────────────────────────────────────def prepare_clinical_features(# من التحاليلsc, bu, hemo, bgr, sod, pot, pcv, wbcc, rbcc,sg, al, su, rbc, pc, pcc, ba,# مانيوالage, bp, htn, dm, cad, appet, pe, ane):"""تحضير الـ 24 feature بالترتيب الصح للـ scaler"""row = {# Numeric"age": float(age),"bp": float(bp),"bgr": float(bgr),"bu": float(bu),"sc": float(sc),"sod": float(sod),"pot": float(pot),"hemo": float(hemo),"pcv": float(pcv),"wbcc": float(wbcc),"rbcc": float(rbcc),# Categorical"sg": str(sg),"al": str(al),"su": str(su),"rbc": str(rbc),"pc": str(pc),"pcc": str(pcc),"ba": str(ba),"htn": str(htn),"dm": str(dm),"cad": str(cad),"appet": str(appet),"pe": str(pe),"ane": str(ane),}df = pd.DataFrame([row])# Encode categoricals بطريقة صح (fixed classes)df = encode_categoricals(df)# رتب الأعمدة بالترتيب الصحdf = df[ALL_COLS]# اعمل numpy array مباشرة علشان نتجنب مشكلة feature namesX = df.values.astype(np.float64)# Scalescaled = clinical_scaler.transform(X)return scaled# ── Grad-CAM++ ────────────────────────────────────────────────────────────────class GradCAMPlusPlus:def __init__(self, model, target_layer):self.model = modelself.gradients = Noneself.activations = Nonetarget_layer.register_forward_hook(self._save_activation)target_layer.register_full_backward_hook(self._save_gradient)39 unmodified lines# ── OCR ───────────────────────────────────────────────────────────────────────LAB_PATTERNS = {# Blood Tests"sc": [r"creatinine[\s\S]{0,40}?(\d+\.?\d*)\s*mg", r"s\.?\s*creat[\s\S]{0,30}?(\d+\.?\d*)"],"bu": [r"(?:blood\s*urea|urea|bun)[\s\S]{0,30}?(\d+\.?\d*)\s*mg", r"b\.?u\.?n[\s\S]{0,20}?(\d+\.?\d*)"],"hemo": [r"h[ae]moglobin[\s\S]{0,30}?(\d+\.?\d*)\s*g", r"hgb[\s\S]{0,20}?(\d+\.?\d*)"],"bgr": [r"(?:blood\s*glucose|glucose|random\s*blood\s*sugar|rbs)[\s\S]{0,30}?(\d+\.?\d*)\s*mg",r"fbs[\s\S]{0,20}?(\d+\.?\d*)"],"sod": [r"sodium[\s\S]{0,30}?(\d+\.?\d*)\s*m?eq", r"na\+?[\s\S]{0,20}?(\d+\.?\d*)"],"pot": [r"potassium[\s\S]{0,30}?(\d+\.?\d*)\s*m?eq", r"k\+?[\s\S]{0,20}?(\d+\.?\d*)"],"pcv": [r"(?:packed\s*cell\s*volume|hematocrit|pcv|hct)[\s\S]{0,30}?(\d+\.?\d*)\s*%?"],"wbcc": [r"(?:white\s*blood\s*cell|wbc|leukocyte)[\s\S]{0,30}?(\d+[\d,]*\.?\d*)",r"wbcc[\s\S]{0,20}?(\d+[\d,]*\.?\d*)"],"rbcc": [r"(?:red\s*blood\s*cell|rbc\s*count|erythrocyte)[\s\S]{0,30}?(\d+\.?\d*)",r"rbcc[\s\S]{0,20}?(\d+\.?\d*)"],# Urine Tests"sg": [r"(?:specific\s*gravity|sp\.?\s*gr\.?)[\s\S]{0,30}?(1\.\d{3})"],"al": [r"(?:albumin|protein)[\s\S]{0,30}?(\d)\s*\+?", r"albumin[\s\S]{0,20}?(\d)"],"su": [r"(?:sugar|glucose)\s*(?:in\s*urine|urine)[\s\S]{0,30}?(\d)", r"glycosuria[\s\S]{0,20}?(\d)"],"bp": [r"(?:blood\s*pressure|bp|diastolic)[\s\S]{0,30}?(\d{2,3})\s*mm",r"\d{2,3}\s*/\s*(\d{2,3})\s*mm"],}VALUE_RANGES = {"sc": (0.1, 20), "bu": (1, 300),"hemo": (1, 25), "bgr": (30, 600),"sod": (100, 170), "pot": (1, 10),"pcv": (10, 60), "wbcc": (2000, 30000),"rbcc": (1, 8), "sg": (1.000, 1.030),"al": (0, 5), "su": (0, 5),"bp": (50, 250),}def parse_lab_values(text):text_lower = text.lower()values = {}for key, patterns in LAB_PATTERNS.items():for pattern in patterns:match = re.search(pattern, text_lower)if match:try:val_str = match.group(1).replace(",", "")val = float(val_str)lo, hi = VALUE_RANGES.get(key, (0, 9999))if lo <= val <= hi:values[key] = valbreakexcept (ValueError, IndexError):pass# استنتاج categorical من النص# RBC in urineif re.search(r"rbc\s*(?:in\s*urine|urine)[\s\S]{0,30}?abnormal", text_lower):values["rbc"] = "abnormal"elif re.search(r"rbc\s*(?:in\s*urine|urine)[\s\S]{0,30}?normal", text_lower):values["rbc"] = "normal"# Pus Cellsif re.search(r"pus\s*cells?[\s\S]{0,30}?abnormal", text_lower):values["pc"] = "abnormal"elif re.search(r"pus\s*cells?[\s\S]{0,30}?normal", text_lower):values["pc"] = "normal"# Pus Cell Clumpsif re.search(r"pus\s*cell\s*clumps?[\s\S]{0,30}?present", text_lower):values["pcc"] = "present"elif re.search(r"pus\s*cell\s*clumps?[\s\S]{0,30}?not\s*present", text_lower):values["pcc"] = "notpresent"# Bacteriaif re.search(r"bacteri[\s\S]{0,30}?present", text_lower):values["ba"] = "present"elif re.search(r"bacteri[\s\S]{0,30}?not\s*present", text_lower):values["ba"] = "notpresent"# Specific Gravity - snap to nearest valid valueif "sg" in values:valid_sg = [1.005, 1.010, 1.015, 1.020, 1.025]sg_val = values["sg"]nearest = min(valid_sg, key=lambda x: abs(x - sg_val))values["sg"] = f"{nearest:.3f}"# Albumin و Sugar -> snap to integer stringfor col in ["al", "su"]:if col in values:values[col] = str(int(round(values[col])))return valuesdef process_lab_file(lab_file):if lab_file is None:return ("No file uploaded.",gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),gr.update(), gr.update(), gr.update(), gr.update(),gr.update(), gr.update(), gr.update())path = lab_file.name if hasattr(lab_file, "name") else lab_file1 unmodified linedoc = fitz.open(path)text = "".join(page.get_text() for page in doc)else:img = Image.open(path)img_np = np.array(img.convert("RGB"))img_cv = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)img_cv = cv2.resize(img_cv, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)4 unmodified linesvalues = parse_lab_values(text)if values:found = [k for k in values]status = f" Extracted {len(found)} values: {', '.join(found)}\nPlease verify and fill missing fields manually."else:status = "️ Could not extract values automatically.\nPlease enter all values manually."def upd(key, default):return gr.update(value=values[key]) if key in values else gr.update(value=default)def upd_cat(key, default):return gr.update(value=values[key]) if key in values else gr.update(value=default)return (status,upd("sc", 1.2),upd("bu", 30),upd("hemo", 13),upd("bgr", 100),upd("sod", 135),upd("pot", 4.0),upd("pcv", 39),upd("wbcc", 7500),upd("rbcc", 4.5),upd("bp", 80),upd_cat("sg", "1.020"),upd_cat("al", "0"),upd_cat("su", "0"),upd_cat("rbc", "normal"),upd_cat("pc", "normal"),upd_cat("pcc", "notpresent"),upd_cat("ba", "notpresent"),)# ── Main Prediction ───────────────────────────────────────────────────────────def predict_ckd_risk(retinal_image,# Blood testssc, bu, hemo, bgr, sod, pot, pcv, wbcc, rbcc,# Blood pressurebp,# Urine tests (categorical)sg, al, su, rbc, pc, pcc, ba,# Manual entryage, htn, dm, cad, appet, pe, ane):if retinal_image is None:return None, "️ Please upload a retinal image.", "", ""# 1. Preprocess retinal imageimg_processed = preprocess_retinal(retinal_image)8 unmodified linesretinal_feat_np = retinal_features.cpu().numpy()retinal_feat_pca = pca_model.transform(retinal_feat_np)# 4. Prepare clinical features (24 columns, correct order)clinical_feat = prepare_clinical_features(sc=sc, bu=bu, hemo=hemo, bgr=bgr, sod=sod, pot=pot,pcv=pcv, wbcc=wbcc, rbcc=rbcc,sg=sg, al=al, su=su, rbc=rbc, pc=pc, pcc=pcc, ba=ba,age=age, bp=bp,htn=htn, dm=dm, cad=cad, appet=appet, pe=pe, ane=ane)# 5. GB clinical predictionclinical_prob = gb_model.predict_proba(clinical_feat)[0, 1]8 unmodified lines# 7. Final riskif fusion_prob >= 0.6:risk_label = " HIGH RISK"risk_color = "red"elif fusion_prob >= 0.35:risk_label = " MEDIUM RISK"risk_color = "orange"else:risk_label = " LOW RISK"risk_color = "green"# 8. Grad-CAM++14 unmodified linesoverlay = (overlay * circ_mask).astype(np.uint8)fig, axes = plt.subplots(1, 3, figsize=(15, 5))axes[0].imshow(img_rgb); axes[0].set_title("Preprocessed Retinal Image"); axes[0].axis("off")axes[1].imshow(cam, cmap="jet"); axes[1].set_title("Grad-CAM++ Heatmap"); axes[1].axis("off")axes[2].imshow(overlay); axes[2].set_title("Overlay"); axes[2].axis("off")plt.suptitle(f"CKD Risk: {risk_label} | Fusion Score: {fusion_prob:.3f}",fontsize=13, color=risk_color, fontweight="bold"4 unmodified linesplt.close()clinical_summary = f"""╔══════════════════════════════════════╗║ CLINICAL VALUES ║╠══════════════════════════════════════╣BLOOD TESTSCreatinine (sc): {sc} mg/dLUrea/BUN (bu): {bu} mg/dLHemoglobin (hemo): {hemo} g/dLBlood Glucose (bgr): {bgr} mg/dLSodium (sod): {sod} mEq/LPotassium (pot): {pot} mEq/LPacked Cell Vol (pcv):{pcv} %WBC Count (wbcc): {wbcc} cells/cummRBC Count (rbcc): {rbcc} millions/cummBlood Pressure (bp): {bp} mmHgURINE TESTSSpecific Gravity (sg):{sg}Albumin (al): {al}Sugar (su): {su}RBC in Urine (rbc): {rbc}Pus Cells (pc): {pc}Pus Cell Clumps (pcc):{pcc}Bacteria (ba): {ba}PATIENT INFOAge: {age} yearsHypertension (htn): {htn}Diabetes (dm): {dm}Coronary Art. (cad): {cad}Appetite (appet): {appet}Pedal Edema (pe): {pe}Anemia (ane): {ane}╠══════════════════════════════════════╣AI PREDICTION BREAKDOWNRetinal Score: {retinal_prob:.4f}Clinical Score: {clinical_prob:.4f}Fusion Score: {fusion_prob:.4f}Risk Level: {risk_label}╚══════════════════════════════════════╝"""risk_display = f"## {risk_label}\n\n**Fusion Score:** {fusion_prob:.4f}\n\n**Retinal:** {retinal_prob:.4f} | **Clinical:** {clinical_prob:.4f}"return gradcam_path, risk_display, clinical_summary, f"Done. Risk: {risk_label}"16 unmodified linesdef chat_with_groq(message, history):if check_emergency(message):return " This sounds like a medical emergency. Please call emergency services immediately."messages = [{"role": "system", "content": SYSTEM_PROMPT}]for item in history:20 unmodified linesreturn f"Error: {str(e)}"# ── Gradio UI ─────────────────────────────────���───────────────────────────────with gr.Blocks(title="CKD-MultiVision", theme=gr.themes.Soft()) as demo:gr.Markdown("""# CKD-MultiVision### Multimodal AI System for Early Chronic Kidney Disease Detection*Retinal Image + Clinical Lab Values → AI Risk Assessment*""")with gr.Tabs():# ── Tab 1: Risk Prediction ─────────────────────────────────────────with gr.TabItem(" Risk Prediction"):# Lab file uploadwith gr.Row():with gr.Column():gr.Markdown("### Upload Lab Report (Optional)")lab_file_input = gr.File(label="Upload Lab Report (PDF or Image)",file_types=[".pdf", ".png", ".jpg", ".jpeg"])extract_btn = gr.Button(" Extract Values from File", variant="secondary")extract_status = gr.Textbox(label="Extraction Status", lines=3, interactive=False)gr.Markdown("---")with gr.Row():# Left: Retinal Imagewith gr.Column(scale=1):gr.Markdown("### ️ Retinal Fundus Image")retinal_input = gr.Image(label="Upload Retinal Image (JPG/PNG)",type="pil", height=300)# Middle: Blood Testswith gr.Column(scale=1):gr.Markdown("### Blood Tests")sc_input = gr.Number(label="Serum Creatinine - sc (mg/dL)", value=1.2, minimum=0.1, maximum=20)bu_input = gr.Number(label="Blood Urea/BUN - bu (mg/dL)", value=30, minimum=1, maximum=300)hemo_input = gr.Number(label="Hemoglobin - hemo (g/dL)", value=13, minimum=1, maximum=25)bgr_input = gr.Number(label="Blood Glucose Random - bgr (mg/dL)", value=100, minimum=30, maximum=600)sod_input = gr.Number(label="Sodium - sod (mEq/L)", value=135, minimum=100, maximum=170)pot_input = gr.Number(label="Potassium - pot (mEq/L)", value=4.0, minimum=1, maximum=10)pcv_input = gr.Number(label="Packed Cell Volume/Hematocrit - pcv (%)", value=39, minimum=10, maximum=60)wbcc_input = gr.Number(label="WBC Count - wbcc (cells/cumm)", value=7500, minimum=2000, maximum=30000)rbcc_input = gr.Number(label="RBC Count - rbcc (millions/cumm)", value=4.5, minimum=1, maximum=8)bp_input = gr.Number(label="Blood Pressure Diastolic - bp (mmHg)", value=80, minimum=50, maximum=200)# Right: Urine Tests + Manualwith gr.Column(scale=1):gr.Markdown("### Urine Tests")sg_input = gr.Dropdown(label="Specific Gravity - sg",choices=["1.005","1.010","1.015","1.020","1.025"],value="1.020")al_input = gr.Dropdown(label="Albumin in Urine - al (0=None, 5=Heavy)",choices=["0","1","2","3","4","5"], value="0")su_input = gr.Dropdown(label="Sugar in Urine - su (0=None, 5=Heavy)",choices=["0","1","2","3","4","5"], value="0")rbc_input = gr.Radio(label="RBC in Urine - rbc",choices=["normal","abnormal"], value="normal")pc_input = gr.Radio(label="Pus Cells - pc",choices=["normal","abnormal"], value="normal")pcc_input = gr.Radio(label="Pus Cell Clumps - pcc",choices=["notpresent","present"], value="notpresent")ba_input = gr.Radio(label="Bacteria in Urine - ba",choices=["notpresent","present"], value="notpresent")gr.Markdown("### Patient Info (Manual)")age_input = gr.Number(label="Age (years)", value=45, minimum=2, maximum=90)htn_input = gr.Radio(label="Hypertension - htn", choices=["no","yes"], value="no")dm_input = gr.Radio(label="Diabetes Mellitus - dm", choices=["no","yes"], value="no")cad_input = gr.Radio(label="Coronary Artery Disease - cad", choices=["no","yes"], value="no")appet_input = gr.Radio(label="Appetite - appet", choices=["good","poor"], value="good")pe_input = gr.Radio(label="Pedal Edema (Swelling) - pe", choices=["no","yes"], value="no")ane_input = gr.Radio(label="Anemia - ane", choices=["no","yes"], value="no")predict_btn = gr.Button(" Run CKD Risk Assessment", variant="primary", size="lg")with gr.Row():with gr.Column():gradcam_output = gr.Image(label="Retinal Analysis + Grad-CAM++")with gr.Column():risk_output = gr.Markdown(label="Risk Result")clinical_output = gr.Textbox(label="Full Report", lines=20, interactive=False)status_output = gr.Textbox(label="Status", interactive=False)# ── Tab 2: CKD Health Coach ────────────────────────────────────────with gr.TabItem(" CKD Health Coach"):gr.Markdown("### Ask about diet, lifestyle, exercise, and kidney health.")chatbot = gr.Chatbot(height=450, type="messages")chat_input = gr.Textbox(placeholder="Ask a question about CKD...", label="Your Message")send_btn = gr.Button("Send", variant="primary")gr.Examples(examples=["What foods should I avoid with CKD?",3 unmodified linesinputs=chat_input)# ── Tab 3: About ───────────────────────────────────────────────────with gr.TabItem("About"):gr.Markdown("""## About CKD-MultiVision**Input Fields (24 total — matching UCI CKD Dataset):**| # | Field | Source | Description ||---|-------|--------|-------------|| 1 | age | Manual | Patient age in years || 2 | bp | Lab | Blood pressure diastolic (mmHg) || 3 | bgr | Lab | Blood glucose random (mg/dL) || 4 | bu | Lab | Blood urea (mg/dL) || 5 | sc | Lab | Serum creatinine (mg/dL) || 6 | sod | Lab | Sodium (mEq/L) || 7 | pot | Lab | Potassium (mEq/L) || 8 | hemo | Lab | Hemoglobin (g/dL) || 9 | pcv | Lab | Packed cell volume (%) || 10 | wbcc | Lab | WBC count (cells/cumm) || 11 | rbcc | Lab | RBC count (millions/cumm) || 12 | sg | Lab | Specific gravity || 13 | al | Lab | Albumin in urine (0-5) || 14 | su | Lab | Sugar in urine (0-5) || 15 | rbc | Lab | RBC in urine || 16 | pc | Lab | Pus cells || 17 | pcc | Lab | Pus cell clumps || 18 | ba | Lab | Bacteria || 19 | htn | Manual | Hypertension || 20 | dm | Manual | Diabetes mellitus || 21 | cad | Manual | Coronary artery disease || 22 | appet | Manual | Appetite || 23 | pe | Manual | Pedal edema || 24 | ane | Manual | Anemia |**Pipeline:**- Retinal Image → EfficientNet-B3 → Feature Vector (1536) → PCA (64 dim)- Clinical Values (24) → StandardScaler → Gradient Boosting + Fusion Model- Cross-Modal Attention Fusion → Final Risk Level*Research prototype — not for clinical use.*""")# ── Event Handlers ─────────────────────────────────────────────────────extract_btn.click(fn=process_lab_file,inputs=[lab_file_input],outputs=[extract_status,sc_input, bu_input, hemo_input, bgr_input, sod_input,pot_input, pcv_input, wbcc_input, rbcc_input, bp_input,sg_input, al_input, su_input, rbc_input, pc_input, pcc_input, ba_input,])predict_btn.click(fn=predict_ckd_risk,inputs=[retinal_input,# Blood testssc_input, bu_input, hemo_input, bgr_input,sod_input, pot_input, pcv_input, wbcc_input, rbcc_input,bp_input,# Urine testssg_input, al_input, su_input, rbc_input, pc_input, pcc_input, ba_input,# Manualage_input, htn_input, dm_input, cad_input, appet_input, pe_input, ane_input,],outputs=[gradcam_output, risk_output, clinical_output, status_output])
app.py+391-139