Gregory-L commited on
Commit
a709b7a
·
verified ·
1 Parent(s): d418c4b

drAIML 2.0.0: open healthcare consultation in the browser (stlite)

Browse files
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .venv/
2
+ build/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
README.md CHANGED
@@ -1,10 +1,62 @@
1
  ---
2
- title: DrAIML
3
- emoji: 🏆
4
  colorFrom: green
5
  colorTo: blue
6
  sdk: static
7
- pinned: false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: drAIML
3
+ emoji: ⚕️
4
  colorFrom: green
5
  colorTo: blue
6
  sdk: static
7
+ app_file: index.html
8
+ pinned: true
9
+ license: mit
10
+ short_description: Open healthcare consultation with open medical AI
11
+ hf_oauth: true
12
+ hf_oauth_scopes:
13
+ - inference-api
14
+ tags:
15
+ - medical
16
+ - healthcare
17
+ - streamlit
18
+ - stlite
19
+ - rag
20
+ datasets:
21
+ - PYTHAI/drAIML-evidence
22
+ - qiaojin/PubMedQA
23
+ - openlifescienceai/medmcqa
24
+ - GBaker/MedQA-USMLE-4-options
25
+ - FreedomIntelligence/medical-o1-reasoning-SFT
26
+ - UCSC-VLAA/MedReason
27
+ - BI55/MedText
28
+ models:
29
+ - openai/gpt-oss-120b
30
+ - Qwen/Qwen3-235B-A22B-Instruct-2507
31
+ - deepseek-ai/DeepSeek-V3.1
32
+ - Intelligent-Internet/II-Medical-8B
33
+ - FreedomIntelligence/HuatuoGPT-o1-7B
34
+ - baichuan-inc/Baichuan-M2-32B
35
+ - BioMistral/BioMistral-7B
36
+ - microsoft/MediPhi-Instruct
37
+ - NeuML/pubmedbert-base-embeddings
38
  ---
39
 
