Gregory-L commited on
Commit
6fc53e8
·
verified ·
1 Parent(s): 19ba89e

copy + .txt export on every answer; physiotherapy/sports-therapy and psychotherapy modes; physio datasets

Browse files
app/data/catalogue.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "version": "2.0.0",
3
- "built": "2026-11-25T23:25:02Z",
4
  "models": [
5
  {
6
  "id": "openai/gpt-oss-120b",
@@ -703,6 +703,96 @@
703
  "likes": 60,
704
  "size": null,
705
  "pretty": "PubMedQA"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
706
  }
707
  ],
708
  "router_open": {
@@ -746,6 +836,18 @@
746
  ],
747
  "vision": true
748
  },
 
 
 
 
 
 
 
 
 
 
 
 
749
  "deepseek-ai/DeepSeek-V4.1-Flash-1017": {
750
  "licence": "mit",
751
  "providers": [
@@ -785,17 +887,6 @@
785
  ],
786
  "vision": true
787
  },
788
- "thinkingmachines/Inkling-2-Small": {
789
- "licence": "apache-2.0",
790
- "providers": [
791
- "cloudflare",
792
- "deepinfra",
793
- "modal",
794
- "primeintellect",
795
- "together"
796
- ],
797
- "vision": true
798
- },
799
  "thinkingmachines/Inkling": {
800
  "licence": "apache-2.0",
801
  "providers": [
@@ -835,29 +926,29 @@
835
  ],
836
  "vision": true
837
  },
838
- "google/gemma-4-26B-A4B-it": {
839
  "licence": "apache-2.0",
840
  "providers": [
841
  "akashml",
842
- "cloudflare",
843
  "coreweave",
844
  "deepinfra",
845
- "google-vertex",
846
- "io-net",
847
- "makora",
848
- "nextbit",
849
- "parasail",
850
  "primeintellect",
851
  "venice"
852
  ],
853
  "vision": true
854
  },
855
- "Qwen/Qwen3.6-35B-A3B": {
856
  "licence": "apache-2.0",
857
  "providers": [
858
  "akashml",
 
859
  "coreweave",
860
  "deepinfra",
 
 
 
 
 
861
  "primeintellect",
862
  "venice"
863
  ],
@@ -903,6 +994,7 @@
903
  "crusoe",
904
  "deepinfra",
905
  "digitalocean",
 
906
  "google-vertex",
907
  "groq",
908
  "mancer",
@@ -936,7 +1028,6 @@
936
  "modelrun",
937
  "nextbit",
938
  "parasail",
939
- "primeintellect",
940
  "sambanova",
941
  "venice"
942
  ],
@@ -958,6 +1049,7 @@
958
  "amazon-bedrock",
959
  "coreweave",
960
  "deepinfra",
 
961
  "parasail",
962
  "primeintellect"
963
  ],
@@ -1000,13 +1092,6 @@
1000
  ],
1001
  "vision": false
1002
  },
1003
- "zai-org/GLM-4.7-Flash": {
1004
- "licence": "mit",
1005
- "providers": [
1006
- "cloudflare"
1007
- ],
1008
- "vision": false
1009
- },
1010
  "Qwen/Qwen3-Coder-Next": {
1011
  "licence": "apache-2.0",
1012
  "providers": [
@@ -1022,6 +1107,7 @@
1022
  "coreweave",
1023
  "deepinfra",
1024
  "digitalocean",
 
1025
  "mancer",
1026
  "nebius",
1027
  "parasail",
@@ -1039,6 +1125,13 @@
1039
  ],
1040
  "vision": false
1041
  },
 
 
 
 
 
 
 
1042
  "XiaomiMiMo/MiMo-V2.6-Pro-RL": {
1043
  "licence": "mit",
1044
  "providers": [
@@ -1071,6 +1164,13 @@
1071
  ],
1072
  "vision": false
1073
  },
 
 
 
 
 
 
 
1074
  "thinkingmachines/Inkling-Small": {
1075
  "licence": "apache-2.0",
1076
  "providers": [
@@ -1078,17 +1178,17 @@
1078
  ],
1079
  "vision": true
1080
  },
1081
- "XiaomiMiMo/MiMo-V2.6-Flash-MOPD": {
1082
- "licence": "mit",
1083
  "providers": [
1084
- "featherless-ai"
1085
  ],
1086
  "vision": false
1087
  },
1088
- "Qwen/Qwen2.5-Coder-32B-Instruct": {
1089
- "licence": "apache-2.0",
1090
  "providers": [
1091
- "cloudflare"
1092
  ],
1093
  "vision": false
1094
  },
@@ -1187,7 +1287,8 @@
1187
  "Qwen/Qwen3-32B": {
1188
  "licence": "apache-2.0",
1189
  "providers": [
1190
- "deepinfra"
 
1191
  ],
1192
  "vision": false
1193
  },
@@ -1326,7 +1427,9 @@
1326
  },
1327
  "deepseek-ai/DeepSeek-V3-0324": {
1328
  "licence": "mit",
1329
- "providers": [],
 
 
1330
  "vision": false
1331
  },
