NabillahBee's picture
RNFL assistant app code (Gradio)
5999247 verified
Raw History Blame Contribute Delete
13.4 kB
"""
RNFL thickness-map assistant - Gradio app (research prototype).
Deterministic core (measure.py / textgen.py / assistant.py) + optional language model behind a verifier (verifier.py).
Run locally: python app.py Hugging Face Space: this file is the entry point.
"""
import os, uuid, tempfile, datetime
import numpy as np, pandas as pd
import gradio as gr
import matplotlib; matplotlib.use("Agg")
import measure as M, textgen as T, render as R, assistant as AS, explorer as EX, demo as D, llm_backend as LB
HERE = os.path.dirname(os.path.abspath(__file__))
ASSETS = AS.load_assets(os.environ.get("RNFL_ASSETS", os.path.join(HERE, "assets")))
LLM = LB.make_backend()
TMP = tempfile.mkdtemp(prefix="rnfl_")
REF = ASSETS["ref"]; CFG = ASSETS["cfg"]
T.GL_AUC, T.PROG_AUC = CFG.get("gl_auc", T.GL_AUC), CFG.get("prog_auc", T.PROG_AUC)
BANNER = ("## RNFL thickness-map assistant \n"
"**Research prototype - not a medical device. It cannot diagnose, and it is not for treatment decisions.** "
"Measurements come from fixed software rules; explanations come from reviewed templates; an optional language model answers only open questions and every draft passes automatic safety checks first. "
"The demo maps are **synthetic**, not patient data.")
ABOUT_MD = f"""
### What this is
An assistant for **OCT retinal-nerve-fibre-layer (RNFL) thickness maps** (6 x 6 mm around the optic disc). It (1) **examines** the map with a standard ring measurement, (2) **explains** the findings in plain language and remembers what you tell it, (3) writes a **structured report**, and (4) lets you **click a region** to see its measurement and the anatomy behind it.
### How it is built (and why)
- **Measurements**: a circumpapillary ring (3.5 mm) centred on the detected optic disc, summarised by quadrant and 12 clock-hour sectors, with invalid (zero) pixels excluded and quality flags. Reference values come from non-glaucoma patients of the Harvard-GDP training split. This is a **research reference, not a validated normative database, and it is not age-adjusted**.
- **Risk bands**: two small logistic-regression models trained on the same dataset (glaucoma-like pattern; later visual-field progression). They are **research estimates, not personal risks**: the dataset comes from a glaucoma clinic, so rates are higher than in the general population.
- **Answers**: the examine summary, explanations, risk wording, report and refusals are generated by **templates** (no language model). A fine-tuned vision-language model (Qwen2.5-VL-3B + LoRA) exists but was found to be **brittle outside its training templates**, so here it is used only for unrecognised questions, and **every model draft is checked** (numbers must come from the measurements; no diagnosis, no cup-to-disc value, no treatment advice, no claims about things a map cannot show). A failed draft is replaced by a safe template, and the chat shows you when that happened.
### Limits you should know about
- One map = one time point. It cannot show change over time.
- The dataset does not state which eye each map is from, so **image-left / image-right are not confirmed as temporal / nasal**.
- A thickness map **cannot give a cup-to-disc ratio, a visual field, or eye pressure**.
- Low-quality scans (artefacts, missing data) are flagged, and affected sectors are reported as "not assessable".
- Image-only classification by the fine-tuned model was weak (glaucoma AUC about 0.65 on held-out test patients vs about 0.80 for the measurement-based model), which is why the risk bands come from the measurements, not from the model's reading of the picture.
### Data and licence
Harvard-GDP (Luo et al., ICCV 2023), licence CC BY-NC-ND 4.0: non-commercial research use, not for clinical decisions. Do not redistribute converted data.
*Evaluation numbers for this project are in the report (held-out test split, manual stress test, verifier evaluation).*
"""
SEX_CHOICES = ["unspecified", "female", "male"]
HELLO = ("Hello! I have analysed the map. Ask me to describe it, explain it simply, or explain any region (e.g. *what about 7 o'clock?*). "
"Tell me things like your age or family history and I'll remember them for the report. I can't diagnose or advise on treatment.")
def _sex(label): return None if label in (None, "unspecified") else label
def _summary_md(A, sess):
f = A["f"]; rk = A["risk"]; bi = CFG["bands_info"]; rng = np.random.default_rng(7)
L = [f"**Map:** {A['name']}", "", T.examine_answer(f, REF, A["reasons"], rng), "",
f"**Software pattern bands** (research dataset, *not a diagnosis*): glaucoma-like pattern **{rk['glaucoma_band']}** (about {bi['glaucoma'][rk['glaucoma_band']]}% of dataset patients in this band had glaucoma); "
f"progression **{rk['prog_band']}** (about {bi['progression'][rk['prog_band']]}% showed later visual-field progression)."]
if A["reasons"]: L += ["", "**Image-quality flags:** " + "; ".join(A["reasons"]) + "."]
if A["warnings"]: L += ["", "**Notes:** " + " ".join(A["warnings"])]
return "\n".join(L)
def _explorer_outputs(A, loc=None):
if loc is None:
img = R.render_clickable(A["m"], A["center"], A["vmax"], disc_r=None)
card = "*Click anywhere on the map (or pick a region below) to see its measurement and what that part of the eye does.*"
fig = EX.profile_figure(A, REF, None)
else:
img = R.render_clickable(A["m"], A["center"], A["vmax"], point=(loc["mx"], loc["my"]), hour=None if loc["zone"] == "disc" else loc["hour"],
disc_r=A["disc_r"] if loc["zone"] == "disc" else None)
card = EX.explain(A, REF, loc); fig = EX.profile_figure(A, REF, None if loc["zone"] == "disc" else loc["theta"])
return img, card, fig
def do_analyse(sample_name, upload_path, age, sex_label):
sess = AS.new_session()
try:
if upload_path:
m = D.load_map_file(upload_path); name = os.path.basename(str(upload_path))
else:
m = D.demo_map(sample_name); name = sample_name
age_i = int(age) if age not in (None, "") and not (isinstance(age, float) and np.isnan(age)) and 18 <= float(age) <= 110 else None
sex = _sex(sex_label)
A = AS.analyse_map(m, ASSETS, name, age_i, sex)
except Exception as e:
return (AS.new_session(), None, f"**Could not analyse this file:** {e}", pd.DataFrame(), None, "", None, [], "", "", "", "")
if age_i: sess["ctx"]["age"] = age_i
if sex: sess["ctx"]["sex"] = sex
A["image_path"] = os.path.join(TMP, f"{uuid.uuid4().hex}.png")
R.render_map(A["m"], A["image_path"], center=A["center"], vmax=A["vmax"])
sess["A"] = A
table = pd.DataFrame(AS.measurement_rows(A, REF), columns=["Region", "Thickness", "Reference median", "Status vs reference group"])
ex_img, ex_card, ex_fig = _explorer_outputs(A)
status = ("*Template mode: the free-form chat model is not loaded, so only questions the router recognises are answered.*" if not LLM.available()
else f"*Free-form chat model: {LLM.name} (every draft is checked before you see it).*")
return (sess, R.render_map_pil(A["m"], A["center"], A["vmax"]), _summary_md(A, sess), table, ex_img, ex_card, ex_fig,
[{"role": "assistant", "content": HELLO}], AS.memory_markdown(sess["ctx"], sess["notes"]), status, "", "")
def do_click(sess, evt: gr.SelectData):
if not sess or not sess.get("A"): return None, "Analyse a map first.", None
x, y = evt.index[0], evt.index[1]
mx, my = R.click_to_map(x, y)
return _explorer_outputs(sess["A"], EX.locate(sess["A"], mx, my))
def do_choice(sess, choice):
if not sess or not sess.get("A") or not choice: return None, "Analyse a map first.", None
return _explorer_outputs(sess["A"], EX.choice_to_loc(sess["A"], choice))
BADGE = {"template": "\n\n*Template answer (no language model) - passed checks*",
"model": "\n\n*Language-model answer - passed the automatic safety checks*",
"fallback": "\n\n*Safe fallback shown instead of a model draft*"}
def do_chat(user_text, history, sess):
history = list(history or [])
if not user_text or not user_text.strip() or not sess or not sess.get("A"): return history, sess, "", gr.skip(), gr.skip()
out = AS.chat_turn(sess, ASSETS, user_text, LLM, sess["A"].get("image_path"))
history += [{"role": "user", "content": user_text}, {"role": "assistant", "content": out["text"] + BADGE[out["source"]]}]
chk = [f"**Route:** `{out['intent']}` \n**Source:** {out['source']} \n**Checks:** " + ("passed" if out["verified"] else "FAILED - " + "; ".join(out["reasons"]))]
if out.get("draft") and out["source"] == "fallback": chk.append("**Rejected model draft (not shown to the user):**\n\n> " + str(out["draft"])[:600].replace("\n", " "))
if out["changes"]: chk.append("**Remembered:** " + "; ".join(out["changes"]))
return history, sess, "", AS.memory_markdown(sess["ctx"], sess["notes"]), "\n\n".join(chk)
def do_report(sess):
if not sess or not sess.get("A"): return "Analyse a map first.", None
txt = AS.report_text_app(sess, ASSETS)
p = os.path.join(TMP, f"rnfl_report_{datetime.date.today().isoformat()}_{uuid.uuid4().hex[:6]}.md")
open(p, "w", encoding="utf-8").write(txt)
return txt, p
def build():
with gr.Blocks(title="RNFL thickness-map assistant") as demo:
sess = gr.State(AS.new_session())
gr.Markdown(BANNER)
with gr.Tabs():
with gr.Tab("1. Analyse"):
with gr.Row():
with gr.Column(scale=1):
sample = gr.Dropdown(list(D.DEMOS), value=list(D.DEMOS)[1], label="Demo map (synthetic)")
upload = gr.File(label="...or upload a thickness map (.npz / .npy, 225x225, micrometres)", file_types=[".npz", ".npy"], type="filepath")
age = gr.Number(label="Age (optional)", value=None, precision=0)
sex = gr.Radio(SEX_CHOICES, value="unspecified", label="Sex (optional)")
go = gr.Button("Analyse", variant="primary")
status = gr.Markdown()
with gr.Column(scale=2):
overlay = gr.Image(label="Map with the measurement ring and clock sectors", type="pil", interactive=False)
summary = gr.Markdown()
table = gr.Dataframe(label="Measurements", interactive=False, wrap=True)
with gr.Tab("2. Explore the anatomy"):
gr.Markdown("**Click a region of the map** to see its measurement and an explanation of the anatomy. (Or choose a region from the list.)")
with gr.Row():
ex_img = gr.Image(label="Click on the map", type="pil", interactive=False)
with gr.Column():
ex_card = gr.Markdown()
choice = gr.Dropdown(EX.REGION_CHOICES, label="...or pick a region", value=None)
ex_plot = gr.Plot(label="Thickness around the ring")
with gr.Tab("3. Chat"):
with gr.Row():
with gr.Column(scale=3):
chat = gr.Chatbot(label="Conversation", height=430)
txt = gr.Textbox(label="Ask about this map", placeholder="e.g. What does this map show? / I'm 64 and my mother has glaucoma. / What about 7 o'clock?")
send = gr.Button("Send", variant="primary")
gr.Examples([["What does this map show?"], ["Explain that in simple terms."], ["What about the inferior part?"], ["Could this get worse over time?"],
["I'm 64 and my mother has glaucoma. Does that matter?"], ["Is this glaucoma?"], ["What is the cup-to-disc ratio?"], ["Please write a report for my GP."]], inputs=txt)
with gr.Column(scale=2):
memory = gr.Markdown()
checks = gr.Markdown(label="Checks on the last answer")
with gr.Tab("4. Report"):
rep_btn = gr.Button("Generate structured report", variant="primary")
report = gr.Textbox(label="Structured summary", lines=30, interactive=False)
rep_file = gr.File(label="Download (.md)", interactive=False)
with gr.Tab("5. About and limits"):
gr.Markdown(ABOUT_MD)
outs = [sess, overlay, summary, table, ex_img, ex_card, ex_plot, chat, memory, status, report, checks]
go.click(do_analyse, [sample, upload, age, sex], outs, api_name="analyse")
demo.load(do_analyse, [sample, upload, age, sex], outs, api_name=False)
ex_img.select(do_click, [sess], [ex_img, ex_card, ex_plot], api_name="click")
choice.change(do_choice, [sess, choice], [ex_img, ex_card, ex_plot], api_name="region")
send.click(do_chat, [txt, chat, sess], [chat, sess, txt, memory, checks], api_name="chat")
txt.submit(do_chat, [txt, chat, sess], [chat, sess, txt, memory, checks], api_name=False)
rep_btn.click(do_report, [sess], [report, rep_file], api_name="report")
return demo
demo = build()
if __name__ == "__main__":
demo.launch(server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"), share=bool(os.environ.get("GRADIO_SHARE")))