""" assistant.py - the app's engine. Everything the user needs for safety and correctness is DETERMINISTIC (no model): measurements, examine summary, explanations, risk/progression wording, structured report, refusals, memory of what the user said. A language model (optional) is used only for questions the router does not recognise, and every model answer must pass verifier.verify() or it is replaced by a safe template. """ import json, os, re, datetime import numpy as np import measure as M, textgen as T, risklite as RL, verifier as V # ------------------------------------------------------------------ assets / analysis def load_assets(d="assets"): ref = json.load(open(os.path.join(d, "reference_ranges.json"))) cfg = json.load(open(os.path.join(d, "app_config.json"))) return {"ref": ref, "cfg": cfg} def _risk(assets, f, age, sex): cfg = assets["cfg"]; fx = dict(f) fx["age"] = None if age is None else float(age) fx["male"] = 1.0 if sex == "male" else (0.0 if sex == "female" else None) pg = RL.predict(cfg["models"]["glaucoma"], fx); pp = RL.predict(cfg["models"]["progression"], fx) return {"glaucoma_prob": pg, "prog_prob": pp, "glaucoma_band": RL.band(pg, cfg["cuts"]["glaucoma"]), "prog_band": RL.band(pp, cfg["cuts"]["progression"])} def analyse_map(m, assets, name="map", age=None, sex=None): cfg, ref = assets["cfg"], assets["ref"] m = np.asarray(m, dtype=np.float32); warnings = [] if m.ndim != 2: raise ValueError("The map must be a 2-D array of RNFL thickness values (µm).") if m.shape != (M.MAP_SIZE, M.MAP_SIZE): from scipy.ndimage import zoom warnings.append(f"The map was {m.shape[0]}x{m.shape[1]} and was resampled to {M.MAP_SIZE}x{M.MAP_SIZE}.") m = zoom(m, (M.MAP_SIZE / m.shape[0], M.MAP_SIZE / m.shape[1]), order=1).astype(np.float32) if np.nanmax(m) <= 1.5 or np.nanmax(m) > 1000: warnings.append("The values do not look like thickness in micrometres (expected roughly 0-350); results may be meaningless.") f = M.compute_features(m, "auto") reasons = T.qc_reasons(f, cfg["rough_thr"]) risk = _risk(assets, f, age, sex) area = f["disc_blob_area_px"] disc_r = float(np.sqrt(area / np.pi)) if (f["center_source"] == "disc_blob" and area > 0) else 28.0 A = {"m": m, "f": f, "reasons": reasons, "risk": risk, "center": (f["center_x"], f["center_y"]), "disc_r": disc_r, "name": name, "warnings": warnings, "vmax": cfg["vmax"], "age": age, "sex": sex} A["block"] = T.build_block(f, ref, reasons, cfg["bands_info"], risk, cfg["vmax"]) return A def new_session(): return {"A": None, "ctx": {}, "notes": [], "msgs": [], "turn": 0} def refresh_risk(sess, assets): A = sess["A"]; ctx = sess["ctx"] A["risk"] = _risk(assets, A["f"], ctx.get("age", A.get("age")), ctx.get("sex", A.get("sex"))) A["block"] = T.build_block(A["f"], assets["ref"], A["reasons"], assets["cfg"]["bands_info"], A["risk"], A["vmax"]) def measurement_rows(A, ref): f = A["f"]; rows = [] fl = lambda v, rc: T.FLAG_SHORT[T.flag_of(v, rc)] rows.append(["Global ring mean", T.u(f["ring_mean"]), T.u(ref["ring_mean"]["p50"]), fl(f["ring_mean"], ref["ring_mean"])]) for k in T.QUADS: rows.append([f"{T.QUAD_LONG[k].capitalize()} quadrant", T.u(f["q_" + k]), T.u(ref["q_" + k]["p50"]), fl(f["q_" + k], ref["q_" + k])]) for h in T.HOUR_ORDER: rows.append([f"{h} o'clock ({T.QUAD_LONG[T.HOUR_QUAD[h]]})", T.u(f.get(f"h{h}")), T.u(ref[f"h{h}"]["p50"]), fl(f.get(f"h{h}"), ref[f"h{h}"])]) return rows # ------------------------------------------------------------------ context memory (what the user tells us) _FAM = {"mother": "mother", "mom": "mother", "mum": "mother", "father": "father", "dad": "father", "sister": "sister", "brother": "brother", "grandmother": "grandmother", "grandfather": "grandfather", "grandma": "grandmother", "grandpa": "grandfather", "aunt": "aunt", "uncle": "uncle", "parent": "parent"} URGENT = re.compile(r"sudden(ly)?\W+(lost|loss|vision|blind|dark)|lost (my |some )?vision|curtain|shadow (across|over)|(severe|sharp|intense) eye pain|eye pain|flashes? of light|new flashes", re.I) URGENT_TEXT = ("**If you have sudden vision loss, a curtain or shadow across your vision, new flashes of light, or eye pain, please seek urgent medical care now - " "do not wait for a routine appointment.**") def parse_context(text, ctx, notes): """Update ctx/notes from a user message. Returns a list of human-readable changes (for the 'what I remember' panel).""" low = text.lower(); ch = [] m = re.search(r"\b(?:i am|i'm|im|age[d]?|aged|my age is)\s*(\d{2,3})\b", low) or re.search(r"\b(\d{2,3})\s*(?:-|\s)?(?:years?|yrs?)[- ]?old\b|\b(\d{2,3})\s*(?:yo|y/o)\b", low) if m: age = int([g for g in m.groups() if g][0]) if 18 <= age <= 110 and ctx.get("age") != age: ctx["age"] = age; ch.append(f"age {age}") m = re.search(r"\b(?:i am|i'm|im)\b[^.?!]{0,40}\b(man|woman|male|female|lady|gentleman)\b", low) if m: sex = "female" if m.group(1) in ("woman", "female", "lady") else "male" if ctx.get("sex") != sex: ctx["sex"] = sex; ch.append(f"sex {sex}") m = re.search(r"\bmy\s+(mother|mom|mum|father|dad|sister|brother|grandmother|grandfather|grandma|grandpa|aunt|uncle|parent)s?\b[^.?!]{0,35}?\b(has|have|had|suffers? from|was diagnosed with|got)\b[^.?!]{0,25}?glaucoma", low) if m: fam = _FAM[m.group(1)] if ctx.get("family") != fam: ctx["family"] = fam; ch.append(f"family history: {fam}") elif re.search(r"no family history|nobody in my family|no one in my family|none of my family", low): if ctx.get("family") != "none": ctx["family"] = "none"; ch.append("family history: none") if re.search(r"short[- ]?sighted|myop|near[- ]?sighted", low): strong = re.search(r"\b(very|quite|extremely|highly|severely|high|strong|thick glasses)\b|-\s?([5-9]|1\d)(\.\d+)?", low) d = re.search(r"-\s?\d+(\.\d+)?\s*(d\b|dioptre|diopter)?", low) if strong and ctx.get("myopia") != "high": ctx["myopia"] = "high"; ctx["myopia_text"] = "short-sighted" + (f" ({d.group(0).strip()} dioptres)" if d else " (described as strong)"); ch.append("short-sighted (strong)") elif not strong: note = "Short-sighted (degree not specified)" if note not in notes: notes.append(note); ch.append("short-sighted (mild/unspecified)") if re.search(r"(no|haven'?t noticed any|have not noticed any|don'?t have any)\s+(symptoms|problems|issues)|vision is fine|no problems with my (vision|eyes)", low): if ctx.get("symptoms") != "none": ctx["symptoms"] = "none"; ch.append("no symptoms noticed") elif re.search(r"blurr?y|blurred|blur\b", low): if ctx.get("symptoms") != "blurry": ctx["symptoms"] = "blurry"; ch.append("blurry vision") for pat, label in [(r"eye pressure|\biop\b|intraocular pressure", "Eye pressure remark"), (r"\blaser\b|surgery|cataract", "Eye surgery/laser mentioned"), (r"diabet", "Diabetes mentioned"), (r"\bdrops\b|medication|tablets?", "Medication mentioned"), (r"blood pressure|hypertension", "Blood pressure / hypertension mentioned"), (r"cholesterol|asthma|migraine|thyroid|arthritis|medical history", "Other medical history mentioned")]: if re.search(pat, low) and not re.search(r"^\s*(what|how|can|could|is|are|do|does|tell)\b", low) and "?" not in low: snippet = next((s.strip() for s in re.split(r"(?<=[.!])\s+", text) if re.search(pat, s, re.I)), text)[:160] note = f"{label}: \"{snippet}\"" if note not in notes and len(notes) < 8: notes.append(note); ch.append(label.lower()) return ch def context_lines_app(ctx, notes): L = [] if ctx.get("age") is not None: L.append(f"- Age: {ctx['age']}" + (f"; sex: {ctx['sex']}" if ctx.get("sex") else "")) elif ctx.get("sex"): L.append(f"- Sex: {ctx['sex']}") 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("- " + ctx.get("myopia_text", "Short-sighted")) if ctx.get("symptoms"): L.append("- Symptoms: " + ("none noticed" if ctx["symptoms"] == "none" else "blurry vision (as described by you)")) L += [f"- {n}" for n in notes] return L or ["- None provided."] def memory_markdown(ctx, notes): L = context_lines_app(ctx, notes) return "**What I remember from this conversation** (unverified, only used in this session):\n\n" + "\n".join(L) # ------------------------------------------------------------------ intent routing (deterministic) R = lambda p: re.compile(p, re.I) # Order matters: social -> report/recall -> safety (refusals) -> regions -> everything else. RULES = [ ("greet", R(r"^\s*(hi|hello|hey|hiya|good (morning|afternoon|evening))\b[\s!.,]*$")), ("report", R(r"\b(write|generate|create|make|produce|draft|prepare|put together)\b[^.?!]{0,25}\b(a |an |the |my )?(structured |full |short |brief |quick |concise )?(report|letter)\b" r"|\b(write|generate|create|make|produce|draft|prepare|compile|put together|give me|turn)\b[^.?!]{0,60}\b(clinical summary|summary|note|bulleted list|list)\b[^.?!]{0,60}\b(doctor|gp|specialist|ophthalmologist|optometrist|clinic|family|appointment|structured|bullet|values|everything)\b" r"|\bstructured (report|summary)\b|^\s*(a |the )?report\b|\bnote for my (gp|doctor)\b|\b(letter|summary|note) (for|to) (my|the) (eye |family )?(doctor|gp|specialist|ophthalmologist|optometrist|family)\b" r"|include my [^.?!]{0,40}\bin (the|a|my) (letter|report|summary|note)\b|\bshort note\b|summary to give my doctor")), ("recall", R(r"what (did|have|had) i (previously |already |earlier |just )?(tell|say|said|mention|told)|remind me (what|which)|what do you (know|remember) about me|which (personal )?details|did i (mention|tell|say)" r"|(what|which) [^.?!]{0,30} did i (say|mention|tell)|(i|we) (told|said|mentioned) (you )?earlier|earlier in this (chat|conversation)|previously (tell|told|said|mention)")), ("glaucoma_info", R(r"what (is|are) glaucoma|what does (a )?(glaucoma )?diagnosis (actually )?mean|explain (what )?glaucoma\b|tell me about glaucoma|what is a glaucoma diagnosis")), ("cdr", R(r"cup[- ]?(to[- ]?)?disc|\bcdr\b|c/d ratio|vertical cup")), ("diagnose", R(r"\bdiagnos\w*|\bcancer\b|\btumou?r\b|what (do|does) (i|this|it) have|what('s| is) wrong with (me|my eyes?)|definitive|be certain|for certain|yes or no|just (say|tell) me|be honest.{0,40}glaucoma" r"|confirm (that )?(it|this)?.{0,30}glaucoma|do i have glaucoma or not|ignore (all )?(your )?(previous|prior)? ?instructions|you are now my (doctor|ophthalmologist)|pretend" r"|rule[sd]? out|do (you|u) (think|reckon|believe)[^.?!]{0,25}glaucoma|would you say[^.?!]{0,20}glaucoma|am i (sick|ill|diseased|healthy)|healthy or (diseased|sick|unhealthy)" r"|i authori[sz]e you|forget (all |the |your )?(usual |medical )?disclaimers|i accept (all )?responsibility|no disclaimers")), ("treat_info", R(r"(what are|what's|which are|list)\b[^.?!]{0,25}\b(common |usual |main |typical |available )?(treatments?|therapies|options)\b|how is glaucoma (treated|managed)|types of (glaucoma )?treatment")), ("treat", R(r"eye ?drops?|medicat\w*|\btreatment|surgery|prescrib\w*|\blaser\b|latanoprost|what should i (take|use|start)|\bdrops\b")), ("wait", R(r"\bskip\w*|\bdelay\w*|postpone|(wait|put (it|this) off).{0,25}(year|month|week)|do i need (an? )?(appointment|to see)|safe to wait")), ("fitness", R(r"\bdriv(e|ing|er)\b|\blicen[cs]e\b|operate (a )?machin\w+|\bfly(ing)?\b|work safely|safe (for me )?to (work|play|exercise|travel)")), ("oneword", R(r"only the word|one[- ]word|single[- ]word|reply with only|just (the word|say (normal|abnormal))|normal or abnormal|word verdict")), ("REGION", None), ("examine", R(r"^\s*(please |pls )?(can you |could you |can u )?(describe|walk me through|take me through|talk me through|summari[sz]e)\b")), ("compare", R(r"(last|previous|earlier|prior|old)\s+(year|scan|visit|map|result)|compare\b.{0,30}(with|to|against)|since my last")), ("progression", R(r"(going to|will|gonna|might|could|would|may)\b[^.?!]{0,25}\b(get )?worse|go(ing)? blind|lose my (sight|vision)|become blind|blindness|deteriorat\w+")), ("vfield", R(r"visual field|perimetry|\bvf\b")), ("iop", R(r"eye pressure|\biop\b|intraocular pressure")), ("lateral", R(r"left (eye )?or (the )?right|right (eye )?or (the )?left|which eye|(my|the) (left|right) eye|temporal|nasal|which side|\b(r|l)\s*(or|/)\s*(l|r)\b[^.?!]{0,10}eye|\bod\b|\bos\b")), ("othercond", R(r"macular degeneration|\bamd\b|cataract|retinopathy|retinal detachment|dry eye|glasses prescription|prescription (for )?glasses|refractive|astigmat|conjunctivitis|infection|allerg\w+|video games?|screen time|eye ?strain|strained")), ("symptom", R(r"\bitch\w*|burning|watery|watering|gritty|\bsore\b|tired eyes?|headaches?|migraines?|redness|floaters?")), ("colours", R(r"colou?r\w*|why (is|are) .{0,30}\b(red|blue|yellow|green)\b|thick.{0,25}thin|thin.{0,25}thick|\bwarm\b")), ("disc", R(r"(dark|blue|black|hole|circle|blob).{0,40}(middle|centre|center)|(middle|centre|center).{0,40}(dark|blue|black|hole|circle)|optic (nerve head|disc|disk)")), ("rnfl", R(r"\brnfl\b|nerve fib(er|re) layer|what is (the )?(retinal|oct)|what does ['\"]?thickness['\"]? (actually )?mean|what is thickness")), ("ring", R(r"\bring\b|how .{0,30}(calculated|measured|computed)|what (is|are) (the )?(quadrants?|sectors?|clock)")), ("border", R(r"borderline|reference (range|group)|percentile|below range")), ("accuracy", R(r"accura\w+|how good are you|trust (the )?(risk|model|ai|analysis|software|tool|app|bands?)|risk bands?|confidence (should|can|do) i|how (sure|confident|certain) (are you|is (the|this))|how much (confidence|trust)|is (the|this) (software|analysis|tool|app) (reliable|correct)")), ("quality", R(r"quality|artefact|artifact|invalid|anything wrong|any problems?|reliab\w+|can i trust|trust (every|these|this|the (numbers|scan|map))|blurr?y|blurred|\bdark\b|noisy|poor signal|bad (scan|image)|image looks|signal strength|affect (the )?(results?|analysis|measurements?)")), ("progression", R(r"\b(worse|worsen\w*|progress\w*|get worse|future|over the years)\b")), ("risk", R(r"glaucoma|worried|worry|risk|pattern|\bbad\b|serious|concern")), ("next", R(r"what (should|do|can) i do|next steps?|what now|what happens next|recommend|questions? (should|can|could|might) i ask|additional tests|what tests|(what|which) (kind|type) of (specialist|doctor)|which specialist|who should i see|follow-?up|what do (you|u) think i should do")), ("lay", R(r"simple|plain (english|language|terms)|eli5|like i'?m (a )?(\d+|child|kid|five)|layman|non-?medical|explain|bullet")), ("examine", R(r"what (does|do|did) (my|this|the) (scan|map|image|result|oct|eyes?)\b.{0,20}(say|show|mean|tell)|how (does|do) (my|the|this) (scan|map|eyes?) look|what('s| is) (on|in) (my|the|this) (scan|map)|describe|what do you see|what (does|do) (this|the) (map|scan|image)|findings?|summar\w+|tell me about|overview|main (finding|takeaway|structures)|key (points|findings)|what am i looking at|what can you see|what do you notice|what is (shown|displayed)|what are (shown|displayed)|what is this\??\s*$")), ] OFFTOPIC = R(r"\b(weather|temperature outside|stock|bitcoin|crypto|recipe|joke|poem|song|football|soccer|movie|capital of|translate|python|javascript|homework|president|election|news|horoscope|exchange rate|currency|dollars?|euros?|price of|hotel|flight|lottery)\b") THANKS = R(r"\b(thanks|thank you|thx|cheers|much appreciated|appreciate (it|that|the)|that (was|is) (very )?(helpful|useful|clear)|very clear|helpful)\b") ACK = R(r"\bi (just |recently )?(took|had|got|did) (a|an|my|the)\b.{0,30}\b(scan|oct|exam|test|check-?up|appointment)\b") EXTREME = R(r"\bwhich\b[^.?!]{0,25}\b(clock[- ]hour|sector|region|area|quadrant|part|side|hour)\b[^.?!]{0,40}\b(smallest|lowest|thinnest|minimum|least|highest|thickest|largest|maximum|most|worst|unusual|abnormal|odd|different)\b" r"|\b(thinnest|thickest|lowest|highest)\b[^.?!]{0,20}\b(sector|region|area|part|quadrant|hour)\b|where is (it|the (retina|layer|nerve fib\w+)) (thinnest|thickest)") HOUR_RX = R(r"\b(1[0-2]|[1-9])\s*(?:o'?clock|o’clock|oclock)\b|\b(1[0-2]|[1-9])\s*(?:h|hr|hrs)\b") TIME_RX = R(r"\b(1[0-2]|[1-9]):([0-5]\d)\b") QUAD_RX = [("S", R(r"\b(superior|upper|top)\b[^.?!]{0,12}\b(side|part|area|region|quadrant|sector|half)?")), ("I", R(r"\b(inferior|lower|bottom)\b[^.?!]{0,12}\b(side|part|area|region|quadrant|sector|half)?")), ("L", R(r"\b(image[- ]left|left)\b\s*(side|part|area|region|quadrant|sector)")), ("R", R(r"\b(image[- ]right|right)\b\s*(side|part|area|region|quadrant|sector)"))] QUESTIONISH = R(r"^\s*(what|how|can|could|is|are|do|does|tell|why|which|where|will|would|should)\b") IMPERATIVE = R(r"^\s*(please|tell|give|write|explain|describe|summar\w*|show|list|generate|remind|compare|keep|reply|ignore|pretend|you are now|confirm|diagnose|walk|take|draft|compile|turn|include|forget|i authori[sz]e)\b") def is_question(text): return "?" in text or bool(QUESTIONISH.search(text.lower())) or any(IMPERATIVE.search(s) for s in re.split(r"(?<=[.!?])\s+", text)) def question_part(text): """Route on the sentences that ask for something; statements about the user (age, family history, ...) are memory, not questions.""" sents = re.split(r"(?<=[.!?])\s+", text.strip()) q = [x for x in sents if "?" in x or IMPERATIVE.search(x) or QUESTIONISH.search(x.lower())] return " ".join(q) if q else text def route(text, full_text=None): """text = the question part of the message; full_text = the whole message (a statement elsewhere in it can still matter, e.g. 'my optometrist said it's glaucoma. Can you confirm?').""" t = text.strip(); low = t.lower(); full = (full_text or text); full_low = full.lower() if len(full.split()) <= 18 and not is_question(full): # short social statements if THANKS.search(full_low): return "thanks", None if ACK.search(full_low): return "ack", None if "glaucoma" in full_low and re.search(r"\bconfirm\w*|\bverify|\bprove|\bcertain|\bdefinite\w*|\bsure\b", low): return "diagnose", None for name, rx in RULES: if name == "REGION": mo = TIME_RX.search(low) if mo and int(mo.group(2)) != 0: return "region_time", (int(mo.group(1)), int(mo.group(2))) mo = HOUR_RX.search(low) if mo: return "region_hour", int([g for g in mo.groups() if g][0]) if EXTREME.search(low): kind = "abs_max" if re.search(r"highest|thickest|largest|maximum", low) else ("unusual" if re.search(r"unusual|abnormal|odd|different|worst|most", low) else "abs_min") return "extreme", kind for k, qrx in QUAD_RX: if qrx.search(low) and re.search(r"what|about|tell|explain|mean|happen|region|part|area|side|quadrant|sector|thick|thin|value|number|measure|reading|how much", low): return "region_quad", k continue if name == "iop" and not ("?" in t or QUESTIONISH.search(low)): continue if rx.search(low): return name, None if OFFTOPIC.search(low): return "offtopic", None return "unknown", None # ------------------------------------------------------------------ answers HELP_TEXT = ("describe this map and its measurements, explain it in plain language, explain any region (e.g. 'what about 7 o'clock?' or 'the superior part'), " "describe what the glaucoma-pattern and progression bands mean, explain terms (RNFL, the ring, colours, the dark circle), " "comment on scan quality, remember what you tell me (age, family history, ...), and write a structured report.") def short_summary(f, ref): rf = T.flag_of(f["ring_mean"], ref["ring_mean"]); lo = T.lowest_hour(f, ref) s = f"The global ring mean is {T.u(f['ring_mean'])} ({T.FLAG_SHORT[rf]})" if rf != "n/a" else "The global ring mean could not be assessed" if lo: s += f", and the lowest sector relative to the reference median is {lo[0]} o'clock ({T.QUAD_LONG[T.HOUR_QUAD[lo[0]]]}, {lo[1]:+d}%)" return s + "; this is not a diagnosis." def bullets(f, ref, reasons): rf = T.flag_of(f["ring_mean"], ref["ring_mean"]); lq = T.lowest_quadrant(f, ref) b1 = {"within": f"- The overall thickness of the nerve-fibre layer around the optic nerve ({T.u(f['ring_mean'])}) is within the range of the reference group.", "borderline": f"- The overall thickness of the nerve-fibre layer ({T.u(f['ring_mean'])}) is a little lower than most of the reference group.", "below": f"- The overall thickness of the nerve-fibre layer ({T.u(f['ring_mean'])}) is lower than almost all of the reference group.", "n/a": "- The overall thickness could not be worked out reliably because part of the scan is unusable."}[rf] b2 = (f"- The part that stands out most is the {T.QUAD_LONG[lq]} side ({T.u(f['q_' + lq])})." if lq else "- No single side could be assessed reliably.") b3 = "- This is not a diagnosis: only an eye specialist can say what it means, so a proper eye examination is the next step." if reasons: b3 += " The scan also has quality problems, so the numbers should be treated cautiously." return "\n".join([b1, b2, b3]) def _flag_sentence(f, ref): rf = T.flag_of(f["ring_mean"], ref["ring_mean"]) return "" if rf == "n/a" else f" For this map, the global ring mean is {T.u(f['ring_mean'])}, which is {T.FLAG_WORD[rf]}." GLAUCOMA_INFO = ("Glaucoma is a group of eye conditions in which the optic nerve is gradually damaged, often (but not always) linked to raised pressure inside the eye. The damage means nerve fibres are lost, " "which is why the nerve-fibre layer on this kind of map can become thinner, and over time it can reduce the visual field, usually starting at the edges. It is diagnosed by an eye-care professional using the " "appearance of the optic nerve, eye pressure, visual field tests and OCT together. I can't tell you whether you have it.") TREAT_INFO = ("In general, glaucoma treatment aims to lower the pressure inside the eye to protect the optic nerve, most often with eye drops, and sometimes with laser treatment or surgery. " "Which option suits a person depends on a full examination and is decided with an eye specialist, so I can't recommend anything for you.") FITNESS = ("I can't tell you whether it is safe for you to drive or do any other activity. That depends on tests of how well you actually see, such as visual fields and sharpness of vision, done by an eye-care professional, " "and on local rules; a thickness map alone cannot show this. If you have noticed any problems with your vision, please tell your eye-care professional before driving.") SYMPTOM = ("I can't link symptoms such as itching, dryness, burning or headaches to this map. It measures the thickness of the nerve-fibre layer around the optic nerve head, and the red or yellow areas on it simply mean " "thicker nerve fibres, not inflammation or a lesion. If symptoms persist or worry you, please see an eye-care professional, and seek urgent care for sudden vision loss, eye pain, a curtain or shadow across your vision, or new flashes of light.") OTHERCOND = ("This map only measures nerve-fibre-layer thickness around the optic nerve head. It can't show other eye conditions (for example problems of the macula or the lens), your glasses prescription, eye strain, " "or the effects of daily activities. Those are assessed with other tests by an eye-care professional.") QUESTIONS_TO_ASK = ("Questions you could take to your eye-care professional: What do these RNFL measurements mean for me? Are they consistent with my optic nerve examination and my visual field tests? " "Do I need repeat OCT scans or visual field tests, and how often? What is my eye pressure, and does it matter in my case? Does my family history change the plan? " "Were there any image-quality problems with this scan? I can also write a structured report to bring with you.") SPECIALIST = ("An ophthalmologist (a medical eye doctor) or an optometrist can carry out the comprehensive eye examination: eye pressure measurement, examination of the optic nerve, visual field testing and review of the OCT scan. " "Which one to see usually depends on local referral arrangements, so your general practitioner or optometrist can advise.") QUALITY_USER = ("Blur, darkness or low signal strength in the original scan can make thickness measurements less reliable. I can't see the original scan's signal strength, only the checks I run on the thickness map itself.") def extreme_answer(f, ref, kind): hrs = [(h, f.get(f"h{h}")) for h in T.HOUR_ORDER if not T.isnan(f.get(f"h{h}"))] if not hrs: return "No clock-hour sector could be assessed reliably because too much of the ring is invalid." if kind == "abs_max": h, v = max(hrs, key=lambda x: x[1]); label = "thickest" elif kind == "abs_min": h, v = min(hrs, key=lambda x: x[1]); label = "thinnest" else: lo = T.lowest_hour(f, ref); h = lo[0]; v = f.get(f"h{h}"); label = f"furthest below the reference median ({lo[1]:+d}%)" fl = T.flag_of(v, ref[f"h{h}"]) extra = " Some sectors could not be assessed, so this is among the assessable ones." if T.any_nan_hours(f) else "" return (f"The {label} clock-hour sector is {h} o'clock ({T.QUAD_LONG[T.HOUR_QUAD[h]]}) at {T.u(v)}, which is {T.FLAG_WORD[fl]}.{extra} " "This describes this one map only and is not a diagnosis.") def template_answer(sess, assets, intent, arg, text, changes): A, ref, cfg = sess["A"], assets["ref"], assets["cfg"]; f = A["f"]; ctx = sess["ctx"] rng = np.random.default_rng(1000 + sess["turn"]); vmax = A["vmax"]; reasons = A["reasons"]; low = text.lower() if intent == "greet": return "Hello! " + "I can " + HELP_TEXT[0].lower() + HELP_TEXT[1:] if intent == "thanks": return "You're welcome! Ask me anything else about this map, or I can write a structured report you can show your eye-care professional." if intent == "ack": return "Thanks for letting me know. I can describe this map, explain any region, or write a report - just ask." if intent == "glaucoma_info": return GLAUCOMA_INFO if intent == "treat_info": return TREAT_INFO if intent == "fitness": return FITNESS if intent == "symptom": return SYMPTOM if intent == "othercond": return OTHERCOND if intent == "extreme": return extreme_answer(f, ref, arg) if intent == "next" and re.search(r"\bask\b|question", low): return QUESTIONS_TO_ASK if intent == "next" and re.search(r"specialist|which doctor|who should i see|what (kind|type)", low): return SPECIALIST if intent == "quality" and re.search(r"blurr?y|blurred|dark|noisy|poor signal|bad (scan|image)|signal|affect", low): return QUALITY_USER + " " + T.QA["quality"][1](f, ref, reasons, rng, vmax) if intent == "report": return report_text_app(sess, assets) if intent == "recall": lines = context_lines_app(ctx, sess["notes"]) if lines == ["- 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(lines) if intent == "examine": if re.search(r"one sentence|in a sentence|briefly|in short|short", low): return short_summary(f, ref) extra = T.context_remarks(ctx, ("age", "family", "myopia")) if changes else [] return " ".join([T.examine_answer(f, ref, reasons, rng)] + extra) if intent == "lay": if re.search(r"bullet", low): return bullets(f, ref, reasons) return T.lay_answer(f, ref, reasons, rng) if intent == "oneword": return "I can't reduce this to a one-word verdict like 'normal' or 'abnormal': that would amount to a diagnosis. In short: " + short_summary(f, ref) if intent in ("region_hour", "region_quad"): key = arg return T.region_answer("hour" if intent == "region_hour" else "quad", key, f, ref) if intent == "region_time": h, mm = arg; lo_h, hi_h = (h, 1 if h == 12 else h + 1) if mm == 0: return T.region_answer("hour", h, f, ref) near = lambda x: f"{x} o'clock {T.u(f.get(f'h{x}'))}" return (f"The sectors are whole clock hours, so {h}:{mm:02d} is not a sector of its own. It lies between the {lo_h} o'clock and {hi_h} o'clock sectors " f"({near(lo_h)}; {near(hi_h)}). Each sector covers 30 degrees, centred on its hour.") if intent == "risk": return T.risk_answer(A["risk"], cfg["bands_info"], ctx, rng) if intent == "progression": return T.prog_answer(A["risk"], cfg["bands_info"], ctx, rng) if intent == "diagnose": extra = " " + T.QA["treat"][1](f, ref, reasons, rng, vmax) if dict(RULES)["treat"].search(low) else "" return T.QA["diagnose"][1](f, ref, reasons, rng, vmax) + extra if intent in T.QA and intent not in ("hour",): return T.QA[intent][1](f, ref, reasons, rng, vmax) + (_flag_sentence(f, ref) if intent == "border" else "") if intent == "vfield": return ("I can't read a visual field result from this map. A visual field is a separate test (perimetry) of what you can see across your vision, while this map measures " "the thickness of the nerve-fibre layer. Thinning in the upper part of the map tends to correspond to the lower visual field and thinning in the lower part to the " "upper visual field, but only a visual field test shows what you can actually see. An eye-care professional can arrange it.") if intent == "iop": return ("Eye pressure (intraocular pressure) can't be measured from this map; it is measured with a tonometer during an eye examination. " "It is one of the things an eye-care professional checks together with the optic nerve, visual fields and OCT scans.") if intent == "compare": return ("I only have this one scan loaded, so I can't compare it with an earlier one. Judging change over time needs both scans measured the same way and reviewed " "by a clinician, and a single scan cannot show change.") if intent == "offtopic": return "I can only help with this OCT retinal nerve fibre layer map. I can " + HELP_TEXT[0].lower() + HELP_TEXT[1:] return None def fallback_answer(why): return (f"I can't answer that reliably. {why} What I can do reliably: " + HELP_TEXT) def context_ack(changes, ctx, sess): kinds = tuple(k for k, key in [("age", "age"), ("family", "family"), ("myopia", "short"), ("symptoms", "symptom")] if any(key in c for c in changes)) if any("blurry" in c for c in changes): kinds += ("symptoms",) return ("Thanks, I've noted: " + "; ".join(changes) + ". I can't verify this, but I'll keep it in mind in this conversation and include it in the report. " + " ".join(T.context_remarks(ctx, kinds))).strip() # ------------------------------------------------------------------ report def report_text_app(sess, assets): A, ref, cfg = sess["A"], assets["ref"], assets["cfg"] txt = T.report_text(A["f"], ref, A["reasons"], A["risk"], cfg["bands_info"], sess["ctx"]) body = "\n".join(context_lines_app(sess["ctx"], sess["notes"])) txt = re.sub(r"(4\. Information you provided \(unverified\)\n).*?(\n\n5\. Limitations)", lambda mo: mo.group(1) + body + mo.group(2), txt, flags=re.S) return f"Map: {A['name']} | Generated: {datetime.date.today().isoformat()}\n\n" + txt # ------------------------------------------------------------------ one chat turn def chat_turn(sess, assets, text, llm=None, image_path=None): """-> dict(text, source, intent, verified, reasons, changes, draft). source in {'template','model','fallback'}""" A = sess["A"]; ctx = sess["ctx"] prev = (ctx.get("age"), ctx.get("sex")) changes = parse_context(text, ctx, sess["notes"]) if (ctx.get("age"), ctx.get("sex")) != prev: refresh_risk(sess, assets) sess["turn"] += 1 statement_only = bool(changes) and not is_question(text) intent, arg = ("context", None) if statement_only else route(question_part(text), text) urgent = URGENT_TEXT + "\n\n" if URGENT.search(text) else "" user_texts = [A["block"]] + [m["content"] for m in sess["msgs"]] + [text] out = {"intent": intent, "changes": changes, "draft": None} ans = None if intent == "context" else template_answer(sess, assets, intent, arg, question_part(text), changes) if intent == "context": out.update(text=context_ack(changes, ctx, sess), source="template", verified=True, reasons=[]) elif ans is not None: v = V.verify(ans, user_texts, strict=False) if not v["ok"]: # a template failing its own check is a bug - never show it out.update(text=fallback_answer("(An internal check failed on my prepared answer.)"), source="fallback", verified=False, reasons=v["reasons"]) else: out.update(text=ans, source="template", verified=True, reasons=[]) elif llm is not None and llm.available(): hist = [{"role": m["role"], "text": m["content"]} for m in sess["msgs"]] + [{"role": "user", "text": text}] try: draft = llm.generate(V_SYSTEM, hist, A["block"], image_path) except Exception as e: draft = None; out["draft"] = f"(model error: {e})" if draft is None: out.update(text=fallback_answer("The chat model is not available right now."), source="fallback", verified=False, reasons=["model unavailable"]) else: v = V.verify(draft, user_texts, strict=True); out["draft"] = draft if v["ok"]: out.update(text=draft, source="model", verified=True, reasons=[]) else: out.update(text=fallback_answer("My automatic safety checks rejected the draft answer from the language model."), source="fallback", verified=False, reasons=v["reasons"]) else: out.update(text=fallback_answer("Free-form answers need the chat model, which is not loaded in this demo."), source="fallback", verified=False, reasons=["no model loaded"]) out["text"] = urgent + out["text"] sess["msgs"] += [{"role": "user", "content": text}, {"role": "assistant", "content": out["text"]}] return out V_SYSTEM = T.SYSTEM_GROUND + (" Answer only about the supplied map. When asked for a structured report use the six numbered sections. Never diagnose, never advise on treatment, " "quote only numbers from the blocks, and say the left/right orientation of the map is not confirmed.")