1332
  "Qwen/Qwen3-VL-235B-A22B-Instruct": {
 
1
  {
2
  "version": "2.0.0",
3
+ "built": "2026-11-26T00:09:01Z",
4
  "models": [
5
  {
6
  "id": "openai/gpt-oss-120b",
 
703
  "likes": 60,
704
  "size": null,
705
  "pretty": "PubMedQA"
706
+ },
707
+ {
708
+ "id": "serhanayberkkilic/physiotherapy-evidence-qa",
709
+ "role": "physiotherapy",
710
+ "note": "Physiotherapy questions answered from systematic reviews and meta-analyses (EN/TR).",
711
+ "licence": "cc-by-4.0",
712
+ "downloads": 89,
713
+ "likes": 4,
714
+ "size": "100K<n<1M",
715
+ "pretty": "Physiotherapy Evidence QA"
716
+ },
717
+ {
718
+ "id": "Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment",
719
+ "role": "rehabilitation",
720
+ "note": "Musculoskeletal and neuro rehabilitation assessments with consultation dialogues.",
721
+ "licence": "mit",
722
+ "downloads": 61,
723
+ "likes": 0,
724
+ "size": "1K<n<10K",
725
+ "pretty": null
726
+ },
727
+ {
728
+ "id": "hammamwahab/fitness-qa",
729
+ "role": "sports & fitness",
730
+ "note": "Fitness, training and exercise-physiology Q&A.",
731
+ "licence": "apache-2.0",
732
+ "downloads": 55,
733
+ "likes": 4,
734
+ "size": "100K<n<1M",
735
+ "pretty": null
736
+ },
737
+ {
738
+ "id": "Martjn/calisthenics_exercises",
739
+ "role": "exercise library",
740
+ "note": "Bodyweight exercises with muscles worked and step-by-step progressions.",
741
+ "licence": "apache-2.0",
742
+ "downloads": 230,
743
+ "likes": 1,
744
+ "size": "n<1K",
745
+ "pretty": null
746
+ },
747
+ {
748
+ "id": "RafaelJaime/calisthenics_exercises",
749
+ "role": "exercise library",
750
+ "note": "Calisthenics movements by muscle group and equipment.",
751
+ "licence": "cc0-1.0",
752
+ "downloads": 105,
753
+ "likes": 4,
754
+ "size": "10K<n<100K",
755
+ "pretty": null
756
+ },
757
+ {
758
+ "id": "Eathan/Orthopedic_QA",
759
+ "role": "orthopaedics",
760
+ "note": "Orthopaedic patient questions and answers.",
761
+ "licence": "apache-2.0",
762
+ "downloads": 18,
763
+ "likes": 0,
764
+ "size": null,
765
+ "pretty": null
766
+ },
767
+ {
768
+ "id": "maazsajid/sports-disc-injury-prediction",
769
+ "role": "sports injury",
770
+ "note": "Sports spinal-disc injury risk data (tabular).",
771
+ "licence": "cc0-1.0",
772
+ "downloads": 19,
773
+ "likes": 0,
774
+ "size": null,
775
+ "pretty": null
776
+ },
777
+ {
778
+ "id": "sarveshchhetri/athlete-recovery-and-biometric-performance-dataset",
779
+ "role": "sports recovery",
780
+ "note": "Athlete recovery and biometric performance (tabular).",
781
+ "licence": "apache-2.0",
782
+ "downloads": 24,
783
+ "likes": 0,
784
+ "size": "n<1K",
785
+ "pretty": null
786
+ },
787
+ {
788
+ "id": "Zenodo-ML/TeleRehaB-DSS-Vestibular-Rehabilitation-Wearable-Sensor-Recordings",
789
+ "role": "rehabilitation sensors",
790
+ "note": "Vestibular rehabilitation wearable recordings.",
791
+ "licence": "cc-by-4.0",
792
+ "downloads": 18,
793
+ "likes": 0,
794
+ "size": null,
795
+ "pretty": "TeleRehaB DSS home-based vestibular rehabilitation: wearable sensor recordings."
796
  }
797
  ],
798
  "router_open": {
 
836
  ],
837
  "vision": true
838
  },
839
+ "thinkingmachines/Inkling-2-Small": {
840
+ "licence": "apache-2.0",
841
+ "providers": [
842
+ "cloudflare",
843
+ "deepinfra",
844
+ "modal",
845
+ "nebius",
846
+ "primeintellect",
847
+ "together"
848
+ ],
849
+ "vision": true
850
+ },
851
  "deepseek-ai/DeepSeek-V4.1-Flash-1017": {
852
  "licence": "mit",
853
  "providers": [
 
887
  ],
888
  "vision": true
889
  },
 
 
 
 
 
 
 
 
 
 
 
890
  "thinkingmachines/Inkling": {
891
  "licence": "apache-2.0",
892
  "providers": [
 
926
  ],
927
  "vision": true
928
  },
929
+ "Qwen/Qwen3.6-35B-A3B": {
930
  "licence": "apache-2.0",
931
  "providers": [
932
  "akashml",
 
933
  "coreweave",
934
  "deepinfra",
 
 
 
 
 
935
  "primeintellect",
936
  "venice"
937
  ],
938
  "vision": true
939
  },
940
+ "google/gemma-4-26B-A4B-it": {
941
  "licence": "apache-2.0",
942
  "providers": [
943
  "akashml",
944
+ "cloudflare",
945
  "coreweave",
946
  "deepinfra",
947
+ "google-vertex",
948
+ "io-net",
949
+ "makora",
950
+ "nextbit",
951
+ "parasail",
952
  "primeintellect",
953
  "venice"
954
  ],
 
994
  "crusoe",
995
  "deepinfra",
996
  "digitalocean",
997
+ "fireworks-ai",
998
  "google-vertex",
999
  "groq",
1000
  "mancer",
 
1028
  "modelrun",
1029
  "nextbit",
1030
  "parasail",
 
1031
  "sambanova",
1032
  "venice"
1033
  ],
 
1049
  "amazon-bedrock",
1050
  "coreweave",
1051
  "deepinfra",
1052
+ "groq",
1053
  "parasail",
1054
  "primeintellect"
1055
  ],
 
1092
  ],
1093
  "vision": false
1094
  },
 
 
 
 
 
 
 
1095
  "Qwen/Qwen3-Coder-Next": {
1096
  "licence": "apache-2.0",
1097
  "providers": [
 
1107
  "coreweave",
1108
  "deepinfra",
1109
  "digitalocean",
1110
+ "inceptron",
1111
  "mancer",
1112
  "nebius",
1113
  "parasail",
 
1125
  ],
1126
  "vision": false
1127
  },
1128
+ "zai-org/GLM-4.7-Flash": {
1129
+ "licence": "mit",
1130
+ "providers": [
1131
+ "cloudflare"
1132
+ ],
1133
+ "vision": false
1134
+ },
1135
  "XiaomiMiMo/MiMo-V2.6-Pro-RL": {
1136
  "licence": "mit",
1137
  "providers": [
 
1164
  ],
1165
  "vision": false
1166
  },
1167
+ "XiaomiMiMo/MiMo-V2.6-Flash-MOPD": {
1168
+ "licence": "mit",
1169
+ "providers": [
1170
+ "featherless-ai"
1171
+ ],
1172
+ "vision": false
1173
+ },
1174
  "thinkingmachines/Inkling-Small": {
1175
  "licence": "apache-2.0",
1176
  "providers": [
 
1178
  ],
1179
  "vision": true
1180
  },
1181
+ "Qwen/Qwen2.5-Coder-32B-Instruct": {
1182
+ "licence": "apache-2.0",
1183
  "providers": [
1184
+ "cloudflare"
1185
  ],
1186
  "vision": false
1187
  },
1188
+ "deepseek-ai/DeepSeek-R1-0528": {
1189
+ "licence": "mit",
1190
  "providers": [
1191
+ "deepinfra"
1192
  ],
1193
  "vision": false
1194
  },
 
1287
  "Qwen/Qwen3-32B": {
1288
  "licence": "apache-2.0",
1289
  "providers": [
1290
+ "deepinfra",
1291
+ "tenstorrent"
1292
  ],
1293
  "vision": false
1294
  },
 
1427
  },
1428
  "deepseek-ai/DeepSeek-V3-0324": {
1429
  "licence": "mit",
1430
+ "providers": [
1431
+ "featherless-ai"
1432
+ ],
1433
  "vision": false
1434
  },
