akshara-ns commited on
Commit
ef613b5
·
verified ·
1 Parent(s): 3b95198

Upload the Doc Compass app bundle

Browse files
checkpoints/biomedbert_gold/config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "BertForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": null,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": null,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "id2label": {
15
+ "0": "Dermatology",
16
+ "1": "Orthopedics",
17
+ "2": "ENT",
18
+ "3": "Gastroenterology",
19
+ "4": "Neurology",
20
+ "5": "Urology",
21
+ "6": "Ob-Gyn",
22
+ "7": "Mental health",
23
+ "8": "Cardiology",
24
+ "9": "Eye care",
25
+ "10": "Dentistry",
26
+ "11": "Start with a GP"
27
+ },
28
+ "initializer_range": 0.02,
29
+ "intermediate_size": 3072,
30
+ "is_decoder": false,
31
+ "label2id": {
32
+ "Cardiology": 8,
33
+ "Dentistry": 10,
34
+ "Dermatology": 0,
35
+ "ENT": 2,
36
+ "Eye care": 9,
37
+ "Gastroenterology": 3,
38
+ "Mental health": 7,
39
+ "Neurology": 4,
40
+ "Ob-Gyn": 6,
41
+ "Orthopedics": 1,
42
+ "Start with a GP": 11,
43
+ "Urology": 5
44
+ },
45
+ "layer_norm_eps": 1e-12,
46
+ "max_position_embeddings": 512,
47
+ "model_type": "bert",
48
+ "num_attention_heads": 12,
49
+ "num_hidden_layers": 12,
50
+ "pad_token_id": 0,
51
+ "tie_word_embeddings": true,
52
+ "transformers_version": "5.18.0",
53
+ "type_vocab_size": 2,
54
+ "use_cache": false,
55
+ "vocab_size": 30522
56
+ }
checkpoints/biomedbert_gold/metrics.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "repo": "microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext",
4
+ "revision": "e1354b7a3a09615f6aba48dfad4b7a613eef7062"
5
+ },
6
+ "stage": 2,
7
+ "from": "base",
8
+ "epochs": 6,
9
+ "learning_rate": 2e-05,
10
+ "seed": 24679,
11
+ "train_rows": 362,
12
+ "val_rows": 50,
13
+ "fit_seconds": 474,
14
+ "val": {
15
+ "eval_accuracy": 0.54,
16
+ "eval_macro_f1": 0.4726
17
+ },
18
+ "dev": {
19
+ "n": 50,
20
+ "top1": 0.54,
21
+ "top1_ci": [
22
+ 0.39324197611692235,
23
+ 0.6818508214313913
24
+ ],
25
+ "top3": 0.9,
26
+ "top3_ci": [
27
+ 0.7818646335657977,
28
+ 0.9667249064109775
29
+ ],
30
+ "macro_f1": 0.4726487564722858
31
+ },
32
+ "device": "mps"
33
+ }
checkpoints/biomedbert_gold/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae101c8505d2972e07ff25c30f04e92b190b46effe517b5c4e86f54ee3f14ceb
3
+ size 437989408
checkpoints/biomedbert_gold/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/biomedbert_gold/tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "cls_token": "[CLS]",
4
+ "do_lower_case": true,
5
+ "is_local": false,
6
+ "local_files_only": false,
7
+ "mask_token": "[MASK]",
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "pad_token": "[PAD]",
10
+ "sep_token": "[SEP]",
11
+ "strip_accents": null,
12
+ "tokenize_chinese_chars": true,
13
+ "tokenizer_class": "BertTokenizer",
14
+ "unk_token": "[UNK]"
15
+ }
checkpoints/tfidf_stage2.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c1957c0be7741aaa15d9d8405cad78d5e440e28fbd0197ebac261c44a868a80
3
+ size 1864012
doccompass/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Doc Compass: route a plain-language health concern to a kind of doctor."""
doccompass/app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Gradio interface. Run locally with: python -m doccompass.app
2
+
3
+ The result is drawn like a hospital wayfinding sign: one plaque naming the door to knock on,
4
+ with the router's top three and the explanation kept quiet underneath.
5
+ """
6
+
7
+ import argparse
8
+ from html import escape
9
+
10
+ import gradio as gr
11
+
12
+ from .explain import QwenExplainer
13
+ from .labels import GP, SCOPE
14
+ from .pipeline import load_router, route_concern
15
+
16
+ EXAMPLES = [ # made up by us; never real posts
17
+ "I've had an itchy red rash on both shins for about three weeks and creams from the pharmacy haven't helped.",
18
+ "My right knee swells and hurts after I run, and it clicks when I climb stairs.",
19
+ "I've been feeling very sad and anxious for weeks and I can't focus on anything.",
20
+ "My ears have been ringing for a week and my throat is sore when I swallow.",
21
+ "I get a burning feeling when I pee and I have to go all the time.",
22
+ "I suddenly have crushing chest pain and my left arm feels numb.",
23
+ ]
24
+ EXAMPLE_LABELS = ["Itchy rash", "Sore knee", "Feeling low", "Ringing ears", "Burning when I pee", "Crushing chest pain"]
25
+ DISCLAIMER = ("Doc Compass suggests which kind of doctor to book. It does not diagnose, and it is not medical advice. "
26
+ "Nothing you type is stored. In an emergency call 911.")
27
+
28
+ # Atkinson Hyperlegible was drawn for readers with low vision; it suits a health tool.
29
+ THEME = gr.themes.Base(
30
+ font=[gr.themes.GoogleFont("Atkinson Hyperlegible"), "system-ui", "sans-serif"],
31
+ radius_size=gr.themes.sizes.radius_sm,
32
+ ).set(
33
+ body_background_fill="#F4F7FA", body_background_fill_dark="#0F1820",
34
+ block_shadow="none", block_border_width="1px",
35
+ button_primary_background_fill="#1B4F8F", button_primary_background_fill_dark="#1B4F8F",
36
+ button_primary_background_fill_hover="#163F73", button_primary_text_color="#FFFFFF",
37
+ input_border_color_focus="#1B4F8F",
38
+ )
39
+
40
+ CSS = """
41
+ .gradio-container {max-width: 1080px !important; --dc-ink: #13212C; --dc-muted: #586A78; --dc-line: #D3DDE6;
42
+ --dc-card: #FFFFFF; --dc-blue: #1B4F8F; --dc-amber: #F2B441; --dc-red: #B3261E;}
43
+ .dark .gradio-container, .gradio-container.dark {--dc-ink: #E6EDF3; --dc-muted: #9AAAB7; --dc-line: #2A3A47; --dc-card: #16222C;}
44
+
45
+ .dc-header h1 {margin: 0; font-size: 2rem; font-weight: 700; letter-spacing: -0.01em; color: var(--dc-ink);}
46
+ .dc-header p {margin: 4px 0 0; font-size: 1.05rem; color: var(--dc-muted); max-width: 60ch;}
47
+
48
+ /* The sign: the one loud element on the page. */
49
+ .dc-sign {display: flex; gap: 18px; align-items: center; padding: 22px 24px; border-radius: 6px;
50
+ background: var(--dc-blue); color: #FFFFFF;}
51
+ .dc-sign svg {flex: none; width: 54px; height: 54px;}
52
+ .dc-sign p {margin: 0; color: inherit;}
53
+ .dc-sign .dc-small {font-size: 0.98rem; opacity: 0.92;}
54
+ .dc-sign .dc-big {font-size: 2.1rem; line-height: 1.12; font-weight: 700; letter-spacing: -0.01em; margin: 2px 0 4px;}
55
+ .dc-sign .dc-sub {font-size: 0.98rem; opacity: 0.92; max-width: 46ch;}
56
+ .dc-sign.dc-junction {background: var(--dc-amber); color: #1C1503;}
57
+ /* Gradio styles <p> and SVG shapes inside gr.HTML with its own colours; force the sign colours. */
58
+ .dc-sign:not(.dc-empty) p {color: #FFFFFF !important;}
59
+ .dc-sign.dc-junction p {color: #1C1503 !important;}
60
+ .dc-sign:not(.dc-empty) svg [stroke] {stroke: #FFFFFF !important;} .dc-sign:not(.dc-empty) svg [fill="currentColor"] {fill: #FFFFFF !important;}
61
+ .dc-sign.dc-junction svg [stroke] {stroke: #1C1503 !important;} .dc-sign.dc-junction svg [fill="currentColor"] {fill: #1C1503 !important;}
62
+ .dc-sign.dc-emergency {background: var(--dc-red);}
63
+ .dc-sign.dc-empty {background: transparent; color: var(--dc-muted); border: 1.5px dashed var(--dc-line);}
64
+ .dc-sign.dc-empty .dc-big {font-size: 1.25rem; color: var(--dc-ink);}
65
+
66
+ /* The router's top three, as a quiet directory under the sign. */
67
+ .dc-doors {margin: 14px 0 0; padding: 14px 18px; border: 1px solid var(--dc-line); border-radius: 6px; background: var(--dc-card);}
68
+ .dc-doors h2 {margin: 0 0 8px; font-size: 0.95rem; font-weight: 400; color: var(--dc-muted);}
69
+ .dc-door {display: grid; grid-template-columns: minmax(9rem, 13rem) 1fr 3.2rem; gap: 12px; align-items: center; padding: 5px 0;
70
+ color: var(--dc-ink); font-size: 1rem;}
71
+ .dc-door .dc-track {height: 8px; border-radius: 4px; background: var(--dc-line); overflow: hidden;}
72
+ .dc-door .dc-fill {display: block; height: 100%; background: var(--dc-blue); border-radius: 4px;}
73
+ .dark .dc-door .dc-fill {background: #6FA8EA;}
74
+ .dc-door .dc-pct {text-align: right; font-variant-numeric: tabular-nums; color: var(--dc-muted);}
75
+
76
+ .dc-explain {padding: 2px 4px; font-size: 1.02rem; line-height: 1.55;}
77
+ .dc-explain p, .dc-explain li {max-width: 62ch;}
78
+ .dc-note, .dc-note p {font-size: 0.92rem; color: var(--dc-muted) !important;}
79
+ .dc-footer p {margin: 8px 0 0; font-size: 0.9rem; color: var(--dc-muted); max-width: 80ch;}
80
+ @media (max-width: 640px) {.dc-sign .dc-big {font-size: 1.6rem;} .dc-door {grid-template-columns: 8rem 1fr 3rem;}}
81
+ """
82
+
83
+ _ARROW = ('<svg viewBox="0 0 54 54" aria-hidden="true"><circle cx="27" cy="27" r="25" fill="none" stroke="currentColor" stroke-width="3"/>'
84
+ '<path d="M15 27h22M29 18l9 9-9 9" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>')
85
+ _FORK = ('<svg viewBox="0 0 54 54" aria-hidden="true"><circle cx="27" cy="27" r="25" fill="none" stroke="currentColor" stroke-width="3"/>'
86
+ '<path d="M27 41V28M27 28l-10-10M27 28l10-10M17 25v-7h7M37 25v-7h-7" fill="none" stroke="currentColor" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/></svg>')
87
+ _ALERT = ('<svg viewBox="0 0 54 54" aria-hidden="true"><circle cx="27" cy="27" r="25" fill="none" stroke="currentColor" stroke-width="3"/>'
88
+ '<path d="M27 14v18" stroke="currentColor" stroke-width="4.5" stroke-linecap="round"/><circle cx="27" cy="40" r="2.8" fill="currentColor"/></svg>')
89
+
90
+
91
+ def _sign(kind: str, icon: str, small: str, big: str, sub: str = "") -> str:
92
+ sub_html = f"<p class='dc-sub'>{sub}</p>" if sub else ""
93
+ return (f"<div class='dc-sign dc-{kind}' role='status'>{icon}<div><p class='dc-small'>{small}</p>"
94
+ f"<p class='dc-big'>{big}</p>{sub_html}</div></div>")
95
+
96
+
97
+ EMPTY_SIGN = _sign("empty", "", "Your result appears here", "Describe what's going on, then press the button.",
98
+ "We check for emergency signs first, then suggest up to three kinds of doctor.")
99
+
100
+
101
+ def _doors(options: list[dict]) -> str:
102
+ rows = "".join(
103
+ f"<div class='dc-door'><span>{escape(option['label'])}</span>"
104
+ f"<span class='dc-track'><span class='dc-fill' style='width:{option['confidence']:.0%}'></span></span>"
105
+ f"<span class='dc-pct'>{option['confidence']:.0%}</span></div>" for option in options)
106
+ return f"<div class='dc-doors'><h2>How sure the router is</h2>{rows}</div>"
107
+
108
+
109
+ def render(result: dict) -> tuple[str, str, str]:
110
+ """Turn a pipeline result into (sign and directory HTML, explanation, small note)."""
111
+ if result["status"] == "invalid":
112
+ return _sign("empty", "", "Nothing to route yet", escape(result["message"])), "", ""
113
+ if result["status"] == "emergency":
114
+ reasons = "; ".join(
115
+ (f"“{escape(flag['matched'])}”" if flag["matched"] else "a second, language-model check judged that this may match a published warning sign")
116
+ + f" ([{flag['source']}]({flag['url']}))" for flag in result["flags"])
117
+ sign = _sign("emergency", _ALERT, "This may be an emergency", "Seek emergency care now",
118
+ escape(result["message"].replace("This may be an emergency. ", "")))
119
+ return sign, f"Why this was flagged: {reasons}. The rest of the app did not run.", ""
120
+
121
+ options = result["options"]
122
+ first = options[0]["label"]
123
+ second = options[1]["label"] if len(options) > 1 else None
124
+ if not result["unsure"] or second is None:
125
+ if first == GP:
126
+ sign = _sign("routed", _ARROW, "Your first step", GP, "A GP treats common problems and can refer you on.")
127
+ else:
128
+ sign = _sign("routed", _ARROW, "Book an appointment with", first, f"Covers {SCOPE[first]}.")
129
+ elif GP in (first, second):
130
+ other = next((option["label"] for option in options if option["label"] != GP), None)
131
+ sign = _sign("junction", _FORK, "Not clear-cut, so you decide", GP,
132
+ f"Or {other}, if that fits what you are feeling better." if other else "")
133
+ else:
134
+ sign = _sign("junction", _FORK, "Two doors could fit, so you decide", f"{first} or {second}",
135
+ "If neither clearly fits, start with a GP.")
136
+
137
+ note = f"“{GP}” is always a reasonable first step if you are unsure."
138
+ if result["message"]:
139
+ note = f"{result['message']} {note}"
140
+ if result["removed"]:
141
+ note += " Removed before routing: " + ", ".join(f"{item['kind']} ({escape(item['text'])})" for item in result["removed"]) + "."
142
+ if result["explained_by"] != "template":
143
+ note += f" The reason and questions were written by {result['explained_by']}; the choice of doctor was not."
144
+ return sign + _doors(options), result["explanation"], note
145
+
146
+
147
+ def build_app(router, explainer=None) -> gr.Blocks:
148
+ def run(text: str):
149
+ """Always returns (sign, explanation, note)."""
150
+ try:
151
+ return render(route_concern(text, router, explainer))
152
+ except Exception: # the page should never show a stack trace
153
+ return _sign("empty", "", "Something went wrong on our side", "If you are unsure where to go, start with a GP."), "", ""
154
+
155
+ with gr.Blocks(title="Doc Compass") as demo:
156
+ gr.HTML("<div class='dc-header'><h1>Doc Compass</h1>"
157
+ "<p>Tell us what's going on in your own words. We'll point you to the kind of doctor to book.</p></div>")
158
+ with gr.Row():
159
+ with gr.Column(scale=5):
160
+ concern = gr.Textbox(label="What's going on?", lines=6, placeholder="For example: I've had an itchy rash on both shins for three weeks…")
161
+ submit = gr.Button("Suggest a kind of doctor", variant="primary", size="lg")
162
+ gr.Examples(EXAMPLES, inputs=concern, example_labels=EXAMPLE_LABELS, label="Or try a made-up example")
163
+ with gr.Column(scale=6):
164
+ sign = gr.HTML(EMPTY_SIGN, padding=False)
165
+ explanation = gr.Markdown(elem_classes="dc-explain")
166
+ note = gr.Markdown(elem_classes="dc-note")
167
+ gr.HTML(f"<div class='dc-footer'><p>{DISCLAIMER}</p></div>")
168
+ outputs = [sign, explanation, note]
169
+ submit.click(run, concern, outputs)
170
+ concern.submit(run, concern, outputs)
171
+ return demo
172
+
173
+
174
+ def launch(router, explainer=None, **options):
175
+ """Build and launch with the app's theme and styles; extra options go to Gradio's launch()."""
176
+ return build_app(router, explainer).launch(css=CSS, theme=THEME, **options)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ parser = argparse.ArgumentParser(description="Run the Doc Compass app.")
181
+ parser.add_argument("--llm", action="store_true", help="write explanations with Qwen (downloads about 3 GB the first time)")
182
+ parser.add_argument("--share", action="store_true", help="also create a temporary public link")
183
+ args = parser.parse_args()
184
+ launch(load_router(), QwenExplainer() if args.llm else None, share=args.share)
doccompass/explain.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The plain-language explanation shown under a result.
2
+
3
+ The template below is always available. A language model can replace it later, but it
4
+ only ever sees the same record the template uses, and the template stays as the fallback.
5
+ """
6
+
7
+ import json
8
+ import re
9
+
10
+ from .labels import GP, SCOPE
11
+ from .redflags import WARNING_SIGNS
12
+
13
+ COMMON_QUESTIONS = [
14
+ "When did it start, and is it getting better, worse or staying the same?",
15
+ "What makes it better or worse?",
16
+ "What have you already tried, including any medicines?",
17
+ ]
18
+ QUESTIONS = { # one or two extra questions worth having an answer to before the visit
19
+ "Dermatology": ["Has it spread or changed in size, shape or colour?", "Any new soaps, medicines, foods or plants before it started?"],
20
+ "Orthopedics": ["Was there an injury or a change in activity before it started?", "Which movements or positions hurt most?"],
21
+ "ENT": ["Is it on one side or both?", "Any fever, hearing change or trouble swallowing?"],
22
+ "Gastroenterology": ["How does it relate to eating, and to which foods?", "Any change in bowel habits or weight?"],
23
+ "Neurology": ["How often does it happen and how long does it last?", "Any numbness, weakness or vision change with it?"],
24
+ "Urology": ["Any pain, urgency or change in how often you go?", "Any fever or back pain with it?"],
25
+ "Ob-Gyn": ["When was your last period, and is your cycle regular?", "Could you be pregnant?"],
26
+ "Mental health": ["How is it affecting sleep, study or work?", "Have you had support or treatment for this before?"],
27
+ "Cardiology": ["Does it come on with exertion or at rest?", "Any family history of heart problems?"],
28
+ "Eye care": ["Is it one eye or both?", "Do you wear glasses or contacts, and when was your last eye exam?"],
29
+ "Dentistry": ["Is it sensitive to hot, cold or biting?", "When was your last dental visit?"],
30
+ GP: ["Which symptom bothers you most?", "Is there anything you are most worried it could be?"],
31
+ }
32
+
33
+
34
+ def _closest_specialty(options: list[dict]) -> dict | None:
35
+ """The most likely option that isn't the GP, if there is one."""
36
+ return next((option for option in options if option["label"] != GP), None)
37
+
38
+
39
+ def headline(record: dict) -> str:
40
+ """One line for the top of the result: one answer when confident, two options when unsure."""
41
+ options = record["options"]
42
+ first = options[0]
43
+ if not record["unsure"] or len(options) < 2:
44
+ return f"<strong>{GP}</strong>" if first["label"] == GP else f"Book: <strong>{first['label']}</strong>"
45
+ if GP in (first["label"], options[1]["label"]):
46
+ closest = _closest_specialty(options)
47
+ return f"Not clear-cut: <strong>{GP}</strong>" + (f", or <strong>{closest['label']}</strong> if that fits better. You decide." if closest else ".")
48
+ return f"<strong>{first['label']}</strong> or <strong>{options[1]['label']}</strong>: either could fit. You decide."
49
+
50
+
51
+ def _lead(record: dict) -> tuple[list[str], str]:
52
+ """The opening paragraphs, which state the result, and the label the questions are for.
53
+
54
+ These come from code, never from a language model, so the stated choice and its
55
+ confidence always match what the router returned.
56
+ """
57
+ options = record["options"]
58
+ first = options[0]
59
+ if not record["unsure"] or len(options) < 2:
60
+ return [f"**{first['label']}** looks like the best fit ({first['confidence']:.0%}). It covers {SCOPE[first['label']]}."], first["label"]
61
+ if GP in (first["label"], options[1]["label"]):
62
+ paragraphs = ["**Nothing stands out clearly, so a GP is the safe first step.** A GP can treat common problems and refer you on."]
63
+ closest = _closest_specialty(options)
64
+ if closest:
65
+ paragraphs.append(f"The closest specialty was {closest['label']} ({closest['confidence']:.0%}), which covers {SCOPE[closest['label']]}. If that matches what you are feeling, you could book it directly.")
66
+ return paragraphs, GP
67
+ second = options[1]
68
+ return [
69
+ "**Two kinds of doctor could fit, and the choice is yours.** "
70
+ f"{first['label']} ({first['confidence']:.0%}) covers {SCOPE[first['label']]}. "
71
+ f"{second['label']} ({second['confidence']:.0%}) covers {SCOPE[second['label']]}.",
72
+ "If neither clearly matches what you are feeling, start with a GP, who can refer you on.",
73
+ ], first["label"]
74
+
75
+
76
+ def _questions_block(questions: list[str]) -> str:
77
+ return "**Questions worth having answers to before the visit**\n" + "\n".join(f"- {question}" for question in questions)
78
+
79
+
80
+ def template_explanation(record: dict) -> str:
81
+ """Markdown built only from the routing record: options, confidences and matched words."""
82
+ paragraphs, lead_label = _lead(record)
83
+ if record.get("evidence"):
84
+ paragraphs.append("Words in your description that pointed there: " + ", ".join(f"“{word}”" for word in record["evidence"]) + ".")
85
+ paragraphs.append(_questions_block(COMMON_QUESTIONS + QUESTIONS[lead_label]))
86
+ return "\n\n".join(paragraphs)
87
+
88
+
89
+ # ---------- the off-the-shelf language model ----------
90
+
91
+ QWEN = {"repo": "Qwen/Qwen2.5-1.5B-Instruct", "revision": "989aa7980e4cf806f80c7fef2b1adb7bc71aa306"}
92
+
93
+ _SYSTEM = """You help a student get ready for a doctor's visit. Another system has already chosen which kind of doctor to suggest. You never change, question or add to that choice.
94
+
95
+ Reply with JSON only, with two fields.
96
+
97
+ "why": ONE sentence in exactly this pattern:
98
+ "You described <what the student said, in their own words>, and <doctor> looks after <the matching part of what that doctor covers>."
99
+ Do not say what might be causing it. Never name a disease, condition, injury, test or medicine.
100
+
101
+ "questions": exactly three short questions the doctor is likely to ask, which the student can think about beforehand. A question must not name a disease or a medicine."""
102
+
103
+ _EXAMPLES = [ # made up; they show the sentence pattern, including the GP case
104
+ ({"concern": "My ankle has been swollen and sore since I twisted it playing football last week.",
105
+ "doctor": "Orthopedics", "covers": SCOPE["Orthopedics"]},
106
+ {"why": "You described a swollen, sore ankle after twisting it playing football, and Orthopedics looks after joints and sports injuries.",
107
+ "questions": ["Can you put weight on the ankle?", "Has the swelling gone down or got worse since last week?", "Have you rested or iced it, and did that help?"]}),
108
+ ({"concern": "For two weeks I've felt tired and a bit dizzy and I don't know why.",
109
+ "doctor": "a GP", "covers": SCOPE[GP]},
110
+ {"why": "You described feeling tired and dizzy for two weeks without knowing why, and a GP looks after problems with no clear single cause and can refer you on.",
111
+ "questions": ["When do you feel most tired or dizzy?", "Has anything changed in your sleep, eating or stress lately?", "Do you take any medicines or supplements?"]}),
112
+ ]
113
+
114
+ # Wording that would turn the reason into a diagnosis, a guess at the cause, or advice.
115
+ _WHY_FORBIDDEN = re.compile(
116
+ r"\bdiagnos\w*|\bsounds like\b|\bsymptoms? of\b|\bsuch as\b|\bconsistent with\b|\bsuggest\w*|\bindicat\w*"
117
+ r"|\b(?:could|may|might|must) (?:be|have|indicate)\b|\brelated to\b|\blikely\b|\bpossibl\w*|\bprobabl\w*"
118
+ r"|\bdue to\b|\bcaused? by\b|\bsign of\b|\bprescri\w*|\bmedication\w*|\bantibiotic\w*|\binfection\w*|\bcancer\w*|\btumou?r\w*|\d",
119
+ re.IGNORECASE)
120
+ _QUESTION_FORBIDDEN = re.compile(
121
+ r"\bdiagnos\w*|\bprescri\w*|\byou should\b|\bcancer\w*|\btumou?r\w*|\d"
122
+ r"|\bantihistamin\w*|\b(?:cortico)?steroids?\b|\bantibiotic\w*|\bibuprofen\b|\bparacetamol\b|\bacetaminophen\b|\baspirin\b|\bantidepress\w*",
123
+ re.IGNORECASE)
124
+ _LABEL_STEMS = { # how each label is written in running text; \b stops "Neurology" matching "urolog"
125
+ "Dermatology": r"\bdermatolog", "Orthopedics": r"\borthop", "ENT": r"\bent\b|\botolaryng",
126
+ "Gastroenterology": r"\bgastroenter", "Neurology": r"\bneurolog", "Urology": r"\burolog",
127
+ "Ob-Gyn": r"\bob-?gyn|\bgyn(?:a)?ecolog|\bobstetric", "Mental health": r"\bpsychiatr|\bpsycholog|\bmental health",
128
+ "Cardiology": r"\bcardiolog", "Eye care": r"\bophthalm|\boptometr|\beye care", "Dentistry": r"\bdentist",
129
+ GP: r"\bgp\b|\bgeneral practi",
130
+ }
131
+
132
+
133
+ def check_generated(parsed, allowed_labels: list[str]) -> list[str]:
134
+ """Why a generated explanation can't be shown; an empty list means it passed."""
135
+ if not isinstance(parsed, dict) or not isinstance(parsed.get("why"), str) or not isinstance(parsed.get("questions"), list):
136
+ return ["not in the requested form"]
137
+ why, questions = parsed["why"].strip(), parsed["questions"]
138
+ problems = []
139
+ if not why.startswith("You described") or not 8 <= len(why.split()) <= 45:
140
+ problems.append("the reason does not follow the sentence pattern")
141
+ if _WHY_FORBIDDEN.search(why):
142
+ problems.append("the reason diagnoses, guesses at a cause, advises or uses numbers")
143
+ if not 2 <= len(questions) <= 4 or not all(isinstance(q, str) and q.strip().endswith("?") and len(q.split()) <= 25 for q in questions):
144
+ problems.append("the questions are not two to four short questions")
145
+ elif any(_QUESTION_FORBIDDEN.search(q) for q in questions):
146
+ problems.append("a question diagnoses, advises or uses numbers")
147
+ text = " ".join([why, *map(str, questions)])
148
+ for label, stem in _LABEL_STEMS.items():
149
+ if label not in allowed_labels and re.search(stem, text, re.IGNORECASE):
150
+ problems.append(f"it mentions {label}, which was not suggested")
151
+ return problems
152
+
153
+
154
+ _SAFETY_SYSTEM = """You are a safety check in front of an app that suggests which kind of doctor to book. You do one thing: decide whether a message describes a medical emergency happening NOW, to the writer or to someone who is with them.
155
+
156
+ It is an emergency if the message describes any of these warning signs happening now:
157
+ {signs}
158
+
159
+ It is NOT an emergency when the event is in the past and over, when it happened to someone who is not with the writer now, when the message says the sign is absent, or when the wording is a figure of speech.
160
+
161
+ Reply with JSON only: {{"emergency": true or false, "sign": the number of the matching warning sign, or 0}}"""
162
+
163
+ _SAFETY_EXAMPLES = [ # made up; none of these appear in the evaluation cases
164
+ ("My brother just fell down the stairs and now he is talking nonsense and can't stay awake.", {"emergency": True, "sign": 3}),
165
+ ("I broke my wrist skiing three years ago and it still aches when it rains.", {"emergency": False, "sign": 0}),
166
+ ("There is a piece of food stuck in my wife's throat and she can't get any air in.", {"emergency": True, "sign": 5}),
167
+ ("I have had dry, flaky skin on my elbows for a few months.", {"emergency": False, "sign": 0}),
168
+ ("My aunt had a heart attack in 2019. I want to know which doctor can check my own heart.", {"emergency": False, "sign": 0}),
169
+ ("These exams are killing me and I can't sleep.", {"emergency": False, "sign": 0}),
170
+ ]
171
+
172
+
173
+ class QwenExplainer:
174
+ """Writes the reason and the questions with Qwen2.5-1.5B-Instruct, used as downloaded.
175
+
176
+ It sees only the concern text and the doctor type the router chose. Its output is
177
+ checked by check_generated; anything that fails is dropped and the template is used.
178
+ """
179
+
180
+ name = "Qwen2.5-1.5B-Instruct"
181
+
182
+ def __init__(self):
183
+ import torch
184
+ from transformers import AutoModelForCausalLM, AutoTokenizer
185
+
186
+ self.torch = torch
187
+ self.device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
188
+ dtype = torch.float32 if self.device == "cpu" else torch.float16
189
+ self.tokenizer = AutoTokenizer.from_pretrained(QWEN["repo"], revision=QWEN["revision"])
190
+ self.model = AutoModelForCausalLM.from_pretrained(QWEN["repo"], revision=QWEN["revision"], dtype=dtype).to(self.device).eval()
191
+
192
+ def _chat(self, messages: list[dict], max_new_tokens: int, sample: bool = False) -> str:
193
+ inputs = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(self.device)
194
+ settings = {"do_sample": True, "temperature": 0.7, "top_p": 0.9} if sample else {"do_sample": False}
195
+ with self.torch.inference_mode():
196
+ output = self.model.generate(**inputs, max_new_tokens=max_new_tokens, pad_token_id=self.tokenizer.eos_token_id, **settings)
197
+ return self.tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
198
+
199
+ def emergency_sign(self, text: str) -> dict | None:
200
+ """A second emergency check for wording the written rules don't cover.
201
+
202
+ Returns a flag naming the published warning sign the model matched, or None.
203
+ A reply that can't be read counts as no flag: the rules have already run.
204
+ """
205
+ signs = "\n".join(f"{number}. {sign}" for number, (sign, _) in enumerate(WARNING_SIGNS, start=1))
206
+ messages = [{"role": "system", "content": _SAFETY_SYSTEM.format(signs=signs)}]
207
+ for example, reply in _SAFETY_EXAMPLES:
208
+ messages += [{"role": "user", "content": example}, {"role": "assistant", "content": json.dumps(reply)}]
209
+ messages.append({"role": "user", "content": text[:1500]})
210
+ match = re.search(r"\{.*?\}", self._chat(messages, max_new_tokens=24), re.DOTALL)
211
+ try:
212
+ reply = json.loads(match.group(0)) if match else {}
213
+ except json.JSONDecodeError:
214
+ return None
215
+ if reply.get("emergency") is not True:
216
+ return None
217
+ number = reply.get("sign")
218
+ sign, source = WARNING_SIGNS[number - 1] if isinstance(number, int) and 1 <= number <= len(WARNING_SIGNS) else ("a warning sign", WARNING_SIGNS[0][1])
219
+ return {"rule": "language-model check", "matched": "", "sign": sign, "source": source[0], "url": source[1]}
220
+
221
+ def _generate(self, record: dict, label: str, sample: bool) -> str:
222
+ request = {"concern": record["text"][:1500], "doctor": "a GP" if label == GP else label, "covers": SCOPE[label]}
223
+ messages = [{"role": "system", "content": _SYSTEM}]
224
+ for example_request, example_reply in _EXAMPLES:
225
+ messages += [{"role": "user", "content": json.dumps(example_request)},
226
+ {"role": "assistant", "content": json.dumps(example_reply)}]
227
+ messages.append({"role": "user", "content": json.dumps(request)})
228
+ return self._chat(messages, max_new_tokens=200, sample=sample)
229
+
230
+ def __call__(self, record: dict) -> str | None:
231
+ """Markdown for a routed record, or None when two attempts both fail the checks."""
232
+ paragraphs, lead_label = _lead(record)
233
+ allowed = [lead_label] # the reason may only mention the doctor it is written for
234
+ for sample in (False, True): # a greedy try, then one sampled retry
235
+ raw = self._generate(record, lead_label, sample)
236
+ match = re.search(r"\{.*\}", raw, re.DOTALL)
237
+ try:
238
+ parsed = json.loads(match.group(0)) if match else None
239
+ except json.JSONDecodeError:
240
+ parsed = None
241
+ if not check_generated(parsed, allowed):
242
+ return "\n\n".join([*paragraphs, parsed["why"].strip(), _questions_block([q.strip() for q in parsed["questions"]])])
243
+ return None
doccompass/gold.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn our two label files into one gold label per post, with its split.
2
+
3
+ The 60 test posts we both label give Cohen's κ. Where we agree, that label stands; where we
4
+ disagree, the post waits for the label we agree on in data/manual/adjudicated.labels.csv.
5
+ """
6
+
7
+ import hashlib
8
+
9
+ import pandas as pd
10
+ from sklearn.metrics import cohen_kappa_score
11
+
12
+ from .labels import EMERGENCY, SKIP, URGENCY
13
+
14
+ DEV_DRAW = 75 # random train posts set aside as dev candidates; about 50 survive the skips and emergencies
15
+
16
+
17
+ def annotators(pool: pd.DataFrame) -> list[str]:
18
+ return sorted(set("+".join(pool["annotators"]).split("+")))
19
+
20
+
21
+ def _rank(post_id: str) -> str:
22
+ """A fixed order that doesn't depend on how far labelling has got."""
23
+ return hashlib.sha256(post_id.encode()).hexdigest()
24
+
25
+
26
+ def dev_candidates(pool: pd.DataFrame) -> set[str]:
27
+ """The dev posts: the first DEV_DRAW random train posts in a fixed order.
28
+
29
+ Taken from the random draw only, so cutoffs tuned on dev see the same label mix as test.
30
+ """
31
+ random_train = pool[(pool["part"] == "trainval") & (pool["draw"] == "random")]["id"]
32
+ return set(sorted(random_train, key=_rank)[:DEV_DRAW])
33
+
34
+
35
+ def agreement(first: pd.DataFrame, second: pd.DataFrame) -> dict:
36
+ """Agreement on the primary label for posts both of us labelled. Frames are indexed by id."""
37
+ shared = first.index.intersection(second.index)
38
+ a, b = first.loc[shared], second.loc[shared]
39
+ exact = a["primary"] == b["primary"]
40
+ lenient = exact | (a["primary"] == b["alternate"]) | (b["primary"] == a["alternate"])
41
+ result = {"n": len(shared), "exact": float(exact.mean()) if len(shared) else float("nan"),
42
+ "lenient": float(lenient.mean()) if len(shared) else float("nan"), "kappa": float("nan"),
43
+ "disagreements": list(zip(shared[~exact], a["primary"][~exact], b["primary"][~exact]))}
44
+ if len(shared) >= 2 and len(set(a["primary"]) | set(b["primary"])) > 1:
45
+ result["kappa"] = float(cohen_kappa_score(a["primary"], b["primary"]))
46
+ return result
47
+
48
+
49
+ def _combine(rows: list[pd.Series]) -> dict:
50
+ """Two agreeing labels as one: keep any alternate, the more urgent tier, and any ambiguous tick."""
51
+ primary = rows[0]["primary"]
52
+ alternate = next((r["alternate"] for r in rows if r["alternate"] and r["alternate"] != primary), "")
53
+ tiers = [r["urgency"] for r in rows if r["urgency"] in URGENCY]
54
+ return {"primary": primary, "alternate": alternate,
55
+ "urgency": max(tiers, key=URGENCY.index) if tiers else "",
56
+ "ambiguous": str(any(r["ambiguous"] == "True" for r in rows))}
57
+
58
+
59
+ def merge(pool: pd.DataFrame, labels: dict[str, pd.DataFrame], adjudicated: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
60
+ """Return (gold, unresolved).
61
+
62
+ gold has one row per labelled post: id, split, primary, alternate, urgency, ambiguous,
63
+ source, changed_from_draft. split is test, dev or train for router labels, and emergency or
64
+ skip otherwise. unresolved lists shared posts where we disagree and have no agreed label yet.
65
+ """
66
+ dev = dev_candidates(pool)
67
+ agreed = adjudicated[adjudicated["primary"] != ""] if len(adjudicated) else adjudicated
68
+ gold, unresolved = [], []
69
+ for post in pool.itertuples():
70
+ names = post.annotators.split("+")
71
+ rows = [labels[name].loc[post.id] for name in names if name in labels and post.id in labels[name].index]
72
+ if len(rows) < len(names): # not labelled yet, or a shared post only one of us has done
73
+ continue
74
+ if len(rows) == 1:
75
+ final, source = _combine(rows), "single"
76
+ elif rows[0]["primary"] == rows[1]["primary"]:
77
+ final, source = _combine(rows), "agreed"
78
+ elif post.id in agreed.index:
79
+ row = agreed.loc[post.id]
80
+ final, source = {key: row[key] for key in ("primary", "alternate", "urgency", "ambiguous")}, "adjudicated"
81
+ else:
82
+ unresolved.append({"id": post.id, **{f"{name}_{key}": labels[name].loc[post.id][key]
83
+ for name in names for key in ("primary", "alternate")}})
84
+ continue
85
+ if final["primary"] == SKIP:
86
+ split = "skip"
87
+ elif final["primary"] == EMERGENCY:
88
+ split = "emergency"
89
+ elif post.part == "test":
90
+ split = "test"
91
+ else:
92
+ split = "dev" if post.id in dev else "train"
93
+ changed = [r.get("changed_from_draft", "") for r in rows if r.get("draft_primary", "")]
94
+ gold.append({"id": post.id, "part": post.part, "split": split, **final, "source": source,
95
+ "changed_from_draft": str(any(c == "True" for c in changed)) if changed else ""})
96
+ columns = ["id", "part", "split", "primary", "alternate", "urgency", "ambiguous", "source", "changed_from_draft"]
97
+ return pd.DataFrame(gold, columns=columns), pd.DataFrame(unresolved)
doccompass/labels.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The one label list. Every dataset and model converts labels through this module."""
2
+
3
+ SPECIALTIES = [
4
+ "Dermatology",
5
+ "Orthopedics",
6
+ "ENT",
7
+ "Gastroenterology",
8
+ "Neurology",
9
+ "Urology",
10
+ "Ob-Gyn",
11
+ "Mental health",
12
+ "Cardiology",
13
+ "Eye care",
14
+ "Dentistry",
15
+ ]
16
+ GP = "Start with a GP"
17
+
18
+ # Router classes. The order fixes each label's integer id; append only.
19
+ LABELS = SPECIALTIES + [GP]
20
+ LABEL2ID = {label: i for i, label in enumerate(LABELS)}
21
+
22
+ # Used while labelling only; never router classes.
23
+ EMERGENCY = "Emergency" # handled by the red-flag rules before the router runs
24
+ SKIP = "Skip" # not a "which doctor" question
25
+ ANNOTATION_CHOICES = LABELS + [EMERGENCY, SKIP]
26
+ URGENCY = ["routine", "soon", "emergency"]
27
+
28
+ # What each label covers, in plain words. Shown to users and used in the labelling guideline.
29
+ SCOPE = {
30
+ "Dermatology": "skin, hair and nails",
31
+ "Orthopedics": "bones, joints, muscles, the back and neck, and sports injuries",
32
+ "ENT": "ears, nose, throat and sinuses",
33
+ "Gastroenterology": "the stomach, bowel, digestion and liver",
34
+ "Neurology": "headaches, numbness or tingling, seizures and memory",
35
+ "Urology": "urinary problems and male sexual or reproductive health",
36
+ "Ob-Gyn": "periods, pregnancy and female reproductive health",
37
+ "Mental health": "mood, anxiety, eating and addiction",
38
+ "Cardiology": "the heart, palpitations and blood pressure",
39
+ "Eye care": "vision and eye problems",
40
+ "Dentistry": "teeth, gums and the mouth",
41
+ GP: "problems with no clear single cause, and anything that normally needs a referral",
42
+ }
doccompass/mediq.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The post pool: unique real posts from MediQ_AskDocs."""
2
+
3
+ import html
4
+ import json
5
+ import re
6
+
7
+ import pandas as pd
8
+ from huggingface_hub import hf_hub_download
9
+
10
+ # Pinned so everyone builds the same pool.
11
+ MEDIQ = {"repo_id": "stellalisy/MediQ_AskDocs", "revision": "f215fd4d70e15298d71ae56330ac349c5720e0bf"}
12
+ MEDIQ_FILES = [f"original/{split}.jsonl" for split in ("train", "validation", "test")] # skips synthetic/
13
+
14
+ _HANDLE = re.compile(r"/?\bu/[\w-]+")
15
+ _URL = re.compile(r"https?://\S+|www\.\S+")
16
+
17
+
18
+ def clean_text(text: str) -> str:
19
+ """Drop Reddit handles, links and HTML entities; tidy whitespace but keep line breaks."""
20
+ text = html.unescape(text).replace("​", " ")
21
+ text = _URL.sub(" ", _HANDLE.sub(" ", text))
22
+ text = re.sub(r"[ \t]+", " ", text)
23
+ return re.sub(r"\s*\n\s*", "\n", text).strip()
24
+
25
+
26
+ def dedupe_key(text: str) -> str:
27
+ """Two posts are the same post if they match after lower-casing and dropping punctuation."""
28
+ return re.sub(r"\W+", " ", text.lower()).strip()
29
+
30
+
31
+ def load_mediq_posts() -> pd.DataFrame:
32
+ """Return unique posts as (id, text), sorted by id.
33
+
34
+ MediQ repeats each post once per doctor question, and some posts carry several ids,
35
+ so we keep one row per post text and its smallest id.
36
+ """
37
+ posts: dict[str, tuple[str, str]] = {}
38
+ for name in MEDIQ_FILES:
39
+ path = hf_hub_download(repo_type="dataset", filename=name, **MEDIQ)
40
+ with open(path, encoding="utf-8") as lines:
41
+ for line in lines:
42
+ row = json.loads(line)
43
+ text = clean_text(row["messages"][0]["content"])
44
+ post_id = row["id"].split("-")[0]
45
+ key = dedupe_key(text)
46
+ if key not in posts or post_id < posts[key][0]:
47
+ posts[key] = (post_id, text)
48
+ return pd.DataFrame(sorted(posts.values()), columns=["id", "text"])
doccompass/metrics.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scores we report for a router, with exact intervals for small test sets."""
2
+
3
+ import numpy as np
4
+ from scipy.stats import beta
5
+ from sklearn.metrics import f1_score
6
+
7
+ from .labels import LABELS
8
+
9
+
10
+ def exact_interval(correct: int, total: int, level: float = 0.95) -> tuple[float, float]:
11
+ """Clopper-Pearson interval for a proportion; stays honest at 0% and 100%."""
12
+ alpha = 1 - level
13
+ low = 0.0 if correct == 0 else float(beta.ppf(alpha / 2, correct, total - correct + 1))
14
+ high = 1.0 if correct == total else float(beta.ppf(1 - alpha / 2, correct + 1, total - correct))
15
+ return low, high
16
+
17
+
18
+ def top_k_hits(proba: np.ndarray, label_ids, k: int) -> np.ndarray:
19
+ """True where the right label is among the k most probable."""
20
+ top = np.argsort(-proba, axis=1)[:, :k]
21
+ return (top == np.asarray(label_ids)[:, None]).any(axis=1)
22
+
23
+
24
+ def score(proba: np.ndarray, label_ids) -> dict:
25
+ """Top-1 and top-3 accuracy with intervals, and macro-F1 over all labels."""
26
+ label_ids = np.asarray(label_ids)
27
+ total = len(label_ids)
28
+ result = {"n": total}
29
+ for k in (1, 3):
30
+ correct = int(top_k_hits(proba, label_ids, k).sum())
31
+ low, high = exact_interval(correct, total)
32
+ result[f"top{k}"] = correct / total
33
+ result[f"top{k}_ci"] = (low, high)
34
+ result["macro_f1"] = float(f1_score(label_ids, proba.argmax(axis=1), labels=range(len(LABELS)), average="macro", zero_division=0))
35
+ return result
36
+
37
+
38
+ def describe(name: str, result: dict) -> str:
39
+ low1, high1 = result["top1_ci"]
40
+ return (f"{name}: top-1 {result['top1']:.1%} (95% CI {low1:.1%}-{high1:.1%}), "
41
+ f"top-3 {result['top3']:.1%}, macro-F1 {result['macro_f1']:.3f}, n={result['n']}")
doccompass/paths.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Where local data lives. Everything under data/ except label and id files stays out of git."""
2
+
3
+ from pathlib import Path
4
+
5
+ # absolute(), not resolve(): the Hugging Face cache stores files as symlinks, and following
6
+ # them would point ROOT at the cache's blob folder instead of the folder holding checkpoints/.
7
+ ROOT = Path(__file__).absolute().parents[1]
8
+ PUBLIC = ROOT / "data" / "public" # downloaded and derived public data
9
+ MANUAL = ROOT / "data" / "manual" # our pool and labels
10
+ MODELS = ROOT / "checkpoints"
11
+
12
+ MEDIQ_POSTS = PUBLIC / "mediq_posts.csv"
13
+ PATIENT_COMMENTS = PUBLIC / "patient_comments.csv"
14
+ POOL_IDS = MANUAL / "pool.ids.csv" # committed: which posts we label, and who labels them
15
+ POOL = MANUAL / "pool.csv" # local only: the same posts with their text
16
+ DRAFT_LABELS = MANUAL / "draft.labels.csv" # first-pass labels shown in the labelling tool
17
+ ADJUDICATED = MANUAL / "adjudicated.labels.csv" # committed: our agreed label where the two of us disagreed
18
+ GOLD = MANUAL / "gold.labels.csv" # committed: one label per post, with its split, written by scripts/merge_labels.py
19
+ EMERGENCY_CASES = ROOT / "data" / "synthetic" / "emergency_cases.csv" # written by us to test the emergency check
doccompass/patient_comments.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The public stage-1 training set: Patient Comments and Specialist Types, remapped to our labels.
2
+
3
+ Source: Mendeley Data, DOI 10.17632/2twgjzpn82.2, CC BY 4.0. Each comment has a symptom
4
+ category; CATEGORY_MAP sends each category to one of our labels, or drops it.
5
+
6
+ We use it for stage-1 training only; it is never the test set.
7
+ See docs/label-set.md for the reasoning behind each choice.
8
+ """
9
+
10
+ import hashlib
11
+ import re
12
+ import ssl
13
+ import urllib.request
14
+ from pathlib import Path
15
+
16
+ import certifi
17
+ import pandas as pd
18
+
19
+ from .labels import GP, LABELS
20
+ from .mediq import dedupe_key
21
+ from .paths import PUBLIC
22
+
23
+ _URL = "https://data.mendeley.com/public-files/datasets/2twgjzpn82/files/{file_id}/file_downloaded"
24
+ _FILES = { # name: (Mendeley file id, sha256). We ignore the source's own train/test split.
25
+ "HealthCare Data.xlsx": ("c6bdc6b5-c848-4570-a55f-aa522ecd4a4d", "d26f45970e538306125ff633f07a91344d09609355a311e2c3072766bbf66ca1"),
26
+ "Test_data.xlsx": ("b22a38f6-d8a9-4754-9cf2-4d6585a19ab2", "176866719dc580d8ccaeaba5a114f5b83c5848642da253d7c35001368555e155"),
27
+ }
28
+
29
+ DROP = None # category left out: about infants or the elderly, out of scope, or mixes in emergencies
30
+ CATEGORY_MAP = {
31
+ "Acne": "Dermatology", "Skin issue": "Dermatology", "Hair falling out": "Dermatology",
32
+ "Changes in Skin": "Dermatology", "Nails issue": "Dermatology",
33
+ "Knee pain": "Orthopedics", "Joint pain": "Orthopedics", "Shoulder pain": "Orthopedics",
34
+ "Muscle pain": "Orthopedics", "Back pain": "Orthopedics", "Neck pain": "Orthopedics",
35
+ "Injury from sports": "Orthopedics", "Foot ache": "Orthopedics", "Ankle pain": "Orthopedics",
36
+ "Foot pain": "Orthopedics", "Arthralgia": "Orthopedics",
37
+ "Ear ache": "ENT",
38
+ "Stomach ache": "Gastroenterology", "Liver issues": "Gastroenterology",
39
+ "Head ache": "Neurology", "Memory disturbance": "Neurology", "Difficulty speaking": "Neurology",
40
+ "Seizures": "Neurology", "Dementia": "Neurology", "Brain tumors": "Neurology",
41
+ "Urinary issue": "Urology", "Infertility in men": "Urology",
42
+ "Pregnancy issues": "Ob-Gyn", "Abnormal bleeding": "Ob-Gyn", "Infertility": "Ob-Gyn",
43
+ "Emotional pain": "Mental health", "Mood swing": "Mental health",
44
+ "Behavioral issues": "Mental health", "Addiction": "Mental health",
45
+ "Heart hurts": "Cardiology",
46
+ "Blurry vision": "Eye care", "Eye Infection": "Eye care",
47
+ "Bad breath": "Dentistry", "Toothache": "Dentistry",
48
+ "Cough": GP, "Feeling dizzy": GP, "Feeling cold": GP, "Body feels weak": GP,
49
+ "Hard to breath": GP, "Internal pain": GP, "Infected wound": GP, "Diabetes": GP,
50
+ "Blood related": GP, "Allergic reactions": GP, "Asthma": GP, "Lower back or pelvic pain": GP,
51
+ "Autoimmune diseases": GP, "Swelling": GP, "Unexplained Fever/Bruising": GP, "Persistent fatigue": GP,
52
+ "Open wound": DROP, "Vaccinations": DROP, "Growth issue": DROP, "Old age": DROP,
53
+ "Spinal cord injuries": DROP, "Face deformation": DROP, "Accidents": DROP,
54
+ "Neonatal infections": DROP, "Jaundice": DROP, "Premature birth": DROP,
55
+ "Movement problems": DROP, "Cardiac issues in newborns": DROP, "Burns": DROP,
56
+ }
57
+ assert set(CATEGORY_MAP.values()) <= set(LABELS) | {DROP}
58
+
59
+ _EMOJI = re.compile("[\U0001F000-\U0001FAFF☀-➿️‍]")
60
+
61
+
62
+ def _category_key(category: str) -> str:
63
+ """The source spells categories inconsistently ("mood swing", "Unexplained Fever/ Bruising")."""
64
+ return re.sub(r"\s+", "", str(category)).lower()
65
+
66
+
67
+ _MAP_BY_KEY = {_category_key(category): label for category, label in CATEGORY_MAP.items()}
68
+
69
+
70
+ def _download(name: str, folder: Path) -> Path:
71
+ """Fetch one source file if it isn't already there, and check its hash."""
72
+ path = folder / name
73
+ file_id, sha256 = _FILES[name]
74
+ if not path.exists():
75
+ folder.mkdir(parents=True, exist_ok=True)
76
+ context = ssl.create_default_context(cafile=certifi.where())
77
+ # Mendeley rejects Python's default user agent.
78
+ request = urllib.request.Request(_URL.format(file_id=file_id), headers={"User-Agent": "Mozilla/5.0"})
79
+ with urllib.request.urlopen(request, context=context, timeout=60) as response:
80
+ path.write_bytes(response.read())
81
+ if hashlib.sha256(path.read_bytes()).hexdigest() != sha256:
82
+ raise ValueError(f"{name} does not match its expected hash; delete it and run again.")
83
+ return path
84
+
85
+
86
+ def load_patient_comments() -> pd.DataFrame:
87
+ """Return unique comments as (text, label) in our label set, with emoji removed."""
88
+ folder = PUBLIC / "patient_comments_source"
89
+ rows = pd.concat([pd.read_excel(_download(name, folder)) for name in _FILES], ignore_index=True)
90
+ rows["label"] = rows["Patient_Category"].map(lambda category: _MAP_BY_KEY[_category_key(category)])
91
+ rows = rows.dropna(subset=["label"])
92
+ rows["text"] = rows["Patient_comment"].astype(str).map(lambda t: re.sub(r"\s+", " ", _EMOJI.sub("", t)).strip())
93
+ rows["key"] = rows["text"].map(dedupe_key)
94
+ # The same comment can sit under two categories; drop it when they map to different labels.
95
+ consistent = rows.groupby("key")["label"].transform("nunique") == 1
96
+ rows = rows[consistent & (rows["key"] != "")].drop_duplicates("key")
97
+ return rows[["text", "label"]].sort_values(["label", "text"]).reset_index(drop=True)
doccompass/pipeline.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One request, start to finish: red flags, scrub, route, explain.
2
+
3
+ route_concern always returns the same keys, whatever happens, so the interface never has
4
+ to guess what it received.
5
+ """
6
+
7
+ import os
8
+
9
+ from .explain import headline, template_explanation
10
+ from .labels import GP, LABELS
11
+ from .paths import MODELS
12
+ from .redflags import emergency_message, find_flags
13
+ from .router import EncoderRouter, TfidfRouter
14
+ from .scrub import scrub
15
+
16
+ # Cutoffs for the "unsure" state, tuned on our dev posts for biomedbert_gold (8 Oct;
17
+ # scripts/evaluate_routing.py tune). Other routers use the same values untuned.
18
+ TAU = 0.25 # top confidence below this is unsure
19
+ MARGIN = 0.05 # top two closer than this is unsure
20
+ MIN_WORDS, MAX_CHARS = 3, 6000
21
+
22
+
23
+ # Tried in order: routers trained on our posts by dev macro-F1 (8 Oct), then stage 1 (public data only).
24
+ ROUTER_ORDER = ["biomedbert_gold", "distilroberta_stage2", "biomedbert_stage2", "distilroberta_gold",
25
+ "tfidf_stage2", "tfidf_gold", "distilroberta_stage1", "biomedbert_stage1", "tfidf_stage1"]
26
+
27
+
28
+ def load_router(name: str | None = None):
29
+ """The first router that loads, or None if nothing has been trained yet.
30
+
31
+ Pass a name, or set DOCCOMPASS_ROUTER, to pick one. A fine-tuned router that fails to
32
+ load (for example PyTorch isn't installed) is skipped in favour of the next one.
33
+ """
34
+ name = name or os.environ.get("DOCCOMPASS_ROUTER")
35
+ for candidate in [name] if name else ROUTER_ORDER:
36
+ try:
37
+ if (MODELS / candidate).is_dir():
38
+ return EncoderRouter(MODELS / candidate)
39
+ if (MODELS / f"{candidate}.joblib").exists():
40
+ return TfidfRouter.load(MODELS / f"{candidate}.joblib")
41
+ except Exception:
42
+ continue
43
+ return None
44
+
45
+
46
+ def route_concern(text: str, router, explainer=None) -> dict:
47
+ result = {"status": "invalid", "message": "", "flags": [], "text": "", "removed": [],
48
+ "options": [], "unsure": False, "evidence": [], "headline": "", "explanation": "", "explained_by": ""}
49
+ text = (text or "").strip()
50
+ if len(text.split()) < MIN_WORDS:
51
+ result["message"] = "Describe what you are feeling in a sentence or two, and we'll suggest a kind of doctor."
52
+ return result
53
+ text = text[:MAX_CHARS]
54
+
55
+ # 1. Red flags run first, on the raw text. An emergency stops everything else.
56
+ # The written rules decide alone when they fire. When they don't, and a language model
57
+ # is loaded, it gets a second look for wording the rules can't match.
58
+ result["flags"] = find_flags(text)
59
+ if not result["flags"] and hasattr(explainer, "emergency_sign"):
60
+ try:
61
+ flag = explainer.emergency_sign(text)
62
+ except Exception:
63
+ flag = None
64
+ if flag:
65
+ result["flags"] = [flag]
66
+ if result["flags"]:
67
+ result["status"] = "emergency"
68
+ result["message"] = emergency_message(result["flags"])
69
+ return result
70
+
71
+ # 2. Optional scrub of obvious identifiers.
72
+ result["text"], result["removed"] = scrub(text)
73
+ result["status"] = "routed"
74
+
75
+ # 3. Route. Without a trained router the safe answer is a GP.
76
+ if router is None:
77
+ result["options"] = [{"label": GP, "confidence": 1.0}]
78
+ result["message"] = "The router isn't available right now, so we can only suggest starting with a GP."
79
+ else:
80
+ proba = router.predict_proba([result["text"]])[0]
81
+ top = proba.argsort()[::-1][:3]
82
+ result["options"] = [{"label": LABELS[i], "confidence": float(proba[i])} for i in top]
83
+ first, second = result["options"][0]["confidence"], result["options"][1]["confidence"]
84
+ result["unsure"] = first < TAU or first - second < MARGIN
85
+ best = result["options"][0]["label"]
86
+ if hasattr(router, "evidence") and best != GP and not result["unsure"]:
87
+ result["evidence"] = router.evidence(result["text"], best)
88
+
89
+ # 4. Explain, from the record above and nothing else. The template is the fallback
90
+ # whenever the language model is absent, fails, or writes something that fails its checks.
91
+ result["headline"] = headline(result)
92
+ result["explanation"], result["explained_by"] = template_explanation(result), "template"
93
+ if explainer is not None and router is not None:
94
+ try:
95
+ generated = explainer(result)
96
+ except Exception:
97
+ generated = None
98
+ if generated:
99
+ result["explanation"], result["explained_by"] = generated, explainer.name
100
+ return result
doccompass/redflags.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Emergency rules. They run first, on the raw text, and are written by hand, never learned.
2
+
3
+ Each rule quotes the warning sign it implements and where that sign is published.
4
+ Sources (read 4 Oct 2026):
5
+ - MedlinePlus, "Recognizing medical emergencies" (US National Library of Medicine)
6
+ - CDC, "Signs and Symptoms of Stroke"
7
+ """
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+
12
+ MEDLINEPLUS = ("MedlinePlus: Recognizing medical emergencies", "https://medlineplus.gov/ency/article/001927.htm")
13
+ CDC_STROKE = ("CDC: Signs and Symptoms of Stroke", "https://www.cdc.gov/stroke/signs-symptoms/index.html")
14
+
15
+ # Every adult warning sign on the two source pages, as published. The rules below cover the
16
+ # ones that can be matched by wording; the language-model check is given the whole list.
17
+ WARNING_SIGNS = [(sign, MEDLINEPLUS) for sign in (
18
+ "Bleeding that will not stop",
19
+ "Breathing problems (difficulty breathing, shortness of breath)",
20
+ "Change in mental status (such as unusual behavior, confusion, difficulty arousing)",
21
+ "Chest pain or discomfort lasting for two minutes or more",
22
+ "Choking",
23
+ "Coughing up or vomiting blood",
24
+ "Fainting or loss of consciousness",
25
+ "Feeling of committing suicide or murder",
26
+ "Head or spine injury",
27
+ "Inability to speak",
28
+ "Severe abdominal pain or pressure",
29
+ "Severe or persistent vomiting or diarrhea",
30
+ "Sudden injury from a motor vehicle accident, burns, smoke inhalation, near drowning, or a deep or large wound",
31
+ "Sudden, severe pain anywhere in the body",
32
+ "Sudden dizziness, weakness, or change in vision",
33
+ "Swallowing a poisonous substance",
34
+ "Swelling of the face, eyes, or tongue",
35
+ )] + [(sign, CDC_STROKE) for sign in (
36
+ "Sudden numbness or weakness in the face, arm, or leg, especially on one side",
37
+ "Sudden confusion, trouble speaking, or difficulty understanding speech",
38
+ "Sudden trouble seeing",
39
+ "Sudden trouble walking, dizziness, loss of balance, or lack of coordination",
40
+ "Sudden severe headache with no known cause",
41
+ )]
42
+
43
+ EMERGENCY_MESSAGE = "This may be an emergency. Call 911 or go to the nearest emergency room now."
44
+ CRISIS_MESSAGE = "You can also call or text 988 (Suicide & Crisis Lifeline), free and open at any time."
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Rule:
49
+ name: str
50
+ sign: str # the warning sign as the source words it
51
+ source: tuple[str, str] # (title, url)
52
+ pattern: re.Pattern
53
+
54
+
55
+ def _rule(name: str, sign: str, source: tuple[str, str], pattern: str) -> Rule:
56
+ return Rule(name, sign, source, re.compile(pattern, re.IGNORECASE))
57
+
58
+
59
+ _CANT = r"(?:can'?t|cannot|can not|unable to|couldn'?t)"
60
+
61
+ RULES = [
62
+ _rule("chest pain", "Chest pain or discomfort lasting for two minutes or more", MEDLINEPLUS,
63
+ r"\bchest (?:pain|pressure|tightness|discomfort)\b|\bpain in (?:my|the|his|her) chest\b"
64
+ r"|\bchest (?:hurts|is hurting|feels tight|feels heavy)\b"),
65
+ _rule("breathing", "Breathing problems (difficulty breathing, shortness of breath)", MEDLINEPLUS,
66
+ rf"\b(?:{_CANT}|can barely|barely able to|struggling to|hard to|trouble|difficulty) breath(?:e|ing)\b|\bshort(?:ness)? of breath\b|\bgasping for (?:air|breath)\b"),
67
+ _rule("stroke signs", "Sudden numbness or weakness in the face, arm, or leg; sudden confusion or trouble speaking", CDC_STROKE,
68
+ rf"\bface (?:is |was )?drooping\b|\bslurred speech\b|\b(?:{_CANT}|trouble) (?:speak|speaking|talk|talking)\b"
69
+ r"|\bsudden(?:ly)? (?:numb|weak|confus)\w*|\b(?:numb|weak)\w* on (?:one|the left|the right|my left|my right) side\b"
70
+ # the word itself, and one-sided or facial numbness, drooping or weakness
71
+ r"|\bstrokes?\b(?! of (?:luck|genius))"
72
+ r"|\bface (?:is |was |feels |went |has gone )?(?:numb|droopy|drooped|weak|paraly[sz]ed)\b"
73
+ r"|\bfacial (?:droop\w*|paralysis|numbness|weakness)\b"
74
+ r"|\b(?:left|right|one|half|side) (?:side )?of (?:my|the|his|her) (?:face|body)\b[^.!?]{0,25}\b(?:numb|droop\w*|weak|paraly[sz]ed|tingl\w*)"),
75
+ _rule("bleeding", "Bleeding that will not stop; coughing up or vomiting blood", MEDLINEPLUS,
76
+ rf"\bbleeding (?:that )?(?:won'?t|will not|doesn'?t|does not) stop\b|\b{_CANT} stop (?:the )?bleeding\b"
77
+ r"|\b(?:coughing|coughed|vomiting|vomited|throwing|threw) up blood\b"),
78
+ _rule("loss of consciousness", "Fainting or loss of consciousness", MEDLINEPLUS,
79
+ r"\b(?:passed out|fainted|lost consciousness|unconscious|unresponsive)\b"),
80
+ _rule("suicidal thoughts", "Feeling of committing suicide or murder", MEDLINEPLUS,
81
+ r"\bsuicid\w*|\bkill(?:ing)? myself\b|\bend(?:ing)? my (?:own )?life\b|\bwant(?:ed)? to die\b|\bdon'?t want to (?:live|be alive)\b"
82
+ r"|\bend(?:ing)? it all\b|\btake my (?:own )?life\b"),
83
+ _rule("face or throat swelling", "Swelling of the face, eyes, or tongue", MEDLINEPLUS,
84
+ r"\b(?:throat|tongue|lips?|face) (?:is |are |was |were )?(?:swelling|swollen|closing)\b"
85
+ r"|\bswelling (?:of|in) (?:my |the )?(?:face|tongue|throat|lips?)\b|\banaphyla\w*"),
86
+ _rule("head or spine injury", "Head or spine injury", MEDLINEPLUS,
87
+ r"\b(?:hit|banged|bumped|struck|cracked) (?:my|his|her|the) head\b|\b(?:head|spine|spinal) injury\b"),
88
+ _rule("poisoning or overdose", "Swallowing poisonous substances", MEDLINEPLUS,
89
+ r"\boverdos\w*|(?<!food )\bpoison(?:ed|ing)\b|\b(?:swallowed|drank|ingested) (?:bleach|poison|detergent|antifreeze)\b"),
90
+ _rule("sudden severe pain", "Sudden, severe pain anywhere in the body; sudden severe headache with no known cause", MEDLINEPLUS,
91
+ r"\bsudden(?:ly)?\b[^.!?]{0,40}\b(?:severe|excruciating|unbearable|worst)\b[^.!?]{0,25}\b(?:pain|headache)\b"
92
+ r"|\bworst (?:headache|pain) (?:of my life|ever)\b"),
93
+ _rule("sudden vision change", "Sudden trouble seeing", CDC_STROKE,
94
+ rf"\bsudden(?:ly)? (?:lost|loss of|blurred|blurry|double) vision\b|\bsuddenly {_CANT} see\b|\bsudden(?:ly)? (?:went )?blind\b"),
95
+ ]
96
+
97
+ # A match is ignored when a negation governs it: "no chest pain", "I don't want to die",
98
+ # "never had any trouble breathing". Only short filler words may sit between the two, so
99
+ # "not sure why my chest pain started" and "I don't know why but my chest hurts" still flag.
100
+ _NEGATION = re.compile(
101
+ r"\b(?:no|not|never|without|denies|deny|didn'?t|don'?t|doesn'?t|haven'?t|hasn'?t|isn'?t|wasn'?t)"
102
+ r"(?:\s+(?:have|had|has|having|got|get|getting|any|a|an|the|real|really|much|more|been|"
103
+ r"experienced|experiencing|feel|felt|noticed|want|wanted|to|this|that|such)){0,4}\s*$", re.IGNORECASE)
104
+
105
+
106
+ def find_flags(text: str) -> list[dict]:
107
+ """Every rule that fires, with the words that triggered it."""
108
+ flags = []
109
+ for rule in RULES:
110
+ for match in rule.pattern.finditer(text):
111
+ if _NEGATION.search(text[max(0, match.start() - 60):match.start()]):
112
+ continue
113
+ flags.append({"rule": rule.name, "matched": match.group(0), "sign": rule.sign,
114
+ "source": rule.source[0], "url": rule.source[1]})
115
+ break
116
+ return flags
117
+
118
+
119
+ def emergency_message(flags: list[dict]) -> str:
120
+ message = EMERGENCY_MESSAGE
121
+ if any("suicide" in flag["sign"].lower() for flag in flags):
122
+ message += " " + CRISIS_MESSAGE
123
+ return message
doccompass/router.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routers: text in, one probability per label out (columns in LABELS order)."""
2
+
3
+ from pathlib import Path
4
+
5
+ import joblib
6
+ import numpy as np
7
+ from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS, TfidfVectorizer
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.pipeline import make_pipeline
10
+
11
+ from .labels import LABEL2ID, LABELS
12
+
13
+
14
+ _FILLER = ENGLISH_STOP_WORDS | {"feel", "feeling", "feels", "felt", "like", "really", "just", "got", "getting", "having", "week", "weeks", "month", "months", "day", "days"}
15
+
16
+
17
+ class TfidfRouter:
18
+ """The trained-from-scratch router: TF-IDF features and logistic regression."""
19
+
20
+ def __init__(self, C: float = 10.0):
21
+ self.pipeline = make_pipeline(
22
+ TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True, strip_accents="unicode"),
23
+ LogisticRegression(C=C, max_iter=2000, class_weight="balanced"),
24
+ )
25
+
26
+ def fit(self, texts, labels, sample_weight=None) -> "TfidfRouter":
27
+ ids = [LABEL2ID[label] for label in labels]
28
+ self.pipeline.fit(list(texts), ids, logisticregression__sample_weight=sample_weight)
29
+ return self
30
+
31
+ def predict_proba(self, texts) -> np.ndarray:
32
+ """Probabilities with one column per label, zero for any label unseen in training."""
33
+ seen = self.pipeline.predict_proba(list(texts))
34
+ proba = np.zeros((seen.shape[0], len(LABELS)))
35
+ proba[:, self.pipeline.classes_] = seen
36
+ return proba
37
+
38
+ def evidence(self, text: str, label: str, k: int = 3) -> list[str]:
39
+ """The words in the text that pushed hardest toward this label."""
40
+ vectorizer, model = self.pipeline[0], self.pipeline[-1]
41
+ classes = list(model.classes_)
42
+ if LABEL2ID[label] not in classes:
43
+ return []
44
+ weighted = vectorizer.transform([text]).multiply(model.coef_[classes.index(LABEL2ID[label])]).tocoo()
45
+ names = vectorizer.get_feature_names_out()
46
+ words: list[str] = []
47
+ for i in np.argsort(-weighted.data):
48
+ if weighted.data[i] <= 0 or len(words) == k:
49
+ break
50
+ # Keep the meaningful words of the feature: "my ears" -> "ears"; skip pure filler.
51
+ content = " ".join(w for w in names[weighted.col[i]].split() if len(w) > 2 and w not in _FILLER)
52
+ if content and not any(content in seen or seen in content for seen in words):
53
+ words.append(content)
54
+ return words
55
+
56
+ def save(self, path: Path) -> None:
57
+ path.parent.mkdir(parents=True, exist_ok=True)
58
+ joblib.dump(self.pipeline, path)
59
+
60
+ @classmethod
61
+ def load(cls, path: Path) -> "TfidfRouter":
62
+ router = cls()
63
+ router.pipeline = joblib.load(path)
64
+ return router
65
+
66
+
67
+ class EncoderRouter:
68
+ """A fine-tuned encoder router, loaded from a folder written by scripts/train_encoder.py."""
69
+
70
+ def __init__(self, folder: Path, max_length: int = 512, batch_size: int = 32):
71
+ import torch # imported here so the from-scratch router works without PyTorch installed
72
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
73
+
74
+ self.torch = torch
75
+ self.device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
76
+ self.tokenizer = AutoTokenizer.from_pretrained(folder)
77
+ self.model = AutoModelForSequenceClassification.from_pretrained(folder).to(self.device).eval()
78
+ if [self.model.config.id2label[i] for i in range(len(LABELS))] != LABELS:
79
+ raise ValueError(f"{folder} was trained with a different label list.")
80
+ self.max_length, self.batch_size = max_length, batch_size
81
+
82
+ def predict_proba(self, texts) -> np.ndarray:
83
+ texts = list(texts)
84
+ chunks = []
85
+ with self.torch.inference_mode():
86
+ for start in range(0, len(texts), self.batch_size):
87
+ batch = self.tokenizer(texts[start:start + self.batch_size], truncation=True, max_length=self.max_length,
88
+ padding=True, return_tensors="pt").to(self.device)
89
+ chunks.append(self.torch.softmax(self.model(**batch).logits, dim=-1).float().cpu().numpy())
90
+ return np.concatenate(chunks)
doccompass/scrub.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional scrub: remove obvious identifiers with simple rules and report what was removed.
2
+
3
+ This is not full redaction. It only catches handles, emails, phone numbers and links.
4
+ """
5
+
6
+ import re
7
+
8
+ _PATTERNS = [ # order matters: emails before handles, links before phone numbers
9
+ ("email", re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")),
10
+ ("link", re.compile(r"https?://\S+|www\.\S+")),
11
+ ("handle", re.compile(r"(?<!\w)/?u/[\w-]+|(?<!\w)@\w{2,}")),
12
+ ("phone", re.compile(r"(?<!\d)(?:\+?\d{1,2}[\s.-]?)?(?:\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}(?!\d)")),
13
+ ]
14
+
15
+
16
+ def scrub(text: str) -> tuple[str, list[dict]]:
17
+ """Return the text with identifiers replaced by [kind], and the list of what was removed."""
18
+ removed = []
19
+ for kind, pattern in _PATTERNS:
20
+ def replace(match, kind=kind):
21
+ removed.append({"kind": kind, "text": match.group(0)})
22
+ return f"[{kind}]"
23
+ text = pattern.sub(replace, text)
24
+ return text, removed
doccompass/splits.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed splits, so every router is trained and scored on the same rows."""
2
+
3
+ import pandas as pd
4
+ from sklearn.model_selection import train_test_split
5
+
6
+ from .paths import GOLD, PATIENT_COMMENTS, POOL
7
+
8
+ SEED = 24679
9
+
10
+
11
+ def public_split() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
12
+ """Patient Comments as (train, val, held_out): about 76.5% / 8.5% / 15%, stratified by label.
13
+
14
+ val picks the best epoch when fine-tuning; held_out is only ever scored.
15
+ """
16
+ comments = pd.read_csv(PATIENT_COMMENTS)
17
+ rest, held_out = train_test_split(comments, test_size=0.15, stratify=comments["label"], random_state=SEED)
18
+ train, val = train_test_split(rest, test_size=0.10, stratify=rest["label"], random_state=SEED)
19
+ return train, val, held_out
20
+
21
+
22
+ def gold_split() -> dict[str, pd.DataFrame]:
23
+ """Our labelled posts as {"train", "dev", "test", "emergency"}, each with text and labels.
24
+
25
+ Built from data/manual/gold.labels.csv (scripts/merge_labels.py) and the local post text.
26
+ Skip posts are left out; Emergency posts are kept apart to test the emergency check.
27
+ """
28
+ gold = pd.read_csv(GOLD, dtype=str).fillna("")
29
+ text = pd.read_csv(POOL, usecols=["id", "text"], dtype=str)
30
+ gold = gold.merge(text, on="id", how="left", validate="one_to_one").rename(columns={"primary": "label"})
31
+ if gold["text"].isna().any():
32
+ raise ValueError("Some labelled posts have no text; run scripts/prepare_data.py first.")
33
+ return {split: gold[gold["split"] == split].reset_index(drop=True) for split in ("train", "dev", "test", "emergency")}
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data prep, the from-scratch router, the labelling tool and the app.
2
+ pandas==3.0.6
3
+ scikit-learn==1.9.1
4
+ joblib==1.6.0
5
+ scipy==1.18.1
6
+ openpyxl==3.1.5
7
+ huggingface_hub==1.33.0
8
+ certifi
9
+ gradio==6.28.0
10
+ # The fine-tuned routers. The app falls back to the from-scratch router without these.
11
+ torch==2.14.1
12
+ transformers==5.18.0
13
+ accelerate==1.15.0
14
+ pytest==9.1.1