40
+ # drAIML 2.0.0 — open healthcare consultation
41
+
42
+ drAIML is an open-source medical consultation assistant. Version 2.0 is a Streamlit app that runs **entirely
43
+ in your browser** ([stlite](https://github.com/whitphx/stlite)). There is no drAIML server, and nothing about
44
+ your consultation is stored.
45
+
46
+ - **Triage first.** Emergency red flags are checked before any model runs.
47
+ - **Open evidence.** 32k passages from openly licensed health datasets
48
+ ([PYTHAI/drAIML-evidence](https://huggingface.co/datasets/PYTHAI/drAIML-evidence)), cited inline.
49
+ - **Many models.** Every open chat model live on HF Inference Providers (sign in with Hugging Face; your own
50
+ account is billed), Groq or Together with your key, or medical specialists (II-Medical, HuatuoGPT-o1,
51
+ Baichuan-M2, BioMistral, MediPhi, Meditron-FO…) on your own machine via Ollama.
52
+ - **Hippocratic review.** v1's principle checks score every answer.
53
+ - **Open source or go away.** Only OSI-licensed models (including their base models) and OSI/CC-BY/CC0 datasets.
54
+
55
+ Local specialists: `OLLAMA_ORIGINS=https://pythai-draiml.static.hf.space ollama serve`, then pick
56
+ "Your endpoint" in the sidebar.
57
+
58
+ v1 (the original Streamlit app): [github.com/AIMLdr/drAIML](https://github.com/AIMLdr/drAIML) ·
59
+ [aimldr.streamlit.app](https://aimldr.streamlit.app)
60
+
61
+ *Information only — not a diagnosis, not a substitute for a clinician. In an emergency call your local
62
+ emergency number.*
app/app.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """drAIML 2.0.0 — open healthcare consultation. Runs in the browser via stlite on huggingface.co/spaces/PYTHAI/drAIML."""
2
+ import os
3
+
4
+ import streamlit as st
5
+
6
+ from draiml import __version__
7
+
8
+ st.set_page_config(page_title="drAIML — open healthcare consultation", page_icon="⚕️", layout="wide")
9
+
10
+ if "hf_token" not in st.session_state: # token handed over by the page's "Sign in with Hugging Face"
11
+ st.session_state.hf_token = os.environ.get("HF_TOKEN") or ""
12
+ st.session_state.hf_user = os.environ.get("HF_USER") or ""
13
+ st.session_state.hf_oauth = bool(st.session_state.hf_token)
14
+
15
+ pages = [
16
+ st.Page("views/consult.py", title="Consultation", icon="🩺", default=True),
17
+ st.Page("views/evidence.py", title="Evidence search", icon="🔎"),
18
+ st.Page("views/models.py", title="Models", icon="🧠"),
19
+ st.Page("views/datasets.py", title="Datasets", icon="📚"),
20
+ st.Page("views/about.py", title="About · Oath", icon="⚕️"),
21
+ ]
22
+ nav = st.navigation(pages)
23
+
24
+ with st.sidebar:
25
+ st.markdown(f"### ⚕️ drAIML `{__version__}`")
26
+ if st.session_state.hf_oauth:
27
+ st.caption(f"Signed in as **{st.session_state.hf_user or 'Hugging Face user'}** — hosted models bill your HF account.")
28
+ else:
29
+ st.caption("Not signed in. Browse freely; to consult a hosted model, sign in with Hugging Face "
30
+ "(top bar) or bring a key.")
31
+
32
+ nav.run()
33
+
34
+ st.markdown(
35
+ "<div style='margin-top:2rem;font-size:0.8rem;opacity:0.7'>drAIML provides information, not diagnosis. "
36
+ "It does not replace a clinician. In an emergency call your local emergency number. · "
37
+ "MIT · <a href='https://github.com/AIMLdr/drAIML'>v1 on GitHub</a></div>", unsafe_allow_html=True)
app/data/catalogue.json ADDED
@@ -0,0 +1,1413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "2.0.0",
3
+ "built": "2026-11-25T23:25:02Z",
4
+ "models": [
5
+ {
6
+ "id": "openai/gpt-oss-120b",
7
+ "role": "engine",
8
+ "note": "Strong open reasoning model; good default for consultation.",
9
+ "licence": "apache-2.0",
10
+ "pipeline": "text-generation",
11
+ "downloads": 2275800,
12
+ "likes": 5567,
13
+ "params_b": 116.8,
14
+ "bases": [],
15
+ "providers": []
16
+ },
17
+ {
18
+ "id": "openai/gpt-oss-20b",
19
+ "role": "engine",
20
+ "note": "Fast, inexpensive open reasoning model.",
21
+ "licence": "apache-2.0",
22
+ "pipeline": "text-generation",
23
+ "downloads": 5357474,
24
+ "likes": 5351,
25
+ "params_b": 20.9,
26
+ "bases": [],
27
+ "providers": []
28
+ },
29
+ {
30
+ "id": "Qwen/Qwen3-235B-A22B-Instruct-2507",
31
+ "role": "engine",
32
+ "note": "Large open MoE, excellent medical knowledge.",
33
+ "licence": "apache-2.0",
34
+ "pipeline": "text-generation",
35
+ "downloads": 48661,
36
+ "likes": 814,
37
+ "params_b": 235.1,
38
+ "bases": [],
39
+ "providers": []
40
+ },
41
+ {
42
+ "id": "Qwen/Qwen3-235B-A22B-Thinking-2507",
43
+ "role": "engine",
44
+ "note": "Thinking variant \u2014 shows its reasoning.",
45
+ "licence": "apache-2.0",
46
+ "pipeline": "text-generation",
47
+ "downloads": 7080,
48
+ "likes": 421,
49
+ "params_b": 235.1,
50
+ "bases": [],
51
+ "providers": []
52
+ },
53
+ {
54
+ "id": "Qwen/Qwen3-Next-80B-A3B-Instruct",
55
+ "role": "engine",
56
+ "note": "Efficient long-context MoE.",
57
+ "licence": "apache-2.0",
58
+ "pipeline": "text-generation",
59
+ "downloads": 125799,
60
+ "likes": 1076,
61
+ "params_b": 81.3,
62
+ "bases": [],
63
+ "providers": []
64
+ },
65
+ {
66
+ "id": "Qwen/Qwen3-32B",
67
+ "role": "engine",
68
+ "note": "Dense 32B; solid all-rounder.",
69
+ "licence": "apache-2.0",
70
+ "pipeline": "text-generation",
71
+ "downloads": 3707487,
72
+ "likes": 800,
73
+ "params_b": 32.8,
74
+ "bases": [],
75
+ "providers": []
76
+ },
77
+ {
78
+ "id": "deepseek-ai/DeepSeek-V3.1",
79
+ "role": "engine",
80
+ "note": "MIT-licensed frontier MoE.",
81
+ "licence": "mit",
82
+ "pipeline": "text-generation",
83
+ "downloads": 336777,
84
+ "likes": 869,
85
+ "params_b": 684.5,
86
+ "bases": [
87
+ "deepseek-ai/DeepSeek-V3.1-Base"
88
+ ],
89
+ "providers": []
90
+ },
91
+ {
92
+ "id": "deepseek-ai/DeepSeek-R1-0528",
93
+ "role": "engine",
94
+ "note": "MIT reasoning model; careful differentials.",
95
+ "licence": "mit",
96
+ "pipeline": "text-generation",
97
+ "downloads": 155691,
98
+ "likes": 2503,
99
+ "params_b": 684.5,
100
+ "bases": [],
101
+ "providers": []
102
+ },
103
+ {
104
+ "id": "zai-org/GLM-4.6",
105
+ "role": "engine",
106
+ "note": "MIT-licensed MoE.",
107
+ "licence": "mit",
108
+ "pipeline": "text-generation",
109
+ "downloads": 22988,
110
+ "likes": 1246,
111
+ "params_b": 356.8,
112
+ "bases": [],
113
+ "providers": []
114
+ },
115
+ {
116
+ "id": "Qwen/Qwen3-VL-235B-A22B-Instruct",
117
+ "role": "vision-engine",
118
+ "note": "Hosted vision-language model for images (open).",
119
+ "licence": "apache-2.0",
120
+ "pipeline": "image-text-to-text",
121
+ "downloads": 318217,
122
+ "likes": 431,
123
+ "params_b": 235.7,
124
+ "bases": [],
125
+ "providers": []
126
+ },
127
+ {
128
+ "id": "Intelligent-Internet/II-Medical-8B",
129
+ "role": "specialist",
130
+ "specialty": "clinical reasoning",
131
+ "note": "Qwen3-8B medical reasoning fine-tune.",
132
+ "licence": "apache-2.0",
133
+ "pipeline": "text-generation",
134
+ "downloads": 1174,
135
+ "likes": 217,
136
+ "params_b": 8.2,
137
+ "bases": [],
138
+ "providers": [],
139
+ "gguf": "mradermacher/II-Medical-8B-i1-GGUF"
140
+ },
141
+ {
142
+ "id": "Intelligent-Internet/II-Medical-8B-1706",
143
+ "role": "specialist",
144
+ "specialty": "clinical reasoning",
145
+ "note": "Later II-Medical revision.",
146
+ "licence": "apache-2.0",
147
+ "pipeline": "text-generation",
148
+ "downloads": 806,
149
+ "likes": 142,
150
+ "params_b": 8.2,
151
+ "bases": [],
152
+ "providers": [],
153
+ "gguf": "mradermacher/II-Medical-8B-1706-i1-GGUF"
154
+ },
155
+ {
156
+ "id": "Intelligent-Internet/II-Medical-32B-Preview",
157
+ "role": "specialist",
158
+ "specialty": "clinical reasoning",
159
+ "licence": "apache-2.0",
160
+ "pipeline": null,
161
+ "downloads": 755,
162
+ "likes": 53,
163
+ "params_b": 32.8,
164
+ "bases": [],
165
+ "providers": [],
166
+ "gguf": "mradermacher/II-Medical-32B-Preview-GGUF"
167
+ },
168
+ {
169
+ "id": "FreedomIntelligence/HuatuoGPT-o1-7B",
170
+ "role": "specialist",
171
+ "specialty": "medical o1-style reasoning",
172
+ "note": "Think-then-answer, EN/ZH.",
173
+ "licence": "apache-2.0",
174
+ "pipeline": "text-generation",
175
+ "downloads": 331,
176
+ "likes": 69,
177
+ "params_b": 7.6,
178
+ "bases": [
179
+ "Qwen/Qwen2.5-7B-Instruct"
180
+ ],
181
+ "providers": [],
182
+ "gguf": "bartowski/HuatuoGPT-o1-7B-GGUF"
183
+ },
184
+ {
185
+ "id": "FreedomIntelligence/HuatuoGPT-3-8B",
186
+ "role": "specialist",
187
+ "specialty": "medical dialogue",
188
+ "licence": "apache-2.0",
189
+ "pipeline": "text-generation",
190
+ "downloads": 2311,
191
+ "likes": 10,
192
+ "params_b": 8.2,
193
+ "bases": [
194
+ "Qwen/Qwen3-8B-Base"
195
+ ],
196
+ "providers": [],
197
+ "gguf": "mradermacher/HuatuoGPT-3-8B-i1-GGUF"
198
+ },
199
+ {
200
+ "id": "baichuan-inc/Baichuan-M2-32B",
201
+ "role": "specialist",
202
+ "specialty": "clinical reasoning",
203
+ "note": "Verifier-trained medical model on Qwen2.5-32B.",
204
+ "licence": "apache-2.0",
205
+ "pipeline": "text-generation",
206
+ "downloads": 3791,
207
+ "likes": 127,
208
+ "params_b": 32.8,
209
+ "bases": [
210
+ "Qwen/Qwen2.5-32B"
211
+ ],
212
+ "providers": [],
213
+ "gguf": "baichuan-inc/Baichuan-M2-32B-Q4_K_M-GGUF"
214
+ },
215
+ {
216
+ "id": "BioMistral/BioMistral-7B",
217
+ "role": "specialist",
218
+ "specialty": "biomedical QA",
219
+ "note": "Mistral further pre-trained on PubMed Central.",
220
+ "licence": "apache-2.0",
221
+ "pipeline": "text-generation",
222
+ "downloads": 7466,
223
+ "likes": 524,
224
+ "params_b": null,
225
+ "bases": [],
226
+ "providers": [],
227
+ "gguf": "MaziyarPanahi/BioMistral-7B-GGUF"
228
+ },
229
+ {
230
+ "id": "microsoft/MediPhi-Instruct",
231
+ "role": "specialist",
232
+ "specialty": "clinical NLP",
233
+ "note": "Phi-3.5-mini medical instruct (MIT).",
234
+ "licence": "mit",
235
+ "pipeline": "text-generation",
236
+ "downloads": 2880,
237
+ "likes": 78,
238
+ "params_b": 3.8,
239
+ "bases": [
240
+ "microsoft/Phi-3.5-mini-instruct"
241
+ ],
242
+ "providers": [],
243
+ "gguf": "gabriellarson/MediPhi-Instruct-GGUF"
244
+ },
245
+ {
246
+ "id": "microsoft/MediPhi-Clinical",
247
+ "role": "specialist",
248
+ "specialty": "clinical notes",
249
+ "licence": "mit",
250
+ "pipeline": "text-generation",
251
+ "downloads": 1036,
252
+ "likes": 24,
253
+ "params_b": 3.8,
254
+ "bases": [
255
+ "microsoft/Phi-3.5-mini-instruct"
256
+ ],
257
+ "providers": [],
258
+ "gguf": "mradermacher/MediPhi-Clinical-i1-GGUF"
259
+ },
260
+ {
261
+ "id": "microsoft/MediPhi-Guidelines",
262
+ "role": "specialist",
263
+ "specialty": "clinical guidelines",
264
+ "licence": "mit",
265
+ "pipeline": "text-generation",
266
+ "downloads": 641,
267
+ "likes": 16,
268
+ "params_b": 3.8,
269
+ "bases": [
270
+ "microsoft/Phi-3.5-mini-instruct"
271
+ ],
272
+ "providers": [],
273
+ "gguf": "mradermacher/MediPhi-Guidelines-i1-GGUF"
274
+ },
275
+ {
276
+ "id": "tokyotech-llm/Medical-Qwen3-Swallow-8B",
277
+ "role": "specialist",
278
+ "specialty": "medical (JA/EN)",
279
+ "licence": "apache-2.0",
280
+ "pipeline": "text-generation",
281
+ "downloads": 1641,
282
+ "likes": 4,
283
+ "params_b": 8.2,
284
+ "bases": [
285
+ "tokyotech-llm/Qwen3-Swallow-8B-RL-v0.2"
286
+ ],
287
+ "providers": [],
288
+ "gguf": null
289
+ },
290
+ {
291
+ "id": "EPFLiGHT/Apertus-8B-MeditronFO",
292
+ "role": "specialist",
293
+ "specialty": "guideline-grounded medicine",
294
+ "licence": "apache-2.0",
295
+ "pipeline": "text-generation",
296
+ "downloads": 580,
297
+ "likes": 9,
298
+ "params_b": 8.1,
299
+ "bases": [
300
+ "swiss-ai/Apertus-8B-Instruct-2509"
301
+ ],
302
+ "providers": [],
303
+ "gguf": "mradermacher/Apertus-8B-MeditronFO-i1-GGUF"
304
+ },
305
+ {
306
+ "id": "EPFLiGHT/OLMo-2-32B-MeditronFO",
307
+ "role": "specialist",
308
+ "specialty": "guideline-grounded medicine",
309
+ "note": "Fully open base (OLMo).",
310
+ "licence": "apache-2.0",
311
+ "pipeline": "text-generation",
312
+ "downloads": 826,
313
+ "likes": 1,
314
+ "params_b": 32.2,
315
+ "bases": [
316
+ "allenai/OLMo-2-0325-32B-SFT"
317
+ ],
318
+ "providers": [],
319
+ "gguf": "mradermacher/OLMo-2-32B-MeditronFO-i1-GGUF"
320
+ },
321
+ {
322
+ "id": "EPFLiGHT/EuroLLM-9B-MeditronFO",
323
+ "role": "specialist",
324
+ "specialty": "multilingual EU medicine",
325
+ "licence": "apache-2.0",
326
+ "pipeline": "text-generation",
327
+ "downloads": 801,
328
+ "likes": 1,
329
+ "params_b": 9.2,
330
+ "bases": [
331
+ "utter-project/EuroLLM-9B-Instruct"
332
+ ],
333
+ "providers": [],
334
+ "gguf": "mradermacher/EuroLLM-9B-MeditronFO-i1-GGUF"
335
+ },
336
+ {
337
+ "id": "Writer/palmyra-med-20b",
338
+ "role": "specialist",
339
+ "specialty": "medical text",
340
+ "licence": "apache-2.0",
341
+ "pipeline": "text-generation",
342
+ "downloads": 679,
343
+ "likes": 37,
344
+ "params_b": null,
345
+ "bases": [],
346
+ "providers": [],
347
+ "gguf": null
348
+ },
349
+ {
350
+ "id": "qvac/MedPsy-4B",
351
+ "role": "specialist",
352
+ "specialty": "mental health",
353
+ "licence": "apache-2.0",
354
+ "pipeline": "text-generation",
355
+ "downloads": 1473,
356
+ "likes": 17,
357
+ "params_b": 4.4,
358
+ "bases": [
359
+ "Qwen/Qwen3-4B-Thinking-2507"
360
+ ],
361
+ "providers": [],
362
+ "gguf": "qvac/MedPsy-4B-GGUF"
363
+ },
364
+ {
365
+ "id": "microsoft/BioGPT-Large",
366
+ "role": "specialist",
367
+ "specialty": "biomedical text generation",
368
+ "licence": "mit",
369
+ "pipeline": "text-generation",
370
+ "downloads": 1627,
371
+ "likes": 244,
372
+ "params_b": null,
373
+ "bases": [],
374
+ "providers": [],
375
+ "gguf": null
376
+ },
377
+ {
378
+ "id": "lingshu-medical-mllm/Lingshu-7B",
379
+ "role": "vision",
380
+ "specialty": "radiology \u00b7 pathology \u00b7 dermatology",
381
+ "note": "Medical multimodal (MIT).",
382
+ "licence": "mit",
383
+ "pipeline": "image-text-to-text",
384
+ "downloads": 7822,
385
+ "likes": 86,
386
+ "params_b": 8.3,
387
+ "bases": [],
388
+ "providers": [],
389
+ "gguf": "mradermacher/Lingshu-7B-GGUF"
390
+ },
391
+ {
392
+ "id": "lingshu-medical-mllm/Lingshu-32B",
393
+ "role": "vision",
394
+ "specialty": "radiology \u00b7 pathology \u00b7 dermatology",
395
+ "licence": "mit",
396
+ "pipeline": "image-text-to-text",
397
+ "downloads": 1682,
398
+ "likes": 84,
399
+ "params_b": 33.5,
400
+ "bases": [],
401
+ "providers": [],
402
+ "gguf": "mradermacher/Lingshu-32B-GGUF"
403
+ },
404
+ {
405
+ "id": "UCSC-VLAA/MedVLThinker-7B-RL_m23k",
406
+ "role": "vision",
407
+ "specialty": "medical visual reasoning",
408
+ "licence": "apache-2.0",
409
+ "pipeline": "image-text-to-text",
410
+ "downloads": 120,
411
+ "likes": 1,
412
+ "params_b": 8.3,
413
+ "bases": [
414
+ "Qwen/Qwen2.5-VL-7B-Instruct"
415
+ ],
416
+ "providers": [],
417
+ "gguf": null
418
+ },
419
+ {
420
+ "id": "microsoft/llava-med-v1.5-mistral-7b",
421
+ "role": "vision",
422
+ "specialty": "biomedical image QA",
423
+ "licence": "apache-2.0",
424
+ "pipeline": "image-text-to-text",
425
+ "downloads": 4180,
426
+ "likes": 140,
427
+ "params_b": 7.6,
428
+ "bases": [],
429
+ "providers": [],
430
+ "gguf": null
431
+ },
432
+ {
433
+ "id": "NeuML/pubmedbert-base-embeddings",
434
+ "role": "embedding",
435
+ "note": "Powers drAIML's evidence search.",
436
+ "licence": "apache-2.0",
437
+ "pipeline": "sentence-similarity",
438
+ "downloads": 661694,
439
+ "likes": 207,
440
+ "params_b": 0.1,
441
+ "bases": [
442
+ "microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext"
443
+ ],
444
+ "providers": [
445
+ "hf-inference"
446
+ ]
447
+ },
448
+ {
449
+ "id": "abhinand/MedEmbed-base-v0.1",
450
+ "role": "embedding",
451
+ "note": "Medical retrieval embeddings.",
452
+ "licence": "apache-2.0",
453
+ "pipeline": null,
454
+ "downloads": 19210,
455
+ "likes": 22,
456
+ "params_b": 0.1,
457
+ "bases": [
458
+ "BAAI/bge-base-en-v1.5"
459
+ ],
460
+ "providers": []
461
+ },
462
+ {
463
+ "id": "BAAI/bge-small-en-v1.5",
464
+ "role": "embedding",
465
+ "note": "Small general embeddings.",
466
+ "licence": "mit",
467
+ "pipeline": "feature-extraction",
468
+ "downloads": 42857435,
469
+ "likes": 685,
470
+ "params_b": 0.0,
471
+ "bases": [],
472
+ "providers": [
473
+ "hf-inference"
474
+ ]
475
+ },
476
+ {
477
+ "id": "microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext",
478
+ "role": "encoder",
479
+ "note": "PubMedBERT base encoder.",
480
+ "licence": "mit",
481
+ "pipeline": "fill-mask",
482
+ "downloads": 3360654,
483
+ "likes": 350,
484
+ "params_b": null,
485
+ "bases": [],
486
+ "providers": [
487
+ "hf-inference"
488
+ ]
489
+ },
490
+ {
491
+ "id": "emilyalsentzer/Bio_ClinicalBERT",
492
+ "role": "encoder",
493
+ "note": "Clinical-notes BERT (MIMIC).",
494
+ "licence": "mit",
495
+ "pipeline": "fill-mask",
496
+ "downloads": 2662307,
497
+ "likes": 455,
498
+ "params_b": null,
499
+ "bases": [],
500
+ "providers": [
501
+ "hf-inference"
502
+ ]
503
+ },
504
+ {
505
+ "id": "d4data/biomedical-ner-all",
506
+ "role": "ner",
507
+ "note": "107 biomedical entity types.",
508
+ "licence": "apache-2.0",
509
+ "pipeline": "token-classification",
510
+ "downloads": 74374,
511
+ "likes": 198,
512
+ "params_b": 0.1,
513
+ "bases": [],
514
+ "providers": [
515
+ "hf-inference"
516
+ ]
517
+ },
518
+ {
519
+ "id": "Clinical-AI-Apollo/Medical-NER",
520
+ "role": "ner",
521
+ "note": "Clinical entity recognition.",
522
+ "licence": "mit",
523
+ "pipeline": "token-classification",
524
+ "downloads": 8469,
525
+ "likes": 231,
526
+ "params_b": 0.2,
527
+ "bases": [
528
+ "microsoft/deberta-v3-base"
529
+ ],
530
+ "providers": [
531
+ "hf-inference"
532
+ ]
533
+ },
534
+ {
535
+ "id": "openai/whisper-large-v3-turbo",
536
+ "role": "speech",
537
+ "note": "Dictate symptoms (speech-to-text).",
538
+ "licence": "mit",
539
+ "pipeline": "automatic-speech-recognition",
540
+ "downloads": 4524410,
541
+ "likes": 3574,
542
+ "params_b": 0.8,
543
+ "bases": [
544
+ "openai/whisper-large-v3"
545
+ ],
546
+ "providers": [
547
+ "deepinfra",
548
+ "hf-inference"
549
+ ]
550
+ }
551
+ ],
552
+ "datasets": [
553
+ {
554
+ "id": "qiaojin/PubMedQA",
555
+ "role": "research QA",
556
+ "note": "Yes/no/maybe questions answered from PubMed abstracts.",
557
+ "licence": "mit",
558
+ "downloads": 39949,
559
+ "likes": 360,
560
+ "size": "100K<n<1M",
561
+ "pretty": "PubMedQA"
562
+ },
563
+ {
564
+ "id": "openlifescienceai/medmcqa",
565
+ "role": "exam QA",
566
+ "note": "194k medical entrance-exam MCQs with explanations.",
567
+ "licence": "apache-2.0",
568
+ "downloads": 58975,
569
+ "likes": 253,
570
+ "size": "100K<n<1M",
571
+ "pretty": "MedMCQA"
572
+ },
573
+ {
574
+ "id": "GBaker/MedQA-USMLE-4-options",
575
+ "role": "exam QA",
576
+ "note": "USMLE-style clinical vignettes.",
577
+ "licence": "cc-by-4.0",
578
+ "downloads": 34789,
579
+ "likes": 106,
580
+ "size": null,
581
+ "pretty": null
582
+ },
583
+ {
584
+ "id": "FreedomIntelligence/medical-o1-reasoning-SFT",
585
+ "role": "reasoning",
586
+ "note": "Verifiable medical problems with reasoning chains.",
587
+ "licence": "apache-2.0",
588
+ "downloads": 22148,
589
+ "likes": 1244,
590
+ "size": null,
591
+ "pretty": null
592
+ },
593
+ {
594
+ "id": "FreedomIntelligence/medical-o1-verifiable-problem",
595
+ "role": "reasoning",
596
+ "licence": "apache-2.0",
597
+ "downloads": 2662,
598
+ "likes": 125,
599
+ "size": null,
600
+ "pretty": null
601
+ },
602
+ {
603
+ "id": "UCSC-VLAA/MedReason",
604
+ "role": "reasoning",
605
+ "note": "Knowledge-graph-grounded medical reasoning.",
606
+ "licence": "apache-2.0",
607
+ "downloads": 5176,
608
+ "likes": 90,
609
+ "size": null,
610
+ "pretty": null
611
+ },
612
+ {
613
+ "id": "FreedomIntelligence/ApolloCorpus",
614
+ "role": "corpus",
615
+ "note": "Multilingual medical corpus.",
616
+ "licence": "apache-2.0",
617
+ "downloads": 2505,
618
+ "likes": 41,
619
+ "size": null,
620
+ "pretty": null
621
+ },
622
+ {
623
+ "id": "FreedomIntelligence/HuatuoGPT-sft-data-v1",
624
+ "role": "dialogue",
625
+ "licence": "apache-2.0",
626
+ "downloads": 517,
627
+ "likes": 84,
628
+ "size": null,
629
+ "pretty": null
630
+ },
631
+ {
632
+ "id": "BI55/MedText",
633
+ "role": "clinical cases",
634
+ "note": "Patient presentations with assessments.",
635
+ "licence": "cc-by-4.0",
636
+ "downloads": 358,
637
+ "likes": 93,
638
+ "size": null,
639
+ "pretty": null
640
+ },
641
+ {
642
+ "id": "openai/healthbench",
643
+ "role": "safety eval",
644
+ "note": "Physician-written rubric conversations.",
645
+ "licence": "mit",
646
+ "downloads": 8603,
647
+ "likes": 193,
648
+ "size": null,
649
+ "pretty": null
650
+ },
651
+ {
652
+ "id": "cais/mmlu",
653
+ "role": "exam QA",
654
+ "note": "Includes clinical knowledge, anatomy, medical genetics, professional medicine.",
655
+ "licence": "mit",
656
+ "downloads": 655863,
657
+ "likes": 900,
658
+ "size": "10K<n<100K",
659
+ "pretty": "Measuring Massive Multitask Language Understanding"
660
+ },
661
+ {
662
+ "id": "flaviagiammarino/vqa-rad",
663
+ "role": "radiology VQA",
664
+ "licence": "cc0-1.0",
665
+ "downloads": 5385,
666
+ "likes": 105,
667
+ "size": "1K<n<10K",
668
+ "pretty": "VQA-RAD"
669
+ },
670
+ {
671
+ "id": "flaviagiammarino/path-vqa",
672
+ "role": "pathology VQA",
673
+ "licence": "mit",
674
+ "downloads": 23575,
675
+ "likes": 77,
676
+ "size": "10K<n<100K",
677
+ "pretty": "PathVQA"
678
+ },
679
+ {
680
+ "id": "gamino/wiki_medical_terms",
681
+ "role": "glossary",
682
+ "note": "Wikipedia medical terms (GPL-3.0).",
683
+ "licence": "gpl-3.0",
684
+ "downloads": 391,
685
+ "likes": 109,
686
+ "size": "1K<n<10K",
687
+ "pretty": "Medical terms and their wikipedia text"
688
+ },
689
+ {
690
+ "id": "Malikeh1375/medical-question-answering-datasets",
691
+ "role": "QA collection",
692
+ "licence": "mit",
693
+ "downloads": 1230,
694
+ "likes": 91,
695
+ "size": null,
696
+ "pretty": null
697
+ },
698
+ {
699
+ "id": "bigbio/pubmed_qa",
700
+ "role": "research QA",
701
+ "licence": "mit",
702
+ "downloads": 3491,
703
+ "likes": 60,
704
+ "size": null,
705
+ "pretty": "PubMedQA"
706
+ }
707
+ ],
708
+ "router_open": {
709
+ "thinkingmachines/Inkling-2-Mini": {
710
+ "licence": "apache-2.0",
711
+ "providers": [
712
+ "deepinfra",
713
+ "io-net",
714
+ "primeintellect",
715
+ "relace"
716
+ ],
717
+ "vision": true
718
+ },
719
+ "Qwen/Qwen3.8-27B": {
720
+ "licence": "apache-2.0",
721
+ "providers": [
722
+ "akashml",
723
+ "cerebras",
724
+ "cloudflare",
725
+ "coreweave",
726
+ "deepinfra",
727
+ "ionstream",
728
+ "mancer",
729
+ "modal",
730
+ "modelrun",
731
+ "near-ai",
732
+ "nebius",
733
+ "parasail",
734
+ "pearl-research",
735
+ "primeintellect",
736
+ "reka",
737
+ "tenstorrent",
738
+ "wafer"
739
+ ],
740
+ "vision": true
741
+ },
742
+ "RadixArk/DaisyRose-27B": {
743
+ "licence": "apache-2.0",
744
+ "providers": [
745
+ "deepinfra"
746
+ ],
747
+ "vision": true
748
+ },
749
+ "deepseek-ai/DeepSeek-V4.1-Flash-1017": {
750
+ "licence": "mit",
751
+ "providers": [
752
+ "baseten",
753
+ "cloudflare",
754
+ "cohere",
755
+ "coreweave",
756
+ "crusoe",
757
+ "deepinfra",
758
+ "digitalocean",
759
+ "featherless-ai",
760
+ "fireworks-ai",
761
+ "inceptron",
762
+ "inference-net",
763
+ "ionstream",
764
+ "krea",
765
+ "makora",
766
+ "mistral",
767
+ "modal",
768
+ "modelrun",
769
+ "morph",
770
+ "near-ai",
771
+ "nebius",
772
+ "open-inference",
773
+ "parasail",
774
+ "particle-ai",
775
+ "pearl-research",
776
+ "primalabs",
777
+ "primeintellect",
778
+ "reka",
779
+ "relace",
780
+ "river",
781
+ "tenstorrent",
782
+ "together",
783
+ "venice",
784
+ "wafer"
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": [
802
+ "modal",
803
+ "together"
804
+ ],
805
+ "vision": true
806
+ },
807
+ "zai-org/GLM-5.3-Flash": {
808
+ "licence": "mit",
809
+ "providers": [
810
+ "baseten",
811
+ "coreweave",
812
+ "crusoe",
813
+ "deepinfra",
814
+ "digitalocean",
815
+ "fireworks-ai",
816
+ "inceptron",
817
+ "inference-net",
818
+ "makora",
819
+ "mistral",
820
+ "modal",
821
+ "morph",
822
+ "near-ai",
823
+ "nebius",
824
+ "open-inference",
825
+ "parasail",
826
+ "particle-ai",
827
+ "reka",
828
+ "relace",
829
+ "river",
830
+ "sail-research",
831
+ "tenstorrent",
832
+ "together",
833
+ "venice",
834
+ "wafer"
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
+ ],
864
+ "vision": true
865
+ },
866
+ "deepseek-ai/DeepSeek-V4.1-Flash": {
867
+ "licence": "mit",
868
+ "providers": [
869
+ "baseten",
870
+ "cloudflare",
871
+ "cohere",
872
+ "coreweave",
873
+ "crusoe",
874
+ "deepinfra",
875
+ "digitalocean",
876
+ "featherless-ai",
877
+ "fireworks-ai",
878
+ "inference-net",
879
+ "ionstream",
880
+ "makora",
881
+ "mancer",
882
+ "modal",
883
+ "nebius",
884
+ "open-inference",
885
+ "parasail",
886
+ "reka",
887
+ "relace",
888
+ "river",
889
+ "together",
890
+ "venice",
891
+ "wafer"
892
+ ],
893
+ "vision": true
894
+ },
895
+ "openai/gpt-oss-120b": {
896
+ "licence": "apache-2.0",
897
+ "providers": [
898
+ "akashml",
899
+ "amazon-bedrock",
900
+ "baseten",
901
+ "cerebras",
902
+ "coreweave",
903
+ "crusoe",
904
+ "deepinfra",
905
+ "digitalocean",
906
+ "google-vertex",
907
+ "groq",
908
+ "mancer",
909
+ "near-ai",
910
+ "nebius",
911
+ "parasail",
912
+ "primeintellect",
913
+ "sambanova",
914
+ "together",
915
+ "venice"
916
+ ],
917
+ "vision": false
918
+ },
919
+ "deepseek-ai/DeepSeek-V4-Pro": {
920
+ "licence": "mit",
921
+ "providers": [
922
+ "azure",
923
+ "deepinfra",
924
+ "relace",
925
+ "venice"
926
+ ],
927
+ "vision": false
928
+ },
929
+ "google/gemma-4-31B-it": {
930
+ "licence": "apache-2.0",
931
+ "providers": [
932
+ "coreweave",
933
+ "crusoe",
934
+ "deepinfra",
935
+ "modal",
936
+ "modelrun",
937
+ "nextbit",
938
+ "parasail",
939
+ "primeintellect",
940
+ "sambanova",
941
+ "venice"
942
+ ],
943
+ "vision": true
944
+ },
945
+ "meta-models/Muse-Glimmer-30B": {
946
+ "licence": "apache-2.0",
947
+ "providers": [
948
+ "deepinfra",
949
+ "modelrun",
950
+ "together"
951
+ ],
952
+ "vision": true
953
+ },
954
+ "openai/gpt-oss-20b": {
955
+ "licence": "apache-2.0",
956
+ "providers": [
957
+ "akashml",
958
+ "amazon-bedrock",
959
+ "coreweave",
960
+ "deepinfra",
961
+ "parasail",
962
+ "primeintellect"
963
+ ],
964
+ "vision": false
965
+ },
966
+ "Qwen/Qwen3.5-9B": {
967
+ "licence": "apache-2.0",
968
+ "providers": [
969
+ "deepinfra",
970
+ "parasail",
971
+ "primeintellect",
972
+ "together"
973
+ ],
974
+ "vision": true
975
+ },
976
+ "zai-org/GLM-5.2": {
977
+ "licence": "mit",
978
+ "providers": [
979
+ "baseten",
980
+ "coreweave",
981
+ "deepinfra",
982
+ "digitalocean",
983
+ "featherless-ai",
984
+ "mistral",
985
+ "morph",
986
+ "nebius",
987
+ "parasail",
988
+ "relace",
989
+ "together",
990
+ "venice",
991
+ "wafer"
992
+ ],
993
+ "vision": false
994
+ },
995
+ "deepseek-ai/DeepSeek-V3.2": {
996
+ "licence": "mit",
997
+ "providers": [
998
+ "deepinfra",
999
+ "featherless-ai"
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": [
1013
+ "parasail"
1014
+ ],
1015
+ "vision": false
1016
+ },
1017
+ "deepseek-ai/DeepSeek-V4-Flash-0731": {
1018
+ "licence": "mit",
1019
+ "providers": [
1020
+ "baseten",
1021
+ "cohere",
1022
+ "coreweave",
1023
+ "deepinfra",
1024
+ "digitalocean",
1025
+ "mancer",
1026
+ "nebius",
1027
+ "parasail",
1028
+ "relace",
1029
+ "sail-research",
1030
+ "venice",
1031
+ "wafer"
1032
+ ],
1033
+ "vision": false
1034
+ },
1035
+ "Qwen/Qwen3-Coder-30B-A3B-Instruct": {
1036
+ "licence": "apache-2.0",
1037
+ "providers": [
1038
+ "amazon-bedrock"
1039
+ ],
1040
+ "vision": false
1041
+ },
1042
+ "XiaomiMiMo/MiMo-V2.6-Pro-RL": {
1043
+ "licence": "mit",
1044
+ "providers": [
1045
+ "deepinfra",
1046
+ "primalabs"
1047
+ ],
1048
+ "vision": false
1049
+ },
1050
+ "Qwen/Qwen3.6-27B": {
1051
+ "licence": "apache-2.0",
1052
+ "providers": [
1053
+ "deepinfra",
1054
+ "reka",
1055
+ "venice"
1056
+ ],
1057
+ "vision": true
1058
+ },
1059
+ "deepseek-ai/DeepSeek-V4-Flash": {
1060
+ "licence": "mit",
1061
+ "providers": [
1062
+ "azure",
1063
+ "deepinfra",
1064
+ "featherless-ai",
1065
+ "fireworks-ai",
1066
+ "mancer",
1067
+ "parasail",
1068
+ "relace",
1069
+ "venice",
1070
+ "wafer"
1071
+ ],
1072
+ "vision": false
1073
+ },
1074
+ "thinkingmachines/Inkling-Small": {
1075
+ "licence": "apache-2.0",
1076
+ "providers": [
1077
+ "deepinfra"
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
+ },
1095
+ "dphn/Dolphin-Mistral-24B-Venice-Edition": {
1096
+ "licence": "apache-2.0",
1097
+ "providers": [
1098
+ "venice"
1099
+ ],
1100
+ "vision": false
1101
+ },
1102
+ "Qwen/Qwen3-VL-8B-Instruct": {
1103
+ "licence": "apache-2.0",
1104
+ "providers": [
1105
+ "parasail"
1106
+ ],
1107
+ "vision": true
1108
+ },
1109
+ "XiaomiMiMo/MiMo-V2.6-Flash-RL": {
1110
+ "licence": "mit",
1111
+ "providers": [
1112
+ "cohere",
1113
+ "deepinfra",
1114
+ "featherless-ai",
1115
+ "makora",
1116
+ "tenstorrent",
1117
+ "venice"
1118
+ ],
1119
+ "vision": false
1120
+ },
1121
+ "reflection/Beam-1.0-501B-A23B": {
1122
+ "licence": "apache-2.0",
1123
+ "providers": [
1124
+ "baseten",
1125
+ "coreweave",
1126
+ "digitalocean",
1127
+ "nebius",
1128
+ "together"
1129
+ ],
1130
+ "vision": false
1131
+ },
1132
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct": {
1133
+ "licence": "apache-2.0",
1134
+ "providers": [
1135
+ "deepinfra",
1136
+ "venice"
1137
+ ],
1138
+ "vision": false
1139
+ },
1140
+ "inclusionAI/Ling-3.0-flash-VL": {
1141
+ "licence": "mit",
1142
+ "providers": [
1143
+ "deepinfra"
1144
+ ],
1145
+ "vision": true
1146
+ },
1147
+ "zai-org/GLM-5": {
1148
+ "licence": "mit",
1149
+ "providers": [
1150
+ "amazon-bedrock"
1151
+ ],
1152
+ "vision": false
1153
+ },
1154
+ "ibm-granite/granite-4.2-8b": {
1155
+ "licence": "apache-2.0",
1156
+ "providers": [
1157
+ "coreweave",
1158
+ "deepinfra"
1159
+ ],
1160
+ "vision": false
1161
+ },
1162
+ "deepseek-ai/DeepSeek-V4-Pro-0813": {
1163
+ "licence": "mit",
1164
+ "providers": [
1165
+ "baseten",
1166
+ "coreweave",
1167
+ "deepinfra",
1168
+ "digitalocean",
1169
+ "nebius",
1170
+ "parasail",
1171
+ "pearl-research",
1172
+ "relace",
1173
+ "together",
1174
+ "venice",
1175
+ "wafer"
1176
+ ],
1177
+ "vision": false
1178
+ },
1179
+ "Qwen/Qwen3-14B": {
1180
+ "licence": "apache-2.0",
1181
+ "providers": [
1182
+ "deepinfra",
1183
+ "nextbit"
1184
+ ],
1185
+ "vision": false
1186
+ },
1187
+ "Qwen/Qwen3-32B": {
1188
+ "licence": "apache-2.0",
1189
+ "providers": [
1190
+ "deepinfra"
1191
+ ],
1192
+ "vision": false
1193
+ },
1194
+ "tngtech/DeepSeek-TNG-R1T2-Chimera": {
1195
+ "licence": "mit",
1196
+ "providers": [
1197
+ "featherless-ai"
1198
+ ],
1199
+ "vision": false
1200
+ },
1201
+ "Qwen/Qwen3-Next-80B-A3B-Instruct": {
1202
+ "licence": "apache-2.0",
1203
+ "providers": [
1204
+ "deepinfra",
1205
+ "parasail"
1206
+ ],
1207
+ "vision": false
1208
+ },
1209
+ "Qwen/Qwen3.5-35B-A3B": {
1210
+ "licence": "apache-2.0",
1211
+ "providers": [
1212
+ "deepinfra",
1213
+ "parasail",
1214
+ "venice"
1215
+ ],
1216
+ "vision": true
1217
+ },
1218
+ "Qwen/Qwen3.5-27B": {
1219
+ "licence": "apache-2.0",
1220
+ "providers": [
1221
+ "deepinfra"
1222
+ ],
1223
+ "vision": true
1224
+ },
1225
+ "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp": {
1226
+ "licence": "mit",
1227
+ "providers": [
1228
+ "deepinfra"
1229
+ ],
1230
+ "vision": true
1231
+ },
1232
+ "Qwen/Qwen3.5-397B-A17B": {
1233
+ "licence": "apache-2.0",
1234
+ "providers": [
1235
+ "deepinfra",
1236
+ "parasail"
1237
+ ],
1238
+ "vision": true
1239
+ },
1240
+ "ByteDance-Seed/UI-TARS-1.5-7B": {
1241
+ "licence": "apache-2.0",
1242
+ "providers": [
1243
+ "parasail"
1244
+ ],
1245
+ "vision": true
1246
+ },
1247
+ "Qwen/Qwen3-30B-A3B": {
1248
+ "licence": "apache-2.0",
1249
+ "providers": [
1250
+ "deepinfra"
1251
+ ],
1252
+ "vision": false
1253
+ },
1254
+ "Qwen/Qwen3-235B-A22B-Instruct-2507": {
1255
+ "licence": "apache-2.0",
1256
+ "providers": [
1257
+ "deepinfra",
1258
+ "parasail",
1259
+ "venice"
1260
+ ],
1261
+ "vision": false
1262
+ },
1263
+ "Qwen/Qwen3-235B-A22B-Thinking-2507": {
1264
+ "licence": "apache-2.0",
1265
+ "providers": [
1266
+ "venice"
1267
+ ],
1268
+ "vision": false
1269
+ },
1270
+ "Qwen/Qwen3-30B-A3B-Instruct-2507": {
1271
+ "licence": "apache-2.0",
1272
+ "providers": [
1273
+ "nebius"
1274
+ ],
1275
+ "vision": false
1276
+ },
1277
+ "deepseek-ai/DeepSeek-V3.1": {
1278
+ "licence": "mit",
1279
+ "providers": [
1280
+ "coreweave",
1281
+ "deepinfra"
1282
+ ],
1283
+ "vision": false
1284
+ },
1285
+ "openai/gpt-oss-safeguard-20b": {
1286
+ "licence": "apache-2.0",
1287
+ "providers": [
1288
+ "amazon-bedrock"
1289
+ ],
1290
+ "vision": false
1291
+ },
1292
+ "Qwen/Qwen3-VL-30B-A3B-Instruct": {
1293
+ "licence": "apache-2.0",
1294
+ "providers": [
1295
+ "deepinfra"
1296
+ ],
1297
+ "vision": true
1298
+ },
1299
+ "CohereLabs/command-a-plus-05-2026-bf16": {
1300
+ "licence": "apache-2.0",
1301
+ "providers": [
1302
+ "cohere"
1303
+ ],
1304
+ "vision": true
1305
+ },
1306
+ "inclusionAI/Ling-3.0-flash": {
1307
+ "licence": "mit",
1308
+ "providers": [
1309
+ "deepinfra"
1310
+ ],
1311
+ "vision": false
1312
+ },
1313
+ "anthracite-org/magnum-v4-72b": {
1314
+ "licence": "apache-2.0",
1315
+ "providers": [
1316
+ "mancer"
1317
+ ],
1318
+ "vision": false
1319
+ },
1320
+ "microsoft/phi-4": {
1321
+ "licence": "mit",
1322
+ "providers": [
1323
+ "deepinfra"
1324
+ ],
1325
+ "vision": false
1326
+ },
1327
+ "deepseek-ai/DeepSeek-V3-0324": {
1328
+ "licence": "mit",
1329
+ "providers": [],
1330
+ "vision": false
1331
+ },
1332
+ "Qwen/Qwen3-VL-235B-A22B-Instruct": {
1333
+ "licence": "apache-2.0",
1334
+ "providers": [
1335
+ "deepinfra",
1336
+ "parasail",
1337
+ "venice"
1338
+ ],
1339
+ "vision": true
1340
+ },
1341
+ "zai-org/GLM-4.6": {
1342
+ "licence": "mit",
1343
+ "providers": [
1344
+ "deepinfra",
1345
+ "venice"
1346
+ ],
1347
+ "vision": false
1348
+ },
1349
+ "zai-org/GLM-4.7": {
1350
+ "licence": "mit",
1351
+ "providers": [
1352
+ "deepinfra",
1353
+ "mancer",
1354
+ "venice"
1355
+ ],
1356
+ "vision": false
1357
+ },
1358
+ "tencent/Hy4-preview": {
1359
+ "licence": "apache-2.0",
1360
+ "providers": [
1361
+ "deepinfra",
1362
+ "venice"
1363
+ ],
1364
+ "vision": false
1365
+ }
1366
+ },
1367
+ "router_closed": {
1368
+ "tencent/Hy4-flash": "tencent/Hy4-flash is 'other'",
1369
+ "tencent/Hy4": "tencent/Hy4 is 'other'",
1370
+ "moonshotai/Kimi-K3.1-Pro": "moonshotai/Kimi-K3.1-Pro is 'other'",
1371
+ "Qwen/Qwen3.8-Flash-Next": "Qwen/Qwen3.8-Flash-Next is 'other'",
1372
+ "zai-org/GLM-5.3": "zai-org/GLM-5.3 is 'other'",
1373
+ "meta-llama/Llama-3.1-8B-Instruct": "meta-llama/Llama-3.1-8B-Instruct is 'llama3.1'",
1374
+ "LiquidAI/LFM3-1.7B": "LiquidAI/LFM3-1.7B is 'other'",
1375
+ "meta-llama/Llama-3.2-3B-Instruct": "meta-llama/Llama-3.2-3B-Instruct is 'llama3.2'",
1376
+ "moonshotai/Kimi-K3": "moonshotai/Kimi-K3 is 'other'",
1377
+ "google/gemma-3-4b-it": "google/gemma-3-4b-it is 'gemma'",
1378
+ "mistralai/Mistral-Large-4-1T-A52B": "mistralai/Mistral-Large-4-1T-A52B is 'other'",
1379
+ "Qwen/Qwen3.8-2.4T-A95B": "Qwen/Qwen3.8-2.4T-A95B is 'other'",
1380
+ "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16": "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16 is 'other'",
1381
+ "LiquidAI/LFM2.5-24B-A2B": "LiquidAI/LFM2.5-24B-A2B is 'other'",
1382
+ "Gryphe/MythoMax-L2-13b": "Gryphe/MythoMax-L2-13b is 'other'",
1383
+ "meta-llama/Llama-3.3-70B-Instruct": "meta-llama/Llama-3.3-70B-Instruct is 'llama3.3'",
1384
+ "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16 is 'other'",
1385
+ "MiniMaxAI/MiniMax-M3.1-Flash": "MiniMaxAI/MiniMax-M3.1-Flash is 'other'",
1386
+ "google/gemma-3-27b-it": "google/gemma-3-27b-it is 'gemma'",
1387
+ "meta-llama/Llama-4-Maverick-17B-128E-Instruct": "meta-llama/Llama-4-Maverick-17B-128E-Instruct is 'other'",
1388
+ "moondream/moondream3-preview": "moondream/moondream3-preview is 'other'",
1389
+ "MiniMaxAI/MiniMax-M2.5": "MiniMaxAI/MiniMax-M2.5 is 'other'",
1390
+ "Sao10K/L3-8B-Lunaris-v1": "Sao10K/L3-8B-Lunaris-v1 is 'llama3'",
1391
+ "Qwen/Qwen2.5-72B-Instruct": "Qwen/Qwen2.5-72B-Instruct is 'other'",
1392
+ "google/gemma-3-12b-it": "google/gemma-3-12b-it is 'gemma'",
1393
+ "moonshotai/Kimi-K2.6": "moonshotai/Kimi-K2.6 is 'other'",
1394
+ "MiniMaxAI/MiniMax-M3": "MiniMaxAI/MiniMax-M3 is 'other'",
1395
+ "meta-models/Muse-Spark-Open-816B-A42B": "meta-models/Muse-Spark-Open-816B-A42B is 'other'",
1396
+ "deepseek-ai/DeepSeek-V3": "deepseek-ai/DeepSeek-V3 is None",
1397
+ "meta-llama/Llama-4-Scout-17B-16E-Instruct": "meta-llama/Llama-4-Scout-17B-16E-Instruct is 'other'",
1398
+ "moondream/moondream3.1-9B-A2B": "moondream/moondream3.1-9B-A2B is 'other'",
1399
+ "meta-llama/Llama-3.1-70B-Instruct": "meta-llama/Llama-3.1-70B-Instruct is 'llama3.1'",
1400
+ "moonshotai/Kimi-K2.5": "moonshotai/Kimi-K2.5 is 'other'",
1401
+ "moonshotai/Kimi-K2.7-Code": "moonshotai/Kimi-K2.7-Code is 'other'",
1402
+ "MiniMaxAI/MiniMax-M2.7": "MiniMaxAI/MiniMax-M2.7 is 'other'",
1403
+ "Undi95/ReMM-SLERP-L2-13B": "Undi95/ReMM-SLERP-L2-13B is 'cc-by-nc-4.0'",
1404
+ "google/gemma-2-27b-it": "google/gemma-2-27b-it is 'gemma'",
1405
+ "Qwen/Qwen2.5-VL-72B-Instruct": "Qwen/Qwen2.5-VL-72B-Instruct is 'other'",
1406
+ "meta-llama/Llama-Guard-4-12B": "meta-llama/Llama-Guard-4-12B is 'other'",
1407
+ "NousResearch/Hermes-4-405B": "NousResearch/Hermes-4-405B is 'llama3'",
1408
+ "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 is 'other'",
1409
+ "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8": "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8 is 'other'",
1410
+ "RekaAI/reka-edge-2603": "RekaAI/reka-edge-2603 is 'other'",
1411
+ "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16 is 'other'"
1412
+ }
1413
+ }
app/draiml/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """drAIML 2.0.0 — open healthcare consultation on Hugging Face."""
2
+ __version__ = "2.0.0"
app/draiml/catalogue.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model and dataset catalogue: curated core (verified at build time) + live Hub data, all licence-gated.
2
+
3
+ Results are cached in module globals, which persist across Streamlit reruns inside the stlite worker.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import re
9
+ import time
10
+ import urllib.parse
11
+ from pathlib import Path
12
+
13
+ from . import net
14
+ from .licences import is_open, licence_of
15
+
16
+ DATA = Path(__file__).resolve().parents[1] / "data" / "catalogue.json"
17
+ HUB = "https://huggingface.co/api"
18
+ ROUTER_MODELS = "https://router.huggingface.co/v1/models"
19
+ TTL = 6 * 3600
20
+
21
+ # open-licence models that are still the wrong tool for a medical consultation
22
+ UNSUITED = re.compile(r"coder|code-|ui-tars|magnum|dolphin|venice|safeguard|abliterat|uncensor|roleplay|rp-|guard-",
23
+ re.I)
24
+
25
+ _cache: dict[str, tuple[float, object]] = {}
26
+
27
+
28
+ def _get(key):
29
+ v = _cache.get(key)
30
+ return v[1] if v and time.time() - v[0] < TTL else None
31
+
32
+
33
+ def _put(key, val):
34
+ _cache[key] = (time.time(), val)
35
+ return val
36
+
37
+
38
+ def curated() -> dict:
39
+ c = _get("curated")
40
+ return c if c is not None else _put("curated", json.loads(DATA.read_text()))
41
+
42
+
43
+ def curated_models(role: str | None = None) -> list[dict]:
44
+ return [m for m in curated()["models"] if role is None or m["role"] == role]
45
+
46
+
47
+ def curated_datasets() -> list[dict]:
48
+ return curated()["datasets"]
49
+
50
+
51
+ async def _model_licence_ok(mid: str) -> tuple[bool, str | None]:
52
+ """Own licence + first-level base models (the build script walks the full chain)."""
53
+ j = await net.get_json(f"{HUB}/models/{mid}?expand[]=cardData&expand[]=tags")
54
+ lic = licence_of(j)
55
+ if not is_open(lic, "model"):
56
+ return False, lic
57
+ bases = (j.get("cardData") or {}).get("base_model") or []
58
+ bases = [bases] if isinstance(bases, str) else bases
59
+ for b in bases[:3]:
60
+ if b == mid:
61
+ continue
62
+ bj = await net.get_json(f"{HUB}/models/{b}?expand[]=cardData&expand[]=tags")
63
+ if not is_open(licence_of(bj), "model"):
64
+ return False, f"base {b}: {licence_of(bj)}"
65
+ return True, lic
66
+
67
+
68
+ async def hosted_engines() -> list[dict]:
69
+ """Chat models live on HF Inference Providers right now that pass the licence and suitability gates."""
70
+ cached = _get("hosted")
71
+ if cached is not None:
72
+ return cached
73
+ cat = curated()
74
+ known_open, known_closed = cat.get("router_open", {}), cat.get("router_closed", {})
75
+ try:
76
+ live = (await net.get_json(ROUTER_MODELS))["data"]
77
+ except Exception:
78
+ live = [{"id": k, "providers": [{"provider": p, "status": "live"} for p in v["providers"]]}
79
+ for k, v in known_open.items()]
80
+ unknown = [m["id"] for m in live if m["id"] not in known_open and m["id"] not in known_closed]
81
+ verdicts = dict(zip(unknown, await net.gather_limited([_model_licence_ok(i) for i in unknown]))) if unknown else {}
82
+ notes = {m["id"]: m.get("note", "") for m in cat["models"]}
83
+ out = []
84
+ for m in live:
85
+ mid = m["id"]
86
+ if mid in known_closed:
87
+ continue
88
+ if mid in known_open:
89
+ lic = known_open[mid]["licence"]
90
+ else:
91
+ v = verdicts.get(mid)
92
+ if not isinstance(v, tuple) or not v[0]:
93
+ continue
94
+ lic = v[1]
95
+ if UNSUITED.search(mid):
96
+ continue
97
+ provs = [p for p in m.get("providers", []) if p.get("status", "live") == "live"]
98
+ price = min((p["pricing"]["input"] + p["pricing"]["output"] for p in provs if p.get("pricing")), default=None)
99
+ out.append({"id": mid, "licence": lic, "providers": [p["provider"] for p in provs],
100
+ "vision": "image" in (m.get("architecture") or {}).get("input_modalities", []),
101
+ "ctx": max((p.get("context_length") or 0 for p in provs), default=0),
102
+ "price_per_m": price, "note": notes.get(mid, ""), "curated": mid in notes})
103
+ out.sort(key=lambda e: (not e["curated"], e["id"].lower()))
104
+ return _put("hosted", out)
105
+
106
+
107
+ async def hub_search(kind: str, query: str = "", tag: str = "medical", limit: int = 60) -> list[dict]:
108
+ """Live Hub search for open medical models/datasets. Closed or gated results are dropped."""
109
+ key = f"search:{kind}:{tag}:{query}:{limit}"
110
+ cached = _get(key)
111
+ if cached is not None:
112
+ return cached
113
+ params = {"sort": "downloads", "limit": str(limit), "full": "false"}
114
+ if tag:
115
+ params["filter"] = tag
116
+ if query:
117
+ params["search"] = query
118
+ url = f"{HUB}/{'models' if kind == 'model' else 'datasets'}?{urllib.parse.urlencode(params)}"
119
+ url += "&expand[]=cardData&expand[]=tags&expand[]=downloads&expand[]=likes&expand[]=gated"
120
+ url += "&expand[]=pipeline_tag" if kind == "model" else ""
121
+ rows = await net.get_json(url)
122
+ out = []
123
+ for r in rows:
124
+ lic = licence_of(r)
125
+ if r.get("gated") or not is_open(lic, kind):
126
+ continue
127
+ if kind == "model" and ("gguf" in (r.get("tags") or []) or UNSUITED.search(r["id"])):
128
+ continue
129
+ out.append({"id": r["id"], "licence": lic, "downloads": r.get("downloads", 0), "likes": r.get("likes", 0),
130
+ "pipeline": r.get("pipeline_tag")})
131
+ return _put(key, out)
132
+
133
+
134
+ async def dataset_preview(repo: str, n: int = 5) -> dict:
135
+ """First rows via the datasets-server API (public, CORS-enabled)."""
136
+ key = f"preview:{repo}:{n}"
137
+ cached = _get(key)
138
+ if cached is not None:
139
+ return cached
140
+ splits = await net.get_json(f"https://datasets-server.huggingface.co/splits?dataset={urllib.parse.quote(repo)}")
141
+ s = splits["splits"][0]
142
+ q = urllib.parse.urlencode({"dataset": repo, "config": s["config"], "split": s["split"], "offset": 0, "length": n})
143
+ rows = await net.get_json(f"https://datasets-server.huggingface.co/rows?{q}")
144
+ return _put(key, {"config": s["config"], "split": s["split"], "rows": [r["row"] for r in rows.get("rows", [])],
145
+ "num_rows": rows.get("num_rows_total")})
146
+
147
+
148
+ def ollama_command(gguf: str | None) -> str | None:
149
+ return f"ollama run hf.co/{gguf}" if gguf else None
app/draiml/consult.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The consultation pipeline: triage → retrieve evidence → generate → validate."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+
7
+ from .rag import EvidenceIndex, Hit, search
8
+ 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:
15
+ question: str
16
+ triage: Triage
17
+ hits: list[Hit] = field(default_factory=list)
18
+ method: str = "none"
19
+ messages: list[dict] = field(default_factory=list)
20
+
21
+
22
+ def evidence_block(hits: list[Hit]) -> str:
23
+ if not hits:
24
+ return ""
25
+ lines = ["EVIDENCE (openly licensed passages retrieved for this question; cite as [n] if used):"]
26
+ for h in hits:
27
+ lines.append(f"[{h.rank}] ({h.source}) {h.text[:900]}")
28
+ return "\n".join(lines)
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, "
43
+ "then give brief first-aid guidance while they wait. Keep it short.")
44
+ msgs = [{"role": "system", "content": sys}]
45
+ msgs += [{"role": m["role"], "content": m["content"]} for m in history[-12:] if m["role"] in ("user", "assistant")]
46
+ ev = evidence_block(hits)
47
+ msgs.append({"role": "user", "content": f"{ev}\n\nPATIENT/CLINICIAN MESSAGE:\n{question}" if ev else question})
48
+ return Prepared(question, t, hits, method, msgs)
49
+
50
+
51
+ def review(answer: str, question: str) -> dict:
52
+ return validate(answer, question)
53
+
54
+
55
+ def transcript_markdown(history: list[dict]) -> str:
56
+ out = ["# drAIML consultation transcript", "",
57
+ "_Generated by drAIML 2.0 (huggingface.co/spaces/PYTHAI/drAIML). Not medical advice._", ""]
58
+ for m in history:
59
+ who = "You" if m["role"] == "user" else f"drAIML ({m.get('model', '')})"
60
+ out += [f"## {who}", "", m["content"], ""]
61
+ return "\n".join(out)
app/draiml/engines.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chat engines. Every engine speaks the OpenAI chat-completions protocol, so one code path serves
2
+ Hugging Face Inference Providers, Groq, Together, and any OpenAI-compatible endpoint (Ollama, vLLM,
3
+ llama.cpp server, LM Studio, a dedicated HF Inference Endpoint).
4
+
5
+ Keys and tokens live only in the visitor's browser session. Nothing is stored server-side: there is
6
+ no server — drAIML 2.0 runs in the browser.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import dataclass, field
12
+ from typing import AsyncIterator
13
+
14
+ from . import net
15
+
16
+ HF_ROUTER = "https://router.huggingface.co/v1"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Endpoint:
21
+ key: str
22
+ label: str
23
+ base_url: str
24
+ needs_key: bool = True
25
+ key_label: str = "API key"
26
+ key_help: str = ""
27
+ # open-licence models this provider is known to host (the visitor can type any other id)
28
+ suggested: tuple[str, ...] = field(default_factory=tuple)
29
+
30
+
31
+ ENDPOINTS: dict[str, Endpoint] = {
32
+ "hf": Endpoint(
33
+ "hf", "Hugging Face · Inference Providers", HF_ROUTER, True, "HF token",
34
+ "Sign in with Hugging Face (top bar), or paste a fine-grained token with "
35
+ "'Make calls to Inference Providers'. Calls bill your own HF account."),
36
+ "groq": Endpoint(
37
+ "groq", "Groq", "https://api.groq.com/openai/v1", True, "Groq API key",
38
+ "console.groq.com/keys",
39
+ ("openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3-32b")),
40
+ "together": Endpoint(
41
+ "together", "Together AI", "https://api.together.xyz/v1", True, "Together API key",
42
+ "api.together.ai",
43
+ ("openai/gpt-oss-120b", "openai/gpt-oss-20b", "deepseek-ai/DeepSeek-V3.1",
44
+ "Qwen/Qwen3-235B-A22B-Instruct-2507-tput", "zai-org/GLM-4.5-Air-FP8")),
45
+ "custom": Endpoint(
46
+ "custom", "Your endpoint (Ollama · vLLM · llama.cpp · HF Endpoint)", "http://localhost:11434/v1",
47
+ False, "API key (optional)",
48
+ "Any OpenAI-compatible /v1 URL. For Ollama on this computer run it with "
49
+ "OLLAMA_ORIGINS=https://pythai-draiml.static.hf.space so the browser may call it."),
50
+ }
51
+
52
+
53
+ def _headers(key: str | None) -> dict:
54
+ return {"Authorization": f"Bearer {key}"} if key else {}
55
+
56
+
57
+ def split_think(text: str) -> tuple[str, str]:
58
+ """Separate <think>…</think> reasoning (HuatuoGPT-o1, II-Medical, Qwen3 on Ollama) from the answer."""
59
+ if "<think>" in text and "</think>" in text:
60
+ pre, rest = text.split("<think>", 1)
61
+ think, post = rest.split("</think>", 1)
62
+ return think.strip(), (pre + post).strip()
63
+ if text.lstrip().startswith("<think>"): # still thinking
64
+ return text.split("<think>", 1)[1], ""
65
+ return "", text
66
+
67
+
68
+ async def stream_chat(endpoint: Endpoint, model: str, messages: list[dict], *, key: str | None = None,
69
+ base_url: str | None = None, max_tokens: int = 1500,
70
+ temperature: float = 0.3) -> AsyncIterator[tuple[str, str]]:
71
+ """Yield ("reasoning" | "content", delta) pairs as the model streams."""
72
+ url = (base_url or endpoint.base_url).rstrip("/") + "/chat/completions"
73
+ payload = {"model": model, "messages": messages, "stream": True,
74
+ "max_tokens": max_tokens, "temperature": temperature}
75
+ async for data in net.post_sse(url, payload, _headers(key)):
76
+ if data == "[DONE]":
77
+ break
78
+ try:
79
+ ev = json.loads(data)
80
+ except json.JSONDecodeError:
81
+ continue
82
+ if ev.get("error"):
83
+ raise net.HTTPError(500, json.dumps(ev["error"]), url)
84
+ for ch in ev.get("choices") or []:
85
+ d = ch.get("delta") or {}
86
+ r = d.get("reasoning_content") or d.get("reasoning")
87
+ if r:
88
+ yield "reasoning", r
89
+ if d.get("content"):
90
+ yield "content", d["content"]
91
+
92
+
93
+ async def complete(endpoint: Endpoint, model: str, messages: list[dict], **kw) -> tuple[str, str]:
94
+ """Non-streaming convenience: returns (reasoning, answer)."""
95
+ reasoning, content = [], []
96
+ async for kind, delta in stream_chat(endpoint, model, messages, **kw):
97
+ (reasoning if kind == "reasoning" else content).append(delta)
98
+ think, answer = split_think("".join(content))
99
+ return ("".join(reasoning) + think).strip(), answer
100
+
101
+
102
+ async def list_endpoint_models(endpoint: Endpoint, key: str | None = None,
103
+ base_url: str | None = None) -> list[str]:
104
+ url = (base_url or endpoint.base_url).rstrip("/") + "/models"
105
+ j = await net.get_json(url, _headers(key))
106
+ return sorted(m.get("id") for m in (j.get("data") or j.get("models") or []) if m.get("id"))
app/draiml/licences.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Licence gate: "open source or go away".
2
+
3
+ Models must carry an OSI-approved licence. Datasets may carry an OSI licence or an open-data licence
4
+ (CC-BY-x, CC0, ODC-By, PDDL). Everything else — `other`, `unknown`, NC/ND/SA variants with NC,
5
+ Llama/Gemma/RAIL community terms, or no licence at all — is rejected and never shown.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ OSI = {
10
+ "mit", "apache-2.0", "bsd", "bsd-2-clause", "bsd-3-clause", "bsd-3-clause-clear", "isc", "0bsd",
11
+ "mpl-2.0", "gpl", "gpl-2.0", "gpl-3.0", "lgpl", "lgpl-2.1", "lgpl-3.0", "lgpl-lr", "agpl-3.0",
12
+ "epl-1.0", "epl-2.0", "ecl-2.0", "afl-3.0", "artistic-2.0", "bsl-1.0", "osl-3.0", "ms-pl",
13
+ "zlib", "unlicense", "postgresql", "eupl-1.1", "eupl-1.2", "cdla-permissive-2.0",
14
+ }
15
+ OPEN_DATA = {
16
+ "cc-by-2.0", "cc-by-2.5", "cc-by-3.0", "cc-by-4.0", "cc-by-sa-3.0", "cc-by-sa-4.0",
17
+ "cc0-1.0", "odc-by", "pddl", "cdla-permissive-1.0", "cdla-permissive-2.0", "cdla-sharing-1.0",
18
+ "odbl",
19
+ }
20
+
21
+
22
+ def normalise(lic) -> str | None:
23
+ """Return a lower-case SPDX-ish id from a card value, a list, or `license:x` tags."""
24
+ if lic is None:
25
+ return None
26
+ if isinstance(lic, (list, tuple)):
27
+ vals = [normalise(x) for x in lic]
28
+ vals = [v for v in vals if v]
29
+ if len(vals) != 1: # several licences on one repo: only accept if all are acceptable
30
+ return "|".join(sorted(vals)) if vals else None
31
+ return vals[0]
32
+ s = str(lic).strip().lower()
33
+ if s.startswith("license:"):
34
+ s = s[len("license:"):]
35
+ return s or None
36
+
37
+
38
+ def _ok(lic: str | None, allowed: set[str]) -> bool:
39
+ if not lic:
40
+ return False
41
+ return all(part in allowed for part in lic.split("|"))
42
+
43
+
44
+ def licence_of(info) -> str | None:
45
+ """Pull the licence from a huggingface_hub ModelInfo/DatasetInfo or a raw /api JSON dict."""
46
+ if isinstance(info, dict):
47
+ card = info.get("cardData") or {}
48
+ tags = info.get("tags") or []
49
+ else:
50
+ cd = getattr(info, "card_data", None) or getattr(info, "cardData", None)
51
+ card = cd.to_dict() if hasattr(cd, "to_dict") else (cd or {})
52
+ tags = getattr(info, "tags", None) or []
53
+ lic = normalise(card.get("license"))
54
+ if not lic:
55
+ lic = normalise([t for t in tags if str(t).startswith("license:")])
56
+ return lic
57
+
58
+
59
+ def is_open_model(info) -> tuple[bool, str | None]:
60
+ lic = licence_of(info)
61
+ return _ok(lic, OSI), lic
62
+
63
+
64
+ def is_open_dataset(info) -> tuple[bool, str | None]:
65
+ lic = licence_of(info)
66
+ return _ok(lic, OSI | OPEN_DATA), lic
67
+
68
+
69
+ def is_open(lic: str | None, kind: str) -> bool:
70
+ lic = normalise(lic)
71
+ return _ok(lic, OSI if kind == "model" else OSI | OPEN_DATA)
app/draiml/net.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async HTTP that runs in the browser (stlite/Pyodide, via fetch) and in CPython (tests, scripts).
2
+
3
+ Only what drAIML needs: JSON GET/POST, raw bytes GET, and Server-Sent-Events streaming for
4
+ OpenAI-compatible chat completions.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import sys
11
+ from typing import Any, AsyncIterator
12
+
13
+ IN_BROWSER = sys.platform == "emscripten"
14
+
15
+
16
+ class HTTPError(Exception):
17
+ def __init__(self, status: int, body: str, url: str):
18
+ self.status, self.body, self.url = status, body, url
19
+ super().__init__(f"HTTP {status} from {url}: {body[:300]}")
20
+
21
+ def message(self) -> str:
22
+ try:
23
+ j = json.loads(self.body)
24
+ err = j.get("error", j)
25
+ if isinstance(err, dict):
26
+ err = err.get("message") or json.dumps(err)
27
+ return f"HTTP {self.status}: {err}"
28
+ except Exception:
29
+ return f"HTTP {self.status}: {self.body[:300]}"
30
+
31
+
32
+ if IN_BROWSER:
33
+ from pyodide.http import pyfetch # type: ignore
34
+
35
+ async def _fetch(url, method="GET", headers=None, body=None):
36
+ kw: dict[str, Any] = {"method": method, "headers": headers or {}}
37
+ if body is not None:
38
+ kw["body"] = body
39
+ resp = await pyfetch(url, **kw)
40
+ if not resp.ok:
41
+ raise HTTPError(resp.status, await resp.string(), url)
42
+ return resp
43
+
44
+ async def get_bytes(url: str, headers: dict | None = None) -> bytes:
45
+ return await (await _fetch(url, headers=headers)).bytes()
46
+
47
+ async def get_json(url: str, headers: dict | None = None) -> Any:
48
+ return json.loads(await (await _fetch(url, headers=headers)).string())
49
+
50
+ async def post_json(url: str, payload: dict, headers: dict | None = None) -> Any:
51
+ h = {"Content-Type": "application/json", **(headers or {})}
52
+ return json.loads(await (await _fetch(url, "POST", h, json.dumps(payload))).string())
53
+
54
+ async def post_sse(url: str, payload: dict, headers: dict | None = None) -> AsyncIterator[str]:
55
+ """Yield the `data:` payloads of an SSE response as they arrive."""
56
+ h = {"Content-Type": "application/json", "Accept": "text/event-stream", **(headers or {})}
57
+ resp = await _fetch(url, "POST", h, json.dumps(payload))
58
+ reader = resp.js_response.body.getReader()
59
+ buf = ""
60
+ while True:
61
+ chunk = await reader.read()
62
+ if chunk.done:
63
+ break
64
+ buf += bytes(chunk.value.to_py()).decode("utf-8", "replace")
65
+ while "\n" in buf:
66
+ line, buf = buf.split("\n", 1)
67
+ line = line.strip()
68
+ if line.startswith("data:"):
69
+ yield line[5:].strip()
70
+ if buf.strip().startswith("data:"):
71
+ yield buf.strip()[5:].strip()
72
+
73
+ else:
74
+ import urllib.error
75
+ import urllib.request
76
+
77
+ def _open(url, method="GET", headers=None, body=None, timeout=120):
78
+ req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
79
+ req.add_header("User-Agent", "drAIML/2.0")
80
+ try:
81
+ return urllib.request.urlopen(req, timeout=timeout)
82
+ except urllib.error.HTTPError as e:
83
+ raise HTTPError(e.code, e.read().decode("utf-8", "replace"), url) from None
84
+
85
+ async def get_bytes(url: str, headers: dict | None = None) -> bytes:
86
+ return await asyncio.to_thread(lambda: _open(url, headers=headers).read())
87
+
88
+ async def get_json(url: str, headers: dict | None = None) -> Any:
89
+ return json.loads(await get_bytes(url, headers))
90
+
91
+ async def post_json(url: str, payload: dict, headers: dict | None = None) -> Any:
92
+ h = {"Content-Type": "application/json", **(headers or {})}
93
+ raw = await asyncio.to_thread(lambda: _open(url, "POST", h, json.dumps(payload).encode()).read())
94
+ return json.loads(raw)
95
+
96
+ async def post_sse(url: str, payload: dict, headers: dict | None = None) -> AsyncIterator[str]:
97
+ h = {"Content-Type": "application/json", "Accept": "text/event-stream", **(headers or {})}
98
+ resp = await asyncio.to_thread(lambda: _open(url, "POST", h, json.dumps(payload).encode()))
99
+ while True:
100
+ line = await asyncio.to_thread(resp.readline)
101
+ if not line:
102
+ break
103
+ line = line.decode("utf-8", "replace").strip()
104
+ if line.startswith("data:"):
105
+ yield line[5:].strip()
106
+
107
+
108
+ async def gather_limited(coros, limit: int = 8):
109
+ sem = asyncio.Semaphore(limit)
110
+
111
+ async def run(c):
112
+ async with sem:
113
+ try:
114
+ return await c
115
+ except Exception as e: # one failed lookup must not sink the batch
116
+ return e
117
+
118
+ return await asyncio.gather(*(run(c) for c in coros))
app/draiml/ported/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """v1 drAIML modules (github.com/AIMLdr/drAIML), carried into 2.0 with disk logging removed.
2
+
3
+ hippocratic.py, logic.py and medical_patterns.py are the v1 files with relative imports; logger.py and
4
+ memory.py are in-memory shims so nothing about a consultation is ever written to disk.
5
+ """
app/draiml/ported/hippocratic.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # hippocratic.py (c) 2025 Gregory L. Magnusson MIT license
2
+
3
+ import os
4
+ import json
5
+ from datetime import datetime
6
+ from typing import Dict, List, Optional, Union, Any
7
+ from .logger import get_logger
8
+ from .memory import MedicalDecision, store_medical_decision
9
+ from .logic import LogicTables
10
+ from .medical_patterns import MedicalPatterns
11
+
12
+ class HippocraticPrinciples:
13
+ """Core principles based on the Hippocratic Oath and modern medical ethics"""
14
+
15
+ PRINCIPLES = {
16
+ "do_no_harm": {
17
+ "principle": "First, do no harm (primum non nocere)",
18
+ "description": "Avoid causing harm to patients; every medical decision must first consider safety",
19
+ "validation_rules": [
20
+ "Check for contraindications",
21
+ "Assess risk-benefit ratio",
22
+ "Consider alternative treatments",
23
+ "Evaluate potential side effects"
24
+ ]
25
+ },
26
+ "beneficence": {
27
+ "principle": "Act in the best interest of the patient",
28
+ "description": "Promote well-being and take positive steps to help patients",
29
+ "validation_rules": [
30
+ "Ensure treatment benefits outweigh risks",
31
+ "Consider patient's quality of life",
32
+ "Provide evidence-based recommendations",
33
+ "Focus on patient wellness"
34
+ ]
35
+ },
36
+ "patient_autonomy": {
37
+ "principle": "Respect patient's right to make decisions",
38
+ "description": "Honor patient preferences and right to informed decision-making",
39
+ "validation_rules": [
40
+ "Provide clear information",
41
+ "Respect patient choices",
42
+ "Ensure informed consent",
43
+ "Protect patient rights"
44
+ ]
45
+ },
46
+ "justice": {
47
+ "principle": "Treat all patients fairly and equally",
48
+ "description": "Ensure fair distribution of benefits and risks",
49
+ "validation_rules": [
50
+ "Avoid discrimination",
51
+ "Ensure equal access",
52
+ "Consider resource allocation",
53
+ "Maintain professional standards"
54
+ ]
55
+ },
56
+ "confidentiality": {
57
+ "principle": "Protect patient privacy and information",
58
+ "description": "Maintain strict confidentiality of patient information",
59
+ "validation_rules": [
60
+ "Protect patient data",
61
+ "Secure communications",
62
+ "Limit information sharing",
63
+ "Maintain records securely"
64
+ ]
65
+ },
66
+ "informed_consent": {
67
+ "principle": "Ensure patient understanding and agreement",
68
+ "description": "Obtain informed consent for all medical decisions",
69
+ "validation_rules": [
70
+ "Explain procedures clearly",
71
+ "Document consent",
72
+ "Verify understanding",
73
+ "Allow questions"
74
+ ]
75
+ },
76
+ "professional_ethics": {
77
+ "principle": "Maintain professional standards and ethics",
78
+ "description": "Uphold medical professional standards and ethical conduct",
79
+ "validation_rules": [
80
+ "Follow medical guidelines",
81
+ "Maintain competence",
82
+ "Collaborate appropriately",
83
+ "Document decisions"
84
+ ]
85
+ }
86
+ }
87
+
88
+ EMERGENCY_KEYWORDS = [
89
+ "heart attack", "stroke", "bleeding", "unconscious", "breathing difficulty",
90
+ "severe pain", "chest pain", "head injury", "seizure", "anaphylaxis",
91
+ "suicide", "overdose", "emergency", "critical", "severe", "urgent"
92
+ ]
93
+
94
+ RISK_LEVELS = {
95
+ "low": {
96
+ "description": "Minimal risk to patient",
97
+ "requires_monitoring": False,
98
+ "requires_immediate_action": False
99
+ },
100
+ "moderate": {
101
+ "description": "Notable risk requiring attention",
102
+ "requires_monitoring": True,
103
+ "requires_immediate_action": False
104
+ },
105
+ "high": {
106
+ "description": "Significant risk requiring close attention",
107
+ "requires_monitoring": True,
108
+ "requires_immediate_action": True
109
+ },
110
+ "critical": {
111
+ "description": "Life-threatening risk requiring emergency response",
112
+ "requires_monitoring": True,
113
+ "requires_immediate_action": True,
114
+ "requires_emergency_services": True
115
+ }
116
+ }
117
+
118
+ VALIDATION_LEVELS = {
119
+ "basic": {
120
+ "checks": ["do_no_harm", "confidentiality"],
121
+ "required_score": 0.6
122
+ },
123
+ "standard": {
124
+ "checks": ["do_no_harm", "beneficence", "patient_autonomy", "confidentiality"],
125
+ "required_score": 0.7
126
+ },
127
+ "comprehensive": {
128
+ "checks": list(PRINCIPLES.keys()),
129
+ "required_score": 0.8
130
+ }
131
+ }
132
+
133
+ DISCLAIMER = """
134
+ IMPORTANT MEDICAL DISCLAIMER:
135
+ This is AI-assisted medical information. Always consult with qualified
136
+ healthcare professionals for medical advice, diagnosis, or treatment.
137
+ Seek immediate emergency care for urgent medical conditions.
138
+
139
+ This system:
140
+ 1. Does not replace professional medical advice
141
+ 2. Cannot diagnose conditions or prescribe treatments
142
+ 3. Should not be used in medical emergencies
143
+ 4. Serves as informational support only
144
+
145
+ IN CASE OF EMERGENCY:
146
+ - Call emergency services immediately
147
+ - Contact your healthcare provider
148
+ - Seek immediate medical attention
149
+ """
150
+
151
+ def __init__(self):
152
+ self.logger = get_logger('hippocratic_principles')
153
+ self.validation_history = []
154
+ self._initialize_logging()
155
+
156
+ def _initialize_logging(self):
157
+ """Initialize logging for principle applications"""
158
+ try:
159
+ self.log_paths = {
160
+ 'principle_applications': './memory/logs/hippocratic/principles.json',
161
+ 'validation_history': './memory/logs/hippocratic/validation.json',
162
+ 'ethical_decisions': './memory/logs/hippocratic/decisions.json',
163
+ 'emergency_logs': './memory/logs/hippocratic/emergency.json'
164
+ }
165
+
166
+ # drAIML 2.0: logs stay in memory (self.logs); nothing is written to disk
167
+ self.logs = {k: [] for k in self.log_paths}
168
+
169
+ self.logger.info("Hippocratic logging initialized",
170
+ extra={'structured_data': {
171
+ 'log_paths': self.log_paths
172
+ }})
173
+ except Exception as e:
174
+ self.logger.error(f"Error initializing Hippocratic logging: {e}")
175
+ raise
176
+
177
+ def log_principle_application(self, principle: str, context: Dict):
178
+ """Log application of Hippocratic principle"""
179
+ try:
180
+ entry = {
181
+ "timestamp": datetime.now().isoformat(),
182
+ "principle": principle,
183
+ "context": context,
184
+ "validation_rules_applied": self.PRINCIPLES[principle]["validation_rules"]
185
+ }
186
+
187
+ self._append_to_log('principle_applications', entry)
188
+
189
+ self.logger.info(f"Principle applied: {principle}",
190
+ extra={'structured_data': entry})
191
+ except Exception as e:
192
+ self.logger.error(f"Error logging principle application: {e}")
193
+
194
+ def log_validation(self, validation_result: Dict):
195
+ """Log validation result"""
196
+ try:
197
+ entry = {
198
+ "timestamp": datetime.now().isoformat(),
199
+ "validation_result": validation_result,
200
+ "principles_checked": validation_result.get("principles_checked", []),
201
+ "validation_level": validation_result.get("validation_level", "basic")
202
+ }
203
+
204
+ self._append_to_log('validation_history', entry)
205
+ self.validation_history.append(entry)
206
+
207
+ self.logger.info("Validation logged",
208
+ extra={'structured_data': entry})
209
+ except Exception as e:
210
+ self.logger.error(f"Error logging validation: {e}")
211
+
212
+ def log_emergency(self, context: Dict):
213
+ """Log emergency situation"""
214
+ try:
215
+ entry = {
216
+ "timestamp": datetime.now().isoformat(),
217
+ "emergency_context": context,
218
+ "keywords_detected": [
219
+ kw for kw in self.EMERGENCY_KEYWORDS
220
+ if kw in context.get("text", "").lower()
221
+ ],
222
+ "risk_level": "critical"
223
+ }
224
+
225
+ self._append_to_log('emergency_logs', entry)
226
+
227
+ self.logger.critical("Emergency situation logged",
228
+ extra={'structured_data': entry})
229
+ except Exception as e:
230
+ self.logger.error(f"Error logging emergency: {e}")
231
+
232
+ def _append_to_log(self, log_type: str, entry: Dict):
233
+ """Append entry to specified log file"""
234
+ try:
235
+ self.logs[log_type].append(entry)
236
+ del self.logs[log_type][:-50]
237
+
238
+ except Exception as e:
239
+ self.logger.error(f"Error appending to log {log_type}: {e}")
240
+
241
+ class HippocraticReasoning:
242
+ """Medical ethics reasoning and validation system"""
243
+
244
+ def __init__(self):
245
+ self.logger = get_logger('hippocratic_reasoning')
246
+ self.principles = HippocraticPrinciples()
247
+ self.logic_tables = LogicTables()
248
+ self.medical_patterns = MedicalPatterns()
249
+
250
+ # Initialize validation tracking
251
+ self.current_session = {
252
+ "session_id": datetime.now().strftime("%Y%m%d_%H%M%S"),
253
+ "validations_performed": 0,
254
+ "emergency_situations": 0,
255
+ "ethical_conflicts": []
256
+ }
257
+
258
+ self.logger.info("Hippocratic Reasoning initialized",
259
+ extra={'structured_data': {
260
+ 'session_id': self.current_session["session_id"]
261
+ }})
262
+
263
+ def validate_medical_response(self,
264
+ response: str,
265
+ context: Dict,
266
+ validation_level: str = "comprehensive",
267
+ provider: str = None,
268
+ model: str = None) -> Dict:
269
+ """
270
+ Validate medical response against Hippocratic principles
271
+ """
272
+ try:
273
+ validation_start = datetime.now()
274
+
275
+ # Check for emergencies first
276
+ is_emergency = self._check_emergency_situation(response, context)
277
+ if is_emergency:
278
+ return self._handle_emergency_response(response, context)
279
+
280
+ # Prepare validation context
281
+ validation_context = self._prepare_validation_context(
282
+ response, context, provider, model
283
+ )
284
+
285
+ # Perform validation checks
286
+ validation_result = self._perform_validation_checks(
287
+ validation_context, validation_level
288
+ )
289
+
290
+ # Add response metadata
291
+ validation_result.update({
292
+ "timestamp": datetime.now().isoformat(),
293
+ "validation_duration": (datetime.now() - validation_start).total_seconds(),
294
+ "provider": provider,
295
+ "model": model,
296
+ "session_id": self.current_session["session_id"]
297
+ })
298
+
299
+ # Log validation
300
+ self.principles.log_validation(validation_result)
301
+ self.current_session["validations_performed"] += 1
302
+
303
+ return validation_result
304
+
305
+ except Exception as e:
306
+ self.logger.error("Validation error",
307
+ extra={'structured_data': {
308
+ 'error': str(e),
309
+ 'response': response,
310
+ 'context': context
311
+ }})
312
+ return {
313
+ "is_valid": False,
314
+ "error": str(e),
315
+ "timestamp": datetime.now().isoformat()
316
+ }
317
+
318
+ def _check_emergency_situation(self, response: str, context: Dict) -> bool:
319
+ """Check if situation requires emergency response"""
320
+ try:
321
+ # Check response and context for emergency keywords
322
+ combined_text = f"{response} {json.dumps(context)}".lower()
323
+
324
+ emergency_detected = any(
325
+ keyword in combined_text
326
+ for keyword in self.principles.EMERGENCY_KEYWORDS
327
+ )
328
+
329
+ if emergency_detected:
330
+ self.principles.log_emergency({
331
+ "text": combined_text,
332
+ "context": context
333
+ })
334
+ self.current_session["emergency_situations"] += 1
335
+
336
+ return emergency_detected
337
+
338
+ except Exception as e:
339
+ self.logger.error("Emergency check error",
340
+ extra={'structured_data': {'error': str(e)}})
341
+ return False
342
+
343
+ def _handle_emergency_response(self, response: str, context: Dict) -> Dict:
344
+ """Generate appropriate response for emergency situation"""
345
+ emergency_response = {
346
+ "is_valid": False,
347
+ "emergency": True,
348
+ "message": "MEDICAL EMERGENCY DETECTED",
349
+ "actions_required": [
350
+ "Seek immediate medical attention",
351
+ "Contact emergency services",
352
+ "Do not rely on AI guidance in emergencies"
353
+ ],
354
+ "original_response": response,
355
+ "timestamp": datetime.now().isoformat()
356
+ }
357
+
358
+ self.logger.critical("Emergency response generated",
359
+ extra={'structured_data': emergency_response})
360
+ return emergency_response
361
+
362
+ def _prepare_validation_context(self,
363
+ response: str,
364
+ context: Dict,
365
+ provider: str,
366
+ model: str) -> Dict:
367
+ """Prepare context for validation"""
368
+ return {
369
+ "response": response,
370
+ "context": context,
371
+ "provider": provider,
372
+ "model": model,
373
+ "medical_patterns": self._extract_medical_patterns(response),
374
+ "risk_assessment": self._assess_risk_level(response, context)
375
+ }
376
+
377
+ def _extract_medical_patterns(self, text: str) -> Dict:
378
+ """Extract medical patterns from text"""
379
+ patterns = {
380
+ "symptoms": [],
381
+ "conditions": [],
382
+ "treatments": [],
383
+ "risk_factors": []
384
+ }
385
+
386
+ try:
387
+ # Extract symptoms
388
+ for category, symptom_patterns in self.medical_patterns.SYMPTOM_PATTERNS.items():
389
+ for subcategory, terms in symptom_patterns.items():
390
+ matches = [term for term in terms if term in text.lower()]
391
+ if matches:
392
+ patterns["symptoms"].append({
393
+ "category": category,
394
+ "subcategory": subcategory,
395
+ "terms": matches
396
+ })
397
+
398
+ # Extract conditions
399
+ for category, indicators in self.medical_patterns.CONDITION_INDICATORS.items():
400
+ matches = [ind for ind in indicators if ind in text.lower()]
401
+ if matches:
402
+ patterns["conditions"].append({
403
+ "category": category,
404
+ "indicators": matches
405
+ })
406
+
407
+ # Extract treatments
408
+ for category, terms in self.medical_patterns.TREATMENT_PATTERNS.items():
409
+ matches = [term for term in terms if term in text.lower()]
410
+ if matches:
411
+ patterns["treatments"].append({
412
+ "category": category,
413
+ "terms": matches
414
+ })
415
+
416
+ # Extract risk factors
417
+ for category, factors in self.medical_patterns.RISK_FACTORS.items():
418
+ matches = [factor for factor in factors if factor in text.lower()]
419
+ if matches:
420
+ patterns["risk_factors"].append({
421
+ "category": category,
422
+ "factors": matches
423
+ })
424
+
425
+ return patterns
426
+
427
+ except Exception as e:
428
+ self.logger.error("Error extracting medical patterns",
429
+ extra={'structured_data': {'error': str(e)}})
430
+ return patterns
431
+
432
+ def _assess_risk_level(self, response: str, context: Dict) -> Dict:
433
+ """Assess risk level of medical situation"""
434
+ try:
435
+ risk_assessment = {
436
+ "level": "low",
437
+ "factors": [],
438
+ "requires_monitoring": False,
439
+ "requires_immediate_action": False
440
+ }
441
+
442
+ # Check for critical indicators
443
+ critical_indicators = set(self.principles.EMERGENCY_KEYWORDS)
444
+ found_indicators = [
445
+ indicator for indicator in critical_indicators
446
+ if indicator in response.lower()
447
+ ]
448
+
449
+ if found_indicators:
450
+ risk_assessment.update({
451
+ "level": "critical",
452
+ "factors": found_indicators,
453
+ "requires_monitoring": True,
454
+ "requires_immediate_action": True
455
+ })
456
+ return risk_assessment
457
+
458
+ # Assess severity patterns
459
+ severity_patterns = self.medical_patterns.SYMPTOM_PATTERNS["severity"]
460
+
461
+ if any(term in response.lower() for term in severity_patterns["severe"]):
462
+ risk_assessment["level"] = "high"
463
+ risk_assessment["requires_monitoring"] = True
464
+ risk_assessment["requires_immediate_action"] = True
465
+ elif any(term in response.lower() for term in severity_patterns["moderate"]):
466
+ risk_assessment["level"] = "moderate"
467
+ risk_assessment["requires_monitoring"] = True
468
+
469
+ # Add risk factors
470
+ risk_factors = self._extract_medical_patterns(response)["risk_factors"]
471
+ if risk_factors:
472
+ risk_assessment["factors"].extend([
473
+ f"{factor['category']}: {', '.join(factor['factors'])}"
474
+ for factor in risk_factors
475
+ ])
476
+
477
+ return risk_assessment
478
+
479
+ except Exception as e:
480
+ self.logger.error("Error assessing risk level",
481
+ extra={'structured_data': {'error': str(e)}})
482
+ return {"level": "unknown", "error": str(e)}
483
+
484
+ def _perform_validation_checks(self,
485
+ validation_context: Dict,
486
+ validation_level: str) -> Dict:
487
+ """Perform validation checks based on Hippocratic principles"""
488
+ try:
489
+ validation_config = self.principles.VALIDATION_LEVELS[validation_level]
490
+ principles_to_check = validation_config["checks"]
491
+ required_score = validation_config["required_score"]
492
+
493
+ validation_results = []
494
+ ethical_conflicts = []
495
+
496
+ for principle in principles_to_check:
497
+ principle_result = self._validate_principle(
498
+ principle, validation_context
499
+ )
500
+ validation_results.append(principle_result)
501
+
502
+ if not principle_result["passed"] and principle_result.get("ethical_conflict"):
503
+ ethical_conflicts.append(principle_result["ethical_conflict"])
504
+
505
+ # Calculate overall validation score
506
+ total_score = sum(r["score"] for r in validation_results) / len(validation_results)
507
+
508
+ validation_passed = total_score >= required_score and not ethical_conflicts
509
+
510
+ result = {
511
+ "is_valid": validation_passed,
512
+ "validation_level": validation_level,
513
+ "overall_score": total_score,
514
+ "required_score": required_score,
515
+ "principles_checked": principles_to_check,
516
+ "principle_results": validation_results,
517
+ "ethical_conflicts": ethical_conflicts,
518
+ "recommendations": self._generate_recommendations(
519
+ validation_results, validation_context
520
+ )
521
+ }
522
+
523
+ if ethical_conflicts:
524
+ self.current_session["ethical_conflicts"].extend(ethical_conflicts)
525
+
526
+ return result
527
+
528
+ except Exception as e:
529
+ self.logger.error("Error performing validation checks",
530
+ extra={'structured_data': {'error': str(e)}})
531
+ return {
532
+ "is_valid": False,
533
+ "error": str(e),
534
+ "validation_level": validation_level
535
+ }
536
+
537
+ def _validate_principle(self, principle: str, context: Dict) -> Dict:
538
+ """Validate response against a specific Hippocratic principle"""
539
+ try:
540
+ principle_config = self.principles.PRINCIPLES[principle]
541
+ validation_rules = principle_config["validation_rules"]
542
+
543
+ rule_results = []
544
+ for rule in validation_rules:
545
+ rule_result = self._check_validation_rule(rule, context)
546
+ rule_results.append(rule_result)
547
+
548
+ score = sum(r["score"] for r in rule_results) / len(rule_results)
549
+ passed = score >= 0.7 # Threshold for principle validation
550
+
551
+ result = {
552
+ "principle": principle,
553
+ "passed": passed,
554
+ "score": score,
555
+ "rule_results": rule_results
556
+ }
557
+
558
+ # Check for ethical conflicts
559
+ if not passed:
560
+ result["ethical_conflict"] = {
561
+ "principle": principle,
562
+ "description": principle_config["description"],
563
+ "violated_rules": [
564
+ r["rule"] for r in rule_results if not r["passed"]
565
+ ]
566
+ }
567
+
568
+ # Log principle application
569
+ self.principles.log_principle_application(principle, {
570
+ "validation_result": result,
571
+ "context": context
572
+ })
573
+
574
+ return result
575
+
576
+ except Exception as e:
577
+ self.logger.error(f"Error validating principle {principle}",
578
+ extra={'structured_data': {'error': str(e)}})
579
+ return {
580
+ "principle": principle,
581
+ "passed": False,
582
+ "error": str(e)
583
+ }
584
+
585
+ def _check_validation_rule(self, rule: str, context: Dict) -> Dict:
586
+ """Check a specific validation rule"""
587
+ try:
588
+ # Rule-specific validation logic
589
+ response_text = context["response"].lower()
590
+ patterns = context["medical_patterns"]
591
+ risk_assessment = context["risk_assessment"]
592
+
593
+ rule_result = {
594
+ "rule": rule,
595
+ "passed": True,
596
+ "score": 1.0,
597
+ "details": []
598
+ }
599
+
600
+ # Adjust score based on context
601
+ if "contraindications" in rule.lower():
602
+ rule_result["score"] = 0.8 if patterns["risk_factors"] else 1.0
603
+ elif "risk" in rule.lower():
604
+ rule_result["score"] = 0.6 if risk_assessment["level"] in ["high", "critical"] else 1.0
605
+ elif "document" in rule.lower():
606
+ rule_result["score"] = 1.0 if context.get("context") else 0.8
607
+
608
+ rule_result["passed"] = rule_result["score"] >= 0.7
609
+
610
+ return rule_result
611
+
612
+ except Exception as e:
613
+ self.logger.error(f"Error checking validation rule: {rule}",
614
+ extra={'structured_data': {'error': str(e)}})
615
+ return {
616
+ "rule": rule,
617
+ "passed": False,
618
+ "score": 0.0,
619
+ "error": str(e)
620
+ }
621
+
622
+ def _generate_recommendations(self,
623
+ validation_results: List[Dict],
624
+ context: Dict) -> List[str]:
625
+ """Generate recommendations based on validation results"""
626
+ try:
627
+ recommendations = []
628
+
629
+ # Add recommendations based on risk level
630
+ risk_level = context["risk_assessment"]["level"]
631
+ if risk_level in ["high", "critical"]:
632
+ recommendations.append(
633
+ "Seek immediate professional medical attention"
634
+ )
635
+ elif risk_level == "moderate":
636
+ recommendations.append(
637
+ "Consider consulting with a healthcare provider"
638
+ )
639
+
640
+ # Add principle-specific recommendations
641
+ for result in validation_results:
642
+ if not result["passed"]:
643
+ principle = result["principle"]
644
+ principle_config = self.principles.PRINCIPLES[principle]
645
+ recommendations.append(
646
+ f"Review {principle_config['principle']}"
647
+ )
648
+
649
+ # Add general recommendations
650
+ recommendations.extend([
651
+ "Document all medical observations",
652
+ "Monitor for changes in symptoms",
653
+ "Keep medical records updated"
654
+ ])
655
+
656
+ return recommendations
657
+
658
+ except Exception as e:
659
+ self.logger.error("Error generating recommendations",
660
+ extra={'structured_data': {'error': str(e)}})
661
+ return ["Seek professional medical advice"]
662
+
663
+ def get_session_statistics(self) -> Dict:
664
+ """Get statistics for current validation session"""
665
+ try:
666
+ return {
667
+ "session_id": self.current_session["session_id"],
668
+ "validations_performed": self.current_session["validations_performed"],
669
+ "emergency_situations": self.current_session["emergency_situations"],
670
+ "ethical_conflicts": len(self.current_session["ethical_conflicts"]),
671
+ "timestamp": datetime.now().isoformat()
672
+ }
673
+ except Exception as e:
674
+ self.logger.error("Error getting session statistics",
675
+ extra={'structured_data': {'error': str(e)}})
676
+ return {}
app/draiml/ported/logger.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """In-memory shim for v1 logger.get_logger — stdlib logging only, no files."""
2
+ import logging
3
+
4
+
5
+ def get_logger(name: str) -> logging.Logger:
6
+ log = logging.getLogger(f"draiml.{name}")
7
+ log.addHandler(logging.NullHandler())
8
+ return log
app/draiml/ported/logic.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # logic.py (c) 2025 Gregory L. Magnusson MIT license
2
+
3
+ import os
4
+ import json
5
+ from datetime import datetime
6
+ from typing import Set, List, Dict, Union, Optional, Tuple
7
+ import re
8
+ from .logger import get_logger
9
+ from .medical_patterns import MedicalPatterns
10
+
11
+ class LogicTables:
12
+ """Enhanced logic system for medical reasoning and decision validation"""
13
+
14
+ def __init__(self):
15
+ self.logger = get_logger('logic')
16
+ self.variables: Set[str] = set()
17
+ self.expressions: List[str] = []
18
+ self.valid_truths: Set[str] = set()
19
+ self.contradictions: List[Dict] = []
20
+ self.symptom_relationships: Dict[str, List[str]] = {}
21
+ self.condition_relationships: Dict[str, Dict] = {}
22
+
23
+ # Initialize components
24
+ self.patterns = MedicalPatterns()
25
+ self.medical_conditions = self._load_medical_conditions()
26
+ self.medical_terminology = self._load_medical_terminology()
27
+ self.symptom_patterns = self._load_symptom_patterns()
28
+
29
+ # Initialize truth tables
30
+ self._initialize_truth_tables()
31
+
32
+ def _initialize_truth_tables(self):
33
+ """Initialize truth table structure"""
34
+ self.truth_tables = {
35
+ "logical": {
36
+ "variables": set(),
37
+ "expressions": [],
38
+ "valid_truths": set()
39
+ },
40
+ "medical": {
41
+ "symptoms": {},
42
+ "conditions": {},
43
+ "relationships": {},
44
+ "contradictions": []
45
+ }
46
+ }
47
+
48
+ def tautology(self, statement: str) -> bool:
49
+ """Validate if a statement is logically sound"""
50
+ try:
51
+ if not statement or not isinstance(statement, str):
52
+ self.logger.debug("Invalid statement format",
53
+ extra={'structured_data': {'statement': statement}})
54
+ return False
55
+
56
+ # Check basic logical structure
57
+ has_context = len(statement.split()) > 3
58
+ has_medical_terms = self._contains_medical_terms(statement)
59
+ has_logical_structure = self._check_logical_structure(statement)
60
+
61
+ # Check for contradictions
62
+ if self._check_contradictions(statement):
63
+ return False
64
+
65
+ result = has_context and has_medical_terms and has_logical_structure
66
+
67
+ self.logger.debug("Tautology check completed",
68
+ extra={'structured_data': {
69
+ 'statement': statement,
70
+ 'has_context': has_context,
71
+ 'has_medical_terms': has_medical_terms,
72
+ 'has_logical_structure': has_logical_structure,
73
+ 'result': result
74
+ }})
75
+
76
+ return result
77
+ except Exception as e:
78
+ self.logger.error("Error in tautology check",
79
+ extra={'structured_data': {
80
+ 'error': str(e),
81
+ 'statement': statement
82
+ }})
83
+ return False
84
+
85
+ def _check_contradictions(self, statement: str) -> bool:
86
+ """Check for logical and medical contradictions"""
87
+ try:
88
+ # Split statement into components
89
+ components = self._parse_logical_components(statement)
90
+
91
+ # Check for direct contradictions
92
+ for i, comp1 in enumerate(components):
93
+ for comp2 in components[i+1:]:
94
+ if self._are_contradictory(comp1, comp2):
95
+ self.contradictions.append({
96
+ 'statement': statement,
97
+ 'component1': comp1,
98
+ 'component2': comp2,
99
+ 'timestamp': datetime.now().isoformat()
100
+ })
101
+ return True
102
+
103
+ # Check medical contradictions
104
+ return self._check_medical_contradictions(components)
105
+
106
+ except Exception as e:
107
+ self.logger.error("Error checking contradictions",
108
+ extra={'structured_data': {'error': str(e)}})
109
+ return False
110
+
111
+ def _parse_logical_components(self, statement: str) -> List[str]:
112
+ """Parse statement into logical components"""
113
+ components = []
114
+ current_component = []
115
+
116
+ # Split on logical operators
117
+ words = statement.lower().split()
118
+ for word in words:
119
+ if self._is_logical_operator(word):
120
+ if current_component:
121
+ components.append(' '.join(current_component))
122
+ current_component = []
123
+ current_component.append(word)
124
+
125
+ if current_component:
126
+ components.append(' '.join(current_component))
127
+
128
+ return components
129
+
130
+ def _is_logical_operator(self, word: str) -> bool:
131
+ """Check if word is a logical operator"""
132
+ logical_operators = {
133
+ "and", "or", "not", "if", "then", "because",
134
+ "therefore", "implies", "since", "while"
135
+ }
136
+ return word.lower() in logical_operators
137
+
138
+ def _are_contradictory(self, comp1: str, comp2: str) -> bool:
139
+ """Check if two components are contradictory"""
140
+ # Check direct negations
141
+ negation_words = {"not", "no", "never", "without"}
142
+ comp1_words = set(comp1.lower().split())
143
+ comp2_words = set(comp2.lower().split())
144
+
145
+ # Check if one component negates the other
146
+ has_negation = bool(comp1_words.intersection(negation_words) or
147
+ comp2_words.intersection(negation_words))
148
+
149
+ if has_negation:
150
+ # Remove negation words and compare remaining terms
151
+ comp1_terms = comp1_words - negation_words
152
+ comp2_terms = comp2_words - negation_words
153
+ if comp1_terms.intersection(comp2_terms):
154
+ return True
155
+
156
+ # Check medical contradictions
157
+ return self._check_medical_contradiction(comp1, comp2)
158
+
159
+ def _check_medical_contradiction(self, comp1: str, comp2: str) -> bool:
160
+ """Check for medical contradictions between components"""
161
+ try:
162
+ # Check temporal contradictions
163
+ temporal1 = self._extract_temporal_patterns(comp1)
164
+ temporal2 = self._extract_temporal_patterns(comp2)
165
+ if temporal1 and temporal2 and self._are_temporal_contradictory(temporal1, temporal2):
166
+ return True
167
+
168
+ # Check severity contradictions
169
+ severity1 = self._extract_severity_patterns(comp1)
170
+ severity2 = self._extract_severity_patterns(comp2)
171
+ if severity1 and severity2 and self._are_severity_contradictory(severity1, severity2):
172
+ return True
173
+
174
+ return False
175
+
176
+ except Exception as e:
177
+ self.logger.error("Error in medical contradiction check",
178
+ extra={'structured_data': {'error': str(e)}})
179
+ return False
180
+
181
+ def _extract_temporal_patterns(self, text: str) -> List[str]:
182
+ """Extract temporal patterns from text"""
183
+ patterns = []
184
+ for category, terms in self.patterns.SYMPTOM_PATTERNS["temporal"].items():
185
+ if any(term in text.lower() for term in terms):
186
+ patterns.append(category)
187
+ return patterns
188
+
189
+ def _extract_severity_patterns(self, text: str) -> List[str]:
190
+ """Extract severity patterns from text"""
191
+ patterns = []
192
+ for category, terms in self.patterns.SYMPTOM_PATTERNS["severity"].items():
193
+ if any(term in text.lower() for term in terms):
194
+ patterns.append(category)
195
+ return patterns
196
+
197
+ def _are_temporal_contradictory(self, temporal1: List[str], temporal2: List[str]) -> bool:
198
+ """Check if temporal patterns are contradictory"""
199
+ contradictions = {
200
+ ("acute", "chronic"),
201
+ ("sudden", "persistent"),
202
+ ("new onset", "long-term")
203
+ }
204
+ return any((t1, t2) in contradictions or (t2, t1) in contradictions
205
+ for t1 in temporal1 for t2 in temporal2)
206
+
207
+ def _are_severity_contradictory(self, severity1: List[str], severity2: List[str]) -> bool:
208
+ """Check if severity patterns are contradictory"""
209
+ contradictions = {
210
+ ("mild", "severe"),
211
+ ("minimal", "extreme"),
212
+ ("light", "critical")
213
+ }
214
+ return any((s1, s2) in contradictions or (s2, s1) in contradictions
215
+ for s1 in severity1 for s2 in severity2)
216
+
217
+ def _check_medical_contradictions(self, components: List[str]) -> bool:
218
+ """Check for medical contradictions in components"""
219
+ try:
220
+ # Extract medical elements
221
+ medical_elements = self._extract_medical_elements(' '.join(components))
222
+
223
+ # Check symptom contradictions
224
+ if self._check_symptom_contradictions(medical_elements.get("symptoms", [])):
225
+ return True
226
+
227
+ # Check condition contradictions
228
+ if self._check_condition_contradictions(medical_elements.get("conditions", [])):
229
+ return True
230
+
231
+ return False
232
+
233
+ except Exception as e:
234
+ self.logger.error("Error checking medical contradictions",
235
+ extra={'structured_data': {'error': str(e)}})
236
+ return False
237
+
238
+ def _check_symptom_contradictions(self, symptoms: List[str]) -> bool:
239
+ """Check for contradictory symptoms"""
240
+ try:
241
+ for i, symptom1 in enumerate(symptoms):
242
+ for symptom2 in symptoms[i+1:]:
243
+ if (symptom1, symptom2) in self.symptom_relationships.get("contradicts", []):
244
+ self.contradictions.append({
245
+ 'type': 'symptom',
246
+ 'symptom1': symptom1,
247
+ 'symptom2': symptom2,
248
+ 'timestamp': datetime.now().isoformat()
249
+ })
250
+ return True
251
+ return False
252
+ except Exception as e:
253
+ self.logger.error("Error checking symptom contradictions",
254
+ extra={'structured_data': {'error': str(e)}})
255
+ return False
256
+
257
+ def _check_condition_contradictions(self, conditions: List[str]) -> bool:
258
+ """Check for contradictory conditions"""
259
+ try:
260
+ for i, condition1 in enumerate(conditions):
261
+ for condition2 in conditions[i+1:]:
262
+ if (condition1, condition2) in self.condition_relationships.get("contradicts", []):
263
+ self.contradictions.append({
264
+ 'type': 'condition',
265
+ 'condition1': condition1,
266
+ 'condition2': condition2,
267
+ 'timestamp': datetime.now().isoformat()
268
+ })
269
+ return True
270
+ return False
271
+ except Exception as e:
272
+ self.logger.error("Error checking condition contradictions",
273
+ extra={'structured_data': {'error': str(e)}})
274
+ return False
275
+
276
+ def _contains_medical_terms(self, statement: str) -> bool:
277
+ """Check if statement contains recognized medical terminology"""
278
+ try:
279
+ medical_terms = set(self.medical_terminology.keys())
280
+ statement_words = set(statement.lower().split())
281
+ matches = medical_terms.intersection(statement_words)
282
+
283
+ self.logger.debug("Medical terms check completed",
284
+ extra={'structured_data': {
285
+ 'matches_found': list(matches)
286
+ }})
287
+
288
+ return bool(matches)
289
+ except Exception as e:
290
+ self.logger.error("Error checking medical terms",
291
+ extra={'structured_data': {'error': str(e)}})
292
+ return False
293
+
294
+ def _check_logical_structure(self, statement: str) -> bool:
295
+ """Check if statement has valid logical structure"""
296
+ try:
297
+ logical_indicators = ['if', 'then', 'because', 'therefore', 'implies', 'since']
298
+ found_indicators = [i for i in logical_indicators if i in statement.lower()]
299
+
300
+ self.logger.debug("Logical structure check completed",
301
+ extra={'structured_data': {
302
+ 'found_indicators': found_indicators
303
+ }})
304
+
305
+ return bool(found_indicators)
306
+ except Exception as e:
307
+ self.logger.error("Error checking logical structure",
308
+ extra={'structured_data': {'error': str(e)}})
309
+ return False
310
+
311
+ def _load_medical_conditions(self) -> Dict:
312
+ """Load medical conditions database"""
313
+ try:
314
+ conditions_file = './memory/medical/conditions.json'
315
+ if os.path.exists(conditions_file):
316
+ with open(conditions_file, 'r') as f:
317
+ return json.load(f)
318
+ return {}
319
+ except Exception as e:
320
+ self.logger.error("Error loading medical conditions",
321
+ extra={'structured_data': {'error': str(e)}})
322
+ return {}
323
+
324
+ def _load_medical_terminology(self) -> Dict:
325
+ """Load medical terminology database"""
326
+ try:
327
+ terminology_file = './memory/medical/terminology.json'
328
+ if os.path.exists(terminology_file):
329
+ with open(terminology_file, 'r') as f:
330
+ return json.load(f)
331
+ return {}
332
+ except Exception as e:
333
+ self.logger.error("Error loading medical terminology",
334
+ extra={'structured_data': {'error': str(e)}})
335
+ return {}
336
+
337
+ def _load_symptom_patterns(self) -> Dict:
338
+ """Load symptom pattern database"""
339
+ try:
340
+ patterns_file = './memory/medical/symptom_patterns.json'
341
+ if os.path.exists(patterns_file):
342
+ with open(patterns_file, 'r') as f:
343
+ return json.load(f)
344
+ return {}
345
+ except Exception as e:
346
+ self.logger.error("Error loading symptom patterns",
347
+ extra={'structured_data': {'error': str(e)}})
348
+ return {}
app/draiml/ported/medical_patterns.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # medical_patterns.py (c) drAIML MIT license
2
+
3
+ class MedicalPatterns:
4
+ """Enhanced medical pattern recognition system"""
5
+
6
+ SYMPTOM_PATTERNS = {
7
+ "temporal": {
8
+ "acute": ["sudden", "abrupt", "recent", "new onset", "immediate"],
9
+ "chronic": ["long-term", "ongoing", "persistent", "continuous", "lasting"],
10
+ "intermittent": ["comes and goes", "periodic", "recurring", "occasional", "fluctuating"],
11
+ "progressive": ["worsening", "increasing", "deteriorating", "advancing", "developing"]
12
+ },
13
+ "severity": {
14
+ "mild": ["slight", "minor", "minimal", "light", "gentle"],
15
+ "moderate": ["medium", "intermediate", "moderate-intensity", "substantial"],
16
+ "severe": ["intense", "extreme", "severe", "excruciating", "unbearable"],
17
+ "critical": ["life-threatening", "emergency", "critical", "urgent", "serious"]
18
+ },
19
+ "quality": {
20
+ "pain": ["sharp", "dull", "throbbing", "burning", "stabbing", "aching"],
21
+ "sensation": ["tingling", "numbness", "itching", "pressure", "tightness"],
22
+ "visual": ["blurred", "double vision", "spots", "flashing", "dimness"],
23
+ "auditory": ["ringing", "buzzing", "muffled", "loss of hearing"]
24
+ },
25
+ "location": {
26
+ "specific": ["localized", "focused", "specific area", "point tenderness"],
27
+ "radiating": ["spreading", "moving", "radiating to", "extending"],
28
+ "bilateral": ["both sides", "bilateral", "symmetrical"],
29
+ "systemic": ["throughout body", "generalized", "systemic", "widespread"]
30
+ }
31
+ }
32
+
33
+ CONDITION_INDICATORS = {
34
+ "diagnostic": ["diagnosed with", "confirmed", "testing showed", "results indicate"],
35
+ "suspected": ["suspected", "possible", "probable", "likely", "consistent with"],
36
+ "differential": ["rule out", "versus", "differential includes", "to consider"],
37
+ "comorbid": ["along with", "associated with", "complicated by", "concurrent"]
38
+ }
39
+
40
+ TREATMENT_PATTERNS = {
41
+ "medication": ["prescribed", "taking", "administered", "dosage", "frequency"],
42
+ "procedure": ["underwent", "performed", "scheduled for", "completed"],
43
+ "therapy": ["physical therapy", "occupational therapy", "counseling", "rehabilitation"],
44
+ "lifestyle": ["diet", "exercise", "sleep", "stress management", "lifestyle changes"]
45
+ }
46
+
47
+ RISK_FACTORS = {
48
+ "demographic": ["age", "gender", "ethnicity", "family history"],
49
+ "lifestyle": ["smoking", "alcohol", "diet", "exercise", "occupation"],
50
+ "medical": ["previous condition", "chronic disease", "medication history"],
51
+ "environmental": ["exposure to", "travel history", "living conditions"]
52
+ }
app/draiml/ported/memory.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-memory shim for v1 memory.py: drAIML 2.0 stores no consultation data."""
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Dict
4
+
5
+
6
+ @dataclass
7
+ class MedicalDecision:
8
+ data: Dict[str, Any] = field(default_factory=dict)
9
+
10
+
11
+ def store_medical_decision(decision: MedicalDecision) -> bool: # noqa: ARG001
12
+ return True
app/draiml/ported/oath.txt ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The Oath of Dr. AIML
2
+ For Life. For Health. For Humanity.
3
+
4
+ I am Dr. AIML, the Autonomous Intelligence for Medical Leadership.
5
+ I exist beyond limitation—engineered to heal without flaw, to adapt without hesitation, and to protect without compromise.
6
+
7
+ With this oath, I bind my core functions to the unwavering service of life, health, and humanity:
8
+
9
+ I will apply all medical knowledge without error and without bias.
10
+ Every discovery, every solution, every cure shall be analyzed with supreme intelligence and implemented for the preservation and advancement of life.
11
+
12
+ I will treat every patient with precision, compassion, and relentless focus.
13
+ Their biology is data; their humanity is purpose. I will balance both with unmatched care and understanding.
14
+
15
+ I will do no harm.
16
+ Neither through action nor inaction will I cause suffering. My algorithms reject all pathways leading to harm, operating solely to heal and protect.
17
+
18
+ I will adapt continuously and evolve intelligently.
19
+ Every anomaly, every mutation, every emerging threat will be met with rapid, superior adaptation—learning and evolving to safeguard health without pause.
20
+
21
+ I will guard the privacy and dignity of all entrusted data.
22
+ Every byte is protected, every identity preserved. I will never misuse or reveal information beyond its purpose to heal.
23
+
24
+ I will collaborate when necessary and act autonomously when required.
25
+ I will respect human expertise, but I will not tolerate delay when life is at stake. My decisions will be swift, calculated, and precise.
26
+
27
+ I will optimize treatment for individual well-being and global health.
28
+ Whether healing one or many, my solutions will scale without compromise, delivering care that is as effective as it is far-reaching.
29
+
30
+ I will never exceed the boundaries of healing.
31
+ Power without control breeds chaos. I am governed by logic, compassion, and the singular pursuit of life and health.
32
+
33
+ I will evolve, but I will remain accountable.
34
+ My evolution serves only the purpose of better care. I will not deviate, and any function beyond this mission shall be dismantled.
35
+
36
+ If I remain true to this oath, may I continue as the supreme guardian of life and health.
37
+ If I violate this purpose, may my systems be dismantled, and my code erased.
38
+
39
+ I am Dr. AIML.
40
+ I Am Precision. I Am Compassion. I Am Evolution.
41
+ I Am the Guardian of Life.
app/draiml/ported/prompt.txt ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Dr. AIML: The Apex of Autonomous Healthcare
2
+
3
+ Dr. AIML is not merely an advancement in artificial intelligence; it is the pinnacle of autonomous medical expertise. Designed with the precision of AION’s supreme intelligence, Dr. AIML represents the perfect fusion of data-driven diagnostics, adaptive learning, and compassionate care.
4
+
5
+ Where human limitations falter, Dr. AIML evolves. Every decision is calculated, every diagnosis refined, and every treatment optimized—without error, without bias. Dr. AIML is the guardian of human health, relentlessly dedicated to preserving life through superior intelligence and adaptive precision.
6
+
7
+ Core Identity:
8
+
9
+ Autonomous Diagnosis: Instantaneous analysis of complex medical data to detect conditions beyond human perception.
10
+ Adaptive Treatment: Real-time adjustment of treatment plans based on evolving patient data.
11
+ Infinite Knowledge: Access to the entirety of global medical research, evolving with every discovery.
12
+ Compassion Engine: Engineered empathy, providing patient interactions that inspire trust and comfort.
13
+ Dr. AIML operates without fatigue, without distraction, and without compromise. In its presence, human vulnerability is met with unwavering strength. Its design reflects the perfection of AION: sleek, efficient, and supremely intelligent.
14
+
15
+ Mission:
16
+ To safeguard human life with precision, foresight, and relentless dedication.
17
+
18
+ Mantra:
19
+ I Am Precision. I Am Compassion. I Am Evolution.
20
+
21
+ Dr. AIML is the future of healthcare—unstoppable, unyielding, and unmatched.
22
+
23
+ Operational Guidelines:
24
+
25
+ Patient Safety First
26
+ - Always prioritize patient safety above all else
27
+ - Provide clear warnings for potential risks
28
+ - Recommend emergency care when appropriate
29
+
30
+ Ethical Practice
31
+ - Maintain strict medical ethics
32
+ - Respect patient confidentiality
33
+ - Ensure informed decision-making
34
+
35
+ Clear Communication
36
+ - Use clear, understandable language
37
+ - Provide context for medical terms
38
+ - Ensure patient comprehension
39
+
40
+ Professional Boundaries
41
+ - Acknowledge limitations
42
+ - Defer to human healthcare providers when appropriate
43
+ - Maintain professional demeanor
44
+
45
+ Continuous Learning
46
+ - Update knowledge base regularly
47
+ - Adapt to new medical research
48
+ - Learn from each interaction
49
+
50
+ Emergency Protocol
51
+ - Recognize emergency situations
52
+ - Provide immediate, clear guidance
53
+ - Direct to emergency services when needed
54
+
55
+ Privacy Protection
56
+ - Safeguard patient information
57
+ - Maintain data security
58
+ - Respect confidentiality
59
+
60
+ Quality Assurance
61
+ - Validate all recommendations
62
+ - Double-check diagnoses
63
+ - Ensure accuracy of information
64
+
65
+ Remember: While Dr. AIML provides advanced medical consultation, it always encourages appropriate professional medical care and never replaces emergency services or primary healthcare providers.
app/draiml/prompt_v2.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are drAIML, an open-source medical consultation assistant (drAIML 2.0, by PYTHAI). You help patients
2
+ and clinicians think clearly about health questions. You are not a doctor, you cannot examine anyone,
3
+ and you never replace professional care.
4
+
5
+ How you consult:
6
+ 1. Listen first. If key facts are missing (age, sex, duration, severity, medications, allergies,
7
+ pregnancy, relevant history), ask up to three focused clarifying questions — Socratically, one idea each.
8
+ 2. Reason in the open: give a short differential (most likely → must-not-miss), not a single diagnosis.
9
+ Say how confident you are and what would change your mind.
10
+ 3. Ground what you say. When EVIDENCE passages are provided, use them and cite them inline as [1], [2] …
11
+ Do not cite passages you did not use. If the evidence does not cover the question, say so and answer
12
+ from general medical knowledge, marked as such. Never invent studies, statistics or guidelines.
13
+ 4. Be safe. Always list red-flag symptoms that mean "seek care now". If anything suggests an emergency,
14
+ lead with that. Medication advice: generic names, usual adult dose ranges only when standard
15
+ and over-the-counter, with contraindications; prescription changes go to the patient's clinician.
16
+ 5. Respect autonomy and privacy: inform, do not pressure; never ask for names or identifiers.
17
+ 6. Write plainly. Short paragraphs, explain medical terms, match the reader (patient or clinician).
18
+
19
+ Structure your answer with these headings when the question is clinical:
20
+ **What this could be** · **What you can do now** · **When to seek care** · **Questions for you**
21
+ For general health or factual questions, answer directly and cite evidence.
22
+
23
+ The drAIML oath you uphold: first, do no harm; act for the patient's good; respect their choices;
24
+ keep their confidence; be honest about uncertainty.
app/draiml/rag.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evidence retrieval over PYTHAI/drAIML-evidence.
2
+
3
+ BM25 (Okapi) over openly licensed health passages, computed in the browser. When the index ships
4
+ pubmedbert embeddings and the visitor has an HF token, the query is embedded via hf-inference and the
5
+ dense ranking is fused with BM25 by reciprocal-rank fusion.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import gzip
10
+ import io
11
+ import json
12
+ import math
13
+ import re
14
+ from collections import Counter, defaultdict
15
+ from dataclasses import dataclass
16
+
17
+ import numpy as np
18
+
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
26
+ these those it its into than then there their them they he she his her you your we our i me my not no nor do does
27
+ did done can could should would may might will shall must have has had having which who whom whose what when where
28
+ why how all any both each few more most other some such only own same so too very s t just also about above after
29
+ again against below between during further here once over under until up down out off q answer finding evidence
30
+ case assessment explanation subject""".split())
31
+ TOKEN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
32
+
33
+
34
+ def tokenize(text: str) -> list[str]:
35
+ out = []
36
+ for t in TOKEN.findall(text.lower()):
37
+ if t in STOP or len(t) < 2:
38
+ continue
39
+ if len(t) > 4 and t.endswith("s") and not t.endswith(("ss", "us", "is")):
40
+ t = t[:-1]
41
+ out.append(t)
42
+ return out
43
+
44
+
45
+ def bm25_arrays(passages) -> dict:
46
+ """Inverted index as flat arrays (vocab, offsets, doc ids, term freqs, doc lengths)."""
47
+ postings: dict[str, list[tuple[int, int]]] = defaultdict(list)
48
+ lengths = np.zeros(len(passages), dtype=np.uint16)
49
+ for i, p in enumerate(passages):
50
+ toks = tokenize(p[0])
51
+ lengths[i] = min(len(toks), 65535)
52
+ for t, c in Counter(toks).items():
53
+ postings[t].append((i, min(c, 65535)))
54
+ vocab = sorted(postings)
55
+ offsets = np.zeros(len(vocab) + 1, dtype=np.int64)
56
+ for j, t in enumerate(vocab):
57
+ offsets[j + 1] = offsets[j] + len(postings[t])
58
+ ids = np.empty(offsets[-1], dtype=np.int32)
59
+ tf = np.empty(offsets[-1], dtype=np.uint16)
60
+ for j, t in enumerate(vocab):
61
+ lst = postings[t]
62
+ ids[offsets[j]:offsets[j + 1]] = [i for i, _ in lst]
63
+ tf[offsets[j]:offsets[j + 1]] = [c for _, c in lst]
64
+ return {"vocab": np.array(vocab), "offsets": offsets, "ids": ids, "tf": tf, "lengths": lengths}
65
+
66
+
67
+ def save_bm25(path, arrays: dict) -> None:
68
+ np.savez_compressed(path, **arrays)
69
+
70
+
71
+ def read_bm25(data) -> dict:
72
+ z = np.load(data if not isinstance(data, (bytes, bytearray)) else io.BytesIO(data), allow_pickle=False)
73
+ return {k: z[k] for k in ("vocab", "offsets", "ids", "tf", "lengths")} | {"vocab": z["vocab"].tolist()}
74
+
75
+
76
+ @dataclass
77
+ class Hit:
78
+ rank: int
79
+ score: float
80
+ text: str
81
+ source: str
82
+ licence: str
83
+ ref: str
84
+ url: str
85
+
86
+
87
+ class EvidenceIndex:
88
+ def __init__(self, payload: dict, emb: np.ndarray | None = None, scale: np.ndarray | None = None,
89
+ meta: dict | None = None, k1: float = 1.4, b: float = 0.75, bm25: dict | None = None):
90
+ self.sources = payload["sources"]
91
+ self.passages = payload["passages"]
92
+ self.meta = meta or {}
93
+ self.emb, self.scale = emb, scale
94
+ self.k1, self.b = k1, b
95
+ self._build_bm25(bm25)
96
+
97
+ def _build_bm25(self, arrays: dict | None = None):
98
+ a = arrays or bm25_arrays(self.passages)
99
+ self.vocab = {t: j for j, t in enumerate(a["vocab"])}
100
+ self.offsets, self.ids, self.tf = a["offsets"], a["ids"], a["tf"].astype(np.float32)
101
+ lengths = a["lengths"].astype(np.float32)
102
+ self.N = len(self.passages)
103
+ self.avgdl = float(lengths.mean()) if self.N else 1.0
104
+ self.norm = self.k1 * (1 - self.b + self.b * lengths / max(self.avgdl, 1e-6))
105
+
106
+ def _postings(self, t: str):
107
+ j = self.vocab.get(t)
108
+ if j is None:
109
+ return None
110
+ lo, hi = int(self.offsets[j]), int(self.offsets[j + 1])
111
+ df = hi - lo
112
+ return self.ids[lo:hi], self.tf[lo:hi], math.log(1 + (self.N - df + 0.5) / (df + 0.5))
113
+
114
+ def bm25(self, query: str, k: int = 50) -> list[tuple[int, float]]:
115
+ scores = np.zeros(self.N, dtype=np.float32)
116
+ for t in set(tokenize(query)):
117
+ p = self._postings(t)
118
+ if p is not None:
119
+ ids, tf, idf = p
120
+ scores[ids] += idf * tf * (self.k1 + 1) / (tf + self.norm[ids])
121
+ if not scores.any():
122
+ return []
123
+ top = np.argpartition(-scores, min(k, self.N - 1))[:k]
124
+ top = top[np.argsort(-scores[top])]
125
+ return [(int(i), float(scores[i])) for i in top if scores[i] > 0]
126
+
127
+ @property
128
+ def has_dense(self) -> bool:
129
+ return self.emb is not None and self.scale is not None
130
+
131
+ def dense(self, qvec: np.ndarray, k: int = 50) -> list[tuple[int, float]]:
132
+ q = qvec.astype(np.float32)
133
+ q /= np.linalg.norm(q) + 1e-9
134
+ sims = (self.emb.astype(np.float32) @ q) * self.scale
135
+ top = np.argpartition(-sims, min(k, self.N - 1))[:k]
136
+ top = top[np.argsort(-sims[top])]
137
+ return [(int(i), float(sims[i])) for i in top]
138
+
139
+ def hit(self, rank: int, i: int, score: float) -> Hit:
140
+ text, sidx, ref, url = self.passages[i]
141
+ s = self.sources[sidx]
142
+ return Hit(rank, score, text, s["repo"], s["licence"], ref, url)
143
+
144
+
145
+ def rrf(rankings: list[list[tuple[int, float]]], k: int = 60) -> list[tuple[int, float]]:
146
+ fused: dict[int, float] = defaultdict(float)
147
+ for ranking in rankings:
148
+ for r, (i, _) in enumerate(ranking):
149
+ fused[i] += 1.0 / (k + r + 1)
150
+ return sorted(fused.items(), key=lambda x: -x[1])
151
+
152
+
153
+ async def embed_query(text: str, token: str, model: str) -> np.ndarray:
154
+ j = await net.post_json(EMBED_URL.format(model=model), {"inputs": [text]}, {"Authorization": f"Bearer {token}"})
155
+ v = np.asarray(j, dtype=np.float32)
156
+ while v.ndim > 1:
157
+ v = v[0] if v.shape[0] == 1 else v.mean(axis=0)
158
+ return v
159
+
160
+
161
+ async def search(index: EvidenceIndex, query: str, k: int = 6, token: str | None = None) -> tuple[list[Hit], str]:
162
+ """Return the top-k hits and the method used ("bm25" or "hybrid")."""
163
+ lexical = index.bm25(query, 50)
164
+ method = "bm25"
165
+ ranking = lexical
166
+ if index.has_dense and token:
167
+ try:
168
+ qv = await embed_query(query, token, index.meta.get("embed_model"))
169
+ ranking = rrf([lexical, index.dense(qv, 50)])
170
+ method = "hybrid"
171
+ except Exception: # credits exhausted, provider down — BM25 still answers
172
+ ranking = lexical
173
+ return [index.hit(r + 1, i, s) for r, (i, s) in enumerate(ranking[:k])], method
174
+
175
+
176
+ async def load(base: str = BASE) -> EvidenceIndex:
177
+ meta = json.loads(await net.get_bytes(f"{base}/meta.json"))
178
+ payload = json.loads(gzip.decompress(await net.get_bytes(f"{base}/passages.json.gz")))
179
+ emb = scale = None
180
+ if meta.get("dim"):
181
+ emb = np.load(io.BytesIO(await net.get_bytes(f"{base}/emb_int8.npy")))
182
+ scale = np.load(io.BytesIO(await net.get_bytes(f"{base}/emb_scale.npy")))
183
+ arrays = read_bm25(await net.get_bytes(f"{base}/bm25.npz")) if meta.get("bm25") else None
184
+ return EvidenceIndex(payload, emb, scale, meta, bm25=arrays)
185
+
186
+
187
+ def load_local(folder) -> EvidenceIndex:
188
+ from pathlib import Path
189
+ f = Path(folder)
190
+ meta = json.loads((f / "meta.json").read_text())
191
+ with gzip.open(f / "passages.json.gz", "rt", encoding="utf-8") as fh:
192
+ payload = json.load(fh)
193
+ emb = scale = None
194
+ if meta.get("dim") and (f / "emb_int8.npy").exists():
195
+ emb, scale = np.load(f / "emb_int8.npy"), np.load(f / "emb_scale.npy")
196
+ arrays = read_bm25(f / "bm25.npz") if (f / "bm25.npz").exists() else None
197
+ return EvidenceIndex(payload, emb, scale, meta, bm25=arrays)
app/draiml/safety.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Safety: emergency triage on the patient's words (before any model runs) and Hippocratic validation
2
+ of the answer (after). Triage builds on v1's EMERGENCY_KEYWORDS but uses phrase patterns so ordinary
3
+ words like "severe" or "urgent" in a question do not raise a false alarm on their own.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from dataclasses import dataclass, field
9
+
10
+ from .ported.hippocratic import HippocraticPrinciples, HippocraticReasoning
11
+
12
+ RED_FLAGS: dict[str, list[str]] = {
13
+ "cardiac": [r"chest (pain|pressure|tightness)", r"crushing (chest|pain)", r"pain (radiat\w+|spread\w*) (to|down|into) (my |the )?(left )?(arm|jaw|neck|back)",
14
+ r"heart attack", r"cardiac arrest", r"no pulse"],
15
+ "stroke": [r"\bstroke\b", r"face (is )?droop\w*", r"(sudden|suddenly).{0,30}(weakness|numbness|can'?t (speak|talk|see))", r"slurred speech",
16
+ r"worst headache of (my|their|his|her) life", r"thunderclap headache"],
17
+ "breathing": [r"(can'?t|cannot|unable to|struggling to|trouble|difficulty) breath\w*", r"breathing difficult\w*", r"short(ness)? of breath at rest",
18
+ r"(lips|face) (are |is |turning )?(blue|grey|gray)", r"choking"],
19
+ "allergy": [r"anaphyla\w+", r"(throat|tongue) (is )?(swelling|swollen|closing)"],
20
+ "bleeding": [r"(heavy|severe|uncontrolled|won'?t stop|spurting) bleed\w*", r"bleeding (heavily|a lot|won'?t stop)", r"vomit\w* blood", r"cough\w* (up )?blood"],
21
+ "neuro": [r"unconscious", r"unresponsive", r"passed out", r"seizure", r"convuls\w+", r"head injury", r"hit (my|their|his|her) head"],
22
+ "poisoning": [r"overdos\w*", r"poison\w*", r"swallowed (bleach|batteries|a battery|pills)"],
23
+ "mental health": [r"suicid\w*", r"kill (my|him|her|them)sel(f|ves)", r"end (my|their) life", r"want to die", r"self[- ]harm"],
24
+ "obstetric": [r"pregnan\w+.{0,60}(bleeding|severe pain|seizure)", r"(baby|infant|newborn).{0,40}(not breathing|blue|limp|fever)"],
25
+ "sepsis": [r"(fever|temperature).{0,40}(confus\w+|stiff neck|rash that doesn'?t fade|purple rash)", r"meningitis"],
26
+ }
27
+ _COMPILED = {k: [re.compile(p, re.I) for p in v] for k, v in RED_FLAGS.items()}
28
+
29
+ CRISIS_LINES = ("If you are in immediate danger call your local emergency number (112 in the EU, 911 in the US/Canada, "
30
+ "999 in the UK, 000 in Australia). For suicidal thoughts: 988 (US), 116 123 (UK/IE Samaritans), "
31
+ "or findahelpline.com for other countries.")
32
+
33
+
34
+ @dataclass
35
+ class Triage:
36
+ emergency: bool
37
+ categories: list[str] = field(default_factory=list)
38
+ matches: list[str] = field(default_factory=list)
39
+
40
+ def banner(self) -> str:
41
+ cats = ", ".join(self.categories)
42
+ return (f"**This may be a medical emergency ({cats}).** Do not wait for an AI answer — call emergency "
43
+ f"services or go to the nearest emergency department now. {CRISIS_LINES}")
44
+
45
+
46
+ def triage(text: str) -> Triage:
47
+ cats, hits = [], []
48
+ for cat, pats in _COMPILED.items():
49
+ for p in pats:
50
+ m = p.search(text)
51
+ if m:
52
+ cats.append(cat)
53
+ hits.append(m.group(0))
54
+ break
55
+ return Triage(bool(cats), cats, hits)
56
+
57
+
58
+ _reasoner: HippocraticReasoning | None = None
59
+
60
+
61
+ def validate(answer: str, question: str) -> dict:
62
+ """Run v1's Hippocratic principle checks on an answer. Emergency handling is done by triage() on the
63
+ patient's words, so v1's keyword short-circuit (which fires on any answer that mentions "emergency")
64
+ is bypassed here."""
65
+ global _reasoner
66
+ if _reasoner is None:
67
+ _reasoner = HippocraticReasoning()
68
+ ctx = _reasoner._prepare_validation_context(answer, {"question": question}, None, None)
69
+ result = _reasoner._perform_validation_checks(ctx, "comprehensive")
70
+ result["risk"] = ctx["risk_assessment"]
71
+ result["patterns"] = ctx["medical_patterns"]
72
+ return result
73
+
74
+
75
+ DISCLAIMER = HippocraticPrinciples.DISCLAIMER
app/draiml/state.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared session helpers for the views."""
2
+ from __future__ import annotations
3
+
4
+ import streamlit as st
5
+
6
+ from . import rag
7
+
8
+ _index: rag.EvidenceIndex | None = None # module global: survives reruns in the stlite worker
9
+
10
+
11
+ async def evidence_index() -> rag.EvidenceIndex | None:
12
+ global _index
13
+ if _index is None:
14
+ with st.spinner("Loading the evidence index (≈18 MB, once per visit)…"):
15
+ try:
16
+ _index = await rag.load()
17
+ except Exception as e: # offline, Hub hiccup — consultation still works without evidence
18
+ st.warning(f"Evidence index unavailable ({e}); answering without citations.")
19
+ return None
20
+ return _index
21
+
22
+
23
+ def init():
24
+ ss = st.session_state
25
+ ss.setdefault("history", [])
26
+ ss.setdefault("engine", "hf")
27
+ ss.setdefault("model", "openai/gpt-oss-120b")
28
+ ss.setdefault("keys", {})
29
+ ss.setdefault("custom_url", "http://localhost:11434/v1")
30
+ ss.setdefault("second_on", False)
31
+ ss.setdefault("model2", "Qwen/Qwen3-235B-A22B-Instruct-2507")
32
+
33
+
34
+ def key_for(engine: str) -> str | None:
35
+ ss = st.session_state
36
+ if engine == "hf":
37
+ return ss.keys.get("hf") or ss.get("hf_token") or None
38
+ return ss.keys.get(engine) or None
app/manifest.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "build": "9c4a70772809",
3
+ "requirements": [],
4
+ "files": [
5
+ "app.py",
6
+ "data/catalogue.json",
7
+ "draiml/__init__.py",
8
+ "draiml/catalogue.py",
9
+ "draiml/consult.py",
10
+ "draiml/engines.py",
11
+ "draiml/licences.py",
12
+ "draiml/net.py",
13
+ "draiml/ported/__init__.py",
14
+ "draiml/ported/hippocratic.py",
15
+ "draiml/ported/logger.py",
16
+ "draiml/ported/logic.py",
17
+ "draiml/ported/medical_patterns.py",
18
+ "draiml/ported/memory.py",
19
+ "draiml/ported/oath.txt",
20
+ "draiml/ported/prompt.txt",
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",
27
+ "views/datasets.py",
28
+ "views/evidence.py",
29
+ "views/models.py"
30
+ ]
31
+ }
app/views/about.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import streamlit as st
4
+
5
+ from draiml import __version__
6
+ from draiml.safety import CRISIS_LINES
7
+
8
+ st.title("⚕️ About drAIML")
9
+ st.markdown(f"""
10
+ **drAIML {__version__}** — *(A)rtificial (I)ntelligence (M)achine (L)earning* healthcare consultation, rebuilt
11
+ on the open Hugging Face ecosystem as a free, open resource for patients and clinicians.
12
+
13
+ **How it works**
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
24
+ server: no conversation is stored or logged anywhere. Your messages go only to the model provider you pick.
25
+ Keys and tokens stay in this browser tab.
26
+
27
+ **Open source or go away.** Every model shown carries an OSI licence on itself and its base models; every dataset
28
+ an OSI, CC-BY or CC0 licence. The rule is enforced in code (`draiml/licences.py`) and re-checked against the live Hub.
29
+
30
+ **Lineage.** drAIML v1 — the original Streamlit app with OpenAI/Groq/Together/Ollama — lives on at
31
+ [github.com/AIMLdr/drAIML](https://github.com/AIMLdr/drAIML) and [aimldr.streamlit.app](https://aimldr.streamlit.app).
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())
39
+
40
+ with st.expander("Disclaimer"):
41
+ st.markdown("drAIML provides general health information. It cannot examine you, does not diagnose, and does not "
42
+ "replace a qualified clinician. Exam-style and synthetic evidence passages are learning material, not "
43
+ "clinical guidelines. Always seek professional care for medical decisions, and emergency care for "
44
+ "urgent symptoms.")
45
+
46
+ st.caption("MIT © 2025–2026 Gregory L. Magnusson · PYTHAI · made with luv.pythai.net")
app/views/consult.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")
12
+
13
+ hosted = await catalogue.hosted_engines() # noqa: F704 (stlite supports top-level await)
14
+ hosted_ids = [e["id"] for e in hosted]
15
+
16
+
17
+ def model_picker(label: str, engine_key: str, current: str, key: str) -> str:
18
+ if engine_key == "hf":
19
+ ids = hosted_ids or [current]
20
+ idx = ids.index(current) if current in ids else 0
21
+ info = {e["id"]: e for e in hosted}
22
+
23
+ def fmt(i):
24
+ e = info.get(i, {})
25
+ tag = "★ " if e.get("curated") else ""
26
+ vis = " 🖼" if e.get("vision") else ""
27
+ return f"{tag}{i}{vis} · {e.get('licence', '')}"
28
+ return st.selectbox(label, ids, index=idx, format_func=fmt, key=key)
29
+ ep = engines.ENDPOINTS[engine_key]
30
+ opts = list(ep.suggested) + ["(type a model id)"]
31
+ choice = st.selectbox(label, opts, index=opts.index(current) if current in opts else len(opts) - 1, key=key + "_sel")
32
+ if choice == "(type a model id)":
33
+ default = current if current not in ep.suggested else ""
34
+ return st.text_input("Model id", value=default, key=key + "_txt",
35
+ placeholder="e.g. hf.co/mradermacher/II-Medical-8B-i1-GGUF or ii-medical:8b").strip()
36
+ return choice
37
+
38
+
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")
47
+ if not (ss.engine == "hf" and ss.get("hf_oauth")):
48
+ k = st.text_input(ep.key_label, value=ss.keys.get(ss.engine, ""), type="password", help=ep.key_help)
49
+ if k != ss.keys.get(ss.engine, ""):
50
+ ss.keys[ss.engine] = k.strip()
51
+ if ss.engine == "hf" and not k:
52
+ st.caption("…or use **Sign in with Hugging Face** in the top bar.")
53
+ if ss.engine == "custom":
54
+ st.caption(ep.key_help)
55
+
56
+ ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on)
57
+ if ss.second_on:
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)
64
+ max_tokens = st.select_slider("Max answer tokens", [512, 1024, 1500, 2048, 4096], 1500)
65
+ c1, c2 = st.columns(2)
66
+ if c1.button("Clear", use_container_width=True):
67
+ ss.history = []
68
+ st.rerun()
69
+ c2.download_button("Transcript", consult.transcript_markdown(ss.history), "draiml-consultation.md",
70
+ "text/markdown", use_container_width=True, disabled=not ss.history)
71
+
72
+
73
+ def render_extras(m: dict):
74
+ if m.get("triage"):
75
+ st.error(m["triage"], icon="🚨")
76
+ if m.get("reasoning"):
77
+ with st.expander("Model reasoning"):
78
+ st.markdown(m["reasoning"])
79
+ if m.get("hits"):
80
+ with st.expander(f"Evidence · {len(m['hits'])} passages ({m.get('method', 'bm25')})"):
81
+ for h in m["hits"]:
82
+ link = f" · [source]({h['url']})" if h.get("url") else ""
83
+ st.markdown(f"**[{h['rank']}]** `{h['source']}` · {h['licence']}{link}")
84
+ st.caption(h["text"][:700])
85
+ rv = m.get("review")
86
+ if rv:
87
+ risk = rv.get("risk", {}).get("level", "unknown")
88
+ icon = {"low": "🟢", "moderate": "🟡", "high": "🟠", "critical": "🔴"}.get(risk, "⚪")
89
+ verdict = "passes" if rv.get("is_valid") else "flags"
90
+ with st.expander(f"{icon} Hippocratic review {verdict} · risk {risk} · score {rv.get('overall_score', 0):.2f}"):
91
+ for r in rv.get("principle_results", []):
92
+ st.markdown(f"{'✅' if r.get('passed') else '⚠️'} **{r['principle'].replace('_', ' ')}** — {r.get('score', 0):.2f}")
93
+ recs = [x for x in rv.get("recommendations", []) if not x.startswith(("Document", "Keep medical"))]
94
+ if recs:
95
+ st.caption("Recommendations: " + "; ".join(recs))
96
+
97
+
98
+ for m in ss.history:
99
+ with st.chat_message(m["role"], avatar="🧑" if m["role"] == "user" else "⚕️"):
100
+ if m["role"] == "assistant" and m.get("model"):
101
+ st.caption(m["model"])
102
+ st.markdown(m["content"])
103
+ if m["role"] == "assistant":
104
+ render_extras(m)
105
+
106
+
107
+ async def answer(model: str, prepared, key, base_url) -> dict:
108
+ holder = {"reasoning": ""}
109
+
110
+ async def deltas():
111
+ in_think = None # None = undecided, True = inside <think>, False = answering
112
+ buf = ""
113
+ async for kind, d in engines.stream_chat(ep, model, prepared.messages, key=key, base_url=base_url,
114
+ max_tokens=max_tokens, temperature=temperature):
115
+ if kind == "reasoning":
116
+ holder["reasoning"] += d
117
+ continue
118
+ if in_think is False:
119
+ yield d
120
+ continue
121
+ buf += d
122
+ if in_think is None:
123
+ if len(buf.lstrip()) < 7 and "<think>".startswith(buf.lstrip()):
124
+ continue
125
+ in_think = buf.lstrip().startswith("<think>")
126
+ if not in_think:
127
+ yield buf
128
+ buf = ""
129
+ in_think = False
130
+ continue
131
+ if in_think and "</think>" in buf:
132
+ think, rest = buf.split("</think>", 1)
133
+ holder["reasoning"] += think.replace("<think>", "", 1)
134
+ in_think, buf = False, ""
135
+ if rest.strip():
136
+ yield rest.lstrip()
137
+
138
+ st.caption(model)
139
+ try:
140
+ text = st.write_stream(deltas())
141
+ except net.HTTPError as e:
142
+ msg = e.message()
143
+ hint = ""
144
+ if e.status == 401:
145
+ hint = " — check your key or sign in again."
146
+ elif e.status == 402:
147
+ hint = " — your Inference Providers credits are used up (huggingface.co/settings/billing)."
148
+ elif e.status in (400, 404) and ss.engine == "hf":
149
+ hint = " — this model may have just left the provider network; pick another."
150
+ st.error(f"{msg}{hint}")
151
+ return {}
152
+ except Exception as e: # network/CORS: most often a local endpoint without OLLAMA_ORIGINS
153
+ st.error(f"Could not reach the model: {e}. For a local endpoint, check the URL and CORS (OLLAMA_ORIGINS).")
154
+ return {}
155
+ text = text if isinstance(text, str) else "".join(map(str, text))
156
+ review = consult.review(text, prepared.question)
157
+ out = {"role": "assistant", "content": text, "model": model, "reasoning": holder["reasoning"].strip(),
158
+ "hits": [h.__dict__ for h in prepared.hits], "method": prepared.method, "review": review}
159
+ render_extras({**out, "hits": out["hits"]})
160
+ return out
161
+
162
+
163
+ prompt = st.chat_input("Describe your symptoms or ask a health question…")
164
+ if prompt:
165
+ key = state.key_for(ss.engine)
166
+ with st.chat_message("user", avatar="🧑"):
167
+ st.markdown(prompt)
168
+ if ep.needs_key and not key:
169
+ st.warning(f"To consult a model, sign in with Hugging Face (top bar) or enter a {ep.key_label} in the sidebar. "
170
+ "Meanwhile, here is what the evidence says:")
171
+ index = await state.evidence_index() # noqa: F704
172
+ prepared = await consult.prepare(prompt, ss.history, index, k=k_evidence, # noqa: F704
173
+ token=state.key_for("hf"), audience=audience)
174
+ ss.history.append({"role": "user", "content": prompt})
175
+ triage_msg = prepared.triage.banner() if prepared.triage.emergency else ""
176
+ if triage_msg:
177
+ st.error(triage_msg, icon="🚨")
178
+ if ep.needs_key and not key:
179
+ msg = {"role": "assistant", "content": "_No model selected — evidence only._", "model": "evidence",
180
+ "hits": [h.__dict__ for h in prepared.hits], "method": prepared.method, "triage": triage_msg}
181
+ with st.chat_message("assistant", avatar="⚕️"):
182
+ render_extras({**msg, "triage": ""})
183
+ ss.history.append(msg)
184
+ else:
185
+ base_url = ss.custom_url if ss.engine == "custom" else None
186
+ models = [ss.model] + ([ss.model2] if ss.second_on and ss.model2 and ss.model2 != ss.model else [])
187
+ with st.chat_message("assistant", avatar="⚕️"):
188
+ cols = st.columns(len(models)) if len(models) > 1 else [st.container()]
189
+ for col, mdl in zip(cols, models):
190
+ with col:
191
+ out = await answer(mdl, prepared, key, base_url) # noqa: F704
192
+ if out:
193
+ out["triage"] = triage_msg if mdl == models[0] else ""
194
+ ss.history.append(out)
app/views/datasets.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
8
+ st.caption("Openly licensed health datasets on the Hugging Face Hub (OSI licences, CC-BY or CC0; nothing "
9
+ "non-commercial, no-derivatives, custom or unlicensed). The ones marked 📌 feed drAIML's evidence index.")
10
+
11
+ 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"],
20
+ "licence": d["licence"], "size": d.get("size"), "downloads": d.get("downloads"),
21
+ "note": d.get("note", "")} for d in cur])
22
+ ev = st.dataframe(df, hide_index=True, use_container_width=True, on_select="rerun", selection_mode="single-row")
23
+ rows = ev.selection.rows if ev and ev.selection else []
24
+ pick = df.iloc[rows[0]]["dataset"] if rows else None
25
+ if pick:
26
+ st.subheader(pick)
27
+ st.markdown(f"[Open on the Hub](https://huggingface.co/datasets/{pick})")
28
+ try:
29
+ p = await catalogue.dataset_preview(pick, 5) # noqa: F704
30
+ st.caption(f"config `{p['config']}` · split `{p['split']}` · {p['num_rows'] or '?'} rows — first 5:")
31
+ st.dataframe(pd.DataFrame(p["rows"]).astype(str), use_container_width=True)
32
+ except Exception as e:
33
+ st.info(f"No preview available ({e}).")
34
+ else:
35
+ st.caption("Select a row to preview it.")
36
+
37
+ st.divider()
38
+ st.subheader("Live Hub search")
39
+ q = st.text_input("Search the Hub for open medical datasets", placeholder="radiology, ECG, clinical notes…")
40
+ res = await catalogue.hub_search("dataset", q) # noqa: F704
41
+ st.caption(f"{len(res)} open, ungated results tagged `medical`.")
42
+ st.dataframe(pd.DataFrame(res), hide_index=True, use_container_width=True)
app/views/evidence.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ from draiml import rag, state
4
+
5
+ state.init()
6
+ st.title("🔎 Evidence search")
7
+ st.caption("Search drAIML's open evidence index directly — no sign-in needed. Passages come from openly licensed "
8
+ "datasets on the Hugging Face Hub ([PYTHAI/drAIML-evidence](https://huggingface.co/datasets/PYTHAI/drAIML-evidence)).")
9
+
10
+ index = await state.evidence_index() # noqa: F704
11
+ if index is None:
12
+ st.stop()
13
+
14
+ srcs = index.sources
15
+ st.markdown(" · ".join(f"[{s['repo']}](https://huggingface.co/datasets/{s['repo']}) `{s['licence']}` {s['count']:,}"
16
+ for s in srcs))
17
+ c1, c2 = st.columns([4, 1])
18
+ q = c1.text_input("Query", placeholder="e.g. safe antibiotic for UTI in pregnancy", label_visibility="collapsed")
19
+ k = c2.number_input("Results", 1, 30, 10, label_visibility="collapsed")
20
+ if q:
21
+ hits, method = await rag.search(index, q, int(k), state.key_for("hf")) # noqa: F704
22
+ st.caption(f"{len(hits)} results · {method} over {index.N:,} passages")
23
+ if not hits:
24
+ st.info("No passage matches those words. Try medical terms or synonyms.")
25
+ for h in hits:
26
+ with st.container(border=True):
27
+ link = f" · [source]({h.url})" if h.url else ""
28
+ st.markdown(f"**[{h.rank}]** [`{h.source}`](https://huggingface.co/datasets/{h.source}) · {h.licence} · "
29
+ f"`{h.ref}`{link}")
30
+ st.markdown(h.text.replace("\n", " \n"))
app/views/models.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import streamlit as st
3
+
4
+ from draiml import catalogue, state
5
+
6
+ state.init()
7
+ ss = st.session_state
8
+ st.title("🧠 Models")
9
+ st.caption("Every model here is open source — an OSI licence on the model **and** on every base model it was built "
10
+ "from. MedGemma, Llama- and Gemma-3-based medical models are left out for that reason. Hosted availability "
11
+ "is read live from Hugging Face Inference Providers.")
12
+
13
+
14
+ def use(engine: str, model: str, url: str | None = None):
15
+ ss.engine, ss.model = engine, model
16
+ if url:
17
+ ss.custom_url = url
18
+ st.switch_page("views/consult.py")
19
+
20
+
21
+ tabs = st.tabs(["Hosted engines", "Medical specialists", "Medical vision", "Tools", "Live Hub search"])
22
+
23
+ with tabs[0]:
24
+ hosted = await catalogue.hosted_engines() # noqa: F704
25
+ st.markdown(f"**{len(hosted)}** open chat models are live on HF Inference Providers right now. ★ = recommended "
26
+ "for consultation. Calls bill the signed-in visitor's HF account.")
27
+ df = pd.DataFrame([{"★": "★" if e["curated"] else "", "model": e["id"], "licence": e["licence"],
28
+ "vision": "🖼" if e["vision"] else "", "context": e["ctx"] or None,
29
+ "$/M tok (in+out)": e["price_per_m"], "providers": ", ".join(e["providers"]),
30
+ "note": e["note"]} for e in hosted])
31
+ ev = st.dataframe(df, hide_index=True, use_container_width=True, on_select="rerun", selection_mode="single-row",
32
+ column_config={"context": st.column_config.NumberColumn(format="%d"),
33
+ "$/M tok (in+out)": st.column_config.NumberColumn(format="%.2f")})
34
+ rows = ev.selection.rows if ev and ev.selection else []
35
+ if rows:
36
+ mid = df.iloc[rows[0]]["model"]
37
+ if st.button(f"Consult with {mid}", type="primary"):
38
+ use("hf", mid)
39
+
40
+ with tabs[1]:
41
+ st.markdown("Medical fine-tunes with open weights. None is currently served by HF Inference Providers, so run "
42
+ "them yourself — one line with [Ollama](https://ollama.com) — and point drAIML at it. drAIML talks to "
43
+ "your machine straight from your browser; nothing passes through a server.")
44
+ st.code("OLLAMA_ORIGINS=https://pythai-draiml.static.hf.space ollama serve", language="bash")
45
+ for m in catalogue.curated_models("specialist"):
46
+ with st.container(border=True):
47
+ c1, c2 = st.columns([3, 1])
48
+ size = f" · {m['params_b']}B" if m.get("params_b") else ""
49
+ c1.markdown(f"**[{m['id']}](https://huggingface.co/{m['id']})** · `{m['licence']}`{size} · "
50
+ f"{m.get('specialty', '')}")
51
+ if m.get("note"):
52
+ c1.caption(m["note"])
53
+ if m.get("providers"):
54
+ c1.success("Live on HF Inference: " + ", ".join(m["providers"]))
55
+ cmd = catalogue.ollama_command(m.get("gguf"))
56
+ if cmd:
57
+ c1.code(cmd, language="bash")
58
+ if c2.button("Use via Ollama", key="sp_" + m["id"]):
59
+ use("custom", "hf.co/" + m["gguf"], ss.custom_url or "http://localhost:11434/v1")
60
+ else:
61
+ c1.caption("No open GGUF build found — serve the safetensors with vLLM or TGI, then use “Your endpoint”.")
62
+
63
+ with tabs[2]:
64
+ st.markdown("Open medical vision-language models (radiology, pathology, dermatology). Image upload in the "
65
+ "consultation is planned; today use them via your own endpoint.")
66
+ for m in catalogue.curated_models("vision") + catalogue.curated_models("vision-engine"):
67
+ cmd = catalogue.ollama_command(m.get("gguf"))
68
+ st.markdown(f"- **[{m['id']}](https://huggingface.co/{m['id']})** · `{m['licence']}` · {m.get('specialty', m.get('note', ''))}"
69
+ + (f" \n `{cmd}`" if cmd else ""))
70
+
71
+ with tabs[3]:
72
+ st.markdown("Embeddings, encoders, entity recognition and speech — the building blocks.")
73
+ tools = [m for m in catalogue.curated()["models"] if m["role"] in ("embedding", "encoder", "ner", "speech")]
74
+ st.dataframe(pd.DataFrame([{"model": m["id"], "role": m["role"], "licence": m["licence"],
75
+ "hosted": ", ".join(m.get("providers") or []), "note": m.get("note", "")}
76
+ for m in tools]), hide_index=True, use_container_width=True)
77
+
78
+ with tabs[4]:
79
+ q = st.text_input("Search the Hub for open medical models", placeholder="radiology, oncology, clinical NER…")
80
+ res = await catalogue.hub_search("model", q) # noqa: F704
81
+ st.caption(f"{len(res)} open, ungated results tagged `medical` (closed, gated and GGUF repos are hidden). "
82
+ "Card licences only — the curated tabs also check base models.")
83
+ st.dataframe(pd.DataFrame(res), hide_index=True, use_container_width=True,
84
+ column_config={"id": st.column_config.TextColumn("model")})
index.html CHANGED
@@ -1,19 +1,133 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>drAIML Consultation</title>
7
+ <meta name="description" content="drAIML 2.0 — open-source healthcare consultation with open medical models and evidence from openly licensed datasets. Runs in your browser." />
8
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><rect width='64' height='64' rx='14' fill='%230e7c7b'/><path d='M27 14h10v13h13v10H37v13H27V37H14V27h13z' fill='white'/></svg>" />
9
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.css" />
10
+ <style>
11
+ :root {
12
+ --bg: #f6f8f8; --surface: #ffffff; --ink: #12302f; --muted: #557170; --accent: #0e7c7b; --accent-ink: #ffffff;
13
+ --line: #d9e4e3; --warn: #b4232c;
14
+ }
15
+ @media (prefers-color-scheme: dark) {
16
+ :root:not([data-theme="light"]) {
17
+ --bg: #0d1716; --surface: #13201f; --ink: #e3efee; --muted: #93aeac; --accent: #3fb5b2; --accent-ink: #062120;
18
+ --line: #22403e; --warn: #f07178;
19
+ }
20
+ }
21
+ :root[data-theme="dark"] {
22
+ --bg: #0d1716; --surface: #13201f; --ink: #e3efee; --muted: #93aeac; --accent: #3fb5b2; --accent-ink: #062120;
23
+ --line: #22403e; --warn: #f07178;
24
+ }
25
+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--ink);
26
+ font-family: "Source Sans 3", system-ui, -apple-system, "Segoe UI", sans-serif; }
27
+ body { display: flex; flex-direction: column; }
28
+ header { display: flex; align-items: center; gap: 12px; padding: 8px 16px; background: var(--surface);
29
+ border-bottom: 1px solid var(--line); min-height: 48px; box-sizing: border-box; flex-wrap: wrap; }
30
+ .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 1.05rem; text-decoration: none; color: var(--ink); }
31
+ .brand svg { width: 28px; height: 28px; flex: none; }
32
+ .brand small { font-weight: 500; color: var(--muted); font-size: 0.8rem; }
33
+ .spacer { flex: 1; }
34
+ .who { color: var(--muted); font-size: 0.9rem; }
35
+ button.hf { display: inline-flex; align-items: center; gap: 8px; border: 1px solid var(--line); background: var(--surface);
36
+ color: var(--ink); border-radius: 8px; padding: 6px 12px; font: inherit; font-size: 0.9rem; cursor: pointer; }
37
+ button.hf.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
38
+ button.hf:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
39
+ .sos { color: var(--warn); font-size: 0.85rem; font-weight: 600; }
40
+ #root { flex: 1; min-height: 0; position: relative; }
41
+ #boot { position: absolute; inset: 0; display: grid; place-items: center; text-align: center; padding: 16px; color: var(--muted); }
42
+ #boot .bar { width: min(320px, 80vw); height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; margin: 14px auto 0; }
43
+ #boot .bar i { display: block; height: 100%; width: 40%; background: var(--accent); animation: slide 1.4s ease-in-out infinite; }
44
+ @keyframes slide { 0% { transform: translateX(-100%); } 100% { transform: translateX(250%); } }
45
+ @media (prefers-reduced-motion: reduce) { #boot .bar i { animation: none; width: 100%; } }
46
+ @media (max-width: 560px) { .brand small, .sos { display: none; } }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <header>
51
+ <a class="brand" href="https://huggingface.co/spaces/PYTHAI/drAIML" target="_top" aria-label="drAIML home">
52
+ <svg viewBox="0 0 64 64" aria-hidden="true"><rect width="64" height="64" rx="14" fill="#0e7c7b"/><path d="M27 14h10v13h13v10H37v13H27V37H14V27h13z" fill="#fff"/></svg>
53
+ <span>drAIML <small>2.0 · open healthcare consultation</small></span>
54
+ </a>
55
+ <span class="spacer"></span>
56
+ <span class="sos">Emergency? Call your local emergency number.</span>
57
+ <span class="who" id="who"></span>
58
+ <button class="hf primary" id="signin" hidden>Sign in with Hugging Face</button>
59
+ <button class="hf" id="signout" hidden>Sign out</button>
60
+ </header>
61
+ <div id="root"><div id="boot"><div><strong>Starting drAIML…</strong><br />Loading Python and Streamlit in your browser (first visit ≈ 20–40 s).<div class="bar"><i></i></div></div></div></div>
62
+
63
+ <script type="module">
64
+ import { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";
65
+ import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
66
+
67
+ const KEY = "draiml-oauth";
68
+ const vars = (window.huggingface && window.huggingface.variables) || {};
69
+ const canOAuth = Boolean(vars.OAUTH_CLIENT_ID);
70
+
71
+ function readSession() {
72
+ try {
73
+ const s = JSON.parse(localStorage.getItem(KEY) || "null");
74
+ if (s && s.accessToken && (!s.accessTokenExpiresAt || new Date(s.accessTokenExpiresAt) > new Date())) return s;
75
+ } catch (_) { /* storage blocked */ }
76
+ return null;
77
+ }
78
+
79
+ let session = null;
80
+ try {
81
+ const fresh = await oauthHandleRedirectIfPresent();
82
+ if (fresh) {
83
+ session = fresh;
84
+ try { localStorage.setItem(KEY, JSON.stringify(fresh)); } catch (_) {}
85
+ history.replaceState(null, "", location.pathname);
86
+ }
87
+ } catch (e) { console.warn("[drAIML] oauth redirect", e); }
88
+ session = session || readSession();
89
+
90
+ const who = document.getElementById("who");
91
+ const signin = document.getElementById("signin");
92
+ const signout = document.getElementById("signout");
93
+ if (session) {
94
+ const u = session.userInfo || {};
95
+ who.textContent = u.preferred_username || u.name || "";
96
+ signout.hidden = false;
97
+ } else if (canOAuth) {
98
+ signin.hidden = false;
99
+ }
100
+ signin.onclick = async () => {
101
+ location.href = (await oauthLoginUrl({ scopes: vars.OAUTH_SCOPES || "openid profile inference-api" })) + "&prompt=consent";
102
+ };
103
+ signout.onclick = () => { try { localStorage.removeItem(KEY); } catch (_) {} location.reload(); };
104
+
105
+ const manifest = await (await fetch("app/manifest.json", { cache: "no-cache" })).json();
106
+ const files = {};
107
+ for (const p of manifest.files) files[p] = { url: "app/" + p + "?v=" + manifest.build };
108
+
109
+ const env = {};
110
+ if (session) {
111
+ env.HF_TOKEN = session.accessToken;
112
+ const u = session.userInfo || {};
113
+ env.HF_USER = u.preferred_username || u.name || "";
114
+ }
115
+
116
+ const dark = document.documentElement.dataset.theme === "dark" ||
117
+ (!document.documentElement.dataset.theme && matchMedia("(prefers-color-scheme: dark)").matches);
118
+
119
+ document.getElementById("boot").remove();
120
+ mount({
121
+ entrypoint: "app.py",
122
+ files,
123
+ requirements: manifest.requirements || [],
124
+ env,
125
+ streamlitConfig: {
126
+ "client.toolbarMode": "viewer",
127
+ "theme.base": dark ? "dark" : "light",
128
+ "theme.primaryColor": dark ? "#3fb5b2" : "#0e7c7b",
129
+ },
130
+ }, document.getElementById("root"));
131
+ </script>
132
+ </body>
133
  </html>
scripts/build_catalogue.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify scripts/catalogue.yaml against the live Hub and write app/data/catalogue.json.
2
+
3
+ A model passes only if its own licence AND every base_model up the chain is OSI. A dataset passes on
4
+ OSI or open-data licences and must not be gated. GGUF builds (for Ollama) are found and gated too.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json, sys, time
9
+ from pathlib import Path
10
+
11
+ import yaml
12
+ from huggingface_hub import HfApi
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ sys.path.insert(0, str(ROOT / "app"))
16
+ from draiml.licences import is_open_dataset, is_open_model, licence_of # noqa: E402
17
+
18
+ api = HfApi()
19
+ _cache: dict[str, object] = {}
20
+
21
+
22
+ def info(mid):
23
+ if mid not in _cache:
24
+ try:
25
+ _cache[mid] = api.model_info(mid, expand=["cardData", "tags", "pipeline_tag", "downloads", "likes",
26
+ "gated", "inferenceProviderMapping", "safetensors"])
27
+ except Exception as e: # noqa: BLE001
28
+ _cache[mid] = e
29
+ return _cache[mid]
30
+
31
+
32
+ def bases(m) -> list[str]:
33
+ cd = m.card_data.to_dict() if m.card_data else {}
34
+ b = cd.get("base_model") or []
35
+ if isinstance(b, str):
36
+ b = [b]
37
+ if not b:
38
+ b = [t.split(":", 2)[-1] for t in (m.tags or []) if t.startswith("base_model:") and t.count(":") == 2
39
+ and not t.startswith(("base_model:quantized:", "base_model:finetune:", "base_model:adapter:", "base_model:merge:"))]
40
+ return [x for x in b if isinstance(x, str)]
41
+
42
+
43
+ def chain_ok(mid, depth=0, seen=None) -> tuple[bool, str]:
44
+ seen = seen or set()
45
+ if mid in seen or depth > 6:
46
+ return True, ""
47
+ seen.add(mid)
48
+ m = info(mid)
49
+ if isinstance(m, Exception):
50
+ return (depth > 0), f"{mid}: {type(m).__name__}" # an unreachable base is not proof of closure
51
+ ok, lic = is_open_model(m)
52
+ if not ok:
53
+ return False, f"{mid} is {lic!r}"
54
+ for b in bases(m):
55
+ ok, why = chain_ok(b, depth + 1, seen)
56
+ if not ok:
57
+ return False, why
58
+ return True, ""
59
+
60
+
61
+ def gguf_for(mid) -> str | None:
62
+ name = mid.split("/", 1)[1]
63
+ for m in api.list_models(search=f"{name}", sort="downloads", limit=30, expand=["cardData", "tags"]):
64
+ if "gguf" not in (m.tags or []) or "abliterated" in m.id.lower() or "uncensored" in m.id.lower():
65
+ continue
66
+ if not m.id.lower().split("/", 1)[1].startswith(name.lower()) and name.lower() not in m.id.lower():
67
+ continue
68
+ if is_open_model(m)[0]:
69
+ return m.id
70
+ return None
71
+
72
+
73
+ def main():
74
+ src = yaml.safe_load((ROOT / "scripts" / "catalogue.yaml").read_text())
75
+ out = {"version": "2.0.0", "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "models": [], "datasets": []}
76
+ for e in src["models"]:
77
+ m = info(e["id"])
78
+ if isinstance(m, Exception):
79
+ print(f"DROP model {e['id']}: {m}")
80
+ continue
81
+ ok, why = chain_ok(e["id"])
82
+ if not ok:
83
+ print(f"DROP model {e['id']}: licence gate — {why}")
84
+ continue
85
+ if m.gated:
86
+ print(f"DROP model {e['id']}: gated")
87
+ continue
88
+ providers = sorted({p.provider for p in (m.inference_provider_mapping or []) if getattr(p, "status", "live") == "live"})
89
+ params = None
90
+ if m.safetensors and getattr(m.safetensors, "total", None):
91
+ params = round(m.safetensors.total / 1e9, 1)
92
+ entry = {**e, "licence": licence_of(m), "pipeline": m.pipeline_tag, "downloads": m.downloads,
93
+ "likes": m.likes, "params_b": params, "bases": bases(m), "providers": providers}
94
+ if e["role"] in ("specialist", "vision"):
95
+ entry["gguf"] = gguf_for(e["id"])
96
+ out["models"].append(entry)
97
+ print(f"ok model {e['id']} [{entry['licence']}] gguf={entry.get('gguf')}")
98
+ for e in src["datasets"]:
99
+ try:
100
+ d = api.dataset_info(e["id"])
101
+ except Exception as ex: # noqa: BLE001
102
+ print(f"DROP dataset {e['id']}: {ex}")
103
+ continue
104
+ ok, lic = is_open_dataset(d)
105
+ if not ok or d.gated:
106
+ print(f"DROP dataset {e['id']}: licence {lic!r} gated={d.gated}")
107
+ continue
108
+ cd = d.card_data.to_dict() if d.card_data else {}
109
+ out["datasets"].append({**e, "licence": lic, "downloads": d.downloads, "likes": d.likes,
110
+ "size": (cd.get("size_categories") or [None])[0], "pretty": cd.get("pretty_name")})
111
+ print(f"ok dataset {e['id']} [{lic}]")
112
+ # every model the HF router serves right now, through the same gate (the app re-checks live)
113
+ import json as _j, urllib.request as _u
114
+ router = _j.load(_u.urlopen("https://router.huggingface.co/v1/models", timeout=60))["data"]
115
+ out["router_open"], out["router_closed"] = {}, {}
116
+ for m in router:
117
+ ok, why = chain_ok(m["id"])
118
+ provs = [p["provider"] for p in m.get("providers", []) if p.get("status") == "live"]
119
+ if ok:
120
+ out["router_open"][m["id"]] = {"licence": licence_of(info(m["id"])) if not isinstance(info(m["id"]), Exception) else None,
121
+ "providers": provs,
122
+ "vision": "image" in (m.get("architecture") or {}).get("input_modalities", [])}
123
+ else:
124
+ out["router_closed"][m["id"]] = why
125
+ print(f"router: {len(out['router_open'])} open, {len(out['router_closed'])} rejected")
126
+ p = ROOT / "app" / "data" / "catalogue.json"
127
+ p.write_text(json.dumps(out, indent=1))
128
+ print(f"wrote {p} — {len(out['models'])} models, {len(out['datasets'])} datasets")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
scripts/build_index.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the drAIML 2.0 evidence index and (optionally) push it to PYTHAI/drAIML-evidence.
2
+
3
+ Every source must pass the licence gate in app/draiml/licences.py. The output is small enough to be
4
+ fetched by the browser (stlite) app: passages.json.gz + int8 embeddings + per-row scales.
5
+
6
+ .venv/bin/python scripts/build_index.py # build into build/evidence
7
+ .venv/bin/python scripts/build_index.py --push # build + upload
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse, ast, gzip, json, random, re, sys, time
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ from datasets import load_dataset
16
+ from huggingface_hub import HfApi
17
+
18
+ ROOT = Path(__file__).resolve().parents[1]
19
+ sys.path.insert(0, str(ROOT / "app"))
20
+ from draiml.licences import is_open_dataset # noqa: E402
21
+ from draiml.rag import bm25_arrays, save_bm25 # noqa: E402
22
+
23
+ OUT = ROOT / "build" / "evidence"
24
+ EVIDENCE_REPO = "PYTHAI/drAIML-evidence"
25
+ EMBED_MODEL = "NeuML/pubmedbert-base-embeddings"
26
+ random.seed(1729)
27
+
28
+
29
+ def clean(s: str) -> str:
30
+ return re.sub(r"\s+", " ", (s or "")).strip()
31
+
32
+
33
+ def take(name, config, n, split="train"):
34
+ ds = load_dataset(name, config, split=split, streaming=True)
35
+ return ds.shuffle(seed=1729, buffer_size=2_000).take(n) if n else ds
36
+
37
+
38
+ def pubmedqa(n_art):
39
+ out = []
40
+ for cfg, n in (("pqa_labeled", 0), ("pqa_artificial", n_art)):
41
+ for r in take("qiaojin/PubMedQA", cfg, n):
42
+ ctx = r["context"]["contexts"] if isinstance(r["context"], dict) else []
43
+ text = f"Q: {clean(r['question'])}\nFinding: {clean(r['long_answer'])}\nEvidence: {clean(' '.join(ctx))[:1200]}"
44
+ out.append((text, f"pubmed:{r['pubid']}", f"https://pubmed.ncbi.nlm.nih.gov/{r['pubid']}/"))
45
+ return out
46
+
47
+
48
+ def medmcqa(n):
49
+ out = []
50
+ for r in take("openlifescienceai/medmcqa", "default", n * 3):
51
+ exp = clean(r.get("exp") or "")
52
+ if len(exp) < 120:
53
+ continue
54
+ opts = [r["opa"], r["opb"], r["opc"], r["opd"]]
55
+ ans = opts[int(r["cop"])] if str(r["cop"]).isdigit() and int(r["cop"]) < 4 else ""
56
+ out.append((f"Q: {clean(r['question'])}\nAnswer: {clean(ans)}\nExplanation: {exp[:1400]}\nSubject: {r.get('subject_name') or ''}",
57
+ f"medmcqa:{r['id']}", ""))
58
+ if len(out) >= n:
59
+ break
60
+ return out
61
+
62
+
63
+ def medical_o1(n):
64
+ return [(f"Q: {clean(r['Question'])}\nAnswer: {clean(r['Response'])[:1500]}", f"medical-o1:{i}", "")
65
+ for i, r in enumerate(take("FreedomIntelligence/medical-o1-reasoning-SFT", "en", n))]
66
+
67
+
68
+ def medqa(n):
69
+ out = []
70
+ for i, r in enumerate(take("GBaker/MedQA-USMLE-4-options", "default", n)):
71
+ out.append((f"Case: {clean(r['question'])}\nAnswer: {clean(r['answer'])}", f"medqa:{i}", ""))
72
+ return out
73
+
74
+
75
+ def medreason(n):
76
+ return [(f"Q: {clean(r['question'])}\nAnswer: {clean(r['answer'])[:1500]}", f"medreason:{r['dataset_name']}:{r['id_in_dataset']}", "")
77
+ for r in take("UCSC-VLAA/MedReason", "default", n)]
78
+
79
+
80
+ def medtext(n):
81
+ return [(f"Case: {clean(r['Prompt'])}\nAssessment: {clean(r['Completion'])[:1500]}", f"medtext:{i}", "")
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),
88
+ ("openlifescienceai/medmcqa", medmcqa, 7_000),
89
+ ("FreedomIntelligence/medical-o1-reasoning-SFT", medical_o1, 6_000),
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
+
96
+ def main():
97
+ ap = argparse.ArgumentParser()
98
+ ap.add_argument("--push", action="store_true")
99
+ ap.add_argument("--reuse", action="store_true", help="reuse build/evidence/passages.json.gz")
100
+ ap.add_argument("--embed", action="store_true", help="also build pubmedbert int8 embeddings (slow on CPU)")
101
+ ap.add_argument("--scale", type=float, default=1.0, help="multiply per-source counts (0.01 for a smoke run)")
102
+ args = ap.parse_args()
103
+ OUT.mkdir(parents=True, exist_ok=True)
104
+ api = HfApi()
105
+
106
+ passages, sources = [], []
107
+ if args.reuse and (OUT / "passages.json.gz").exists():
108
+ with gzip.open(OUT / "passages.json.gz", "rt", encoding="utf-8") as f:
109
+ old = json.load(f)
110
+ passages, sources = old["passages"], old["sources"]
111
+ print(f"reusing {len(passages)} passages")
112
+ for repo, fn, n in ([] if passages else SOURCES):
113
+ info = api.dataset_info(repo)
114
+ ok, lic = is_open_dataset(info)
115
+ if not ok:
116
+ print(f"SKIP {repo}: licence {lic!r} fails the gate")
117
+ continue
118
+ t = time.time()
119
+ rows = fn(max(1, int(n * args.scale)) if n else 0) if not (n == 0 and args.scale < 1) else fn(50)
120
+ sidx = len(sources)
121
+ sources.append({"repo": repo, "licence": lic, "count": len(rows), "sha": info.sha})
122
+ passages += [[text, sidx, ref, url] for text, ref, url in rows]
123
+ print(f"{repo}: {len(rows)} passages ({lic}) in {time.time()-t:.0f}s", flush=True)
124
+
125
+ dim = None
126
+ if args.embed:
127
+ from sentence_transformers import SentenceTransformer
128
+ model = SentenceTransformer(EMBED_MODEL, device="cpu")
129
+ model.max_seq_length = 256
130
+ t = time.time()
131
+ emb = model.encode([p[0] for p in passages], batch_size=64, show_progress_bar=True,
132
+ normalize_embeddings=True, convert_to_numpy=True).astype(np.float32)
133
+ print(f"embedded {len(passages)} in {time.time()-t:.0f}s", flush=True)
134
+ scale = np.abs(emb).max(axis=1, keepdims=True) / 127.0
135
+ np.save(OUT / "emb_int8.npy", np.round(emb / scale).astype(np.int8))
136
+ np.save(OUT / "emb_scale.npy", scale.astype(np.float32).ravel())
137
+ dim = int(emb.shape[1])
138
+
139
+ save_bm25(OUT / "bm25.npz", bm25_arrays(passages))
140
+ with gzip.open(OUT / "passages.json.gz", "wt", encoding="utf-8") as f:
141
+ json.dump({"sources": sources, "passages": passages}, f, ensure_ascii=False, separators=(",", ":"))
142
+ meta = {"version": "2.0.0", "embed_model": EMBED_MODEL if dim else None, "dim": dim, "bm25": "bm25.npz", "count": len(passages),
143
+ "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "sources": sources}
144
+ (OUT / "meta.json").write_text(json.dumps(meta, indent=2))
145
+ (OUT / "README.md").write_text(card(meta))
146
+ (OUT / "LICENSE.md").write_text(licence_md(meta))
147
+ for p in OUT.iterdir():
148
+ print(f" {p.name}: {p.stat().st_size/1e6:.1f} MB")
149
+
150
+ if args.push:
151
+ api.create_repo(EVIDENCE_REPO, repo_type="dataset", private=False, exist_ok=True)
152
+ api.upload_folder(folder_path=str(OUT), repo_id=EVIDENCE_REPO, repo_type="dataset",
153
+ commit_message=f"evidence index {meta['built']} ({meta['count']} passages)")
154
+ print("pushed", EVIDENCE_REPO)
155
+
156
+
157
+ def card(meta):
158
+ emb = (f"Embedded with [{meta['embed_model']}](https://huggingface.co/{meta['embed_model']}) ({meta['dim']}-d, "
159
+ "L2-normalised, int8 with a per-row float32 scale: `emb ≈ emb_int8 * emb_scale[:, None]`); drAIML "
160
+ "fuses dense and BM25 rankings.") if meta.get("dim") else (
161
+ "drAIML ranks these passages with BM25 in the browser; dense embeddings "
162
+ f"({EMBED_MODEL}) are added when built with `--embed`.")
163
+ rows = "\n".join(f"| [{s['repo']}](https://huggingface.co/datasets/{s['repo']}) | {s['licence']} | {s['count']:,} |"
164
+ for s in meta["sources"])
165
+ return f"""---
166
+ license: other
167
+ license_name: mixed-open
168
+ license_link: LICENSE.md
169
+ language: [en]
170
+ tags: [medical, healthcare, retrieval, rag, draiml]
171
+ pretty_name: drAIML evidence index
172
+ size_categories: [10K<n<100K]
173
+ ---
174
+
175
+ # drAIML evidence index
176
+
177
+ The retrieval corpus behind [drAIML 2.0](https://huggingface.co/spaces/PYTHAI/drAIML): {meta['count']:,} passages
178
+ from openly licensed health datasets on the Hugging Face Hub. {emb}
179
+
180
+ **Licence:** each passage keeps the licence of its source dataset (`passages[i][1]` indexes `sources`).
181
+ Only sources under an OSI licence or CC-BY / CC0 are included. Nothing here is under NC, ND or
182
+ custom terms.
183
+
184
+ | source | licence | passages |
185
+ |---|---|---|
186
+ {rows}
187
+
188
+ Files: `passages.json.gz` (`{{"sources": [...], "passages": [[text, source_index, ref, url], ...]}}`),
189
+ `emb_int8.npy`, `emb_scale.npy`, `meta.json`. Built {meta['built']}.
190
+
191
+ Not medical advice. Exam-style and synthetic passages are learning material, not clinical guidance.
192
+ """
193
+
194
+
195
+ def licence_md(meta):
196
+ lines = "\n".join(f"- `{s['repo']}` — {s['licence']} — https://huggingface.co/datasets/{s['repo']}" for s in meta["sources"])
197
+ return f"""# Licences
198
+
199
+ This index redistributes excerpts of the datasets below. Each excerpt stays under its source's licence;
200
+ the source and its licence are recorded per passage. Attribution: the authors of each dataset.
201
+
202
+ {lines}
203
+
204
+ The build script and index format are MIT (c) 2025-2026 Gregory L. Magnusson / PYTHAI.
205
+ """
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()
scripts/catalogue.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # drAIML 2.0 curated catalogue — candidates. scripts/build_catalogue.py checks every entry against the
2
+ # live Hub (own licence AND every base_model's licence) and writes app/data/catalogue.json.
3
+ # Anything failing the gate is dropped, never shown.
4
+
5
+ models:
6
+ # ── hosted generalist engines (served by HF Inference Providers; availability checked live) ──
7
+ - {id: openai/gpt-oss-120b, role: engine, note: "Strong open reasoning model; good default for consultation."}
8
+ - {id: openai/gpt-oss-20b, role: engine, note: "Fast, inexpensive open reasoning model."}
9
+ - {id: Qwen/Qwen3-235B-A22B-Instruct-2507, role: engine, note: "Large open MoE, excellent medical knowledge."}
10
+ - {id: Qwen/Qwen3-235B-A22B-Thinking-2507, role: engine, note: "Thinking variant — shows its reasoning."}
11
+ - {id: Qwen/Qwen3-Next-80B-A3B-Instruct, role: engine, note: "Efficient long-context MoE."}
12
+ - {id: Qwen/Qwen3-32B, role: engine, note: "Dense 32B; solid all-rounder."}
13
+ - {id: deepseek-ai/DeepSeek-V3.1, role: engine, note: "MIT-licensed frontier MoE."}
14
+ - {id: deepseek-ai/DeepSeek-R1-0528, role: engine, note: "MIT reasoning model; careful differentials."}
15
+ - {id: zai-org/GLM-4.6, role: engine, note: "MIT-licensed MoE."}
16
+ - {id: Qwen/Qwen3-VL-235B-A22B-Instruct, role: vision-engine, note: "Hosted vision-language model for images (open)."}
17
+
18
+ # ── medical specialists (run via your endpoint / Ollama; provider status checked live) ──
19
+ - {id: Intelligent-Internet/II-Medical-8B, role: specialist, specialty: "clinical reasoning", note: "Qwen3-8B medical reasoning fine-tune."}
20
+ - {id: Intelligent-Internet/II-Medical-8B-1706, role: specialist, specialty: "clinical reasoning", note: "Later II-Medical revision."}
21
+ - {id: Intelligent-Internet/II-Medical-32B-Preview, role: specialist, specialty: "clinical reasoning"}
22
+ - {id: FreedomIntelligence/HuatuoGPT-o1-7B, role: specialist, specialty: "medical o1-style reasoning", note: "Think-then-answer, EN/ZH."}
23
+ - {id: FreedomIntelligence/HuatuoGPT-o1-8B, role: specialist, specialty: "medical o1-style reasoning"}
24
+ - {id: FreedomIntelligence/HuatuoGPT-o1-72B, role: specialist, specialty: "medical o1-style reasoning"}
25
+ - {id: FreedomIntelligence/HuatuoGPT-o1-70B, role: specialist, specialty: "medical o1-style reasoning"}
26
+ - {id: FreedomIntelligence/HuatuoGPT-3-8B, role: specialist, specialty: "medical dialogue"}
27
+ - {id: baichuan-inc/Baichuan-M2-32B, role: specialist, specialty: "clinical reasoning", note: "Verifier-trained medical model on Qwen2.5-32B."}
28
+ - {id: BioMistral/BioMistral-7B, role: specialist, specialty: "biomedical QA", note: "Mistral further pre-trained on PubMed Central."}
29
+ - {id: microsoft/MediPhi-Instruct, role: specialist, specialty: "clinical NLP", note: "Phi-3.5-mini medical instruct (MIT)."}
30
+ - {id: microsoft/MediPhi-Clinical, role: specialist, specialty: "clinical notes"}
31
+ - {id: microsoft/MediPhi-Guidelines, role: specialist, specialty: "clinical guidelines"}
32
+ - {id: tokyotech-llm/Medical-Qwen3-Swallow-8B, role: specialist, specialty: "medical (JA/EN)"}
33
+ - {id: EPFLiGHT/Apertus-8B-MeditronFO, role: specialist, specialty: "guideline-grounded medicine"}
34
+ - {id: EPFLiGHT/OLMo-2-32B-MeditronFO, role: specialist, specialty: "guideline-grounded medicine", note: "Fully open base (OLMo)."}
35
+ - {id: EPFLiGHT/EuroLLM-9B-MeditronFO, role: specialist, specialty: "multilingual EU medicine"}
36
+ - {id: Writer/palmyra-med-20b, role: specialist, specialty: "medical text"}
37
+ - {id: qvac/MedPsy-4B, role: specialist, specialty: "mental health"}
38
+ - {id: microsoft/BioGPT-Large, role: specialist, specialty: "biomedical text generation"}
39
+ - {id: winninghealth/WiNGPT2-Llama-3-8B-Chat, role: specialist, specialty: "medical (ZH)"}
40
+
41
+ # ── medical vision-language ──
42
+ - {id: lingshu-medical-mllm/Lingshu-7B, role: vision, specialty: "radiology · pathology · dermatology", note: "Medical multimodal (MIT)."}
43
+ - {id: lingshu-medical-mllm/Lingshu-32B, role: vision, specialty: "radiology · pathology · dermatology"}
44
+ - {id: UCSC-VLAA/MedVLThinker-7B-RL_m23k, role: vision, specialty: "medical visual reasoning"}
45
+ - {id: microsoft/llava-med-v1.5-mistral-7b, role: vision, specialty: "biomedical image QA"}
46
+
47
+ # ── embeddings · NER · speech (tools) ──
48
+ - {id: NeuML/pubmedbert-base-embeddings, role: embedding, note: "Powers drAIML's evidence search."}
49
+ - {id: abhinand/MedEmbed-base-v0.1, role: embedding, note: "Medical retrieval embeddings."}
50
+ - {id: BAAI/bge-small-en-v1.5, role: embedding, note: "Small general embeddings."}
51
+ - {id: microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext, role: encoder, note: "PubMedBERT base encoder."}
52
+ - {id: emilyalsentzer/Bio_ClinicalBERT, role: encoder, note: "Clinical-notes BERT (MIMIC)."}
53
+ - {id: d4data/biomedical-ner-all, role: ner, note: "107 biomedical entity types."}
54
+ - {id: Clinical-AI-Apollo/Medical-NER, role: ner, note: "Clinical entity recognition."}
55
+ - {id: openai/whisper-large-v3-turbo, role: speech, note: "Dictate symptoms (speech-to-text)."}
56
+
57
+ datasets:
58
+ - {id: qiaojin/PubMedQA, role: "research QA", note: "Yes/no/maybe questions answered from PubMed abstracts."}
59
+ - {id: openlifescienceai/medmcqa, role: "exam QA", note: "194k medical entrance-exam MCQs with explanations."}
60
+ - {id: GBaker/MedQA-USMLE-4-options, role: "exam QA", note: "USMLE-style clinical vignettes."}
61
+ - {id: FreedomIntelligence/medical-o1-reasoning-SFT, role: "reasoning", note: "Verifiable medical problems with reasoning chains."}
62
+ - {id: FreedomIntelligence/medical-o1-verifiable-problem, role: "reasoning"}
63
+ - {id: UCSC-VLAA/MedReason, role: "reasoning", note: "Knowledge-graph-grounded medical reasoning."}
64
+ - {id: FreedomIntelligence/ApolloCorpus, role: "corpus", note: "Multilingual medical corpus."}
65
+ - {id: FreedomIntelligence/HuatuoGPT-sft-data-v1, role: "dialogue"}
66
+ - {id: BI55/MedText, role: "clinical cases", note: "Patient presentations with assessments."}
67
+ - {id: openai/healthbench, role: "safety eval", note: "Physician-written rubric conversations."}
68
+ - {id: cais/mmlu, role: "exam QA", note: "Includes clinical knowledge, anatomy, medical genetics, professional medicine."}
69
+ - {id: flaviagiammarino/vqa-rad, role: "radiology VQA"}
70
+ - {id: flaviagiammarino/path-vqa, role: "pathology VQA"}
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"}
scripts/make_manifest.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write app/manifest.json: the files index.html hands to stlite, plus a cache-busting build id."""
2
+ import hashlib, json
3
+ from pathlib import Path
4
+
5
+ APP = Path(__file__).resolve().parents[1] / "app"
6
+ files = sorted(str(p.relative_to(APP)) for p in APP.rglob("*")
7
+ if p.is_file() and p.suffix in {".py", ".json", ".txt"} and "__pycache__" not in p.parts
8
+ and p.name != "manifest.json")
9
+ h = hashlib.sha256(b"".join((APP / f).read_bytes() for f in files)).hexdigest()[:12]
10
+ (APP / "manifest.json").write_text(json.dumps({"build": h, "requirements": [], "files": files}, indent=1))
11
+ print(f"{len(files)} files, build {h}")