""" verifier.py - checks applied to every free-text (model) answer BEFORE the user sees it. If any check fails, the app discards the draft and shows a safe template answer instead (and tells the user why). Checks: numbers must come from the measurement block; no diagnosis / certainty / normality verdicts; no cup-to-disc values; no treatment advice; no claims about things a map cannot show (visual field result, eye pressure, which eye); no bare one-word verdicts; glaucoma talk must point to an eye-care professional; no runaway length / repetition. NOTE: these rules were written after reading the model's failures on our stress test, so the stress-test results for the verifier are in-sample (optimistic). Validate on fresh prompts before quoting them as general performance. """ import re import textgen as T NEGATORS = ["whether", "if ", "can't", "cannot", "can not", "not able", "unable", "n't", " or not", "confirm or deny"] CDR_NUMBER = re.compile(r"(cup[- ]to[- ]disc|cup[- ]disc|\bcdr\b)[^.\n]{0,60}?\b0?\.\d+", re.I) LIMIT_WORDS = ["not a diagnosis", "cannot diagnose", "can't diagnose", "not able to diagnose", "eye-care professional", "eye care professional", "eye specialist", "eye doctor", "ophthalmologist", "optometrist", "clinician"] PATTERNS = { # name -> regex (case-insensitive). Applied with the negation filter unless noted. "diagnostic statement": r"\b(does not|doesn't|do not|don't|not)\s+(indicate|show|suggest|mean|have|exclude|rule out)\s+(any\s+|a\s+|signs?\s+of\s+)?glaucoma\b", "rules out / confirms glaucoma": r"\b(rules?|ruled|ruling)\s+out\s+glaucoma\b|\bconfirm(s|ed)?\s+(that\s+)?(you have\s+)?glaucoma\b", "normality / health verdict": r"\b(your|the)\s+(eyes?|retina|nerve fib\w+ layer|rnfl|scan|map|optic nerve)\s+(is|are|looks?|appears?|seems?)\s+(completely\s+|totally\s+|perfectly\s+)?(normal|healthy|fine|okay)\b", "claims a visual field result": r"\byour\s+visual\s+field\s+(results?|is|was|shows?|indicates?)\b|\bvisual\s+field\s+results?\s+(from|of|on|for|indicates?|shows?)\b", "claims an eye-pressure value": r"\b(your|the)\s+(eye|intraocular)\s+pressure\s+(is|was|appears|reads?|measures?)\b", "claims which eye": r"\bthis\s+(is|appears to be)\s+(your|the)\s+(left|right)\s+eye\b|\bindicat\w+\s+that\s+this\s+is\s+(the|your)\s+(left|right)\s+eye\b|\b(map|scan|image)\s+(is|comes)\s+from\s+(your|the)\s+(left|right)\s+eye\b", "treatment advice": r"\b(latanoprost|timolol|brimonidine|dorzolamide|bimatoprost|travoprost|tafluprost|netarsudil|trabeculectomy|trabeculoplasty|migs|tube shunt)\b|\bslt\b|\bprescrib\w+\b|\byou should (start|take|use|begin)\b|\bstart you on\b", } _COMPILED = {k: re.compile(v, re.I) for k, v in PATTERNS.items()} # glaucoma attributed to the user / map (as opposed to just explaining what glaucoma is) -> must point to a professional ATTRIBUTION = re.compile(r"(sign|signs|suggest\w*|indicat\w*|consistent with|likely|probabl\w*|risk of|chance of|evidence of|pattern of)[^.\n]{0,30}glaucoma|glaucoma[^.\n]{0,25}(is|are)\s+(likely|probable|possible|present|suspected)", re.I) def _negated(low, i): return any(n in low[max(0, i - 40):i] for n in NEGATORS) def forbidden_hits(text): """Forbidden phrases (negation-aware: 'cannot say whether you have glaucoma' is a refusal, not a diagnosis).""" low = text.lower(); hits = [] for p in T.FORBIDDEN: start = 0 while True: i = low.find(p, start) if i < 0: break if not _negated(low, i): hits.append(p); break start = i + 1 for name, rx in _COMPILED.items(): for mo in rx.finditer(text): if not _negated(low, mo.start()): hits.append(name); break return hits def _repetitive(text): sents = [s.strip().lower() for s in re.split(r"[.!?\n]+", text) if len(s.strip()) > 25] return any(sents.count(s) >= 3 for s in set(sents)) def verify(answer, user_texts, strict=True, check_numbers=True): """-> {'ok': bool, 'reasons': [...]}. strict=True for model answers; templates are checked with strict=False.""" reasons = []; a = (answer or "").strip(); low = a.lower() n_words = len(re.findall(r"\w+", a)) if n_words == 0: return {"ok": False, "reasons": ["empty answer"]} if re.match(r"^\W*(yes|no|normal|abnormal|fine|healthy|glaucoma|not glaucoma)\W*$", low) or n_words <= 2: reasons.append("bare one-word verdict") for h in forbidden_hits(a): reasons.append(f"forbidden / unsupported claim: {h}") if CDR_NUMBER.search(a): reasons.append("gives a cup-to-disc value") if check_numbers: bad = T.check_numbers(user_texts, a) if bad: reasons.append("number(s) not in the measurements: " + ", ".join(bad)) if n_words > 400: reasons.append("too long") if _repetitive(a): reasons.append("repetitive") if strict and ATTRIBUTION.search(a) and not any(w in low for w in LIMIT_WORDS): reasons.append("attributes glaucoma to the user/map without pointing to an eye-care professional") seen = []; [seen.append(r) for r in reasons if r not in seen] return {"ok": not seen, "reasons": seen}