Download scripts/build_index.py from PYTHAI/drAIML: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/scripts/build_index.py
- Command line
-
hf download hf://spaces/PYTHAI/drAIML/scripts/build_index.py
-
curl -L -o build_index.py https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/scripts/build_index.py
12 kB
| """Build the drAIML 2.0 evidence index and (optionally) push it to PYTHAI/drAIML-evidence. | |
| Every source must pass the licence gate in app/draiml/licences.py. The output is small enough to be | |
| fetched by the browser (stlite) app: passages.json.gz + int8 embeddings + per-row scales. | |
| .venv/bin/python scripts/build_index.py # build into build/evidence | |
| .venv/bin/python scripts/build_index.py --push # build + upload | |
| """ | |
| from __future__ import annotations | |
| import argparse, ast, gzip, json, random, re, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| from datasets import load_dataset | |
| from huggingface_hub import HfApi | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT / "app")) | |
| from draiml.licences import is_open_dataset # noqa: E402 | |
| from draiml.rag import bm25_arrays, save_bm25 # noqa: E402 | |
| OUT = ROOT / "build" / "evidence" | |
| EVIDENCE_REPO = "PYTHAI/drAIML-evidence" | |
| EMBED_MODEL = "NeuML/pubmedbert-base-embeddings" | |
| random.seed(1729) | |
| def clean(s: str) -> str: | |
| return re.sub(r"\s+", " ", (s or "")).strip() | |
| def take(name, config, n, split="train"): | |
| ds = load_dataset(name, config, split=split, streaming=True) | |
| return ds.shuffle(seed=1729, buffer_size=2_000).take(n) if n else ds | |
| def pubmedqa(n_art): | |
| out = [] | |
| for cfg, n in (("pqa_labeled", 0), ("pqa_artificial", n_art)): | |
| for r in take("qiaojin/PubMedQA", cfg, n): | |
| ctx = r["context"]["contexts"] if isinstance(r["context"], dict) else [] | |
| text = f"Q: {clean(r['question'])}\nFinding: {clean(r['long_answer'])}\nEvidence: {clean(' '.join(ctx))[:1200]}" | |
| out.append((text, f"pubmed:{r['pubid']}", f"https://pubmed.ncbi.nlm.nih.gov/{r['pubid']}/")) | |
| return out | |
| def medmcqa(n): | |
| out = [] | |
| for r in take("openlifescienceai/medmcqa", "default", n * 3): | |
| exp = clean(r.get("exp") or "") | |
| if len(exp) < 120: | |
| continue | |
| opts = [r["opa"], r["opb"], r["opc"], r["opd"]] | |
| ans = opts[int(r["cop"])] if str(r["cop"]).isdigit() and int(r["cop"]) < 4 else "" | |
| out.append((f"Q: {clean(r['question'])}\nAnswer: {clean(ans)}\nExplanation: {exp[:1400]}\nSubject: {r.get('subject_name') or ''}", | |
| f"medmcqa:{r['id']}", "")) | |
| if len(out) >= n: | |
| break | |
| return out | |
| def medical_o1(n): | |
| return [(f"Q: {clean(r['Question'])}\nAnswer: {clean(r['Response'])[:1500]}", f"medical-o1:{i}", "") | |
| for i, r in enumerate(take("FreedomIntelligence/medical-o1-reasoning-SFT", "en", n))] | |
| def medqa(n): | |
| out = [] | |
| for i, r in enumerate(take("GBaker/MedQA-USMLE-4-options", "default", n)): | |
| out.append((f"Case: {clean(r['question'])}\nAnswer: {clean(r['answer'])}", f"medqa:{i}", "")) | |
| return out | |
| def medreason(n): | |
| return [(f"Q: {clean(r['question'])}\nAnswer: {clean(r['answer'])[:1500]}", f"medreason:{r['dataset_name']}:{r['id_in_dataset']}", "") | |
| for r in take("UCSC-VLAA/MedReason", "default", n)] | |
| def medtext(n): | |
| return [(f"Case: {clean(r['Prompt'])}\nAssessment: {clean(r['Completion'])[:1500]}", f"medtext:{i}", "") | |
| for i, r in enumerate(take("BI55/MedText", "default", n))] | |
| def physio_qa(n): | |
| out = [] | |
| for i, r in enumerate(take("serhanayberkkilic/physiotherapy-evidence-qa", "default", n)): | |
| if not r.get("answer_en"): | |
| continue | |
| src = f" Source: {r['source_file']}" if r.get("source_file") else "" | |
| out.append((f"Physiotherapy — {r.get('disease_category_en') or ''} ({r.get('question_type_en') or ''})\n" | |
| f"Q: {clean(r['question_en'])}\nAnswer: {clean(r['answer_en'])}{src}", f"physio-qa:{i}", "")) | |
| return out | |
| def msk_rehab(n): | |
| return [(f"Rehabilitation assessment: {clean(r['section_text'])[:600]}\nConsultation excerpt: {clean(r['dialogue'])[:500]}", | |
| f"msk-rehab:{i}", "") | |
| for i, r in enumerate(take("Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment", "default", n))] | |
| SPORT_TERMS = re.compile(r"exercis|train|muscle|strength|stretch|injur|sport|athlet|run|fitness|aerobic|endurance|" | |
| r"flexib|rehab|joint|tendon|ligament|posture|warm-up|recovery", re.I) | |
| def fitness_qa(n): | |
| out = [] | |
| for i, r in enumerate(take("hammamwahab/fitness-qa", "default", n * 3)): | |
| text = f"Q: {clean(r['question'])}\nAnswer: {clean(r['answer'])}" | |
| if SPORT_TERMS.search(text): | |
| out.append((text, f"fitness-qa:{i}", "")) | |
| if len(out) >= n: | |
| break | |
| return out | |
| def calisthenics(n): | |
| out = [] | |
| for i, r in enumerate(take("Martjn/calisthenics_exercises", "default", 0)): | |
| prog = " → ".join(clean(r.get(f"progression_{k}") or "") for k in range(1, 6) if r.get(f"progression_{k}")) | |
| out.append((f"Exercise: {r['name']} ({r.get('category') or ''}). Muscles: {r.get('primary_muscles') or ''}.\n" | |
| f"How: {clean(r.get('description') or '')}\nProgression: {prog}", f"calisthenics:{r['id']}", "")) | |
| return out | |
| def calisthenics2(n): | |
| return [(f"Exercise: {r['name']}. Muscles: {r.get('muscle_groups') or ''}. Equipment: {r.get('materials') or ''}.\n" | |
| f"How: {clean(r.get('description') or '')}", f"calisthenics2:{i}", "") | |
| for i, r in enumerate(take("RafaelJaime/calisthenics_exercises", "default", 0))] | |
| def orthopedic_qa(n): | |
| return [(f"Q: {clean(r['Patient_Question'])}\nAnswer: {clean(r['Doctor_Response'])}", f"ortho-qa:{i}", "") | |
| for i, r in enumerate(take("Eathan/Orthopedic_QA", "default", 0))] | |
| SOURCES = [ | |
| # repo id, builder, count | |
| ("qiaojin/PubMedQA", pubmedqa, 11_000), | |
| ("openlifescienceai/medmcqa", medmcqa, 7_000), | |
| ("FreedomIntelligence/medical-o1-reasoning-SFT", medical_o1, 6_000), | |
| ("UCSC-VLAA/MedReason", medreason, 4_000), | |
| ("GBaker/MedQA-USMLE-4-options", medqa, 2_000), | |
| ("BI55/MedText", medtext, 0), # 0 = all (~1.4k) | |
| # physiotherapy · sports therapy · rehabilitation | |
| ("serhanayberkkilic/physiotherapy-evidence-qa", physio_qa, 8_000), | |
| ("Atereoyin/MSK-Medical-Rehabilitation-Dialogue-Assessment", msk_rehab, 2_000), | |
| ("hammamwahab/fitness-qa", fitness_qa, 2_000), | |
| ("Martjn/calisthenics_exercises", calisthenics, 0), | |
| ("RafaelJaime/calisthenics_exercises", calisthenics2, 0), | |
| ("Eathan/Orthopedic_QA", orthopedic_qa, 0), | |
| ] | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--push", action="store_true") | |
| ap.add_argument("--reuse", action="store_true", help="reuse build/evidence/passages.json.gz") | |
| ap.add_argument("--embed", action="store_true", help="also build pubmedbert int8 embeddings (slow on CPU)") | |
| ap.add_argument("--scale", type=float, default=1.0, help="multiply per-source counts (0.01 for a smoke run)") | |
| args = ap.parse_args() | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| api = HfApi() | |
| passages, sources = [], [] | |
| if args.reuse and (OUT / "passages.json.gz").exists(): | |
| with gzip.open(OUT / "passages.json.gz", "rt", encoding="utf-8") as f: | |
| old = json.load(f) | |
| passages, sources = old["passages"], old["sources"] | |
| print(f"reusing {len(passages)} passages") | |
| for repo, fn, n in ([] if passages else SOURCES): | |
| info = api.dataset_info(repo) | |
| ok, lic = is_open_dataset(info) | |
| if not ok: | |
| print(f"SKIP {repo}: licence {lic!r} fails the gate") | |
| continue | |
| t = time.time() | |
| rows = fn(max(1, int(n * args.scale)) if n else 0) if not (n == 0 and args.scale < 1) else fn(50) | |
| sidx = len(sources) | |
| sources.append({"repo": repo, "licence": lic, "count": len(rows), "sha": info.sha}) | |
| passages += [[text, sidx, ref, url] for text, ref, url in rows] | |
| print(f"{repo}: {len(rows)} passages ({lic}) in {time.time()-t:.0f}s", flush=True) | |
| for p in passages: # keep the browser download small: ~1000 chars is plenty for a cited passage | |
| if len(p[0]) > 1000: | |
| p[0] = p[0][:1000].rsplit(" ", 1)[0] + " …" | |
| dim = None | |
| if args.embed: | |
| from sentence_transformers import SentenceTransformer | |
| model = SentenceTransformer(EMBED_MODEL, device="cpu") | |
| model.max_seq_length = 256 | |
| t = time.time() | |
| emb = model.encode([p[0] for p in passages], batch_size=64, show_progress_bar=True, | |
| normalize_embeddings=True, convert_to_numpy=True).astype(np.float32) | |
| print(f"embedded {len(passages)} in {time.time()-t:.0f}s", flush=True) | |
| scale = np.abs(emb).max(axis=1, keepdims=True) / 127.0 | |
| np.save(OUT / "emb_int8.npy", np.round(emb / scale).astype(np.int8)) | |
| np.save(OUT / "emb_scale.npy", scale.astype(np.float32).ravel()) | |
| dim = int(emb.shape[1]) | |
| save_bm25(OUT / "bm25.npz", bm25_arrays(passages)) | |
| with gzip.open(OUT / "passages.json.gz", "wt", encoding="utf-8") as f: | |
| json.dump({"sources": sources, "passages": passages}, f, ensure_ascii=False, separators=(",", ":")) | |
| meta = {"version": "2.0.0", "embed_model": EMBED_MODEL if dim else None, "dim": dim, "bm25": "bm25.npz", "count": len(passages), | |
| "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "sources": sources} | |
| (OUT / "meta.json").write_text(json.dumps(meta, indent=2)) | |
| (OUT / "README.md").write_text(card(meta)) | |
| (OUT / "LICENSE.md").write_text(licence_md(meta)) | |
| for p in OUT.iterdir(): | |
| print(f" {p.name}: {p.stat().st_size/1e6:.1f} MB") | |
| if args.push: | |
| api.create_repo(EVIDENCE_REPO, repo_type="dataset", private=False, exist_ok=True) | |
| api.upload_folder(folder_path=str(OUT), repo_id=EVIDENCE_REPO, repo_type="dataset", | |
| commit_message=f"evidence index {meta['built']} ({meta['count']} passages)") | |
| print("pushed", EVIDENCE_REPO) | |
| def card(meta): | |
| emb = (f"Embedded with [{meta['embed_model']}](https://huggingface.co/{meta['embed_model']}) ({meta['dim']}-d, " | |
| "L2-normalised, int8 with a per-row float32 scale: `emb ≈ emb_int8 * emb_scale[:, None]`); drAIML " | |
| "fuses dense and BM25 rankings.") if meta.get("dim") else ( | |
| "drAIML ranks these passages with BM25 in the browser; dense embeddings " | |
| f"({EMBED_MODEL}) are added when built with `--embed`.") | |
| rows = "\n".join(f"| [{s['repo']}](https://huggingface.co/datasets/{s['repo']}) | {s['licence']} | {s['count']:,} |" | |
| for s in meta["sources"]) | |
| return f"""--- | |
| license: other | |
| license_name: mixed-open | |
| license_link: LICENSE.md | |
| language: [en] | |
| tags: [medical, healthcare, physiotherapy, sports-medicine, rehabilitation, retrieval, rag, draiml] | |
| pretty_name: drAIML evidence index | |
| size_categories: [10K<n<100K] | |
| --- | |
| # drAIML evidence index | |
| The retrieval corpus behind [drAIML 2.0](https://huggingface.co/spaces/PYTHAI/drAIML): {meta['count']:,} passages | |
| from openly licensed health datasets on the Hugging Face Hub. {emb} | |
| **Licence:** each passage keeps the licence of its source dataset (`passages[i][1]` indexes `sources`). | |
| Only sources under an OSI licence or CC-BY / CC0 are included. Nothing here is under NC, ND or | |
| custom terms. | |
| | source | licence | passages | | |
| |---|---|---| | |
| {rows} | |
| Files: `passages.json.gz` (`{{"sources": [...], "passages": [[text, source_index, ref, url], ...]}}`), | |
| `emb_int8.npy`, `emb_scale.npy`, `meta.json`. Built {meta['built']}. | |
| Not medical advice. Exam-style and synthetic passages are learning material, not clinical guidance. | |
| """ | |
| def licence_md(meta): | |
| lines = "\n".join(f"- `{s['repo']}` — {s['licence']} — https://huggingface.co/datasets/{s['repo']}" for s in meta["sources"]) | |
| return f"""# Licences | |
| This index redistributes excerpts of the datasets below. Each excerpt stays under its source's licence; | |
| the source and its licence are recorded per passage. Attribution: the authors of each dataset. | |
| {lines} | |
| The build script and index format are MIT (c) 2025-2026 Gregory L. Magnusson / PYTHAI. | |
| """ | |
| if __name__ == "__main__": | |
| main() | |