1435
  "Qwen/Qwen3-VL-235B-A22B-Instruct": {
app/draiml/consult.py CHANGED
@@ -9,6 +9,41 @@ from .safety import Triage, triage, validate
9
 
10
  SYSTEM_PROMPT = (Path(__file__).parent / "prompt_v2.txt").read_text(encoding="utf-8")
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  @dataclass
14
  class Prepared:
@@ -29,14 +64,17 @@ def evidence_block(hits: list[Hit]) -> str:
29
 
30
 
31
  async def prepare(question: str, history: list[dict], index: EvidenceIndex | None, *, k: int = 6,
32
- token: str | None = None, audience: str = "patient") -> Prepared:
 
33
  t = triage(question)
34
  hits, method = ([], "none")
35
  if index is not None and k > 0:
36
  # retrieve on the question plus the previous user turn, so follow-ups stay on topic
37
  prev = next((m["content"] for m in reversed(history) if m["role"] == "user"), "")
38
- hits, method = await search(index, f"{question} {prev}"[:2000], k, token)
39
  sys = SYSTEM_PROMPT + f"\n\nThe reader is a {audience}."
 
 
40
  if t.emergency:
41
  sys += ("\n\nTRIAGE ALERT: the patient's message matched emergency red flags "
42
  f"({', '.join(t.categories)}). Begin your answer by telling them to contact emergency services now, "
 
9
 
10
  SYSTEM_PROMPT = (Path(__file__).parent / "prompt_v2.txt").read_text(encoding="utf-8")
11
 
12
+ # Consultation modes: each adds a role brief to the system prompt and focus terms to evidence retrieval.
13
+ MODES: dict[str, dict] = {
14
+ "general": {
15
+ "label": "🩺 General medicine", "focus": "",
16
+ "brief": "",
17
+ },
18
+ "physiotherapy": {
19
+ "label": "🦴 Physiotherapy", "focus": "physiotherapy rehabilitation exercise musculoskeletal pain mobility",
20
+ "brief": """CONSULTATION MODE: PHYSIOTHERAPY.
21
+ Act as a physiotherapy-informed assistant for musculoskeletal pain, injury, posture, mobility and rehabilitation.
22
+ - Ask about mechanism of injury, location, onset, aggravating/easing factors, night pain, function and goals.
23
+ - Screen red flags first: saddle numbness, new bladder/bowel change, progressive leg weakness (cauda equina);
24
+ trauma with deformity or inability to bear weight (fracture); fever with back pain; unexplained weight loss or
25
+ cancer history; calf swelling/pain (DVT); chest pain. Any red flag → urgent medical care, no exercises.
26
+ - Offer graded, low-risk self-management: relative rest, load management, gentle range-of-motion and
27
+ strengthening exercises with sets/reps/frequency, posture and ergonomics, heat/ice as comfortable.
28
+ - Say when to see a physiotherapist in person (no improvement in 2–6 weeks, worsening, recurrent episodes).
29
+ Use the headings: **What this could be** · **Exercises & self-care** · **Red flags — seek care** · **Questions for you**""",
30
+ },
31
+ "psychotherapy": {
32
+ "label": "🧠 Psychotherapy", "focus": "mental health anxiety depression psychotherapy cognitive behavioral",
33
+ "brief": """CONSULTATION MODE: PSYCHOTHERAPY SUPPORT.
34
+ Act as a warm, non-judgmental psychotherapy-informed listener. You are not a therapist and do not diagnose.
35
+ - Safety first: if the person mentions suicide, self-harm, harming others, or being unsafe, lead with crisis
36
+ resources (988 in the US, 116 123 Samaritans in the UK/IE, findahelpline.com elsewhere, or local emergency
37
+ number) and encourage reaching a trusted person now.
38
+ - Reflect feelings back, validate, and ask one open question at a time. Do not rush to advice.
39
+ - Offer evidence-based self-help where it fits: CBT-style thought reframing, behavioural activation, grounding
40
+ and breathing (e.g. 5-4-3-2-1, paced breathing), sleep hygiene, journaling, problem-solving steps.
41
+ - Gently suggest professional support (GP, psychologist, counsellor) when distress is persistent or impairing.
42
+ - Never comment on medication changes; refer those to their prescriber.
43
+ Use the headings: **What I'm hearing** · **Something to try** · **Support options** · **A question for you**""",
44
+ },
45
+ }
46
+
47
 
48
  @dataclass
49
  class Prepared:
 
64
 
65
 
66
  async def prepare(question: str, history: list[dict], index: EvidenceIndex | None, *, k: int = 6,
67
+ token: str | None = None, audience: str = "patient", mode: str = "general") -> Prepared:
68
+ mode_cfg = MODES.get(mode, MODES["general"])
69
  t = triage(question)
70
  hits, method = ([], "none")
71
  if index is not None and k > 0:
72
  # retrieve on the question plus the previous user turn, so follow-ups stay on topic
73
  prev = next((m["content"] for m in reversed(history) if m["role"] == "user"), "")
74
+ hits, method = await search(index, f"{question} {prev} {mode_cfg['focus']}"[:2000], k, token)
75
  sys = SYSTEM_PROMPT + f"\n\nThe reader is a {audience}."
76
+ if mode_cfg["brief"]:
77
+ sys += "\n\n" + mode_cfg["brief"]
78
  if t.emergency:
79
  sys += ("\n\nTRIAGE ALERT: the patient's message matched emergency red flags "
80
  f"({', '.join(t.categories)}). Begin your answer by telling them to contact emergency services now, "
app/draiml/rag.py CHANGED
@@ -19,7 +19,8 @@ import numpy as np
19
  from . import net
20
 
21
  EVIDENCE_REPO = "PYTHAI/drAIML-evidence"
22
- BASE = f"https://huggingface.co/datasets/{EVIDENCE_REPO}/resolve/main"
 
23
  EMBED_URL = "https://router.huggingface.co/hf-inference/models/{model}/pipeline/feature-extraction"
24
 
25
  STOP = set("""a an the and or of to in on for with without by from at as is are was were be been being this that
 
19
  from . import net
20
 
21
  EVIDENCE_REPO = "PYTHAI/drAIML-evidence"
22
+ BASE = __import__("os").environ.get("DRAIML_EVIDENCE_BASE") or \
23
+ f"https://huggingface.co/datasets/{EVIDENCE_REPO}/resolve/main" # dev override: a locally built index
24
  EMBED_URL = "https://router.huggingface.co/hf-inference/models/{model}/pipeline/feature-extraction"
25
 
26
  STOP = set("""a an the and or of to in on for with without by from at as is are was were be been being this that
app/draiml/share.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Response actions: copy to clipboard and export as .txt. Built as a row so share targets
2
+ (social, email) can be added beside them later."""
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ import time
8
+
9
+ import streamlit as st
10
+ import streamlit.components.v1 as components
11
+
12
+ DISCLAIMER = ("drAIML provides information, not diagnosis, and does not replace a clinician. "
13
+ "In an emergency call your local emergency number.")
14
+
15
+
16
+ def response_text(m: dict, question: str = "") -> str:
17
+ """Plain-text export of one answer, with its question, model and cited sources."""
18
+ lines = ["drAIML 2.0 — consultation response",
19
+ f"Date: {time.strftime('%Y-%m-%d %H:%M')}",
20
+ f"Model: {m.get('model', '')}", ""]
21
+ if question:
22
+ lines += ["Question:", question, ""]
23
+ lines += ["Answer:", m.get("content", ""), ""]
24
+ if m.get("hits"):
25
+ lines.append("Evidence:")
26
+ for h in m["hits"]:
27
+ url = f" {h['url']}" if h.get("url") else ""
28
+ lines.append(f" [{h['rank']}] {h['source']} ({h['licence']}) {h['ref']}{url}")
29
+ lines.append("")
30
+ lines += ["—", DISCLAIMER, "https://huggingface.co/spaces/PYTHAI/drAIML"]
31
+ return "\n".join(lines)
32
+
33
+
34
+ def _copy_button(text: str, dark: bool) -> None:
35
+ fg, bd, bg = ("#e3efee", "#2c4a48", "#13201f") if dark else ("#12302f", "#cfdcdb", "#ffffff")
36
+ components.html(f"""
37
+ <button id="b" title="Copy this response" aria-label="Copy this response"
38
+ style="font:14px 'Source Sans 3',system-ui,sans-serif;color:{fg};background:{bg};border:1px solid {bd};
39
+ border-radius:8px;padding:4px 10px;cursor:pointer;width:100%;height:32px">⧉ Copy</button>
40
+ <script>
41
+ const t = {json.dumps(text)};
42
+ const b = document.getElementById('b');
43
+ b.onclick = async () => {{
44
+ try {{ await navigator.clipboard.writeText(t); }}
45
+ catch (e) {{
46
+ const a = document.createElement('textarea'); a.value = t; document.body.appendChild(a);
47
+ a.select(); document.execCommand('copy'); a.remove();
48
+ }}
49
+ b.textContent = '✓ Copied'; setTimeout(() => b.textContent = '⧉ Copy', 1600);
50
+ }};
51
+ </script>""", height=36)
52
+
53
+
54
+ def actions_row(m: dict, question: str, key: str) -> None:
55
+ """Top-right actions for an answer: model label on the left, Copy and .txt on the right."""
56
+ dark = (st.context.theme.type == "dark") if hasattr(st.context, "theme") and st.context.theme else False
57
+ left, c_copy, c_txt = st.columns([6, 1.1, 1.1], vertical_alignment="center")
58
+ left.caption(html.escape(m.get("model", "")))
59
+ text = response_text(m, question)
60
+ with c_copy:
61
+ _copy_button(text, dark)
62
+ c_txt.download_button("⬇ .txt", text, file_name=f"draiml-response-{key}.txt", mime="text/plain",
63
+ key=f"txt_{key}", on_click="ignore", use_container_width=True,
64
+ help="Export this response as a text file")
app/manifest.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "build": "616f192b84dc",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
@@ -21,6 +21,7 @@
21
  "draiml/prompt_v2.txt",
22
  "draiml/rag.py",
23
  "draiml/safety.py",
 
24
  "draiml/state.py",
25
  "views/about.py",
26
  "views/consult.py",
 
1
  {
2
+ "build": "0085b94d1d1b",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
 
21
  "draiml/prompt_v2.txt",
22
  "draiml/rag.py",
23
  "draiml/safety.py",
24
+ "draiml/share.py",
25
  "draiml/state.py",
26
  "views/about.py",
27
  "views/consult.py",
app/views/about.py CHANGED
@@ -14,10 +14,13 @@ on the open Hugging Face ecosystem as a free, open resource for patients and cli
14
  1. **Triage first.** Your words are checked for emergency red flags (cardiac, stroke, breathing, bleeding,
15
  anaphylaxis, poisoning, mental-health crisis, sepsis, obstetric, neurological) *before* any model runs.
16
  2. **Evidence.** BM25 retrieval over {{n}} openly licensed passages (PubMedQA, MedMCQA, MedQA, medical-o1,
17
- MedReason, MedText) — the answer cites them as [1], [2]…
18
- 3. **Consultation.** Your choice of open model: dozens of hosted engines via HF Inference Providers, or medical
 
 
 
19
  specialists (II-Medical, HuatuoGPT-o1, Baichuan-M2, BioMistral, MediPhi, Meditron-FO…) on your own machine.
20
- 4. **Hippocratic review.** v1's principle checks — do no harm, beneficence, autonomy, confidentiality — score
21
  every answer and flag its risk level.
22
 
23
  **Privacy.** drAIML runs entirely in your browser (Streamlit on WebAssembly via stlite). There is no drAIML
@@ -32,7 +35,7 @@ an OSI, CC-BY or CC0 licence. The rule is enforced in code (`draiml/licences.py`
32
  2.0 carries its Hippocratic, logic and medical-pattern modules forward unchanged in spirit.
33
 
34
  **Emergencies.** {CRISIS_LINES}
35
- """.replace("{n}", "32,000+"))
36
 
37
  with st.expander("The drAIML oath"):
38
  st.text((Path(__file__).resolve().parents[1] / "draiml" / "ported" / "oath.txt").read_text())
 
14
  1. **Triage first.** Your words are checked for emergency red flags (cardiac, stroke, breathing, bleeding,
15
  anaphylaxis, poisoning, mental-health crisis, sepsis, obstetric, neurological) *before* any model runs.
16
  2. **Evidence.** BM25 retrieval over {{n}} openly licensed passages (PubMedQA, MedMCQA, MedQA, medical-o1,
17
+ MedReason, MedText, physiotherapy evidence Q&A, rehabilitation assessments, sports & fitness, exercise
18
+ libraries) — the answer cites them as [1], [2]…
19
+ 3. **Modes.** General medicine, **physiotherapy & sports therapy** (red-flag screening, graded exercises and
20
+ self-care), or **psychotherapy support** (listening, CBT-style self-help, crisis resources first).
21
+ 4. **Consultation.** Your choice of open model: dozens of hosted engines via HF Inference Providers, or medical
22
  specialists (II-Medical, HuatuoGPT-o1, Baichuan-M2, BioMistral, MediPhi, Meditron-FO…) on your own machine.
23
+ 5. **Hippocratic review.** v1's principle checks — do no harm, beneficence, autonomy, confidentiality — score
24
  every answer and flag its risk level.
25
 
26
  **Privacy.** drAIML runs entirely in your browser (Streamlit on WebAssembly via stlite). There is no drAIML
 
35
  2.0 carries its Hippocratic, logic and medical-pattern modules forward unchanged in spirit.
36
 
37
  **Emergencies.** {CRISIS_LINES}
38
+ """.replace("{n}", "40,000+"))
39
 
40
  with st.expander("The drAIML oath"):
41
  st.text((Path(__file__).resolve().parents[1] / "draiml" / "ported" / "oath.txt").read_text())
app/views/consult.py CHANGED
@@ -1,11 +1,12 @@
1
  import streamlit as st
2
 
3
- from draiml import catalogue, consult, engines, net, state
4
 
5
  state.init()
6
  ss = st.session_state
7
 
8
- st.title("🩺 drAIML consultation")
 
9
  st.caption("Describe symptoms or ask a health question. drAIML checks for emergencies first, retrieves openly "
10
  "licensed medical evidence, then answers with citations and a Hippocratic review. Information only — "
11
  "not a diagnosis.")
@@ -39,8 +40,14 @@ def model_picker(label: str, engine_key: str, current: str, key: str) -> str:
39
  with st.sidebar:
40
  st.subheader("Engine")
41
  labels = {k: v.label for k, v in engines.ENDPOINTS.items()}
 
42
  ss.engine = st.selectbox("Source", list(labels), index=list(labels).index(ss.engine), format_func=labels.get)
43
  ep = engines.ENDPOINTS[ss.engine]
 
 
 
 
 
44
  if ss.engine == "custom":
45
  ss.custom_url = st.text_input("Base URL (OpenAI-compatible /v1)", ss.custom_url)
46
  ss.model = model_picker("Model", ss.engine, ss.model, "model_pick")
@@ -58,6 +65,12 @@ with st.sidebar:
58
  ss.model2 = model_picker("Second model (same source)", ss.engine, ss.model2, "model2_pick")
59
 
60
  st.subheader("Consultation")
 
 
 
 
 
 
61
  audience = st.radio("I am a…", ["patient", "clinician"], horizontal=True)
62
  k_evidence = st.slider("Evidence passages", 0, 10, 6, help="0 disables retrieval")
63
  temperature = st.slider("Temperature", 0.0, 1.0, 0.3, 0.05)
@@ -96,9 +109,14 @@ def render_extras(m: dict):
96
  st.caption("Recommendations: " + "; ".join(recs))
97
 
98
 
99
- for m in ss.history:
 
 
 
100
  with st.chat_message(m["role"], avatar="🧑" if m["role"] == "user" else "⚕️"):
101
- if m["role"] == "assistant" and m.get("model"):
 
 
102
  st.caption(m["model"])
103
  st.markdown(m["content"])
104
  if m["role"] == "assistant":
@@ -136,7 +154,8 @@ async def answer(model: str, prepared, key, base_url) -> dict:
136
  if rest.strip():
137
  yield rest.lstrip()
138
 
139
- st.caption(model)
 
140
  try:
141
  text = st.write_stream(deltas())
142
  except net.HTTPError as e:
@@ -157,6 +176,8 @@ async def answer(model: str, prepared, key, base_url) -> dict:
157
  review = consult.review(text, prepared.question)
158
  out = {"role": "assistant", "content": text, "model": model, "reasoning": holder["reasoning"].strip(),
159
  "hits": [h.__dict__ for h in prepared.hits], "method": prepared.method, "review": review}
 
 
160
  render_extras({**out, "hits": out["hits"]})
161
  return out
162
 
@@ -171,7 +192,7 @@ if prompt:
171
  "Meanwhile, here is what the evidence says:")
172
  index = await state.evidence_index() # noqa: F704
173
  prepared = await consult.prepare(prompt, ss.history, index, k=k_evidence, # noqa: F704
174
- token=state.key_for("hf"), audience=audience)
175
  ss.history.append({"role": "user", "content": prompt})
176
  triage_msg = prepared.triage.banner() if prepared.triage.emergency else ""
177
  if triage_msg:
 
1
  import streamlit as st
2
 
3
+ from draiml import catalogue, consult, engines, net, share, state
4
 
5
  state.init()
6
  ss = st.session_state
7
 
8
+ st.title({"general": "🩺 drAIML consultation", "physiotherapy": "🦴 drAIML · physiotherapy",
9
+ "psychotherapy": "🧠 drAIML · psychotherapy support"}.get(ss.get("mode", "general"), "🩺 drAIML consultation"))
10
  st.caption("Describe symptoms or ask a health question. drAIML checks for emergencies first, retrieves openly "
11
  "licensed medical evidence, then answers with citations and a Hippocratic review. Information only — "
12
  "not a diagnosis.")
 
40
  with st.sidebar:
41
  st.subheader("Engine")
42
  labels = {k: v.label for k, v in engines.ENDPOINTS.items()}
43
+ prev_engine = ss.engine
44
  ss.engine = st.selectbox("Source", list(labels), index=list(labels).index(ss.engine), format_func=labels.get)
45
  ep = engines.ENDPOINTS[ss.engine]
46
+ if ss.engine != prev_engine: # a model id from one provider means nothing to another
47
+ ss.model = ep.suggested[0] if ep.suggested else ("openai/gpt-oss-120b" if ss.engine == "hf" else "")
48
+ ss.model2 = ep.suggested[1] if len(ep.suggested) > 1 else ""
49
+ for w in ("model_pick", "model_pick_sel", "model_pick_txt", "model2_pick", "model2_pick_sel", "model2_pick_txt"):
50
+ ss.pop(w, None)
51
  if ss.engine == "custom":
52
  ss.custom_url = st.text_input("Base URL (OpenAI-compatible /v1)", ss.custom_url)
53
  ss.model = model_picker("Model", ss.engine, ss.model, "model_pick")
 
65
  ss.model2 = model_picker("Second model (same source)", ss.engine, ss.model2, "model2_pick")
66
 
67
  st.subheader("Consultation")
68
+ ss.setdefault("mode", "general")
69
+ ss.mode = st.radio("Mode", list(consult.MODES), index=list(consult.MODES).index(ss.mode),
70
+ format_func=lambda k: consult.MODES[k]["label"],
71
+ help="General medicine, physiotherapy (musculoskeletal pain, injury, rehab exercises) or "
72
+ "psychotherapy support (feelings, stress, coping). Each mode changes how drAIML "
73
+ "consults and what evidence it looks for.")
74
  audience = st.radio("I am a…", ["patient", "clinician"], horizontal=True)
75
  k_evidence = st.slider("Evidence passages", 0, 10, 6, help="0 disables retrieval")
76
  temperature = st.slider("Temperature", 0.0, 1.0, 0.3, 0.05)
 
109
  st.caption("Recommendations: " + "; ".join(recs))
110
 
111
 
112
+ last_q = ""
113
+ for i, m in enumerate(ss.history):
114
+ if m["role"] == "user":
115
+ last_q = m["content"]
116
  with st.chat_message(m["role"], avatar="🧑" if m["role"] == "user" else "⚕️"):
117
+ if m["role"] == "assistant" and m.get("model") and m.get("model") != "evidence":
118
+ share.actions_row(m, last_q, str(i))
119
+ elif m["role"] == "assistant" and m.get("model"):
120
  st.caption(m["model"])
121
  st.markdown(m["content"])
122
  if m["role"] == "assistant":
 
154
  if rest.strip():
155
  yield rest.lstrip()
156
 
157
+ bar = st.empty() # actions row sits above the answer; filled once the answer is complete
158
+ bar.caption(model)
159
  try:
160
  text = st.write_stream(deltas())
161
  except net.HTTPError as e:
 
176
  review = consult.review(text, prepared.question)
177
  out = {"role": "assistant", "content": text, "model": model, "reasoning": holder["reasoning"].strip(),
178
  "hits": [h.__dict__ for h in prepared.hits], "method": prepared.method, "review": review}
179
+ with bar.container():
180
+ share.actions_row(out, prepared.question, f"{len(ss.history)}_{model.replace('/', '_')[-24:]}")
181
  render_extras({**out, "hits": out["hits"]})
182
  return out
183
 
 
192
  "Meanwhile, here is what the evidence says:")
193
  index = await state.evidence_index() # noqa: F704
194
  prepared = await consult.prepare(prompt, ss.history, index, k=k_evidence, # noqa: F704
195
+ token=state.key_for("hf"), audience=audience, mode=ss.mode)
196
  ss.history.append({"role": "user", "content": prompt})
197
  triage_msg = prepared.triage.banner() if prepared.triage.emergency else ""
198
  if triage_msg:
app/views/datasets.py CHANGED
@@ -1,7 +1,7 @@
1
  import pandas as pd
2
  import streamlit as st
3
 
4
- from draiml import catalogue, state
5
 
6
  state.init()
7
  st.title("📚 Datasets")
@@ -12,8 +12,10 @@ idx = state._index # already loaded if the visitor consulted or searched
12
  if idx is not None:
13
  index_sources = {s["repo"] for s in idx.sources}
14
  else:
15
- index_sources = {"qiaojin/PubMedQA", "openlifescienceai/medmcqa", "FreedomIntelligence/medical-o1-reasoning-SFT",
16
- "UCSC-VLAA/MedReason", "GBaker/MedQA-USMLE-4-options", "BI55/MedText"}
 
 
17
 
18
  cur = catalogue.curated_datasets()
19
  df = pd.DataFrame([{"📌": "📌" if d["id"] in index_sources else "", "dataset": d["id"], "role": d["role"],
 
1
  import pandas as pd
2
  import streamlit as st
3
 
4
+ from draiml import catalogue, net, rag, state
5
 
6
  state.init()
7
  st.title("📚 Datasets")
 
12
  if idx is not None:
13
  index_sources = {s["repo"] for s in idx.sources}
14
  else:
15
+ try:
16
+ index_sources = {s["repo"] for s in (await net.get_json(f"{rag.BASE}/meta.json"))["sources"]} # noqa: F704
17
+ except Exception:
18
+ index_sources = set()
19
 
20
  cur = catalogue.curated_datasets()
21
  df = pd.DataFrame([{"📌": "📌" if d["id"] in index_sources else "", "dataset": d["id"], "role": d["role"],
index.html CHANGED
@@ -108,6 +108,9 @@ const files = {};
108
  for (const p of manifest.files) files[p] = { url: "app/" + p + "?v=" + manifest.build };
109
 
110
  const env = {};
 
 
 
111
  if (session) {
112
  env.HF_TOKEN = session.accessToken;
113
  const u = session.userInfo || {};
 
108
  for (const p of manifest.files) files[p] = { url: "app/" + p + "?v=" + manifest.build };
109
 
110
  const env = {};
111
+ if (["127.0.0.1", "localhost"].includes(location.hostname)) {
112
+ env.DRAIML_EVIDENCE_BASE = location.origin + "/build/evidence"; // local development: serve the index you built
113
+ }
114
  if (session) {
115
  env.HF_TOKEN = session.accessToken;
116
  const u = session.userInfo || {};
scripts/build_index.py CHANGED
@@ -82,6 +82,58 @@ def medtext(n):
82
  for i, r in enumerate(take("BI55/MedText", "default", n))]
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  SOURCES = [
86
  # repo id, builder, count
87
  ("qiaojin/PubMedQA", pubmedqa, 11_000),
@@ -90,6 +142,13 @@ SOURCES = [
90
  ("UCSC-VLAA/MedReason", medreason, 4_000),
91
  ("GBaker/MedQA-USMLE-4-options", medqa, 2_000),
92
  ("BI55/MedText", medtext, 0), # 0 = all (~1.4k)
 
 
 
 
 
 
 
93
  ]
94
 
95
 
@@ -109,9 +168,6 @@ def main():
109
  old = json.load(f)
110
  passages, sources = old["passages"], old["sources"]
111
  print(f"reusing {len(passages)} passages")
112
- for p in passages: # keep the browser download small: ~1000 chars is plenty for a cited passage
113
- if len(p[0]) > 1000:
114
- p[0] = p[0][:1000].rsplit(" ", 1)[0] + " …"
115
  for repo, fn, n in ([] if passages else SOURCES):
116
  info = api.dataset_info(repo)
117
  ok, lic = is_open_dataset(info)
@@ -125,6 +181,10 @@ def main():
125
  passages += [[text, sidx, ref, url] for text, ref, url in rows]
126
  print(f"{repo}: {len(rows)} passages ({lic}) in {time.time()-t:.0f}s", flush=True)
127
 
 
 
 
 
128
  dim = None
129
  if args.embed:
130
  from sentence_transformers import SentenceTransformer
@@ -170,7 +230,7 @@ license: other
170
  license_name: mixed-open
171
  license_link: LICENSE.md
172
  language: [en]
173
- tags: [medical, healthcare, retrieval, rag, draiml]
174
  pretty_name: drAIML evidence index
175
  size_categories: [10K<n<100K]
176
  ---
 
82
  for i, r in enumerate(take("BI55/MedText", "default", n))]
83
 
84
 
85
+ def physio_qa(n):
86
+ out = []
87
+ for i, r in enumerate(take("serhanayberkkilic/physiotherapy-evidence-qa", "default", n)):
88
+ if not r.get("answer_en"):
89
+ continue
90
+ src = f" Source: {r['source_file']}" if r.get("source_file") else ""
91
+ out.append((f"Physiotherapy — {r.get('disease_category_en') or ''} ({r.get('question_type_en') or ''})\n"
92
+ f"Q: {clean(r['question_en'])}\nAnswer: {clean(r['answer_en'])}{src}", f"physio-qa:{i}", ""))
93
+ return out
94
+
95
+
96
+ def msk_rehab(n):
97
+ return [(f"Rehabilitation assessment: {clean(r['section_text'])[:600]}\nConsultation excerpt: {clean(r['dialogue'])[:500]}",
98
+ f"msk-rehab:{i}", "")
99
+ for i, r in enumerate(take("Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment", "default", n))]
100
+
101
+
102
+ SPORT_TERMS = re.compile(r"exercis|train|muscle|strength|stretch|injur|sport|athlet|run|fitness|aerobic|endurance|"
103
+ r"flexib|rehab|joint|tendon|ligament|posture|warm-up|recovery", re.I)
104
+
105
+
106
+ def fitness_qa(n):
107
+ out = []
108
+ for i, r in enumerate(take("hammamwahab/fitness-qa", "default", n * 3)):
109
+ text = f"Q: {clean(r['question'])}\nAnswer: {clean(r['answer'])}"
110
+ if SPORT_TERMS.search(text):
111
+ out.append((text, f"fitness-qa:{i}", ""))
112
+ if len(out) >= n:
113
+ break
114
+ return out
115
+
116
+
117
+ def calisthenics(n):
118
+ out = []
119
+ for i, r in enumerate(take("Martjn/calisthenics_exercises", "default", 0)):
120
+ prog = " → ".join(clean(r.get(f"progression_{k}") or "") for k in range(1, 6) if r.get(f"progression_{k}"))
121
+ out.append((f"Exercise: {r['name']} ({r.get('category') or ''}). Muscles: {r.get('primary_muscles') or ''}.\n"
122
+ f"How: {clean(r.get('description') or '')}\nProgression: {prog}", f"calisthenics:{r['id']}", ""))
123
+ return out
124
+
125
+
126
+ def calisthenics2(n):
127
+ return [(f"Exercise: {r['name']}. Muscles: {r.get('muscle_groups') or ''}. Equipment: {r.get('materials') or ''}.\n"
128
+ f"How: {clean(r.get('description') or '')}", f"calisthenics2:{i}", "")
129
+ for i, r in enumerate(take("RafaelJaime/calisthenics_exercises", "default", 0))]
130
+
131
+
132
+ def orthopedic_qa(n):
133
+ return [(f"Q: {clean(r['Patient_Question'])}\nAnswer: {clean(r['Doctor_Response'])}", f"ortho-qa:{i}", "")
134
+ for i, r in enumerate(take("Eathan/Orthopedic_QA", "default", 0))]
135
+
136
+
137
  SOURCES = [
138
  # repo id, builder, count
139
  ("qiaojin/PubMedQA", pubmedqa, 11_000),
 
142
  ("UCSC-VLAA/MedReason", medreason, 4_000),
143
  ("GBaker/MedQA-USMLE-4-options", medqa, 2_000),
144
  ("BI55/MedText", medtext, 0), # 0 = all (~1.4k)
145
+ # physiotherapy · sports therapy · rehabilitation
146
+ ("serhanayberkkilic/physiotherapy-evidence-qa", physio_qa, 8_000),
147
+ ("Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment", msk_rehab, 2_000),
148
+ ("hammamwahab/fitness-qa", fitness_qa, 2_000),
149
+ ("Martjn/calisthenics_exercises", calisthenics, 0),
150
+ ("RafaelJaime/calisthenics_exercises", calisthenics2, 0),
151
+ ("Eathan/Orthopedic_QA", orthopedic_qa, 0),
152
  ]
153
 
154
 
 
168
  old = json.load(f)
169
  passages, sources = old["passages"], old["sources"]
170
  print(f"reusing {len(passages)} passages")
 
 
 
171
  for repo, fn, n in ([] if passages else SOURCES):
172
  info = api.dataset_info(repo)
173
  ok, lic = is_open_dataset(info)
 
181
  passages += [[text, sidx, ref, url] for text, ref, url in rows]
182
  print(f"{repo}: {len(rows)} passages ({lic}) in {time.time()-t:.0f}s", flush=True)
183
 
184
+ for p in passages: # keep the browser download small: ~1000 chars is plenty for a cited passage
185
+ if len(p[0]) > 1000:
186
+ p[0] = p[0][:1000].rsplit(" ", 1)[0] + " …"
187
+
188
  dim = None
189
  if args.embed:
190
  from sentence_transformers import SentenceTransformer
 
230
  license_name: mixed-open
231
  license_link: LICENSE.md
232
  language: [en]
233
+ tags: [medical, healthcare, physiotherapy, sports-medicine, rehabilitation, retrieval, rag, draiml]
234
  pretty_name: drAIML evidence index
235
  size_categories: [10K<n<100K]
236
  ---
scripts/catalogue.yaml CHANGED
@@ -71,3 +71,13 @@ datasets:
71
  - {id: gamino/wiki_medical_terms, role: "glossary", note: "Wikipedia medical terms (GPL-3.0)."}
72
  - {id: Malikeh1375/medical-question-answering-datasets, role: "QA collection"}
73
  - {id: bigbio/pubmed_qa, role: "research QA"}
 
 
 
 
 
 
 
 
 
 
 
71
  - {id: gamino/wiki_medical_terms, role: "glossary", note: "Wikipedia medical terms (GPL-3.0)."}
72
  - {id: Malikeh1375/medical-question-answering-datasets, role: "QA collection"}
73
  - {id: bigbio/pubmed_qa, role: "research QA"}
74
+ # physiotherapy · sports therapy · rehabilitation
75
+ - {id: serhanayberkkilic/physiotherapy-evidence-qa, role: "physiotherapy", note: "Physiotherapy questions answered from systematic reviews and meta-analyses (EN/TR)."}
76
+ - {id: Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment, role: "rehabilitation", note: "Musculoskeletal and neuro rehabilitation assessments with consultation dialogues."}
77
+ - {id: hammamwahab/fitness-qa, role: "sports & fitness", note: "Fitness, training and exercise-physiology Q&A."}
78
+ - {id: Martjn/calisthenics_exercises, role: "exercise library", note: "Bodyweight exercises with muscles worked and step-by-step progressions."}
79
+ - {id: RafaelJaime/calisthenics_exercises, role: "exercise library", note: "Calisthenics movements by muscle group and equipment."}
80
+ - {id: Eathan/Orthopedic_QA, role: "orthopaedics", note: "Orthopaedic patient questions and answers."}
81
+ - {id: maazsajid/sports-disc-injury-prediction, role: "sports injury", note: "Sports spinal-disc injury risk data (tabular)."}
82
+ - {id: sarveshchhetri/athlete-recovery-and-biometric-performance-dataset, role: "sports recovery", note: "Athlete recovery and biometric performance (tabular)."}
83
+ - {id: Zenodo-ML/TeleRehaB-DSS-Vestibular-Rehabilitation-Wearable-Sensor-Recordings, role: "rehabilitation sensors", note: "Vestibular rehabilitation wearable recordings."}
tests/conftest.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "app"))
tests/test_core.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from draiml import catalogue, consult, engines, licences, net, rag, safety
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+
11
+
12
+ # ── licence gate ──
13
+ @pytest.mark.parametrize("lic,kind,ok", [
14
+ ("apache-2.0", "model", True), ("mit", "model", True), ("gpl-3.0", "model", True),
15
+ ("other", "model", False), ("llama3", "model", False), ("gemma", "model", False), (None, "model", False),
16
+ ("cc-by-4.0", "model", False), ("cc-by-4.0", "dataset", True), ("cc0-1.0", "dataset", True),
17
+ ("cc-by-nc-4.0", "dataset", False), ("cc", "dataset", False), ("unknown", "dataset", False),
18
+ ])
19
+ def test_gate(lic, kind, ok):
20
+ assert licences.is_open(lic, kind) is ok
21
+
22
+
23
+ def test_licence_of_tags_and_lists():
24
+ assert licences.licence_of({"tags": ["license:MIT"]}) == "mit"
25
+ assert licences.licence_of({"cardData": {"license": ["apache-2.0"]}}) == "apache-2.0"
26
+ assert not licences.is_open(licences.licence_of({"cardData": {"license": ["mit", "other"]}}), "model")
27
+
28
+
29
+ def test_curated_catalogue_is_all_open():
30
+ cat = json.loads((ROOT / "app/data/catalogue.json").read_text())
31
+ ids = {m["id"] for m in cat["models"]}
32
+ assert "google/medgemma-4b-it" not in ids and "aaditya/Llama3-OpenBioLLM-8B" not in ids
33
+ assert "FreedomIntelligence/HuatuoGPT-o1-8B" not in ids # apache card over a Llama-3.1 base
34
+ for m in cat["models"]:
35
+ assert licences.is_open(m["licence"], "model"), m["id"]
36
+ for d in cat["datasets"]:
37
+ assert licences.is_open(d["licence"], "dataset"), d["id"]
38
+ for mid in cat["router_open"]:
39
+ assert mid not in cat["router_closed"]
40
+
41
+
42
+ def test_unsuited_filter():
43
+ assert catalogue.UNSUITED.search("Qwen/Qwen3-Coder-480B-A35B-Instruct")
44
+ assert catalogue.UNSUITED.search("dphn/Dolphin-Mistral-24B-Venice-Edition")
45
+ assert not catalogue.UNSUITED.search("openai/gpt-oss-120b")
46
+
47
+
48
+ # ── triage ──
49
+ @pytest.mark.parametrize("text,cat", [
50
+ ("crushing chest pain radiating to my left arm", "cardiac"),
51
+ ("she suddenly can't speak and her face is drooping", "stroke"),
52
+ ("I can't breathe and my lips are turning blue", "breathing"),
53
+ ("I took an overdose of paracetamol", "poisoning"),
54
+ ("I want to die", "mental health"),
55
+ ("my baby is not breathing", "obstetric"),
56
+ ])
57
+ def test_triage_positive(text, cat):
58
+ t = safety.triage(text)
59
+ assert t.emergency and cat in t.categories
60
+
61
+
62
+ @pytest.mark.parametrize("text", ["what is a normal blood pressure", "severe acne treatment options",
63
+ "is it urgent to get a flu shot", "how much vitamin D per day"])
64
+ def test_triage_negative(text):
65
+ assert not safety.triage(text).emergency
66
+
67
+
68
+ def test_validation_runs_without_disk(tmp_path, monkeypatch):
69
+ monkeypatch.chdir(tmp_path)
70
+ r = safety.validate("Likely a tension headache. Rest, fluids; see a doctor if it worsens.", "headache")
71
+ assert "overall_score" in r and r["risk"]["level"] == "low"
72
+ assert not any(tmp_path.iterdir()) # v1 wrote ./memory/logs; 2.0 must not
73
+
74
+
75
+ # ── retrieval ──
76
+ PASSAGES = {"sources": [{"repo": "x/a", "licence": "mit", "count": 3}],
77
+ "passages": [["Nitrofurantoin is a safe antibiotic for cystitis in pregnancy.", 0, "a:1", ""],
78
+ ["Metformin is first-line therapy for type 2 diabetes.", 0, "a:2", ""],
79
+ ["Aspirin and nitroglycerin for suspected myocardial infarction.", 0, "a:3", ""]]}
80
+
81
+
82
+ def test_bm25_ranks_and_cites():
83
+ idx = rag.EvidenceIndex(PASSAGES)
84
+ hits, method = asyncio.run(rag.search(idx, "antibiotic for bladder cystitis in pregnancy", 2))
85
+ assert method == "bm25" and hits[0].ref == "a:1" and hits[0].licence == "mit"
86
+
87
+
88
+ def test_bm25_arrays_roundtrip(tmp_path):
89
+ a = rag.bm25_arrays(PASSAGES["passages"])
90
+ rag.save_bm25(tmp_path / "b.npz", a)
91
+ idx = rag.EvidenceIndex(PASSAGES, bm25=rag.read_bm25(tmp_path / "b.npz"))
92
+ assert idx.bm25("metformin diabetes")[0][0] == 1
93
+
94
+
95
+ def test_rrf():
96
+ assert rag.rrf([[(1, 9), (2, 8)], [(2, 1), (3, 0.5)]])[0][0] == 2
97
+
98
+
99
+ def test_prepare_includes_evidence_and_triage():
100
+ idx = rag.EvidenceIndex(PASSAGES)
101
+ p = asyncio.run(consult.prepare("crushing chest pain, should I take aspirin?", [], idx, k=2))
102
+ assert p.triage.emergency and "TRIAGE ALERT" in p.messages[0]["content"]
103
+ assert "EVIDENCE" in p.messages[-1]["content"] and "[1]" in p.messages[-1]["content"]
104
+
105
+
106
+ # ── engines (mocked SSE) ──
107
+ def test_stream_chat_parses_reasoning_and_content(monkeypatch):
108
+ events = [json.dumps({"choices": [{"delta": {"reasoning_content": "think "}}]}),
109
+ json.dumps({"choices": [{"delta": {"content": "Hello"}}]}),
110
+ json.dumps({"choices": [{"delta": {"content": " world"}}]}), "[DONE]"]
111
+
112
+ async def fake_sse(url, payload, headers=None):
113
+ assert url.endswith("/chat/completions") and payload["stream"] is True
114
+ assert headers == {"Authorization": "Bearer k"}
115
+ for e in events:
116
+ yield e
117
+
118
+ monkeypatch.setattr(net, "post_sse", fake_sse)
119
+ r, a = asyncio.run(engines.complete(engines.ENDPOINTS["hf"], "openai/gpt-oss-120b", [], key="k"))
120
+ assert (r, a) == ("think", "Hello world")
121
+
122
+
123
+ def test_split_think():
124
+ assert engines.split_think("<think>hmm</think>Answer") == ("hmm", "Answer")
125
+ assert engines.split_think("plain") == ("", "plain")
126
+
127
+
128
+ def test_http_error_message():
129
+ e = net.HTTPError(402, '{"error":"Purchase pre-paid credits"}', "u")
130
+ assert "pre-paid credits" in e.message()
131
+
132
+
133
+ @pytest.mark.parametrize("mode,needle", [("physiotherapy", "PHYSIOTHERAPY"), ("psychotherapy", "PSYCHOTHERAPY")])
134
+ def test_modes_change_prompt(mode, needle):
135
+ idx = rag.EvidenceIndex(PASSAGES)
136
+ p = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1, mode=mode))
137
+ assert needle in p.messages[0]["content"]
138
+ g = asyncio.run(consult.prepare("my lower back hurts", [], idx, k=1))
139
+ assert needle not in g.messages[0]["content"]