"""Gradio app: federated, differentially-private, fairness-aware disease-risk prediction from medical images. Runs on a free CPU Hugging Face Space.""" import numpy as np import gradio as gr from PIL import Image from fl import data as D from fl import experiment as E from fl.fed import Config, proba import os # ZeroGPU Spaces refuse to start unless at least one @spaces.GPU function exists. # This tiny no-op satisfies that; the app itself never uses the GPU (so no quota is spent). try: import spaces @spaces.GPU def _gpu_ping(): return "ok" except ImportError: # local machine / Colab / any non-ZeroGPU host pass TASK_CHOICES = [(v["title"], k) for k, v in D.TASKS.items()] DISCLAIMER = ("Research prototype for a dissertation. Not a medical device; not for diagnosis. " "Models use a frozen ImageNet backbone and small public-dataset samples.") def run(task, n_clients, rounds, local_epochs, noise_mult, clip, alpha, per_class, seed): logs = [] def log(m): logs.append(str(m)) def status(extra=""): return "```\n" + "\n".join(logs[-14:]) + "\n```\n" + extra try: log("Preparing data (first run per disease downloads a small sample and takes a few minutes) ...") yield status(), gr.update(), gr.update(), gr.update(), gr.update() raw = D.load_raw(task, int(per_class), int(seed), log=log) yield status(), gr.update(), gr.update(), gr.update(), gr.update() cfg = Config(n_clients=int(n_clients), rounds=int(rounds), local_epochs=int(local_epochs), noise_mult=float(noise_mult), clip=float(clip), alpha=float(alpha), seed=int(seed)) prepared = D.prepare_split(raw, cfg.n_clients, cfg.alpha, cfg.proj_dim, cfg.seed) log(f"Hospitals: sizes={prepared['meta']['client_sizes']} " f"positive rates={[round(x, 2) for x in prepared['meta']['client_pos_rate']]}") log("Running 3 federated experiments (baseline, +DP, +DP+fairness) ...") yield status(), gr.update(), gr.update(), gr.update(), gr.update() results = E.run_modes(prepared, cfg) table = E.results_table(results) E.STATE[task] = {"w": results[2]["w"], "prep": prepared["prep"], "synthetic": raw["synthetic"]} report = E.report_markdown(D.TASKS[task]["title"], prepared, results, table) warn = "\n\n**Synthetic fallback data in use - results are NOT real.**" if raw["synthetic"] else "" log("Done.") yield (status("**Finished.**" + warn), table, E.fig_curves(results), E.fig_groups(results, prepared["meta"]["group_name"]), report) except Exception as e: # noqa: BLE001 log(f"ERROR: {type(e).__name__}: {e}") yield status(), gr.update(), gr.update(), gr.update(), gr.update() def predict(task, image): st = E.STATE.get(task) if st is None: return None, "Run the experiment for this disease first (tab 1)." if st["synthetic"]: return None, "The model was trained on SYNTHETIC data, so it cannot score real images. Fix the data source first." if image is None: return None, "Upload an image." try: from fl import vision proc = vision.preprocess(task, Image.fromarray(image)) feats = vision.extract_features([proc]) z = D.transform_features(st["prep"], feats) p = float(proba(st["w"], z)[0]) except ImportError: return None, ("Image scoring needs torch + torchvision, which this deployment does not install " "(the experiments in tab 1 do not need them).") except Exception as e: # noqa: BLE001 return None, f"Could not score image: {type(e).__name__}: {e}" label = "elevated" if p >= 0.5 else "low" return proc, f"**Risk score: {p:.2f}** ({label} risk by this demo model)\n\n_{DISCLAIMER}_" with gr.Blocks(title="Federated DP Fair Disease Risk", theme=gr.themes.Soft()) as demo: gr.Markdown("# Privacy-preserving federated learning for early disease-risk prediction (with fairness)\n" "Simulated hospitals train locally with **DP-SGD**, the server aggregates with **FedAvg**, " "and a **fairness controller** equalises recall across patient groups. " + DISCLAIMER) with gr.Tab("1. Run federated experiment"): with gr.Row(): with gr.Column(scale=1): task = gr.Dropdown(TASK_CHOICES, value="heart", label="Disease / image modality") n_clients = gr.Slider(2, 6, value=3, step=1, label="Hospitals (clients)") rounds = gr.Slider(5, 40, value=15, step=1, label="Federated rounds") epochs = gr.Slider(1, 5, value=2, step=1, label="Local epochs per round") noise = gr.Slider(0.5, 3.0, value=1.5, step=0.1, label="DP noise multiplier (higher = more private)") clip = gr.Slider(0.5, 3.0, value=1.0, step=0.1, label="Gradient clip norm") alpha = gr.Slider(0.1, 10.0, value=1.0, step=0.1, label="Non-IID strength (low = very different hospitals)") per_class = gr.Slider(50, 300, value=150, step=10, label="Images per class (first run only)") seed = gr.Number(value=0, precision=0, label="Seed") go = gr.Button("Run experiment", variant="primary") with gr.Column(scale=2): status_md = gr.Markdown() table = gr.Dataframe(label="Results (final round, held-out global test set)") curves = gr.Plot(label="Training curves") groups = gr.Plot(label="Per-group recall") report = gr.Markdown(label="Copy-paste report") go.click(run, [task, n_clients, rounds, epochs, noise, clip, alpha, per_class, seed], [status_md, table, curves, groups, report]) with gr.Tab("2. Try an image"): gr.Markdown("Score one image with the trained **DP + Fairness** global model " "(chest X-ray for heart, retinal fundus photo for diabetes).") t2 = gr.Dropdown(TASK_CHOICES, value="heart", label="Disease / image modality") img = gr.Image(type="numpy", label="Input image") btn = gr.Button("Predict") out_img = gr.Image(label="After OpenCV preprocessing (CLAHE / local contrast)") out_txt = gr.Markdown() btn.click(predict, [t2, img], [out_img, out_txt]) if __name__ == "__main__": # GRADIO_SHARE=1 creates a temporary public link (useful in Google Colab) demo.queue().launch(share=os.environ.get("GRADIO_SHARE") == "1")