Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / generate_med_db.py
generate_med_db.py673 lines · 26.5 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Offline generator for the health app's medical reference catalogues. |
| 3 | |
| 4 | The Medication, Vaccinations and Conditions screens let the user pick from a |
| 5 | real terminology rather than typing free text, so that the FHIR resources |
| 6 | written to Health Connect carry proper codes. Everything is compiled into the |
| 7 | APK, so no picker makes a network request at runtime - the downloads below |
| 8 | happen here, at build time, not on the device. |
| 9 | |
| 10 | Two outputs, deliberately handled differently: |
| 11 | |
| 12 | health/src/main/assets/cvx.json committed |
| 13 | health/src/main/assets/catalog.db.br gitignored, plus a .meta.json |
| 14 | |
| 15 | Vaccines - CVX |
| 16 | -------------- |
| 17 | The CDC's CVX code set is the vocabulary FHIR's `Immunization.vaccineCode` |
| 18 | expects. Retired and non-US codes are kept alongside the active ones because a |
| 19 | vaccination log is retrospective: see `build_cvx`. That is about 250 codes and |
| 20 | roughly 40 KB as JSON, small enough that the app parses it straight into memory. |
| 21 | Because it is small it is committed, so the vaccination picker works in a clean |
| 22 | checkout with no build step. Public domain. |
| 23 | |
| 24 | https://www2a.cdc.gov/vaccines/iis/iisstandards/downloads/cvx.txt |
| 25 | |
| 26 | Medications - RxNorm |
| 27 | -------------------- |
| 28 | RxNorm Current Prescribable Content, the subset of RxNorm covering drugs |
| 29 | currently prescribable in the US. Unlike full RxNorm it carries no UMLS licence |
| 30 | requirement and may be redistributed freely. |
| 31 | |
| 32 | https://download.nlm.nih.gov/rxnorm/RxNorm_full_prescribe_current.zip |
| 33 | |
| 34 | That is a ~75 MB zip of pipe-delimited RRF files. We keep the prescribable drug |
| 35 | products (TTY of SCD, SBD, GPCK or BPCK), each of which has an RXCUI for |
| 36 | `medicationCodeableConcept` and a name like "amoxicillin 500 MG Oral Capsule", |
| 37 | and resolve each one's ingredient and dose form through RXNREL so the app can |
| 38 | offer the two-step ingredient-then-strength picker. That is ~21,000 rows. |
| 39 | |
| 40 | Conditions - ICD-10-CM |
| 41 | ---------------------- |
| 42 | The CDC's ICD-10-CM release, which is public domain. ~75,000 billable codes for |
| 43 | `Condition.code`. |
| 44 | |
| 45 | https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10CM/ |
| 46 | |
| 47 | US Core actually prefers SNOMED CT for Condition, but SNOMED needs a UMLS |
| 48 | licence and cannot be shipped in an APK, so ICD-10-CM it is. Codes are stored |
| 49 | dotted (A00.0), which is the form FHIR expects, though the source file is |
| 50 | dotless. Search ranks shorter descriptions first, which keeps the everyday |
| 51 | diagnoses above the long tail of "struck by turtle, subsequent encounter". |
| 52 | |
| 53 | Lab tests - LOINC |
| 54 | ----------------- |
| 55 | LOINC is free to use and redistribute with attribution, but unlike every other |
| 56 | source here the download sits behind a login, so this script cannot fetch it. |
| 57 | Take "LOINC Table File (CSV)" from |
| 58 | |
| 59 | https://loinc.org/downloads/ |
| 60 | |
| 61 | and pass the zip, or the extracted Loinc.csv, with --loinc. Without it the lab |
| 62 | table is built empty and the app falls back to free-text entry. |
| 63 | |
| 64 | This content LOINC(R) is copyright (c) 1995-2024 Regenstrief Institute, Inc. |
| 65 | and the LOINC Committee, and is available at no cost under the licence at |
| 66 | http://loinc.org/license. That notice ships with the app. |
| 67 | |
| 68 | Of the ~112,000 LOINC codes, this keeps the ~62,000 that are active laboratory |
| 69 | codes (CLASSTYPE=1). Excluded are: |
| 70 | |
| 71 | * everything but CLASSTYPE 1 - clinical, claims and survey codes are real |
| 72 | LOINC but none of them is a lab result |
| 73 | * the handful of rows carrying EXTERNAL_COPYRIGHT_NOTICE, which are |
| 74 | third-party instruments inside LOINC under their own terms |
| 75 | |
| 76 | Orderable panels are kept rather than filtered to reportable results only. That |
| 77 | looks like the tidier rule but throws away "CBC panel", "lipid panel" and |
| 78 | "comprehensive metabolic panel", which rank 162, 208 and 87 among common tests |
| 79 | and are how people describe their own blood work. |
| 80 | |
| 81 | Ranking is LOINC's own COMMON_TEST_RANK, which covers ~18,000 codes and puts |
| 82 | the tests making up nearly all real lab volume first. |
| 83 | |
| 84 | Three name fields go into the index, not one. LONG_COMMON_NAME is what gets |
| 85 | displayed, but it spells everything out - 1742-6 is "Alanine aminotransferase |
| 86 | [Enzymatic activity/volume] in Serum or Plasma" - so searching it alone for |
| 87 | "ALT" finds nothing. The abbreviation lives in SHORTNAME and DisplayName, so |
| 88 | both are indexed as hidden aliases. CONSUMER_NAME would be the ideal display |
| 89 | name but is empty for every laboratory row in 2.83. |
| 90 | |
| 91 | Columns are looked up by name from the CSV header rather than by position, |
| 92 | because LOINC adds and reorders them between releases. |
| 93 | |
| 94 | Both database-backed catalogues share one SQLite file so the app has a single |
| 95 | asset to unpack and a single schema version to check. |
| 96 | |
| 97 | Unlike `generate_food_db.py`, this ships a finished SQLite database rather than |
| 98 | a columnar file the app rebuilds. That script's format exists because at Open |
| 99 | Food Facts' 465,000-row scale the SQLite container and FTS index cost more than |
| 100 | the data; at these sizes they do not, and shipping the database directly removes |
| 101 | the whole on-device build step and the format-version coupling with it. Brotli, |
| 102 | because the app already links a decoder for the food database. |
| 103 | |
| 104 | Usage |
| 105 | ----- |
| 106 | python3 scripts/generate_med_db.py # everything |
| 107 | python3 scripts/generate_med_db.py --cvx-only # just the committed JSON |
| 108 | """ |
| 109 | |
| 110 | from __future__ import annotations |
| 111 | |
| 112 | import argparse |
| 113 | import csv |
| 114 | import io |
| 115 | import json |
| 116 | import re |
| 117 | import shutil |
| 118 | import sqlite3 |
| 119 | import subprocess |
| 120 | import sys |
| 121 | import zipfile |
| 122 | from pathlib import Path |
| 123 | |
| 124 | REPO_ROOT = Path(__file__).resolve().parent.parent |
| 125 | ASSETS = REPO_ROOT / "health" / "src" / "main" / "assets" |
| 126 | |
| 127 | CVX_URL = "https://www2a.cdc.gov/vaccines/iis/iisstandards/downloads/cvx.txt" |
| 128 | RXNORM_URL = "https://download.nlm.nih.gov/rxnorm/RxNorm_full_prescribe_current.zip" |
| 129 | ICD10_YEAR = 2027 |
| 130 | ICD10_URL = ( |
| 131 | "https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10CM/" |
| 132 | f"{ICD10_YEAR}/icd10cm-code-descriptions-{ICD10_YEAR}.zip" |
| 133 | ) |
| 134 | |
| 135 | CACHE_DIR = Path.home() / ".cache" / "rxnorm" |
| 136 | CACHED_ZIP = CACHE_DIR / "RxNorm_full_prescribe_current.zip" |
| 137 | CACHED_ICD10 = CACHE_DIR / f"icd10cm-code-descriptions-{ICD10_YEAR}.zip" |
| 138 | |
| 139 | # Bumped in lockstep with SUPPORTED_SCHEMA_VERSION in ReferenceCatalog.kt. |
| 140 | SCHEMA_VERSION = 4 |
| 141 | |
| 142 | # Prescribable drug products. SCD is generic, SBD branded, GPCK/BPCK are packs |
| 143 | # such as a course of tablets sold as one unit. |
| 144 | PRODUCT_TTYS = {"SCD", "SBD", "GPCK", "BPCK"} |
| 145 | PACK_TTYS = {"GPCK", "BPCK"} |
| 146 | # Semantic clinical drug components - "amoxicillin 500 MG". A drug product points |
| 147 | # at one of these per ingredient, and only the component points at the |
| 148 | # ingredient itself, so resolving an ingredient is always a two-hop walk. |
| 149 | COMPONENT_TTYS = {"SCDC"} |
| 150 | INGREDIENT_TTYS = {"IN"} |
| 151 | DOSE_FORM_TTYS = {"DF"} |
| 152 | |
| 153 | |
| 154 | def mb(n: int) -> str: |
| 155 | return f"{n / 1_000_000:.1f} MB" |
| 156 | |
| 157 | |
| 158 | def download(url: str, dest: Path) -> Path: |
| 159 | """Fetch `url` to `dest`, skipping the download if it is already cached.""" |
| 160 | if dest.exists() and dest.stat().st_size > 0: |
| 161 | print(f" cached {dest} ({mb(dest.stat().st_size)})") |
| 162 | return dest |
| 163 | dest.parent.mkdir(parents=True, exist_ok=True) |
| 164 | print(f" fetching {url}") |
| 165 | # curl rather than urllib: these redirect, and curl's resume and progress |
| 166 | # reporting matter on the 75 MB one. The CDC's FTP host refuses a default |
| 167 | # Python user agent, hence -A. |
| 168 | subprocess.run( |
| 169 | ["curl", "-sSL", "--fail", "-A", "Mozilla/5.0", "-o", str(dest), url], check=True |
| 170 | ) |
| 171 | print(f" saved {dest} ({mb(dest.stat().st_size)})") |
| 172 | return dest |
| 173 | |
| 174 | |
| 175 | # --- Vaccines -------------------------------------------------------------- |
| 176 | |
| 177 | |
| 178 | def build_cvx(out_path: Path) -> int: |
| 179 | """Write the CVX codes to `out_path` as JSON. Returns the row count. |
| 180 | |
| 181 | Retired and non-US codes are kept, not just the 115 currently active ones. A |
| 182 | vaccination log is retrospective by nature, so the codes an older record uses |
| 183 | are precisely the ones that have since been retired - filtering to Active |
| 184 | would leave a user unable to enter the shot they had in 2004. "Never Active" |
| 185 | codes never described a real product and are dropped, as are the non-vaccine |
| 186 | placeholder rows such as "no vaccine administered". |
| 187 | """ |
| 188 | raw = download(CVX_URL, CACHE_DIR / "cvx.txt") |
| 189 | text = raw.read_text(encoding="utf-8-sig", errors="replace") |
| 190 | |
| 191 | vaccines = [] |
| 192 | for line in text.splitlines(): |
| 193 | if not line.strip(): |
| 194 | continue |
| 195 | # code|shortDescription|fullName|note|status|nonVaccine|lastUpdated |
| 196 | parts = [p.strip() for p in line.split("|")] |
| 197 | if len(parts) < 6: |
| 198 | continue |
| 199 | code, short, full, _note, status, non_vaccine = parts[:6] |
| 200 | if not code or status not in ("Active", "Inactive", "Non-US"): |
| 201 | continue |
| 202 | if non_vaccine.strip().lower() == "true": |
| 203 | continue |
| 204 | vaccines.append( |
| 205 | { |
| 206 | "code": code, |
| 207 | "name": short, |
| 208 | "fullName": full or short, |
| 209 | "active": status == "Active", |
| 210 | } |
| 211 | ) |
| 212 | |
| 213 | vaccines.sort(key=lambda v: (not v["active"], v["name"].lower())) |
| 214 | out_path.parent.mkdir(parents=True, exist_ok=True) |
| 215 | # newline="\n" because this file is committed and .gitattributes normalises the |
| 216 | # tree to LF; Python's text mode would otherwise write CRLF on Windows and |
| 217 | # every line would show as changed on the next regeneration from a Mac. |
| 218 | out_path.write_text( |
| 219 | json.dumps(vaccines, ensure_ascii=False, indent=1) + "\n", |
| 220 | encoding="utf-8", |
| 221 | newline="\n", |
| 222 | ) |
| 223 | print(f" wrote {out_path} ({len(vaccines)} vaccines, {mb(out_path.stat().st_size)})") |
| 224 | return len(vaccines) |
| 225 | |
| 226 | |
| 227 | # --- Medications ----------------------------------------------------------- |
| 228 | |
| 229 | |
| 230 | def read_rrf(zf: zipfile.ZipFile, name: str): |
| 231 | """Yield each RRF row as a list of fields.""" |
| 232 | with zf.open(name) as handle: |
| 233 | for raw in handle: |
| 234 | yield raw.decode("utf-8", errors="replace").rstrip("\n").split("|") |
| 235 | |
| 236 | |
| 237 | def load_concepts(zf: zipfile.ZipFile): |
| 238 | """RXCUI -> name, split by the role the concept plays.""" |
| 239 | products: dict[str, str] = {} |
| 240 | components: dict[str, str] = {} |
| 241 | ingredients: dict[str, str] = {} |
| 242 | dose_forms: dict[str, str] = {} |
| 243 | |
| 244 | for row in read_rrf(zf, "rrf/RXNCONSO.RRF"): |
| 245 | if len(row) < 17: |
| 246 | continue |
| 247 | rxcui, sab, tty, name, suppress = row[0], row[11], row[12], row[14], row[16] |
| 248 | if sab != "RXNORM" or suppress != "N" or not name: |
| 249 | continue |
| 250 | if tty in PRODUCT_TTYS: |
| 251 | products.setdefault(rxcui, name) |
| 252 | elif tty in COMPONENT_TTYS: |
| 253 | components.setdefault(rxcui, name) |
| 254 | elif tty in INGREDIENT_TTYS: |
| 255 | ingredients.setdefault(rxcui, name) |
| 256 | elif tty in DOSE_FORM_TTYS: |
| 257 | dose_forms.setdefault(rxcui, name) |
| 258 | |
| 259 | print( |
| 260 | f" concepts {len(products)} products, {len(components)} components, " |
| 261 | f"{len(ingredients)} ingredients, {len(dose_forms)} dose forms" |
| 262 | ) |
| 263 | return products, ingredients, components, dose_forms |
| 264 | |
| 265 | |
| 266 | def load_relations(zf: zipfile.ZipFile, products, ingredients, components, dose_forms): |
| 267 | """product RXCUI -> (ingredient names, dose form name). |
| 268 | |
| 269 | RXNREL rows read from RXCUI2 to RXCUI1, and RxNorm ships both directions of |
| 270 | every relationship, so only the forward names are consumed here. |
| 271 | |
| 272 | A drug product never points at an ingredient directly. The path is |
| 273 | |
| 274 | SCD --consists_of--> SCDC --has_ingredient--> IN |
| 275 | |
| 276 | and a branded drug goes through the same generic SCDC. Packs point at the |
| 277 | products they contain with `contains`, so they resolve in a third hop once |
| 278 | everything else is known. `has_ingredient` on an SBD or SBDC leads to a brand |
| 279 | name rather than an ingredient and is deliberately not followed. |
| 280 | """ |
| 281 | component_ingredients: dict[str, set[str]] = {} |
| 282 | product_components: dict[str, set[str]] = {} |
| 283 | pack_contents: dict[str, set[str]] = {} |
| 284 | product_dose_form: dict[str, str] = {} |
| 285 | |
| 286 | for row in read_rrf(zf, "rrf/RXNREL.RRF"): |
| 287 | if len(row) < 8: |
| 288 | continue |
| 289 | target, source, rela = row[0], row[4], row[7] |
| 290 | if rela == "has_ingredient": |
| 291 | if source in components and target in ingredients: |
| 292 | component_ingredients.setdefault(source, set()).add(ingredients[target]) |
| 293 | elif rela == "consists_of": |
| 294 | if source in products and target in components: |
| 295 | product_components.setdefault(source, set()).add(target) |
| 296 | elif rela == "contains": |
| 297 | if source in products and target in products: |
| 298 | pack_contents.setdefault(source, set()).add(target) |
| 299 | elif rela == "has_dose_form": |
| 300 | if source in products and target in dose_forms: |
| 301 | product_dose_form.setdefault(source, dose_forms[target]) |
| 302 | |
| 303 | product_ingredients: dict[str, set[str]] = {} |
| 304 | for product, component_ids in product_components.items(): |
| 305 | names = set() |
| 306 | for component in component_ids: |
| 307 | names |= component_ingredients.get(component, set()) |
| 308 | if names: |
| 309 | product_ingredients[product] = names |
| 310 | for pack, contained in pack_contents.items(): |
| 311 | names = set() |
| 312 | for product in contained: |
| 313 | names |= product_ingredients.get(product, set()) |
| 314 | if names: |
| 315 | product_ingredients[pack] = names |
| 316 | |
| 317 | print( |
| 318 | f" relations {len(product_ingredients)} with an ingredient, " |
| 319 | f"{len(product_dose_form)} with a dose form" |
| 320 | ) |
| 321 | return product_ingredients, product_dose_form |
| 322 | |
| 323 | |
| 324 | BRAND_SUFFIX = re.compile(r"\s*\[[^\]]*\]\s*$") |
| 325 | STRENGTH = re.compile(r"\d") |
| 326 | |
| 327 | |
| 328 | def derive_strength(name: str, ingredient: str, dose_form: str | None) -> str | None: |
| 329 | """What is left of the RxNorm name once the ingredient and dose form are gone. |
| 330 | |
| 331 | RxNorm product names are strictly "{ingredients and strengths} {dose form}" |
| 332 | with an optional "[Brand]" suffix, so stripping the two known ends leaves the |
| 333 | strength. Returns None when nothing with a digit in it survives, which is the |
| 334 | case for packs and for a handful of products with no stated strength. |
| 335 | """ |
| 336 | remainder = BRAND_SUFFIX.sub("", name).strip() |
| 337 | if dose_form and remainder.lower().endswith(dose_form.lower()): |
| 338 | remainder = remainder[: -len(dose_form)].strip() |
| 339 | if remainder.lower().startswith(ingredient.lower()): |
| 340 | remainder = remainder[len(ingredient):].strip() |
| 341 | return remainder if remainder and STRENGTH.search(remainder) else None |
| 342 | |
| 343 | |
| 344 | def build_medications(zip_path: Path, conn: sqlite3.Connection) -> tuple[int, int]: |
| 345 | with zipfile.ZipFile(zip_path) as zf: |
| 346 | products, ingredients, components, dose_forms = load_concepts(zf) |
| 347 | product_ingredients, product_dose_form = load_relations( |
| 348 | zf, products, ingredients, components, dose_forms |
| 349 | ) |
| 350 | |
| 351 | conn.execute( |
| 352 | """ |
| 353 | CREATE TABLE medications ( |
| 354 | rxcui TEXT PRIMARY KEY, |
| 355 | name TEXT NOT NULL, |
| 356 | ingredient TEXT NOT NULL, |
| 357 | strength TEXT, |
| 358 | dose_form TEXT |
| 359 | ) |
| 360 | """ |
| 361 | ) |
| 362 | |
| 363 | rows = [] |
| 364 | for rxcui, name in products.items(): |
| 365 | names = product_ingredients.get(rxcui) |
| 366 | if not names: |
| 367 | # No resolvable ingredient means the two-step picker cannot place it, |
| 368 | # and its name alone is not enough to file it under anything. |
| 369 | continue |
| 370 | ingredient = " / ".join(sorted(names)) |
| 371 | dose_form = product_dose_form.get(rxcui) |
| 372 | rows.append( |
| 373 | (rxcui, name, ingredient, derive_strength(name, ingredient, dose_form), dose_form) |
| 374 | ) |
| 375 | |
| 376 | rows.sort(key=lambda r: (r[2].lower(), r[1].lower())) |
| 377 | conn.executemany("INSERT INTO medications VALUES (?, ?, ?, ?, ?)", rows) |
| 378 | |
| 379 | # detail=none: no token positions. The app ranks by name length rather |
| 380 | # than bm25 and never issues a phrase query, so positions buy nothing. |
| 381 | # |
| 382 | # Deliberately no prefix= index, even though the app prefix-matches every |
| 383 | # token. Measured on this data it saved ~0.4 ms on a one-letter query and |
| 384 | # nothing at all past three letters, for 1.7 MB of database: the cost of a |
| 385 | # broad prefix is sorting the candidates, not finding them. The app declines |
| 386 | # to search on a single character instead, which removes the case entirely. |
| 387 | conn.execute( |
| 388 | """ |
| 389 | CREATE VIRTUAL TABLE medications_fts USING fts5( |
| 390 | name, ingredient, |
| 391 | content='medications', content_rowid='rowid', detail='none' |
| 392 | ) |
| 393 | """ |
| 394 | ) |
| 395 | conn.execute( |
| 396 | "INSERT INTO medications_fts(rowid, name, ingredient) " |
| 397 | "SELECT rowid, name, ingredient FROM medications" |
| 398 | ) |
| 399 | print(f" medications {len(rows)} products") |
| 400 | return len(rows), build_ingredients(conn, ingredients) |
| 401 | |
| 402 | |
| 403 | def build_ingredients(conn: sqlite3.Connection, ingredients: dict[str, str]) -> int: |
| 404 | """RxNorm ingredients, for coding drug allergies. |
| 405 | |
| 406 | An allergy is to the ingredient rather than to a particular strength and pack, so the allergy |
| 407 | picker needs the ingredient's own RXCUI — which the product table does not carry, it only has |
| 408 | the ingredient's name. |
| 409 | """ |
| 410 | conn.execute( |
| 411 | "CREATE TABLE ingredients (rxcui TEXT PRIMARY KEY, name TEXT NOT NULL)" |
| 412 | ) |
| 413 | rows = sorted(ingredients.items(), key=lambda kv: kv[1].lower()) |
| 414 | conn.executemany("INSERT OR IGNORE INTO ingredients VALUES (?, ?)", rows) |
| 415 | conn.execute( |
| 416 | """ |
| 417 | CREATE VIRTUAL TABLE ingredients_fts USING fts5( |
| 418 | name, content='ingredients', content_rowid='rowid', detail='none' |
| 419 | ) |
| 420 | """ |
| 421 | ) |
| 422 | conn.execute( |
| 423 | "INSERT INTO ingredients_fts(rowid, name) SELECT rowid, name FROM ingredients" |
| 424 | ) |
| 425 | print(f" ingredients {len(rows)} for allergy coding") |
| 426 | return len(rows) |
| 427 | |
| 428 | |
| 429 | def build_conditions(zip_path: Path, conn: sqlite3.Connection) -> int: |
| 430 | """ICD-10-CM billable codes, stored dotted because that is what FHIR expects.""" |
| 431 | rows = [] |
| 432 | with zipfile.ZipFile(zip_path) as zf: |
| 433 | name = next( |
| 434 | n for n in zf.namelist() if n.endswith(f"icd10cm-codes-{ICD10_YEAR}.txt") |
| 435 | ) |
| 436 | with zf.open(name) as handle: |
| 437 | for raw in handle: |
| 438 | line = raw.decode("utf-8", errors="replace").rstrip("\n") |
| 439 | if not line.strip(): |
| 440 | continue |
| 441 | # "A000 Cholera due to …" - code, run of spaces, description. |
| 442 | parts = line.split(None, 1) |
| 443 | if len(parts) != 2: |
| 444 | continue |
| 445 | code, description = parts[0], parts[1].strip() |
| 446 | rows.append((dotted(code), description)) |
| 447 | |
| 448 | conn.execute( |
| 449 | "CREATE TABLE conditions (code TEXT PRIMARY KEY, description TEXT NOT NULL)" |
| 450 | ) |
| 451 | conn.executemany("INSERT OR IGNORE INTO conditions VALUES (?, ?)", rows) |
| 452 | conn.execute( |
| 453 | """ |
| 454 | CREATE VIRTUAL TABLE conditions_fts USING fts5( |
| 455 | description, |
| 456 | content='conditions', content_rowid='rowid', detail='none' |
| 457 | ) |
| 458 | """ |
| 459 | ) |
| 460 | conn.execute( |
| 461 | "INSERT INTO conditions_fts(rowid, description) " |
| 462 | "SELECT rowid, description FROM conditions" |
| 463 | ) |
| 464 | print(f" conditions {len(rows)} codes") |
| 465 | return len(rows) |
| 466 | |
| 467 | |
| 468 | def dotted(code: str) -> str: |
| 469 | """A00.0 from A000. ICD-10-CM ships dotless; FHIR and humans both want the dot.""" |
| 470 | return code if len(code) <= 3 else f"{code[:3]}.{code[3:]}" |
| 471 | |
| 472 | |
| 473 | def read_loinc(path: Path): |
| 474 | """Yield (code, name, ucum_unit, rank) for active laboratory LOINC codes. |
| 475 | |
| 476 | Accepts either the release zip or an extracted Loinc.csv. Columns are found |
| 477 | by header name because LOINC adds and reorders them between releases, and a |
| 478 | positional reader would silently start importing the wrong field. |
| 479 | """ |
| 480 | if path.suffix.lower() == ".zip": |
| 481 | with zipfile.ZipFile(path) as zf: |
| 482 | name = next( |
| 483 | (n for n in zf.namelist() if n.lower().endswith("loinc.csv")), None |
| 484 | ) |
| 485 | if name is None: |
| 486 | raise SystemExit(f"{path} has no Loinc.csv in it") |
| 487 | with zf.open(name) as handle: |
| 488 | yield from parse_loinc_csv(io.TextIOWrapper(handle, encoding="utf-8-sig")) |
| 489 | else: |
| 490 | with path.open(encoding="utf-8-sig", newline="") as handle: |
| 491 | yield from parse_loinc_csv(handle) |
| 492 | |
| 493 | |
| 494 | def parse_loinc_csv(handle): |
| 495 | reader = csv.DictReader(handle) |
| 496 | required = {"LOINC_NUM", "LONG_COMMON_NAME", "CLASSTYPE", "STATUS"} |
| 497 | missing = required - set(reader.fieldnames or []) |
| 498 | if missing: |
| 499 | raise SystemExit(f"LOINC table is missing columns: {sorted(missing)}") |
| 500 | |
| 501 | for row in reader: |
| 502 | # CLASSTYPE 1 is Laboratory. 2 is Clinical, 3 Claims, 4 Surveys - all of |
| 503 | # which are real LOINC but none of which is a lab result. |
| 504 | if row.get("CLASSTYPE") != "1" or row.get("STATUS") != "ACTIVE": |
| 505 | continue |
| 506 | # Third-party instruments inside LOINC, under their own terms. |
| 507 | if (row.get("EXTERNAL_COPYRIGHT_NOTICE") or "").strip(): |
| 508 | continue |
| 509 | |
| 510 | # Panels are deliberately kept even though ORDER_OBS marks them as things |
| 511 | # you order rather than results you get back. "CBC", "lipid panel" and |
| 512 | # "comprehensive metabolic panel" are how people refer to their own blood |
| 513 | # work, and they rank 162, 208 and 87 among common tests - filtering them |
| 514 | # out removed the five most recognisable names in the table. |
| 515 | |
| 516 | code = (row.get("LOINC_NUM") or "").strip() |
| 517 | name = (row.get("LONG_COMMON_NAME") or "").strip() |
| 518 | if not code or not name: |
| 519 | continue |
| 520 | |
| 521 | # Hidden search text. "ALT" and "HbA1c" appear only here, never in the |
| 522 | # long name, so without these the picker cannot find a test by the |
| 523 | # abbreviation anybody would actually type. |
| 524 | aliases = { |
| 525 | (row.get("SHORTNAME") or "").strip(), |
| 526 | (row.get("DisplayName") or "").strip(), |
| 527 | } |
| 528 | alias = " ".join(sorted(a for a in aliases if a and a != name)) |
| 529 | |
| 530 | unit = (row.get("EXAMPLE_UCUM_UNITS") or "").strip() or None |
| 531 | # Unranked codes sort last rather than being dropped: the rank covers only |
| 532 | # the common few thousand, and the rest are still valid answers. |
| 533 | raw_rank = (row.get("COMMON_TEST_RANK") or "").strip() |
| 534 | rank = int(raw_rank) if raw_rank.isdigit() and raw_rank != "0" else 0 |
| 535 | yield code, name, alias, unit, rank |
| 536 | |
| 537 | |
| 538 | def build_labs(loinc_path: Path | None, conn: sqlite3.Connection) -> int: |
| 539 | conn.execute( |
| 540 | """ |
| 541 | CREATE TABLE labs ( |
| 542 | code TEXT PRIMARY KEY, |
| 543 | name TEXT NOT NULL, |
| 544 | alias TEXT NOT NULL, |
| 545 | unit TEXT, |
| 546 | rank INTEGER NOT NULL |
| 547 | ) |
| 548 | """ |
| 549 | ) |
| 550 | conn.execute( |
| 551 | """ |
| 552 | CREATE VIRTUAL TABLE labs_fts USING fts5( |
| 553 | name, alias, content='labs', content_rowid='rowid', detail='none' |
| 554 | ) |
| 555 | """ |
| 556 | ) |
| 557 | |
| 558 | rows = sorted(read_loinc(loinc_path), key=lambda r: r[1].lower()) if loinc_path else [] |
| 559 | if not rows: |
| 560 | print(" labs none - pass --loinc to include them (see the module docstring)") |
| 561 | return 0 |
| 562 | |
| 563 | conn.executemany("INSERT OR IGNORE INTO labs VALUES (?, ?, ?, ?, ?)", rows) |
| 564 | conn.execute( |
| 565 | "INSERT INTO labs_fts(rowid, name, alias) SELECT rowid, name, alias FROM labs" |
| 566 | ) |
| 567 | ranked = sum(1 for r in rows if r[4]) |
| 568 | print(f" labs {len(rows)} laboratory codes, {ranked} of them commonly ordered") |
| 569 | return len(rows) |
| 570 | |
| 571 | |
| 572 | def build_catalog( |
| 573 | rxnorm_zip: Path, |
| 574 | icd10_zip: Path, |
| 575 | loinc_path: Path | None, |
| 576 | db_path: Path, |
| 577 | ) -> tuple[int, int, int, int]: |
| 578 | db_path.unlink(missing_ok=True) |
| 579 | conn = sqlite3.connect(db_path) |
| 580 | try: |
| 581 | conn.execute("PRAGMA journal_mode = OFF") |
| 582 | conn.execute("PRAGMA synchronous = OFF") |
| 583 | medications, ingredients = build_medications(rxnorm_zip, conn) |
| 584 | conditions = build_conditions(icd10_zip, conn) |
| 585 | labs = build_labs(loinc_path, conn) |
| 586 | # DELETE, not OFF: the app reopens the file read-only, which a journal |
| 587 | # mode of OFF does not survive cleanly. |
| 588 | conn.execute("PRAGMA journal_mode = DELETE") |
| 589 | conn.commit() |
| 590 | conn.execute("VACUUM") |
| 591 | conn.commit() |
| 592 | finally: |
| 593 | conn.close() |
| 594 | |
| 595 | print(f" built {db_path} ({mb(db_path.stat().st_size)})") |
| 596 | return medications, ingredients, conditions, labs |
| 597 | |
| 598 | |
| 599 | def compress(src: Path, dest: Path) -> None: |
| 600 | try: |
| 601 | import brotli |
| 602 | except ImportError: |
| 603 | sys.exit("brotli is required to compress the asset: pip install brotli") |
| 604 | dest.parent.mkdir(parents=True, exist_ok=True) |
| 605 | dest.write_bytes(brotli.compress(src.read_bytes(), quality=11)) |
| 606 | print(f" wrote {dest} ({mb(dest.stat().st_size)})") |
| 607 | |
| 608 | |
| 609 | def release_label(zip_path: Path) -> str: |
| 610 | """The release date the zip's readme is named for, e.g. "2026-09-08".""" |
| 611 | with zipfile.ZipFile(zip_path) as zf: |
| 612 | for name in zf.namelist(): |
| 613 | match = re.search(r"Readme_Full_Prescribe_(\d{2})(\d{2})(\d{4})\.txt", name) |
| 614 | if match: |
| 615 | month, day, year = match.groups() |
| 616 | return f"{year}-{month}-{day}" |
| 617 | return "" |
| 618 | |
| 619 | |
| 620 | def main() -> None: |
| 621 | ap = argparse.ArgumentParser(description=__doc__) |
| 622 | ap.add_argument("--cvx-only", action="store_true", |
| 623 | help="build only the committed vaccine catalogue") |
| 624 | ap.add_argument("--zip", type=Path, default=CACHED_ZIP, |
| 625 | help="a previously downloaded RxNorm prescribable release") |
| 626 | ap.add_argument("--icd10", type=Path, default=CACHED_ICD10, |
| 627 | help="a previously downloaded ICD-10-CM code description release") |
| 628 | ap.add_argument("--loinc", type=Path, default=None, |
| 629 | help="LOINC Table File (CSV) zip or Loinc.csv; see the module docstring, " |
| 630 | "since LOINC cannot be downloaded without a login") |
| 631 | ap.add_argument("--keep-db", action="store_true", |
| 632 | help="keep the uncompressed SQLite file next to the asset") |
| 633 | args = ap.parse_args() |
| 634 | |
| 635 | print("Vaccines (CVX)") |
| 636 | build_cvx(ASSETS / "cvx.json") |
| 637 | |
| 638 | if args.cvx_only: |
| 639 | return |
| 640 | |
| 641 | print("Medications (RxNorm), conditions (ICD-10-CM) and labs (LOINC)") |
| 642 | rxnorm_zip = download(RXNORM_URL, args.zip) |
| 643 | icd10_zip = download(ICD10_URL, args.icd10) |
| 644 | if args.loinc and not args.loinc.exists(): |
| 645 | raise SystemExit(f"--loinc {args.loinc} does not exist") |
| 646 | staging = ASSETS / "catalog.db" |
| 647 | medications, ingredients, conditions, labs = build_catalog( |
| 648 | rxnorm_zip, icd10_zip, args.loinc, staging |
| 649 | ) |
| 650 | compress(staging, ASSETS / "catalog.db.br") |
| 651 | |
| 652 | meta = { |
| 653 | "schemaVersion": SCHEMA_VERSION, |
| 654 | "medications": medications, |
| 655 | "ingredients": ingredients, |
| 656 | "conditions": conditions, |
| 657 | "labs": labs, |
| 658 | "bytes": staging.stat().st_size, |
| 659 | "compressedBytes": (ASSETS / "catalog.db.br").stat().st_size, |
| 660 | "release": release_label(rxnorm_zip), |
| 661 | "icd10Year": ICD10_YEAR, |
| 662 | } |
| 663 | (ASSETS / "catalog.db.meta.json").write_text( |
| 664 | json.dumps(meta, indent=1) + "\n", newline="\n" |
| 665 | ) |
| 666 | print(f" wrote {ASSETS / 'catalog.db.meta.json'}") |
| 667 | |
| 668 | if not args.keep_db: |
| 669 | staging.unlink(missing_ok=True) |
| 670 | |
| 671 | |
| 672 | if __name__ == "__main__": |
| 673 | main() |