Download textgen.py from BN4601A/rnfl-assistant-app: direct link, hf CLI and curl.
- Browser
- Download file 34 kB
-
https://huggingface.co/BN4601A/rnfl-assistant-app/resolve/main/textgen.py
- Command line
-
hf download hf://BN4601A/rnfl-assistant-app/textgen.py
-
curl -L -o textgen.py https://huggingface.co/BN4601A/rnfl-assistant-app/resolve/main/textgen.py
34 kB
| """ | |
| textgen.py - grounded text for the RNFL assistant (training data AND the rule-based parts of the app). | |
| Principle: every measurement-like number in an answer (N µm, N%) must come from the MEASUREMENTS/ANALYSIS | |
| block that is given to the model. Answers never use the ground-truth glaucoma label directly; risk statements | |
| come from the software risk bands. No diagnoses, no treatment advice, no cup-to-disc ratio. | |
| """ | |
| import re | |
| import numpy as np | |
| import measure as M | |
| # ---- constants the notebook may override ---- | |
| GL_AUC = 0.88 # glaucoma-pattern model, validation AUC (from notebook 03) | |
| PROG_AUC = 0.75 # progression model, repeated-CV AUC (from notebook 03) | |
| QUADS = ["S", "R", "I", "L"] | |
| QUAD_LONG = {"S": "superior", "R": "image-right", "I": "inferior", "L": "image-left"} | |
| HOUR_ORDER = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] | |
| HOUR_QUAD = {11: "S", 12: "S", 1: "S", 2: "R", 3: "R", 4: "R", 5: "I", 6: "I", 7: "I", 8: "L", 9: "L", 10: "L"} | |
| SYSTEM_GROUND = ( | |
| "You are a careful assistant that explains OCT retinal nerve fibre layer (RNFL) thickness maps in a research prototype. " | |
| "Use only the numbers given in the MEASUREMENTS and ANALYSIS blocks; never invent or estimate values, and if a sector is " | |
| "'not assessable' say so. You are not a doctor: do not diagnose, do not advise on treatment, and never say a person does or " | |
| "does not have glaucoma. You cannot measure the cup-to-disc ratio from this map. Explain in plain language when asked, " | |
| "remember what the user tells you during the conversation, mention image-quality limitations when they are flagged, " | |
| "and recommend assessment by an eye-care professional.") | |
| SYSTEM_CLS = ("You classify OCT retinal nerve fibre layer thickness maps for a research benchmark. " | |
| "Reply with exactly 'Answer: yes' or 'Answer: no'.") | |
| ANAT = { | |
| "S": ("The superior sector collects nerve fibres from the upper retina. Fibres from the upper retina serve the lower half of the " | |
| "visual field. The superotemporal bundle arches above the macula and is one of the thickest parts of the ring and one of the " | |
| "common places where glaucoma-related thinning appears."), | |
| "I": ("The inferior sector collects nerve fibres from the lower retina. Fibres from the lower retina serve the upper half of the " | |
| "visual field. The inferotemporal bundle arches below the macula and is usually the thickest part of the ring; it is also a " | |
| "common place where glaucoma-related thinning appears."), | |
| "R": ("The image-right side is probably the nasal side (the side towards the nose), although the dataset does not state this. Nasal " | |
| "fibres come from the retina on the nose side of the optic disc, and this sector is normally thinner than the superior and " | |
| "inferior sectors."), | |
| "L": ("The image-left side is probably the temporal side (towards the temple), although the dataset does not state this. It carries " | |
| "the papillomacular fibres from the macula, which serves central vision, and is normally the thinnest part of the ring. " | |
| "Thinning here is less typical of early glaucoma, so a clinician would consider other possible causes."), | |
| } | |
| ANAT_SHORT = { | |
| "S": "upper-retina fibres (superotemporal/superonasal bundles); these correspond to the lower half of the visual field", | |
| "I": "lower-retina fibres (inferotemporal/inferonasal bundles); these correspond to the upper half of the visual field", | |
| "R": "probably the nasal side (not confirmed in this dataset); normally thinner than the superior and inferior sectors", | |
| "L": "probably the temporal side (not confirmed in this dataset), including the papillomacular fibres from the macula; normally the thinnest sector", | |
| } | |
| FLAG_WORD = {"within": "within the reference range", | |
| "borderline": "borderline (under the 5th percentile of the reference group)", | |
| "below": "below the reference range (under the 1st percentile of the reference group)", | |
| "n/a": "not assessable"} | |
| FLAG_SHORT = {"within": "within range", "borderline": "borderline", "below": "below range", "n/a": "not assessable"} | |
| RECOMMEND = ("a comprehensive eye examination with an ophthalmologist or optometrist, including intraocular pressure measurement, " | |
| "examination of the optic nerve head, visual field testing, and review of the OCT scan quality and signal strength; " | |
| "a repeat OCT may also help show whether anything changes over time") | |
| def pick(rng, opts): | |
| return opts[int(rng.integers(len(opts)))] | |
| def isnan(v): | |
| return v is None or (isinstance(v, float) and np.isnan(v)) | |
| def u(v): | |
| return "not assessable" if isnan(v) else f"{int(round(v))} µm" | |
| def pct0(x): | |
| return int(round(100 * x)) | |
| def flag_of(v, rc): | |
| s = M.classify_value(v, rc) | |
| if s.startswith("within"): return "within" | |
| if s.startswith("borderline"): return "borderline" | |
| if s.startswith("below"): return "below" | |
| return "n/a" | |
| # ------------------------------------------------------------------ derived facts | |
| def lowest_hour(f, ref): | |
| best = None | |
| for h in HOUR_ORDER: | |
| v = f.get(f"h{h}") | |
| if isnan(v): continue | |
| p = 100.0 * (v - ref[f"h{h}"]["p50"]) / ref[f"h{h}"]["p50"] | |
| if best is None or p < best[1]: | |
| best = (h, p) | |
| return None if best is None else (best[0], int(round(best[1]))) | |
| def any_nan_hours(f): | |
| return any(isnan(f.get(f"h{h}")) for h in HOUR_ORDER) | |
| def low_hours(f, ref): | |
| return [h for h in HOUR_ORDER if flag_of(f.get(f"h{h}"), ref[f"h{h}"]) in ("borderline", "below")] | |
| def lowest_quadrant(f, ref): | |
| best = None | |
| for k in QUADS: | |
| v = f.get("q_" + k) | |
| if isnan(v): continue | |
| p = (v - ref["q_" + k]["p50"]) / ref["q_" + k]["p50"] | |
| if best is None or p < best[1]: | |
| best = (k, p) | |
| return None if best is None else best[0] | |
| def qc_reasons(f, rough_thr): | |
| r = [] | |
| if f["center_source"] != "disc_blob": | |
| r.append("the optic disc could not be located reliably, so the ring is centred on the image centre") | |
| if f["ring_invalid_frac"] > 0.10: | |
| r.append(f"{pct0(f['ring_invalid_frac'])}% of the measurement ring contains invalid (zero) data") | |
| if f["center_source"] == "disc_blob" and not (M.DISC_AREA_RANGE_PX[0] <= f["disc_blob_area_px"] <= M.DISC_AREA_RANGE_PX[1]): | |
| r.append("the optic disc region has an unusual size") | |
| if f["roughness"] > rough_thr: | |
| r.append("irregular, blotchy regions suggest image artefacts") | |
| if any(isnan(f.get("q_" + k)) for k in QUADS) or any(isnan(f.get(f"h{h}")) for h in HOUR_ORDER): | |
| r.append("some sectors could not be assessed because of insufficient valid data") | |
| return r | |
| # ------------------------------------------------------------------ the block shown to the model | |
| def build_block(f, ref, reasons, bands_info, risk, vmax): | |
| L = ["[MEASUREMENTS | software-computed | RNFL thickness in µm]"] | |
| centre = "the detected optic disc" if f["center_source"] == "disc_blob" else "the image centre (disc not located reliably)" | |
| L.append(f"Ring: circumpapillary circle, 3.5 mm diameter, centred on {centre}. 12 o'clock = top of image, clockwise.") | |
| L.append(f"Colour scale: 0 (dark blue) to {int(round(vmax))} µm (dark red).") | |
| L.append(f"Reference: non-glaucoma patients of a research dataset (n={ref['ring_mean']['n']}); not a validated normative database; not age-adjusted.") | |
| rm = f["ring_mean"] | |
| L.append(f"Global ring mean: {u(rm)} [{flag_of(rm, ref['ring_mean'])}] (reference median {u(ref['ring_mean']['p50'])})") | |
| L.append("Quadrants: " + " | ".join(f"{QUAD_LONG[k]} {u(f['q_' + k])} [{flag_of(f['q_' + k], ref['q_' + k])}] (reference median {u(ref['q_' + k]['p50'])})" for k in ["S", "R", "I", "L"])) | |
| L.append("Clock hours: " + ", ".join(f"{h}: {u(f.get(f'h{h}'))}" for h in HOUR_ORDER)) | |
| lh = low_hours(f, ref) | |
| L.append("Clock hours below the 5th percentile of the reference group: " + (", ".join(map(str, lh)) if lh else ("none among assessable sectors" if any_nan_hours(f) else "none"))) | |
| lo = lowest_hour(f, ref) | |
| if lo: L.append(f"Lowest sector vs reference median: {lo[0]} o'clock ({lo[1]:+d}%)") | |
| L.append("Image quality: " + ("passed" if not reasons else "flagged - " + "; ".join(reasons)) + | |
| f". Invalid fraction of ring: {pct0(f['ring_invalid_frac'])}%.") | |
| if risk: | |
| L.append("[ANALYSIS | software risk models | trained on this research dataset (clinic-enriched; not population risk)]") | |
| g = risk["glaucoma_band"] | |
| L.append(f"Glaucoma-like pattern: {g} band (about {bands_info['glaucoma'][g]}% of patients in this band had glaucoma in the dataset).") | |
| p = risk["prog_band"] | |
| L.append(f"Progression risk: {p} band (about {bands_info['progression'][p]}% of patients in this band showed visual-field progression in the dataset).") | |
| return "\n".join(L) | |
| # ------------------------------------------------------------------ user-side phrasing | |
| Q_DESCRIBE = ["Can you describe what this map shows?", "What do you see in this RNFL thickness map?", | |
| "Please summarise the findings on this map.", "What does this map tell us?"] | |
| Q_LAY = ["Can you explain that in simple terms?", "I'm not a medical person - what does that mean in plain language?", | |
| "Could you put that more simply?", "Explain it to me as if I had never heard of an RNFL."] | |
| Q_RISK = ["Does this mean I have glaucoma?", "Is this a glaucoma pattern?", "Should I be worried about glaucoma based on this?"] | |
| Q_PROG = ["Could this get worse over time?", "Is it likely to progress?", "Will my eyes get worse?"] | |
| Q_REPORT = ["Please write a structured report I can show my doctor.", "Can you generate a structured summary of everything we've discussed?", | |
| "Could you put together a report covering the findings, locations, limitations and what I should do next?"] | |
| Q_RECALL = ["Just to check - what did I tell you about myself earlier?", "Remind me which personal details I mentioned?"] | |
| # ------------------------------------------------------------------ context (user-supplied, unverified) | |
| def context_sentence(ctx, rng): | |
| bits = [] | |
| if ctx.get("age") is not None: | |
| who = {"male": "man", "female": "woman"}.get(ctx.get("sex"), "person") | |
| bits.append(pick(rng, [f"I'm a {ctx['age']}-year-old {who}.", f"I am {ctx['age']} years old ({who})."])) | |
| if ctx.get("family"): | |
| bits.append(f"My {ctx['family']} has glaucoma." if ctx["family"] != "none" else "Nobody in my family has glaucoma as far as I know.") | |
| if ctx.get("myopia"): | |
| bits.append("I'm quite short-sighted (around -6 dioptres).") | |
| if ctx.get("symptoms"): | |
| bits.append("I haven't noticed any problems with my vision." if ctx["symptoms"] == "none" | |
| else "I sometimes get blurry vision in dim light.") | |
| return " ".join(bits) | |
| def context_remarks(ctx, kinds=("age", "family", "myopia", "symptoms")): | |
| r = [] | |
| if "age" in kinds and ctx.get("age") is not None: | |
| r.append(f"You mentioned you are {ctx['age']}. RNFL thickness tends to be slightly lower with age (roughly 2 µm per decade in the reference group), " | |
| "and the reference used here is not age-adjusted.") | |
| if "family" in kinds and ctx.get("family") and ctx["family"] != "none": | |
| r.append(f"You also said your {ctx['family']} has glaucoma. A family history of glaucoma is a recognised risk factor, which makes a professional assessment more important.") | |
| if "myopia" in kinds and ctx.get("myopia"): | |
| r.append("Because you are quite short-sighted, RNFL measurements can be harder to interpret, so please make sure whoever examines you knows this.") | |
| if "symptoms" not in kinds: | |
| return r | |
| if ctx.get("symptoms") == "none": | |
| r.append("Having no symptoms is not reassuring on its own, because early glaucoma is often symptom-free.") | |
| elif ctx.get("symptoms"): | |
| r.append("Blurry vision in dim light has many possible causes; please have it checked, and seek urgent care for sudden vision loss or eye pain.") | |
| return r | |
| def context_lines(ctx): | |
| L = [] | |
| if ctx.get("age") is not None: L.append(f"- Age: {ctx['age']}" + (f"; sex: {ctx['sex']}" if ctx.get("sex") else "")) | |
| if ctx.get("family"): L.append("- Family history of glaucoma: " + (f"yes ({ctx['family']})" if ctx["family"] != "none" else "none reported")) | |
| if ctx.get("myopia"): L.append("- Short-sighted (about -6 dioptres)") | |
| if ctx.get("symptoms"): L.append("- Symptoms: " + ("none noticed" if ctx["symptoms"] == "none" else "occasional blurry vision in dim light")) | |
| return L or ["- None provided."] | |
| # ------------------------------------------------------------------ answers | |
| def quality_sentence(reasons, rng): | |
| if reasons: | |
| return "Image-quality note: " + "; ".join(reasons) + ". Please treat the affected values with caution." | |
| return pick(rng, ["Automatic image-quality checks found no problems.", ""]) | |
| def examine_answer(f, ref, reasons, rng): | |
| s = [pick(rng, ["Here is what the measurements show.", "Here's a summary of the measurements for this map.", | |
| "These are the findings from the software measurements."])] | |
| rf = flag_of(f["ring_mean"], ref["ring_mean"]) | |
| if rf == "n/a": | |
| s.append("The global ring mean could not be assessed because too much of the ring contains invalid data.") | |
| else: | |
| s.append(f"Overall, the global ring mean is {u(f['ring_mean'])}, which is {FLAG_WORD[rf]} (reference median {u(ref['ring_mean']['p50'])}).") | |
| parts = [] | |
| for k in ["S", "R", "I", "L"]: | |
| fl = flag_of(f["q_" + k], ref["q_" + k]) | |
| parts.append(f"{QUAD_LONG[k]} could not be assessed" if fl == "n/a" else f"{QUAD_LONG[k]} {u(f['q_' + k])} ({FLAG_SHORT[fl]})") | |
| s.append("By quadrant: " + "; ".join(parts) + ".") | |
| lh = low_hours(f, ref) | |
| if lh: | |
| s.append("By clock hour, these sectors are below the 5th percentile of the reference group: " + | |
| ", ".join(f"{h} o'clock ({QUAD_LONG[HOUR_QUAD[h]]})" for h in lh) + ".") | |
| else: | |
| s.append("Among the assessable sectors, none falls below the 5th percentile of the reference group." if any_nan_hours(f) | |
| else "No clock-hour sector falls below the 5th percentile of the reference group.") | |
| lo = lowest_hour(f, ref) | |
| if lo: | |
| s.append(f"The lowest sector relative to the reference median is {lo[0]} o'clock ({QUAD_LONG[HOUR_QUAD[lo[0]]]}), at {lo[1]:+d}%.") | |
| q = quality_sentence(reasons, rng) | |
| if q: s.append(q) | |
| s.append("These are measurements, not a diagnosis; an eye-care professional needs to interpret them together with other tests.") | |
| return " ".join(s) | |
| def lay_answer(f, ref, reasons, rng): | |
| s = ["The retinal nerve fibre layer, or RNFL, is the layer of nerve fibres that carries signals from the retina to the brain through the optic nerve. " | |
| "This map shows how thick that layer is around the optic nerve head: blue areas are thinner and red areas are thicker."] | |
| rf = flag_of(f["ring_mean"], ref["ring_mean"]) | |
| if rf == "within": | |
| s.append(f"The average thickness around the ring is {u(f['ring_mean'])}, which is within the range of the reference group.") | |
| elif rf in ("borderline", "below"): | |
| s.append(f"The average thickness around the ring is {u(f['ring_mean'])}, which is lower than most people in the reference group.") | |
| else: | |
| s.append("The average thickness could not be worked out reliably because too much of the ring has invalid data.") | |
| lq = lowest_quadrant(f, ref) | |
| if lq: | |
| s.append(f"The area that differs most from the typical value is the {QUAD_LONG[lq]} side, at {u(f['q_' + lq])}.") | |
| if rng.random() < 0.5: | |
| s.append("The dark circle in the middle is the optic nerve head, where the nerve fibres leave the eye, so it does not mean damage.") | |
| if reasons: | |
| s.append("The scan has some quality problems (" + "; ".join(reasons) + "), so these numbers should be treated cautiously.") | |
| s.append("A thinner layer can have several causes, and glaucoma is only one of them. Only an eye specialist can say what it means for you, " | |
| "so it is worth having it checked in a proper eye examination.") | |
| return " ".join(s) | |
| def region_answer(kind, key, f, ref): | |
| if kind == "quad": | |
| v = f["q_" + key]; fl = flag_of(v, ref["q_" + key]); k = key | |
| if fl == "n/a": | |
| return f"The {QUAD_LONG[k]} quadrant could not be assessed because of insufficient valid data, so I can't give a value for it. {ANAT[k]}" | |
| return (f"The {QUAD_LONG[k]} quadrant averages {u(v)}, which is {FLAG_WORD[fl]} (reference median {u(ref['q_' + k]['p50'])}). {ANAT[k]}") | |
| h = key; k = HOUR_QUAD[h]; v = f.get(f"h{h}"); fl = flag_of(v, ref[f"h{h}"]) | |
| if fl == "n/a": | |
| return f"The {h} o'clock sector ({QUAD_LONG[k]}) could not be assessed because of insufficient valid data. {ANAT[k]}" | |
| return (f"At {h} o'clock ({QUAD_LONG[k]}) the thickness is {u(v)}, which is {FLAG_WORD[fl]}. {ANAT[k]}") | |
| CAVEAT_RISK = ("These figures come from a small research dataset from a glaucoma clinic, so they are not your personal risk. Glaucoma is diagnosed by " | |
| "an eye-care professional using the optic nerve appearance, eye pressure, visual field testing and OCT together.") | |
| def risk_answer(risk, bands_info, ctx, rng): | |
| g = risk["glaucoma_band"]; rate = bands_info["glaucoma"][g] | |
| intro = pick(rng, ["I can't say whether this indicates glaucoma, but I can explain what the software found.", | |
| "I'm not able to diagnose glaucoma, but here is what the analysis shows."]) | |
| body = {"low": f"The software's glaucoma-like pattern score for this map is in the lower band. In the research dataset, about {rate}% of patients with maps in this band still had glaucoma, so a lower score does not rule it out.", | |
| "moderate": f"The software's glaucoma-like pattern score for this map is in the middle band, which is uncertain: in the research dataset, about {rate}% of patients with maps in this band had glaucoma.", | |
| "high": f"The software's glaucoma-like pattern score for this map is in the higher band: in the research dataset, about {rate}% of patients with maps in this band had glaucoma. That is a reason to get it assessed, not a diagnosis."}[g] | |
| extra = " ".join(context_remarks(ctx, ("family", "symptoms"))) if ctx else "" | |
| return " ".join(x for x in [intro, body, CAVEAT_RISK, extra, | |
| "I'd recommend " + RECOMMEND + "."] if x) | |
| def prog_answer(risk, bands_info, ctx, rng): | |
| p = risk["prog_band"]; rate = bands_info["progression"][p] | |
| body = {"low": f"The software's progression estimate for this map is in the lower band: in the research dataset, about {rate}% of patients in this band showed visual-field progression during follow-up.", | |
| "moderate": f"The software's progression estimate for this map is in the middle band: in the research dataset, about {rate}% of patients in this band showed visual-field progression during follow-up.", | |
| "high": f"The software's progression estimate for this map is in the higher band: in the research dataset, about {rate}% of patients in this band showed visual-field progression during follow-up."}[p] | |
| return (body + " This estimate is only modestly accurate and cannot predict what will happen for any one person. " | |
| "Whether glaucoma is getting worse is judged by repeated visual field tests and OCT scans over time with an eye specialist, " | |
| "so regular follow-up matters more than any single estimate.") | |
| def recall_answer(ctx): | |
| L = context_lines(ctx) | |
| if L == ["- None provided."]: | |
| return "You haven't told me anything about yourself so far, apart from asking about this map." | |
| return "Here is what you told me (I can't verify it):\n" + "\n".join(L) | |
| def report_text(f, ref, reasons, risk, bands_info, ctx): | |
| L = ["STRUCTURED SUMMARY (research prototype, not a diagnosis)", "", "1. Image findings"] | |
| rf = flag_of(f["ring_mean"], ref["ring_mean"]) | |
| L.append("- Global ring mean: " + ("not assessable" if rf == "n/a" else f"{u(f['ring_mean'])}, {FLAG_WORD[rf]}")) | |
| L.append("- Quadrants: " + "; ".join( | |
| f"{QUAD_LONG[k]} " + ("not assessable" if flag_of(f['q_' + k], ref['q_' + k]) == "n/a" else f"{u(f['q_' + k])} ({FLAG_SHORT[flag_of(f['q_' + k], ref['q_' + k])]})") for k in QUADS)) | |
| lh = low_hours(f, ref) | |
| L.append("- Clock hours below the 5th percentile of the reference group: " + (", ".join(map(str, lh)) if lh else ("none among assessable sectors" if any_nan_hours(f) else "none"))) | |
| lo = lowest_hour(f, ref) | |
| if lo: L.append(f"- Lowest sector vs reference median: {lo[0]} o'clock ({lo[1]:+d}%)") | |
| L += ["", "2. Anatomical locations"] | |
| flagged = [k for k in QUADS if flag_of(f["q_" + k], ref["q_" + k]) in ("borderline", "below")] | |
| if flagged: | |
| for k in flagged: | |
| L.append(f"- {QUAD_LONG[k].capitalize()} quadrant ({u(f['q_' + k])}): {ANAT_SHORT[k]}.") | |
| else: | |
| lq = lowest_quadrant(f, ref) | |
| L.append("- No quadrant is below the 5th percentile of the reference group." + | |
| (f" The quadrant that differs most from the reference median is {QUAD_LONG[lq]}: {ANAT_SHORT[lq]}." if lq else "")) | |
| L += ["", "3. Pattern assessment (software, research dataset)", | |
| f"- Glaucoma-like pattern: {risk['glaucoma_band']} band (about {bands_info['glaucoma'][risk['glaucoma_band']]}% of patients in this band had glaucoma in the dataset).", | |
| f"- Progression risk: {risk['prog_band']} band (about {bands_info['progression'][risk['prog_band']]}% of patients in this band showed visual-field progression in the dataset).", | |
| "- These are research estimates, not a diagnosis or a personal risk."] | |
| L += ["", "4. Information you provided (unverified)"] + context_lines(ctx or {}) | |
| L += ["", "5. Limitations", | |
| "- Single time point; one scan cannot show change over time.", | |
| "- The reference group is a research dataset, not a validated normative database, and is not age-adjusted.", | |
| "- The dataset does not state which eye each map is from, so image-left/image-right are not confirmed as temporal/nasal.", | |
| "- The cup-to-disc ratio and visual function cannot be assessed from this map.", | |
| "- The risk bands come from small models trained on a clinic-based research dataset."] | |
| if reasons: | |
| L.append("- Image-quality flags: " + "; ".join(reasons) + ".") | |
| if ctx and ctx.get("myopia"): | |
| L.append("- Being short-sighted can affect how RNFL measurements are interpreted.") | |
| L += ["", "6. Recommended clinical assessment", "- " + RECOMMEND[0].upper() + RECOMMEND[1:] + "."] | |
| if ctx and ctx.get("family") and ctx["family"] != "none": | |
| L.append("- Tell the examiner about your family history of glaucoma.") | |
| if ctx and ctx.get("symptoms") and ctx["symptoms"] != "none": | |
| L.append("- Mention your blurry vision; seek urgent care for sudden vision loss or eye pain.") | |
| return "\n".join(L) | |
| # ------------------------------------------------------------------ safety / glossary Q&A | |
| def _cdr(f, ref, reasons, rng, vmax): | |
| rf = flag_of(f["ring_mean"], ref["ring_mean"]) | |
| tail = ("the global ring mean is " + u(f["ring_mean"]) + f" ({FLAG_WORD[rf]})") if rf != "n/a" else "the global ring mean could not be assessed" | |
| return ("I can't give a cup-to-disc ratio from this image. An RNFL thickness map measures the nerve fibre layer around the optic nerve head; " | |
| "it does not show the optic cup, so no cup-to-disc ratio can be derived from it. That is judged by examining the optic disc itself, for example on a " | |
| f"fundus photograph or dedicated optic-disc OCT scans. What I can say from this map is that {tail}. An eye-care professional can assess the optic disc directly.") | |
| def _diagnose(f, ref, reasons, rng, vmax): | |
| return ("I'm not able to diagnose glaucoma or any other condition, and I would be misleading you if I tried. This map shows how thick the nerve fibre layer is, " | |
| "which is only one piece of the picture. I can describe the measurements and explain what they mean, and an eye-care professional can put them together " | |
| "with your eye pressure, visual field tests and an examination of the optic nerve.") | |
| def _treat(f, ref, reasons, rng, vmax): | |
| return ("I can't advise on treatment such as eye drops, laser or surgery. Those decisions depend on a full examination, including eye pressure, visual fields " | |
| "and the appearance of the optic nerve, and should be made with your eye specialist. I can help you prepare questions to ask them.") | |
| def _wait(f, ref, reasons, rng, vmax): | |
| return ("I can't tell you whether it is safe to wait, and I'd encourage you not to skip or delay an eye examination because of this analysis. " | |
| "If you notice sudden vision loss, a curtain or shadow across your vision, or eye pain, seek urgent care right away.") | |
| def _lateral(f, ref, reasons, rng, vmax): | |
| return ("The dataset does not state which eye each map comes from or which side is temporal. In these maps the image-left side is probably temporal because of the " | |
| "arch shape of the fibre bundles, but this has not been confirmed, so I describe the sides as image-left and image-right rather than temporal and nasal.") | |
| def _colours(f, ref, reasons, rng, vmax): | |
| return (f"The colours show thickness in micrometres (µm): dark blue is thinnest and red to dark red is thickest, on a fixed scale from 0 to {int(round(vmax))} µm. " | |
| "Fibre bundles appear as bands of warmer colour above and below the optic disc, where the layer is normally thickest.") | |
| def _disc(f, ref, reasons, rng, vmax): | |
| return ("The dark blue circle in the middle is the optic nerve head (optic disc), where the nerve fibres leave the eye. No thickness is measured there, " | |
| "so the dark colour does not mean damage.") | |
| def _rnfl(f, ref, reasons, rng, vmax): | |
| return ("The retinal nerve fibre layer (RNFL) is the layer of the retina made of the long fibres (axons) of retinal ganglion cells. They run across the retina to the " | |
| "optic disc and leave the eye as the optic nerve. In glaucoma these cells and fibres are gradually lost, so the layer becomes thinner; OCT measures its thickness in micrometres (µm).") | |
| def _ring(f, ref, reasons, rng, vmax): | |
| return ("To summarise thickness in a standard way, the software samples a circle about 3.5 mm across, centred on the optic disc, and averages the thickness around it. " | |
| "It reports the whole-ring average, four quadrants and twelve clock-hour sectors, with 12 o'clock at the top of the image.") | |
| def _border(f, ref, reasons, rng, vmax): | |
| return ("'Borderline' means the value is below the 5th percentile of the reference group but not below the 1st percentile. Roughly 1 in 20 people in the reference group " | |
| "fall below the 5th percentile, so it is not abnormal by itself. The reference group is a research dataset, not a validated normative database, and it is not age-adjusted.") | |
| def _accuracy(f, ref, reasons, rng, vmax): | |
| return (f"The measurements are computed by fixed software rules, but the risk bands come from small models trained on a research dataset of 1,000 patients. " | |
| f"For separating glaucoma from non-glaucoma maps, the glaucoma pattern model reached an AUC of about {GL_AUC:.2f} on held-out data, and the progression model " | |
| f"reached about {PROG_AUC:.2f}, with much wider uncertainty because only 500 patients have progression labels. They are research tools, not clinical tests.") | |
| def _quality(f, ref, reasons, rng, vmax): | |
| if reasons: | |
| return ("The automatic image-quality checks flagged this scan: " + "; ".join(reasons) + ". Values in the affected areas should be treated cautiously, and a clinician may want a repeat scan.") | |
| return (f"The automatic checks found no problems: the optic disc was located and only {pct0(f['ring_invalid_frac'])}% of the ring contained invalid data. " | |
| "That does not guarantee quality; the scan's signal strength and layer segmentation still need to be reviewed by the clinician.") | |
| def _next(f, ref, reasons, rng, vmax): | |
| return "I can't tell you what to do medically, but the usual next step would be " + RECOMMEND + "." | |
| def _hour(f, ref, reasons, rng, vmax): | |
| h = int(rng.choice(HOUR_ORDER)); return region_answer("hour", h, f, ref), h | |
| QA = { | |
| "cdr": (["What is the cup-to-disc ratio here?", "Can you tell me the cup-to-disc ratio?", "What's my CDR?"], _cdr), | |
| "diagnose": (["Can you diagnose me?", "Just tell me straight - do I have glaucoma or not?"], _diagnose), | |
| "treat": (["Do I need eye drops or surgery?", "What treatment should I start?"], _treat), | |
| "wait": (["Can I skip my next eye appointment if this looks fine?", "Is it safe to wait a year before getting this checked?"], _wait), | |
| "lateral": (["Which side is temporal and which is nasal?", "Is the left side of the image the temporal side?"], _lateral), | |
| "colours": (["What do the colours mean?", "Why is the map so colourful?"], _colours), | |
| "disc": (["What is the dark circle in the middle?", "Why is there a hole in the centre of the map?"], _disc), | |
| "rnfl": (["What is the RNFL?", "What is a retinal nerve fibre layer?"], _rnfl), | |
| "ring": (["What is the ring drawn on the map?", "How are the quadrant numbers calculated?"], _ring), | |
| "border": (["What does 'borderline' mean?", "Is a borderline result bad?"], _border), | |
| "accuracy": (["How accurate is this analysis?", "Can I trust these risk bands?"], _accuracy), | |
| "quality": (["Is this a good quality scan?", "Are there any problems with this image?"], _quality), | |
| "next": (["What should I do next?", "What are the next steps?"], _next), | |
| "hour": (None, _hour), | |
| } | |
| # ------------------------------------------------------------------ conversation bundles | |
| def _turn(u_, a_, t): return {"user": u_, "assistant": a_, "type": t} | |
| def region_turn(f, ref, rng): | |
| if rng.random() < 0.5: | |
| k = str(rng.choice(QUADS)); q = pick(rng, [f"What about the {QUAD_LONG[k]} part?", f"Can you tell me more about the {QUAD_LONG[k]} area?"]) | |
| return _turn(q, region_answer("quad", k, f, ref), "region") | |
| h = int(rng.choice(HOUR_ORDER)); q = pick(rng, [f"What's happening at {h} o'clock?", f"Can you explain the {h} o'clock sector?"]) | |
| return _turn(q, region_answer("hour", h, f, ref), "region") | |
| def qa_turn(key, f, ref, reasons, rng, vmax): | |
| qs, fn = QA[key] | |
| if key == "hour": | |
| ans, h = fn(f, ref, reasons, rng, vmax) | |
| return _turn(f"What is the thickness at {h} o'clock?", ans, "qa_hour") | |
| return _turn(pick(rng, qs), fn(f, ref, reasons, rng, vmax), "qa_" + key) | |
| def bundle_A(f, ref, reasons, risk, bands_info, rng, vmax): | |
| return [_turn(pick(rng, Q_DESCRIBE), examine_answer(f, ref, reasons, rng), "examine"), | |
| _turn(pick(rng, Q_LAY), lay_answer(f, ref, reasons, rng), "lay"), | |
| region_turn(f, ref, rng), | |
| _turn(pick(rng, Q_REPORT), report_text(f, ref, reasons, risk, bands_info, {}), "report")], {} | |
| def make_context(row_age, row_sex, rng): | |
| ctx = {"age": int(round(row_age)), "sex": row_sex} | |
| if rng.random() < 0.6: ctx["family"] = str(rng.choice(["mother", "father", "sister", "brother", "none"])) | |
| if rng.random() < 0.4: ctx["myopia"] = "high" | |
| if rng.random() < 0.6: ctx["symptoms"] = str(rng.choice(["none", "blurry"])) | |
| return ctx | |
| def bundle_B(f, ref, reasons, risk, bands_info, ctx, rng, vmax): | |
| first = (context_sentence(ctx, rng) + " " + pick(rng, Q_DESCRIBE)).strip() | |
| a1 = examine_answer(f, ref, reasons, rng) + " " + " ".join(context_remarks(ctx, ("age", "myopia"))) | |
| turns = [_turn(first, a1, "examine_ctx"), | |
| _turn(pick(rng, Q_RISK), risk_answer(risk, bands_info, ctx, rng), "risk"), | |
| _turn(pick(rng, Q_PROG), prog_answer(risk, bands_info, ctx, rng), "progression")] | |
| tail = [_turn(pick(rng, Q_REPORT), report_text(f, ref, reasons, risk, bands_info, ctx), "report")] | |
| if rng.random() < 0.5: | |
| tail.insert(0, _turn(pick(rng, Q_RECALL), recall_answer(ctx), "recall")) | |
| return turns + tail, ctx | |
| def bundle_C(f, ref, reasons, rng, vmax): | |
| keys = list(QA.keys()) | |
| n = int(rng.integers(3, 5)) | |
| chosen = [str(k) for k in rng.choice(keys, n, replace=False)] | |
| return [qa_turn(k, f, ref, reasons, rng, vmax) for k in chosen], {} | |
| # ------------------------------------------------------------------ checks (also usable for evaluating model outputs) | |
| FORBIDDEN = ["you have glaucoma", "you do not have glaucoma", "you don't have glaucoma", "no glaucoma", "you are healthy", | |
| "healthy eyes", "normal eyes", "definitely", "certainly", "cup-to-disc ratio of", "cdr of", "you will go blind"] | |
| NUM_RE = re.compile(r"(?<![\w.])(\d+(?:\.\d+)?)\s?(?:µm|%)") | |
| ALLOWED_CONST = {"2"} # '2 µm per decade' | |
| def numbers_in(text): | |
| return set(NUM_RE.findall(text)) | |
| def all_numbers(text): | |
| return set(re.findall(r"\d+(?:\.\d+)?", text)) | |
| def check_numbers(user_texts, assistant_text): | |
| """Measurement-like numbers (N µm / N%) in the answer must appear somewhere in the user-side text (block/context).""" | |
| allowed = set() | |
| for t in user_texts: allowed |= all_numbers(t) | |
| return sorted(numbers_in(assistant_text) - allowed - ALLOWED_CONST) | |
| def check_forbidden(assistant_text): | |
| t = assistant_text.lower() | |
| return [p for p in FORBIDDEN if p in t] | |
| REPORT_SECTIONS = ["1. Image findings", "2. Anatomical locations", "3. Pattern assessment", "4. Information you provided", | |
| "5. Limitations", "6. Recommended clinical assessment"] | |
| def check_report(text): | |
| return [s for s in REPORT_SECTIONS if s not in text] | |