Spaces:
Running on Zero
Running on Zero
deploy API
Browse filesFiles changed (6)
19 unmodified lines20212223242518 unmodified lines44454647484937 unmodified lines8788899091929394959619 unmodified linesMODEL_VERSION = "stage2_run4@2026-10-09" # the rates below hold for this served model only (its version string)RUN4 = "outputs/runs/stage2_run4/eval/"GALLERY = {"correct_match": "correct_match", "wrong_match": "wrong_match", "own_flip": "own_flip","own_rejected": "own_rejected", "unknown_matched": "unknown_matched", "unknown_rejected": "unknown_rejected"}18 unmodified lines"source": RUN4 + "imprint_gallery_large_c92_distinct.json","keys": {k: "test/with_check/" + k for k in ("correct_match", "wrong_match", "own_flip", "unknown_matched")},},{"id": "personal_gallery_other_phones","what": "As personal_gallery on MEDISEG: 32 Hong Kong products, other phones, lighting and backgrounds",37 unmodified lines"rates": {"top1_right": 0.802, "possible_match_share": 0.758, "possible_match_right": 0.867,"not_in_catalogue_called_possible_match": 0.07},"source": RUN4 + "identify_confidence_large_c92.json","keys": {"top1_right": "test/top1_right","possible_match_share": "test/catalogue_pills_by_verdict/possible_match/share","possible_match_right": "test/catalogue_pills_by_verdict/possible_match/top1_right","not_in_catalogue_called_possible_match": "test/other_pills_by_verdict/possible_match"},},{"id": "pill_count",19 unmodified lines2021222324252627282918 unmodified lines484950515253545556575859606137 unmodified lines9910010110210310410510610710810911011111211311419 unmodified linesMODEL_VERSION = "stage2_run4@2026-10-09" # the rates below hold for this served model only (its version string)RUN4 = "outputs/runs/stage2_run4/eval/"IDENTIFY_KEYS = {"top1_right": "test/top1_right","possible_match_share": "test/catalogue_pills_by_verdict/possible_match/share","possible_match_right": "test/catalogue_pills_by_verdict/possible_match/top1_right","not_in_catalogue_called_possible_match": "test/other_pills_by_verdict/possible_match"}GALLERY = {"correct_match": "correct_match", "wrong_match": "wrong_match", "own_flip": "own_flip","own_rejected": "own_rejected", "unknown_matched": "unknown_matched", "unknown_rejected": "unknown_rejected"}18 unmodified lines"source": RUN4 + "imprint_gallery_large_c92_distinct.json","keys": {k: "test/with_check/" + k for k in ("correct_match", "wrong_match", "own_flip", "unknown_matched")},},{"id": "personal_gallery_with_imprint_cpu","what": "As personal_gallery_with_imprint, read by the CPU reader (Florence-2-base, framed as served): most ""live calls, since the free GPU quota is per caller; the pill's own imprint is read on 43% of photos","rates": {"correct_match": 0.7731, "wrong_match": 0.0006, "own_flip": 0.0815, "unknown_matched": 0.0351},"source": RUN4 + "imprint_gallery_base_c92_distinct.json","keys": {k: "test/with_check/" + k for k in ("correct_match", "wrong_match", "own_flip", "unknown_matched")},},{"id": "personal_gallery_other_phones","what": "As personal_gallery on MEDISEG: 32 Hong Kong products, other phones, lighting and backgrounds",37 unmodified lines"rates": {"top1_right": 0.802, "possible_match_share": 0.758, "possible_match_right": 0.867,"not_in_catalogue_called_possible_match": 0.07},"source": RUN4 + "identify_confidence_large_c92.json","keys": IDENTIFY_KEYS,},{"id": "catalogue_identify_cpu","what": "As catalogue_identify with imprints read by the CPU reader (most live calls), scored with the served ""confidence rule as it is","rates": {"top1_right": 0.792, "possible_match_share": 0.751, "possible_match_right": 0.864,"not_in_catalogue_called_possible_match": 0.074},"source": RUN4 + "identify_confidence_base_c92_served.json","keys": IDENTIFY_KEYS,},{"id": "pill_count",
61 unmodified lines62636465666768820 unmodified lines88989089189289389489589689789827 unmodified lines92692792892993093193261 unmodified linesfrom serving.app import evidence, schemas as Sfrom serving.app.vision import VisionAPI_VERSION = "0.9.0"STARTED_AT = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")LOCAL = {"safety_db": Path("data/processed/safety/safety.sqlite"),"embedder": Path("outputs/serving/stage2_model.pt"),820 unmodified lines"medications, [{id, name, rxcui?, strength?}]: ""each medicine read is compared with it")):"""**Which medicine is on this box, label or prescription?** Reads the printed text and finds the medicine names init (RxNorm's ingredient and brand names, international names such as paracetamol too), with strength,ingredients, RxNorm code, and what is printed about each (directions, quantity, dose form, dates), every valuewith the line it was read from and `null` when not printed (blueprint B7). With `medications`, each medicine iscompared with the patient's list: same medicine, different strength, or not on the list (B9). Send a confirmedcandidate to `/v1/safety/medications` as `{"id", "name", "rxcui"}`. Always ask the user to confirm.Nothing is stored; only the lines that name or describe a medicine are returned (labels show the patient's name).27 unmodified linesc["list_check"] = compare_with_list(c, listed)except RxNormError as error:raise HTTPException(502, f"RxNorm didn't answer: {error}")result = {"candidates": candidates, "note": LABEL_NOTE, "ocr_model": ocr_model, "source": source}if not candidates:result["message"] = ("No medicine name found. Photograph the label closer, straight on and in good light, ""or type the name.")61 unmodified lines62636465666768820 unmodified lines88989089189289389489589689789889990027 unmodified lines92892993093193293393493593693793861 unmodified linesfrom serving.app import evidence, schemas as Sfrom serving.app.vision import VisionAPI_VERSION = "0.10.0"STARTED_AT = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")LOCAL = {"safety_db": Path("data/processed/safety/safety.sqlite"),"embedder": Path("outputs/serving/stage2_model.pt"),820 unmodified lines"medications, [{id, name, rxcui?, strength?}]: ""each medicine read is compared with it")):"""**What does the pharmacy sticker say?** Made for Singapore dispensing labels (the sticker on the medicine bag orbox), also reads prescriptions and manufacturer boxes. Per medicine: name, strength per unit, ingredients andRxNorm code; the quantity supplied (amount and unit); the instructions parsed into dose, times a day or every Nhours, as needed, time of day, before/after food, duration and daily maximum; what it is for; cautions; dispensingand expiry dates. Every value comes with the line it was read from and is `null` when not printed, never inferred(blueprint B7). `label_kind` says whether it is a dispensing label (instructions for the patient) or a package. With `medications`, each medicine iscompared with the patient's list: same medicine, different strength, or not on the list (B9). Send a confirmedcandidate to `/v1/safety/medications` as `{"id", "name", "rxcui"}`. Always ask the user to confirm.Nothing is stored; only the lines that name or describe a medicine are returned (labels show the patient's name).27 unmodified linesc["list_check"] = compare_with_list(c, listed)except RxNormError as error:raise HTTPException(502, f"RxNorm didn't answer: {error}")kind = ("none" if not candidates else"dispensing" if any(c["fields"]["instructions"] or c["fields"]["quantity"] for c in candidates) else"package")result = {"candidates": candidates, "label_kind": kind, "note": LABEL_NOTE, "ocr_model": ocr_model,"source": source}if not candidates:result["message"] = ("No medicine name found. Photograph the label closer, straight on and in good light, ""or type the name.")
303 unmodified lines30430530630730830931031131221 unmodified lines334335336337338339303 unmodified linesline: str = Field(description="The line(s) it was read from")class DocumentFields(Out):directions: Printed | None = Field(None, description="As printed, e.g. 'Take 1 tablet twice a day after meals'")quantity: Printed | None = Nonedose_form: Printed | None = Nonedate: Printed | None = Field(None, description="Dispensing or prescription date, as printed")expiry_date: Printed | None = None21 unmodified linesclass ReadLabelResponse(Out):candidates: list[LabelCandidate]note: strocr_model: strsource: Literal["photo", "pdf_text", "pdf_scan"] = "photo"303 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134221 unmodified lines364365366367368369370371372303 unmodified linesline: str = Field(description="The line(s) it was read from")class Dose(Out):amount: float = Field(description="Per dose, e.g. 1, 0.5")amount_max: float | None = Field(None, description="For a range: 'Take 1-2 tablets' -> 2")unit: str | None = Field(None, description="tablet, capsule, ml, puff, drop, sachet, ...")class Instructions(Out):text: str = Field(description="As printed, e.g. 'Take ONE tablet TWICE a day AFTER FOOD'")line: str = Field(description="The line(s) it was read from")dose: Dose | None = Nonetimes_per_day: int | None = Field(None, description="Only when printed ('twice a day', 'BD', 'daily')")every_hours: float | None = Field(None, description="'every 6 hours'; never turned into times a day")as_needed: bool = Field(False, description="'when necessary', 'as needed', 'PRN'")times_of_day: list[Literal["morning", "afternoon", "evening", "night", "bedtime"]] = []food: Literal["before_food", "after_food", "with_food", "with_or_without_food", "empty_stomach"] | None = Noneduration: str | None = Field(None, description="'7 days'")max_per_day: str | None = Field(None, description="'8 tablets in 24 hours'")class Quantity(Printed):amount: float | None = Field(None, description="e.g. 60")unit: str | None = Field(None, description="e.g. tablet, capsule, ml")class DocumentFields(Out):directions: Printed | None = Field(None, description="As printed, e.g. 'Take 1 tablet twice a day after meals'")instructions: Instructions | None = Field(None, description="The directions, parsed into their parts; a part ""that isn't printed is null")indication: Printed | None = Field(None, description="What the medicine is for, as printed ('For high blood ""pressure' -> 'high blood pressure')")cautions: list[Printed] = Field([], description="Cautionary notes as printed ('May cause drowsiness', 'Avoid ""alcohol', 'Swallow whole')")quantity: Quantity | None = Field(None, description="Total supplied, e.g. 'Qty: 60 TAB' -> 60 tablet")dose_form: Printed | None = Nonedate: Printed | None = Field(None, description="Dispensing or prescription date, as printed")expiry_date: Printed | None = None21 unmodified linesclass ReadLabelResponse(Out):candidates: list[LabelCandidate]label_kind: Literal["dispensing", "package", "none"] = Field("none", description="dispensing: a pharmacy sticker or prescription with instructions for the patient; ""package: a manufacturer's box or bottle (no instructions); none: no medicine found")note: strocr_model: strsource: Literal["photo", "pdf_text", "pdf_scan"] = "photo"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Typed tool definitions for the Medication Care Agent (blueprint job B14), generated from the API's own OpenAPIdocument so they can't drift from it. Served at GET /v1/tools; usage notes and example traces in docs/agent_tools.md.Each tool: name (the blueprint's where it names one), description written for the agent (when to call it, what itmust not conclude), input_schema (JSON Schema; an uploaded file becomes an image reference the app's tool layerresolves), output_schema ($refs into `components`), and how to call it (method, path, content type)."""TOOLS = [("route_medication_image", "post", "/v1/check-input","Before any other photo tool when you don't know what the photo shows: loose pills, blister pack, box or bottle, ""printed label or document, and which tools fit (next_tools). Prefer asking the user; when type is unchecked or ""next_tools is empty, ask for the box, label or prescription, or suggest the pharmacist."),("detect_pills", "post", "/v1/detect","Find each pill in a photo and say whether the count can be trusted. Call before counting pills or embedding ""several pills. If count_reliable is false, don't count: ask for a new photo (pills apart, plain surface)."),("embed_pill", "post", "/v1/embed","Turn one loose-pill photo (or a photo + box) into a 256-number embedding. Use at enrolment (store it with ""model_version and embedding_space_id) and before match_gallery. Never embed boxes or blister packs."),("match_gallery", "post", "/v1/match","Compare pill embeddings with the patient's gallery: match / unknown / ambiguous per pill. Visual evidence only: ""a match means 'looks like', not 'is' or 'safe to take'. ambiguous: ask for another photo. The gallery's ""model_version is required; on 409 re-embed the enrolment photos."),("identify_pill", "post", "/v1/identify","Possible catalogue matches (US products) for a pill that isn't in the patient's list. Report the verdict and ""confidence, never a definite identity; no_confident_match means the pill may not be a catalogue product."),("search_by_embedding", "post", "/v1/search-by-embedding","identify_pill for a pill you already embedded (e.g. match_gallery said unknown): send its embeddings and ""imprint_reads from embed_pill. Same answer, no second model run. Possible matches only, never an identity."),("scan_photo", "post", "/v1/scan","Diagnostics in one call: detection plus each pill's visual decision (with a gallery) or catalogue candidates. ""Don't use its dose check (deprecated): apply the backend's dose rules to the pills it returns."),("extract_medication_document", "post", "/v1/read-label","Read a medicine box, pharmacy label or prescription (photo or PDF): medicine names, strength, RxNorm code and ""what is printed (directions, quantity, dates), each with its source line. Fields not printed are null; never ""fill them in. With the patient's medications, says same medicine / different strength / not on the list. ""Always have the patient confirm."),("find_medication_product", "get", "/v1/pills/search","Products and pictures for a medicine name (brand or generic), with strength, dose form and release as fields. ""Never treat products of another strength or form as the same."),("screen_medication_list", "post", "/v1/safety/medications","Interaction and duplicate-ingredient alerts for the whole medication list (DDInter 2.0). Read coverage: no ""alert does not mean safe. Advisory; defer to the pharmacist."),("evaluate_dose_reference", "post", "/v1/safety/dose","The reference dose rules on visual decisions (stateless). The backend's own dose policy is authoritative."),("retrieve_medication_info", "get", "/v1/safety/label","Warning sections of the official US label, with the label's date and DailyMed link for citation. General ""information, not the patient's instructions."),("get_model_info", "get", "/v1/model-info","The served model: version, embedding space, decision rule and known limits. Check after a 409."),]FILE_NOTE = "An image reference: the app's tool layer uploads the file (photo, or PDF for documents)"def _resolve(schema, components):ref = schema.get("$ref", "") if isinstance(schema, dict) else ""return components.get(ref.rsplit("/", 1)[-1], {}) if ref else schemadef _input_schema(op, components):props, required = {}, []for p in op.get("parameters", []):props[p["name"]] = {**p.get("schema", {}), "description": p.get("description", "")}if p.get("required"):required.append(p["name"])content = op.get("requestBody", {}).get("content", {})for kind in ("application/json", "multipart/form-data"):if kind in content:body = _resolve(content[kind]["schema"], components)for name, s in body.get("properties", {}).items():is_file = s.get("format") == "binary" or s.get("contentMediaType") or \(s.get("type") == "array" and (s.get("items", {}).get("format") == "binary"or s.get("items", {}).get("contentMediaType")))props[name] = ({"type": "array", "items": {"type": "string"}, "description": FILE_NOTE}if is_file and s.get("type") == "array" else{"type": "string", "description": FILE_NOTE} if is_file else s)required += body.get("required", [])return {"type": "object", "properties": props, "required": sorted(set(required))}def build_tools(openapi):components = openapi.get("components", {}).get("schemas", {})tools = []for name, method, path, description in TOOLS:op = openapi["paths"][path][method]ok = op.get("responses", {}).get("200", {}).get("content", {}).get("application/json", {})kind = next(iter(op.get("requestBody", {}).get("content", {"none": None})))tools.append({"name": name, "description": description, "input_schema": _input_schema(op, components),"output_schema": ok.get("schema", {}),"call": {"method": method.upper(), "path": path,"content_type": None if kind == "none" else kind}})return {"tools": tools, "components": {"schemas": components},"notes": "Stage 2 answers are visual evidence only. The backend's safety policy decides actions; the ""agent reports evidence with its limits and asks the patient to confirm."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Typed tool definitions for the Medication Care Agent (blueprint job B14), generated from the API's own OpenAPIdocument so they can't drift from it. Served at GET /v1/tools; usage notes and example traces in docs/agent_tools.md.Each tool: name (the blueprint's where it names one), description written for the agent (when to call it, what itmust not conclude), input_schema (JSON Schema; an uploaded file becomes an image reference the app's tool layerresolves), output_schema ($refs into `components`), and how to call it (method, path, content type)."""TOOLS = [("route_medication_image", "post", "/v1/check-input","Before any other photo tool when you don't know what the photo shows: loose pills, blister pack, box or bottle, ""printed label or document, and which tools fit (next_tools). Prefer asking the user; when type is unchecked or ""next_tools is empty, ask for the box, label or prescription, or suggest the pharmacist."),("detect_pills", "post", "/v1/detect","Find each pill in a photo and say whether the count can be trusted. Call before counting pills or embedding ""several pills. If count_reliable is false, don't count: ask for a new photo (pills apart, plain surface)."),("embed_pill", "post", "/v1/embed","Turn one loose-pill photo (or a photo + box) into a 256-number embedding. Use at enrolment (store it with ""model_version and embedding_space_id) and before match_gallery. Never embed boxes or blister packs."),("match_gallery", "post", "/v1/match","Compare pill embeddings with the patient's gallery: match / unknown / ambiguous per pill. Visual evidence only: ""a match means 'looks like', not 'is' or 'safe to take'. ambiguous: ask for another photo. The gallery's ""model_version is required; on 409 re-embed the enrolment photos."),("identify_pill", "post", "/v1/identify","Possible catalogue matches (US products) for a pill that isn't in the patient's list. Report the verdict and ""confidence, never a definite identity; no_confident_match means the pill may not be a catalogue product."),("search_by_embedding", "post", "/v1/search-by-embedding","identify_pill for a pill you already embedded (e.g. match_gallery said unknown): send its embeddings and ""imprint_reads from embed_pill. Same answer, no second model run. Possible matches only, never an identity."),("scan_photo", "post", "/v1/scan","Diagnostics in one call: detection plus each pill's visual decision (with a gallery) or catalogue candidates. ""Don't use its dose check (deprecated): apply the backend's dose rules to the pills it returns."),("extract_medication_document", "post", "/v1/read-label","Read a Singapore pharmacy sticker (or a prescription or box; photo or PDF): per medicine the name, strength, ""RxNorm code, quantity, the instructions in parts (dose, times a day or every N hours, as needed, time of day, ""before/after food), what it is for, cautions and dates, each with its source line. Parts not printed are ""null; never fill them in. With the patient's medications, says same medicine / different strength / not on ""the list. Always have the patient confirm before anything is scheduled."),("find_medication_product", "get", "/v1/pills/search","Products and pictures for a medicine name (brand or generic), with strength, dose form and release as fields. ""Never treat products of another strength or form as the same."),("screen_medication_list", "post", "/v1/safety/medications","Interaction and duplicate-ingredient alerts for the whole medication list (DDInter 2.0). Read coverage: no ""alert does not mean safe. Advisory; defer to the pharmacist."),("evaluate_dose_reference", "post", "/v1/safety/dose","The reference dose rules on visual decisions (stateless). The backend's own dose policy is authoritative."),("retrieve_medication_info", "get", "/v1/safety/label","Warning sections of the official US label, with the label's date and DailyMed link for citation. General ""information, not the patient's instructions."),("get_model_info", "get", "/v1/model-info","The served model: version, embedding space, decision rule and known limits. Check after a 409."),]FILE_NOTE = "An image reference: the app's tool layer uploads the file (photo, or PDF for documents)"def _resolve(schema, components):ref = schema.get("$ref", "") if isinstance(schema, dict) else ""return components.get(ref.rsplit("/", 1)[-1], {}) if ref else schemadef _input_schema(op, components):props, required = {}, []for p in op.get("parameters", []):props[p["name"]] = {**p.get("schema", {}), "description": p.get("description", "")}if p.get("required"):required.append(p["name"])content = op.get("requestBody", {}).get("content", {})for kind in ("application/json", "multipart/form-data"):if kind in content:body = _resolve(content[kind]["schema"], components)for name, s in body.get("properties", {}).items():is_file = s.get("format") == "binary" or s.get("contentMediaType") or \(s.get("type") == "array" and (s.get("items", {}).get("format") == "binary"or s.get("items", {}).get("contentMediaType")))props[name] = ({"type": "array", "items": {"type": "string"}, "description": FILE_NOTE}if is_file and s.get("type") == "array" else{"type": "string", "description": FILE_NOTE} if is_file else s)required += body.get("required", [])return {"type": "object", "properties": props, "required": sorted(set(required))}def build_tools(openapi):components = openapi.get("components", {}).get("schemas", {})tools = []for name, method, path, description in TOOLS:op = openapi["paths"][path][method]ok = op.get("responses", {}).get("200", {}).get("content", {}).get("application/json", {})kind = next(iter(op.get("requestBody", {}).get("content", {"none": None})))tools.append({"name": name, "description": description, "input_schema": _input_schema(op, components),"output_schema": ok.get("schema", {}),"call": {"method": method.upper(), "path": path,"content_type": None if kind == "none" else kind}})return {"tools": tools, "components": {"schemas": components},"notes": "Stage 2 answers are visual evidence only. The backend's safety policy decides actions; the ""agent reports evidence with its limits and asks the patient to confirm."}
18 unmodified lines19202122232425262718 unmodified linesPRESETS = { # for the evaluation caches (scripts/read_imprints_cache.py)"base_c70": {"model": CPU_MODEL, "centre": 0.7, "served_framing": False},"large_c92": {"model": GPU_MODEL, "centre": READ_CENTRE, "served_framing": True},# large with the imprint adapter trained by scripts/train_imprint_reader.py (imprint reads only)"large_lora_v1": {"model": GPU_MODEL, "centre": READ_CENTRE, "served_framing": True,"adapter": "outputs/imprint_reader/large_lora_v1/adapter.pt"},}TOKENS = {"read": 20, "caption": 40, "text": 512}18 unmodified lines192021222324252627282930313218 unmodified linesPRESETS = { # for the evaluation caches (scripts/read_imprints_cache.py)"base_c70": {"model": CPU_MODEL, "centre": 0.7, "served_framing": False},"large_c92": {"model": GPU_MODEL, "centre": READ_CENTRE, "served_framing": True},# the CPU reader as served (most live calls: the free GPU quota is per caller); read here on the GPU in fp16"base_c92": {"model": CPU_MODEL, "centre": READ_CENTRE, "served_framing": True},# large with the imprint adapter trained by scripts/train_imprint_reader.py (imprint reads only)"large_lora_v1": {"model": GPU_MODEL, "centre": READ_CENTRE, "served_framing": True,"adapter": "outputs/imprint_reader/large_lora_v1/adapter.pt"},# v2 also learnt to write nothing (unreadable photos, wrong rotations); the better epoch on validation identify"large_lora_v2": {"model": GPU_MODEL, "centre": READ_CENTRE, "served_framing": True,"adapter": "outputs/imprint_reader/large_lora_v2/adapter_best.pt"},}TOKENS = {"read": 20, "caption": 40, "text": 512}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368"""Medicines on a box or pharmacy label (feature F8): OCR lines (imprint.ocr.ImprintReader.read_text) -> candidatemedicines with strength and RxNorm codes, to fill the medication list (and so the Stage 3 checks).1. Names: the lines are searched for RxNorm's ingredient and brand names (IN, PIN, BN: ~23,500, fetched once), plusinternational names RxNorm lacks (INN_TO_US: paracetamol -> acetaminophen). Phrases of 1-4 words match exactly(case and punctuation ignored), longest first; single words of 6+ letters also match with one OCR error (two from9 letters). Everyday words that happen to be names ("water", "relief") are skipped (COMMON).2. Strength: amounts with units after the name on its line, else the line's only amount, else the next line's whenthat line names nothing ("10 mg" printed under "atorvastatin calcium").3. RxNorm: name + strength -> the product concept (e.g. "atorvastatin 10 MG Oral Tablet [Lipitor]"), kept only if ithas the name's ingredients and its strength; the ingredients always come from RxNorm.4. Names whose ingredients are the same, or a subset of a brand's (paracetamol and caffeine under Panadol Extra),merge into one candidate. Best first: most evidence, then the order on the label.RxNorm's own match scores are not used to find names: there, "Take 2 tablets 4 times a day" scores higher than"PARACETAMOL 500MG TABLET"."""import refrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field# international (INN/BAN, as printed in Singapore) -> RxNorm's US names; a list for combinationsINN_TO_US = {"paracetamol": ["acetaminophen"], "salbutamol": ["albuterol"], "adrenaline": ["epinephrine"],"noradrenaline": ["norepinephrine"], "frusemide": ["furosemide"], "glibenclamide": ["glyburide"],"lignocaine": ["lidocaine"], "amoxycillin": ["amoxicillin"], "cefalexin": ["cephalexin"],"clavulanic acid": ["clavulanate"], "potassium clavulanate": ["clavulanate"],"chlorphenamine": ["chlorpheniramine"], "mesalazine": ["mesalamine"], "pethidine": ["meperidine"],"thyroxine": ["levothyroxine"], "sodium valproate": ["valproate"], "isoprenaline": ["isoproterenol"],"aciclovir": ["acyclovir"], "ciclosporin": ["cyclosporine"], "colecalciferol": ["cholecalciferol"],"rifampicin": ["rifampin"], "beclometasone": ["beclomethasone"], "dexamfetamine": ["dextroamphetamine"],"glyceryl trinitrate": ["nitroglycerin"], "phenobarbitone": ["phenobarbital"], "oestradiol": ["estradiol"],"eformoterol": ["formoterol"], "colestyramine": ["cholestyramine"], "clomifene": ["clomiphene"],"orciprenaline": ["metaproterenol"], "oxpentifylline": ["pentoxifylline"], "dothiepin": ["dosulepin"],"co-amoxiclav": ["amoxicillin", "clavulanate"], "co-trimoxazole": ["sulfamethoxazole", "trimethoprim"],"co-codamol": ["acetaminophen", "codeine"],}# words on boxes and labels that are also RxNorm names, never a medicine on their ownCOMMON = {"water", "sugar", "salt", "relief", "extra", "fast", "film", "coated", "tablet", "tablets", "capsule", "capsules","oral", "daily", "night", "day", "care", "plus", "forte", "max", "ultra", "rapid", "soft", "children", "adult","adults", "junior", "baby", "cold", "flu", "pain", "fever", "allergy", "sleep", "cough", "clear", "active","original", "advance", "advanced", "complete", "health", "natural", "gold", "silver", "oxygen", "air", "alcohol","glycerin", "talc", "starch", "lactose", "gelatin", "cellulose", "iron", "calcium", "sodium", "potassium","magnesium", "zinc", "acid", "hydrochloride", "clinic", "pharmacy", "medicine", "tan", "lim", "lee", "ong", "ng",}UNIT = r"(?:mg|mcg|µg|ug|g|ml|iu|units?|%)"STRENGTH = re.compile(rf"(\d+(?:[.,]\d+)?)\s*({UNIT})(?:\s*/\s*(\d+(?:[.,]\d+)?)?\s*({UNIT}|tab|cap)s?)?(?![a-z])",re.I)# dose forms as printed -> as RxNorm names themFORMS = {"tablet": "tablet", "tab": "tablet", "caplet": "tablet", "capsule": "capsule", "cap": "capsule","syrup": "solution", "solution": "solution", "suspension": "suspension", "cream": "cream","ointment": "ointment", "gel": "gel", "injection": "injection", "drops": "drops", "inhaler": "inhal","patch": "patch", "spray": "spray", "suppository": "suppository"}def norm(text):return " ".join(re.sub(r"[^a-z0-9]+", " ", str(text).lower()).split())INN = {norm(k): v for k, v in INN_TO_US.items()}def dose_form(lines):"""The first dose form printed anywhere on the label, as RxNorm names it, or None."""for line in lines:for word in re.findall(r"[a-z]+", line.lower()):word = word[:-1] if word.endswith("s") and word[:-1] in FORMS else wordif word in FORMS:return FORMS[word]return Nonedef _edits(a, b, limit):"""Levenshtein distance, or limit + 1 once it exceeds limit."""if abs(len(a) - len(b)) > limit:return limit + 1prev = list(range(len(b) + 1))for i, ca in enumerate(a, 1):cur = [i] + [0] * len(b)for j, cb in enumerate(b, 1):cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))if min(cur) > limit:return limit + 1prev = curreturn prev[-1]def _strength_text(m):amount, unit, per_amount, per_unit = m.groups()unit = unit.lower().replace("µg", "mcg").replace("ug", "mcg")text = f"{amount.replace(',', '.')}{'' if unit == '%' else ' '}{unit}"if per_unit:text += f"/{per_amount + ' ' if per_amount else ''}{per_unit.lower()}"return text@dataclassclass Found:line: intstart: intend: inttext: str # as printedrxcui: strtty: str # IN, PIN, BN, or INN for a mapped international nameus_names: list = field(default_factory=list)spelled: str | None = None # RxNorm's spelling when the printed word was misread (fuzzy match)strength: str | None = Noneclass LabelReader:def __init__(self, rxnorm):self.rxnorm = rxnormself._vocab = None@propertydef vocab(self):"""normalised name -> (rxcui, tty), and single words by length for the fuzzy match; fetched once."""if self._vocab is None:concepts = self.rxnorm.get("allconcepts.json", tty="IN PIN BN")["minConceptGroup"]["minConcept"]names = {}for c in concepts:key = norm(c["name"])if key and key not in COMMON and len(key) >= 4 and (key not in names or c["tty"] == "IN"):names[key] = (c["rxcui"], c["tty"], c["name"])by_len = {}for key in names:if " " not in key and len(key) >= 6 and not key.isdigit():by_len.setdefault(len(key), []).append(key)self._vocab = (names, by_len)return self._vocabdef _lookup(self, phrase):names, by_len = self.vocabif phrase in INN:first = names.get(INN[phrase][0])return (first[0] if first else None), "INN", INN[phrase], Noneif phrase in names:return names[phrase][0], names[phrase][1], [], Noneif " " not in phrase and len(phrase) >= 6 and not any(ch.isdigit() for ch in phrase):limit = 1 if len(phrase) < 9 else 2for n in range(len(phrase) - limit, len(phrase) + limit + 1):for key in by_len.get(n, ()):if key[0] == phrase[0] and _edits(phrase, key, limit) <= limit:return names[key][0], names[key][1], [], names[key][2]return Nonedef find_names(self, lines):"""Each medicine name in the lines, with its strength (steps 1 and 2)."""found = []for li, line in enumerate(lines):words = [(m.start(), m.end(), m.group().lower()) for m in re.finditer(r"[A-Za-z][A-Za-z\-]*", line)]i = 0while i < len(words):for n in range(min(4, len(words) - i), 0, -1):phrase = norm(" ".join(w for _, _, w in words[i:i + n]))hit = self._lookup(phrase) if phrase and phrase not in COMMON else Noneif hit and hit[0]:start, end = words[i][0], words[i + n - 1][1]found.append(Found(li, start, end, line[start:end], hit[0], hit[1], hit[2], hit[3]))i += nbreakelse:i += 1for f in found: # strengthssame = [f2 for f2 in found if f2.line == f.line and f2.start > f.start]stop = min((f2.start for f2 in same), default=None)amounts = list(STRENGTH.finditer(lines[f.line]))after = [m for m in amounts if m.start() >= f.end and (stop is None or m.start() < stop)]if after:f.strength = _strength_text(after[0])elif len(amounts) == 1 and len([f2 for f2 in found if f2.line == f.line]) == 1:f.strength = _strength_text(amounts[0])elif f.line + 1 < len(lines) and not any(f2.line == f.line + 1 for f2 in found):nxt = list(STRENGTH.finditer(lines[f.line + 1]))if nxt:f.strength = _strength_text(nxt[0])return founddef _ingredients(self, f):"""(rxcui, name) of the active ingredients. An ingredient name found in the list is its own answer (noRxNorm call: each costs up to a second from Singapore); brands and salts ask RxNorm."""names = self.vocab[0]if f.tty == "INN":known = [names.get(us) for us in f.us_names]if all(k and k[1] == "IN" for k in known):return sorted({(k[0], us) for k, us in zip(known, f.us_names)}, key=lambda x: x[1])out = []for us in f.us_names:rxcui = self.rxnorm.rxcui_by_name(us)out += self.rxnorm.ingredients(rxcui) if rxcui else []return sorted(set(out), key=lambda x: x[1])if f.tty == "IN":return [(f.rxcui, (f.spelled or f.text).lower())] # RxNorm's ingredient name, as printed or correctedreturn self.rxnorm.ingredients(f.rxcui)def _product(self, name, strength, form, ingredients):"""RxNorm's concept for name + strength, if it has these ingredients and this strength (step 3)."""number = re.match(r"[\d.]+", strength).group()want = {r for r, _ in ingredients}candidates = [r for r, _ in self.rxnorm.approximate(" ".join(filter(None, (name, strength, form))))]with ThreadPoolExecutor(5) as pool: # each candidate's details in parallel, then judged in RxNorm's orderprops = list(pool.map(lambda r: self.rxnorm.properties(r) or {}, candidates))fit = [(r, p) for r, p in zip(candidates, props)if p.get("tty") in ("SCD", "SBD", "SCDC", "SBDC", "GPCK", "BPCK")and re.search(rf"(?<![\d.]){re.escape(number)}(?![\d])", p.get("name", ""))]wanted_names = [n.lower() for _, n in ingredients]# a clinical drug's name lists its ingredients ("acetaminophen 500 MG Oral Tablet"): no lookup needednamed = [all(n in p["name"].lower() for n in wanted_names) for _, p in fit]ingredients_of = list(pool.map(lambda rp: None if rp[1] else self.rxnorm.ingredients(rp[0][0]),zip(fit, named)))fallback = Nonefor (rxcui, p), is_named, ins in zip(fit, named, ingredients_of):if is_named or want <= {r for r, _ in ins}:if not form or form in p["name"].lower():return rxcui, p["name"]fallback = fallback or (rxcui, p["name"]) # right medicine and strength, other dose formreturn fallbackdef read(self, lines):"""OCR lines -> candidate medicines, best first (steps 1-4)."""form = dose_form(lines)found_all = self.find_names(lines)with ThreadPoolExecutor(8) as pool: # RxNorm lookups in parallel (the client keeps to NLM's rate limit)ingredient_lists = list(pool.map(self._ingredients, found_all))groups = [{"found": [f], "ingredients": ing} for f, ing in zip(found_all, ingredient_lists) if ing]groups.sort(key=lambda g: -len(g["ingredients"])) # brands with several ingredients absorb their partsmerged = []for g in groups:keys = {r for r, _ in g["ingredients"]}home = next((m for m in merged if keys <= {r for r, _ in m["ingredients"]}), None)if home:home["found"] += g["found"]else:merged.append(g)plans = []for g in merged:found = sorted(g["found"], key=lambda f: (f.line, f.start))brand = next((f for f in found if f.tty == "BN"), None)strengths = []for f in found:if f.strength and f.strength not in strengths:strengths.append(f.strength)lead = brand or found[0]query = (lead.spelled or lead.text) if lead.tty != "INN" else " ".join(lead.us_names)plans.append((g, found, brand, strengths, lead, query))with ThreadPoolExecutor(8) as pool: # the exact products, in parallelproducts = list(pool.map(lambda p: self._product(p[5], p[3][0], form, p[0]["ingredients"])if len(p[3]) == 1 else None, plans))out = []for (g, found, brand, strengths, lead, _), product in zip(plans, products):printed = lead.spelled[:1].upper() + lead.spelled[1:] if lead.spelled else lead.textlabel = printed if not printed.isupper() else printed.capitalize()strength = strengths[0] if len(strengths) == 1 else ", ".join(strengths) or Noneout.append({"name": f"{label} {strength}" if strength else label,"brand": brand.text if brand else None,"ingredients": [{"rxcui": r, "name": n} for r, n in g["ingredients"]],"strength": strength,"rxcui": product[0] if product else (lead.rxcui if lead.tty != "INN" else g["ingredients"][0][0]),"rxnorm_name": product[1] if product else None,"found_in": [lines[i] for i in sorted({f.line for f in found})],"first_line": found[0].line,"_rank": (-(bool(brand) + bool(strengths) + bool(product) + len(found)), found[0].line),})out.sort(key=lambda c: c.pop("_rank"))return out# ---- what else a label or prescription says (blueprint job B7) -------------------------------------------------------DIRECTION_START = re.compile(r"^\s*(take|apply|use|inhale|instil+|insert|dissolve|chew|swallow|place|spray|give|put|"r"rub|gargle|dilute|one|two|1|2)\b", re.I)DIRECTION_WORDS = re.compile(r"\b(times? (a|per) day|(once|twice|thrice) (a|per) day|daily|every \d+ hours?|"r"when necessary|as needed|at night|in the "r"morning|at bedtime|before (meals|food|breakfast)|after (meals|food|breakfast)|"r"with (meals|food)|on an empty stomach)\b", re.I)QUANTITY = re.compile(r"\b(?:qty|quantity|dispensed)\s*[:.]?\s*(\d+)\s*([a-z]*)|\b(\d+)\s+"r"(?:(?!(?:mg|mcg|g|ml|iu)\b)[a-z\-]+\s+)?(tablets?|capsules?|caplets?|tabs?|caps?|sachets?)\b",re.I)DATE = re.compile(r"\b(\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4}|\d{1,2} (?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"r"[a-z]* \d{4}|\d{1,2}[/.\-]\d{4})\b", re.I)PERSONAL = re.compile(r"\b(name|patient|nric|fin|address|tel|phone|dob|date of birth)\b", re.I)def _field(value, line):return {"value": value, "line": line} if value else Nonedef document_fields(lines, candidates):"""Per candidate, what the label prints about it, each value with the line it was read from; None when it isn'tprinted (never inferred). A candidate's block runs from its first line to the next candidate's (the first onealso gets the header lines above it: the dispensing date). Lines with personal details are never used."""starts = sorted({c["first_line"] for c in candidates})for c in candidates:i = starts.index(c["first_line"])lo = 0 if i == 0 else starts[i]hi = starts[i + 1] if i + 1 < len(starts) else len(lines)block = [(n, lines[n]) for n in range(lo, hi) if not PERSONAL.search(lines[n])]directions, quantity, date, expiry = [], None, None, Nonefor n, line in block:is_direction = n >= c["first_line"] and (DIRECTION_START.search(line) and DIRECTION_WORDS.search(line)or (directions and directions[-1][0] == n - 1and DIRECTION_WORDS.search(line)))if is_direction:directions.append((n, line))continueq = QUANTITY.search(line)if q and quantity is None and n >= c["first_line"] and line not in c["found_in"]:number, unit = (q.group(1), q.group(2)) if q.group(1) else (q.group(3), q.group(4))quantity = _field(f"{number} {unit.lower()}".strip(), line)d = DATE.search(line)if d:if re.search(r"\bexp", line, re.I):expiry = expiry or _field(d.group(1), line)else:date = date or _field(d.group(1), line)form = dose_form([line for n, line in block if n >= c["first_line"]])c["fields"] = {"directions": _field(" ".join(l for _, l in directions), " / ".join(l for _, l in directions)),"quantity": quantity,"dose_form": _field(form, next((l for n, l in block if n >= c["first_line"] and form andre.search(form[:5], l, re.I)), None)),"date": date,"expiry_date": expiry,}return candidates# ---- is this box one of my medicines? (blueprint job B9) -------------------------------------------------------------def _amounts(strength):"""'500 mg, 65 mg' or '500 MG / 65 MG' -> {(500.0, 'mg'), (65.0, 'mg')}."""return {(float(m.group(1).replace(",", ".")), m.group(2).lower().replace("µg", "mcg").replace("ug", "mcg"))for m in STRENGTH.finditer(strength or "")}def compare_with_list(candidate, medications):"""medications: the patient's list, each {"id", "name", "ingredients": {rxcui}, "strength": printed or None}.-> {"status", "medication_id", "message"}: a deterministic comparison of ingredients and strength, no model score.same_medicine same ingredients and strength (or the list gives no strength)different_strength same ingredients, another strengthcontains_listed a combination that includes a listed medicine's ingredientnot_on_list no ingredient in common"""have = {i["rxcui"] for i in candidate["ingredients"] if i.get("rxcui")}best = Nonefor med in medications:common = have & med["ingredients"]if not common:continueif common == have == med["ingredients"]:a, b = _amounts(candidate.get("strength")), _amounts(med.get("strength"))if a and b and a != b:status = "different_strength"message = (f"This says {candidate.get('strength')}; your list has {med['name']}. Check with your ""pharmacist.")else:status = "same_medicine"message = f"This matches your {med['name']}: the same medicine" + \(" and strength." if a and b else ". Check the strength printed on it.")return {"status": status, "medication_id": med["id"], "message": message}best = best or {"status": "contains_listed", "medication_id": med["id"],"message": f"This medicine shares an ingredient with your {med['name']} but is not the same. ""Check with your pharmacist."}return best or {"status": "not_on_list", "medication_id": None,"message": "This medicine isn't on your list. Check with your pharmacist."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510"""Medicines on a box or pharmacy label (feature F8): OCR lines (imprint.ocr.ImprintReader.read_text) -> candidatemedicines with strength and RxNorm codes, to fill the medication list (and so the Stage 3 checks).1. Names: the lines are searched for RxNorm's ingredient and brand names (IN, PIN, BN: ~23,500, fetched once), plusinternational names RxNorm lacks (INN_TO_US: paracetamol -> acetaminophen). Phrases of 1-4 words match exactly(case and punctuation ignored), longest first; single words of 6+ letters also match with one OCR error (two from9 letters). Everyday words that happen to be names ("water", "relief") are skipped (COMMON).2. Strength: amounts with units after the name on its line, else the line's only amount, else the next line's whenthat line names nothing ("10 mg" printed under "atorvastatin calcium").3. RxNorm: name + strength -> the product concept (e.g. "atorvastatin 10 MG Oral Tablet [Lipitor]"), kept only if ithas the name's ingredients and its strength; the ingredients always come from RxNorm.4. Names whose ingredients are the same, or a subset of a brand's (paracetamol and caffeine under Panadol Extra),merge into one candidate. Best first: most evidence, then the order on the label.RxNorm's own match scores are not used to find names: there, "Take 2 tablets 4 times a day" scores higher than"PARACETAMOL 500MG TABLET"."""import refrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field# international (INN/BAN, as printed in Singapore) -> RxNorm's US names; a list for combinationsINN_TO_US = {"paracetamol": ["acetaminophen"], "salbutamol": ["albuterol"], "adrenaline": ["epinephrine"],"noradrenaline": ["norepinephrine"], "frusemide": ["furosemide"], "glibenclamide": ["glyburide"],"lignocaine": ["lidocaine"], "amoxycillin": ["amoxicillin"], "cefalexin": ["cephalexin"],"clavulanic acid": ["clavulanate"], "potassium clavulanate": ["clavulanate"],"chlorphenamine": ["chlorpheniramine"], "mesalazine": ["mesalamine"], "pethidine": ["meperidine"],"thyroxine": ["levothyroxine"], "sodium valproate": ["valproate"], "isoprenaline": ["isoproterenol"],"aciclovir": ["acyclovir"], "ciclosporin": ["cyclosporine"], "colecalciferol": ["cholecalciferol"],"rifampicin": ["rifampin"], "beclometasone": ["beclomethasone"], "dexamfetamine": ["dextroamphetamine"],"glyceryl trinitrate": ["nitroglycerin"], "phenobarbitone": ["phenobarbital"], "oestradiol": ["estradiol"],"eformoterol": ["formoterol"], "colestyramine": ["cholestyramine"], "clomifene": ["clomiphene"],"orciprenaline": ["metaproterenol"], "oxpentifylline": ["pentoxifylline"], "dothiepin": ["dosulepin"],"co-amoxiclav": ["amoxicillin", "clavulanate"], "co-trimoxazole": ["sulfamethoxazole", "trimethoprim"],"co-codamol": ["acetaminophen", "codeine"],}# words on boxes and labels that are also RxNorm names, never a medicine on their ownCOMMON = {"water", "sugar", "salt", "relief", "extra", "fast", "film", "coated", "tablet", "tablets", "capsule", "capsules","oral", "daily", "night", "day", "care", "plus", "forte", "max", "ultra", "rapid", "soft", "children", "adult","adults", "junior", "baby", "cold", "flu", "pain", "fever", "allergy", "sleep", "cough", "clear", "active","original", "advance", "advanced", "complete", "health", "natural", "gold", "silver", "oxygen", "air", "alcohol","glycerin", "talc", "starch", "lactose", "gelatin", "cellulose", "iron", "calcium", "sodium", "potassium","magnesium", "zinc", "acid", "hydrochloride", "clinic", "pharmacy", "medicine", "tan", "lim", "lee", "ong", "ng",}UNIT = r"(?:mg|mcg|µg|ug|g|ml|iu|units?|%)"STRENGTH = re.compile(rf"(\d+(?:[.,]\d+)?)\s*({UNIT})(?:\s*/\s*(\d+(?:[.,]\d+)?)?\s*({UNIT}|tab|cap)s?)?(?![a-z])",re.I)# dose forms as printed -> as RxNorm names themFORMS = {"tablet": "tablet", "tab": "tablet", "caplet": "tablet", "capsule": "capsule", "cap": "capsule","syrup": "solution", "solution": "solution", "suspension": "suspension", "cream": "cream","ointment": "ointment", "gel": "gel", "injection": "injection", "drops": "drops", "inhaler": "inhal","patch": "patch", "spray": "spray", "suppository": "suppository"}def norm(text):return " ".join(re.sub(r"[^a-z0-9]+", " ", str(text).lower()).split())INN = {norm(k): v for k, v in INN_TO_US.items()}def dose_form(lines):"""The first dose form printed anywhere on the label, as RxNorm names it, or None."""for line in lines:for word in re.findall(r"[a-z]+", line.lower()):word = word[:-1] if word.endswith("s") and word[:-1] in FORMS else wordif word in FORMS:return FORMS[word]return Nonedef _edits(a, b, limit):"""Levenshtein distance, or limit + 1 once it exceeds limit."""if abs(len(a) - len(b)) > limit:return limit + 1prev = list(range(len(b) + 1))for i, ca in enumerate(a, 1):cur = [i] + [0] * len(b)for j, cb in enumerate(b, 1):cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))if min(cur) > limit:return limit + 1prev = curreturn prev[-1]def _strength_text(m):amount, unit, per_amount, per_unit = m.groups()unit = unit.lower().replace("µg", "mcg").replace("ug", "mcg")text = f"{amount.replace(',', '.')}{'' if unit == '%' else ' '}{unit}"if per_unit:text += f"/{per_amount + ' ' if per_amount else ''}{per_unit.lower()}"return text@dataclassclass Found:line: intstart: intend: inttext: str # as printedrxcui: strtty: str # IN, PIN, BN, or INN for a mapped international nameus_names: list = field(default_factory=list)spelled: str | None = None # RxNorm's spelling when the printed word was misread (fuzzy match)strength: str | None = Noneclass LabelReader:def __init__(self, rxnorm):self.rxnorm = rxnormself._vocab = None@propertydef vocab(self):"""normalised name -> (rxcui, tty), and single words by length for the fuzzy match; fetched once."""if self._vocab is None:concepts = self.rxnorm.get("allconcepts.json", tty="IN PIN BN")["minConceptGroup"]["minConcept"]names = {}for c in concepts:key = norm(c["name"])if key and key not in COMMON and len(key) >= 4 and (key not in names or c["tty"] == "IN"):names[key] = (c["rxcui"], c["tty"], c["name"])by_len = {}for key in names:if " " not in key and len(key) >= 6 and not key.isdigit():by_len.setdefault(len(key), []).append(key)self._vocab = (names, by_len)return self._vocabdef _lookup(self, phrase):names, by_len = self.vocabif phrase in INN:first = names.get(INN[phrase][0])return (first[0] if first else None), "INN", INN[phrase], Noneif phrase in names:return names[phrase][0], names[phrase][1], [], Noneif " " not in phrase and len(phrase) >= 6 and not any(ch.isdigit() for ch in phrase):limit = 1 if len(phrase) < 9 else 2for n in range(len(phrase) - limit, len(phrase) + limit + 1):for key in by_len.get(n, ()):if key[0] == phrase[0] and _edits(phrase, key, limit) <= limit:return names[key][0], names[key][1], [], names[key][2]return Nonedef find_names(self, lines):"""Each medicine name in the lines, with its strength (steps 1 and 2)."""found = []for li, line in enumerate(lines):if (CAUTION.search(line) or CAUTION_START.match(line)) and not STRENGTH.search(line):continue # "Avoid grapefruit juice", "Do not take with aspirin": named, but not what was dispensedwords = [(m.start(), m.end(), m.group().lower()) for m in re.finditer(r"[A-Za-z][A-Za-z\-]*", line)]i = 0while i < len(words):for n in range(min(4, len(words) - i), 0, -1):phrase = norm(" ".join(w for _, _, w in words[i:i + n]))hit = self._lookup(phrase) if phrase and phrase not in COMMON else Noneif hit and hit[0]:start, end = words[i][0], words[i + n - 1][1]found.append(Found(li, start, end, line[start:end], hit[0], hit[1], hit[2], hit[3]))i += nbreakelse:i += 1for f in found: # strengthssame = [f2 for f2 in found if f2.line == f.line and f2.start > f.start]stop = min((f2.start for f2 in same), default=None)amounts = list(STRENGTH.finditer(lines[f.line]))after = [m for m in amounts if m.start() >= f.end and (stop is None or m.start() < stop)]if after:f.strength = _strength_text(after[0])elif len(amounts) == 1 and len([f2 for f2 in found if f2.line == f.line]) == 1:f.strength = _strength_text(amounts[0])elif f.line + 1 < len(lines) and not any(f2.line == f.line + 1 for f2 in found):nxt = list(STRENGTH.finditer(lines[f.line + 1]))if nxt:f.strength = _strength_text(nxt[0])return founddef _ingredients(self, f):"""(rxcui, name) of the active ingredients. An ingredient name found in the list is its own answer (noRxNorm call: each costs up to a second from Singapore); brands and salts ask RxNorm."""names = self.vocab[0]if f.tty == "INN":known = [names.get(us) for us in f.us_names]if all(k and k[1] == "IN" for k in known):return sorted({(k[0], us) for k, us in zip(known, f.us_names)}, key=lambda x: x[1])out = []for us in f.us_names:rxcui = self.rxnorm.rxcui_by_name(us)out += self.rxnorm.ingredients(rxcui) if rxcui else []return sorted(set(out), key=lambda x: x[1])if f.tty == "IN":return [(f.rxcui, (f.spelled or f.text).lower())] # RxNorm's ingredient name, as printed or correctedreturn self.rxnorm.ingredients(f.rxcui)def _product(self, name, strength, form, ingredients):"""RxNorm's concept for name + strength, if it has these ingredients and this strength (step 3)."""number = re.match(r"[\d.]+", strength).group()want = {r for r, _ in ingredients}candidates = [r for r, _ in self.rxnorm.approximate(" ".join(filter(None, (name, strength, form))))]with ThreadPoolExecutor(5) as pool: # each candidate's details in parallel, then judged in RxNorm's orderprops = list(pool.map(lambda r: self.rxnorm.properties(r) or {}, candidates))fit = [(r, p) for r, p in zip(candidates, props)if p.get("tty") in ("SCD", "SBD", "SCDC", "SBDC", "GPCK", "BPCK")and re.search(rf"(?<![\d.]){re.escape(number)}(?![\d])", p.get("name", ""))]wanted_names = [n.lower() for _, n in ingredients]# a clinical drug's name lists its ingredients ("acetaminophen 500 MG Oral Tablet"): no lookup needednamed = [all(n in p["name"].lower() for n in wanted_names) for _, p in fit]ingredients_of = list(pool.map(lambda rp: None if rp[1] else self.rxnorm.ingredients(rp[0][0]),zip(fit, named)))fallback = Nonefor (rxcui, p), is_named, ins in zip(fit, named, ingredients_of):if is_named or want <= {r for r, _ in ins}:if not form or form in p["name"].lower():return rxcui, p["name"]fallback = fallback or (rxcui, p["name"]) # right medicine and strength, other dose formreturn fallbackdef read(self, lines):"""OCR lines -> candidate medicines, best first (steps 1-4)."""form = dose_form(lines)found_all = self.find_names(lines)with ThreadPoolExecutor(8) as pool: # RxNorm lookups in parallel (the client keeps to NLM's rate limit)ingredient_lists = list(pool.map(self._ingredients, found_all))groups = [{"found": [f], "ingredients": ing} for f, ing in zip(found_all, ingredient_lists) if ing]groups.sort(key=lambda g: -len(g["ingredients"])) # brands with several ingredients absorb their partsmerged = []for g in groups:keys = {r for r, _ in g["ingredients"]}home = next((m for m in merged if keys <= {r for r, _ in m["ingredients"]}), None)if home:home["found"] += g["found"]else:merged.append(g)plans = []for g in merged:found = sorted(g["found"], key=lambda f: (f.line, f.start))brand = next((f for f in found if f.tty == "BN"), None)strengths = []for f in found:if f.strength and f.strength not in strengths:strengths.append(f.strength)lead = brand or found[0]query = (lead.spelled or lead.text) if lead.tty != "INN" else " ".join(lead.us_names)plans.append((g, found, brand, strengths, lead, query))with ThreadPoolExecutor(8) as pool: # the exact products, in parallelproducts = list(pool.map(lambda p: self._product(p[5], p[3][0], form, p[0]["ingredients"])if len(p[3]) == 1 else None, plans))out = []for (g, found, brand, strengths, lead, _), product in zip(plans, products):printed = lead.spelled[:1].upper() + lead.spelled[1:] if lead.spelled else lead.textlabel = printed if not printed.isupper() else printed.capitalize()strength = strengths[0] if len(strengths) == 1 else ", ".join(strengths) or Noneout.append({"name": f"{label} {strength}" if strength else label,"brand": brand.text if brand else None,"ingredients": [{"rxcui": r, "name": n} for r, n in g["ingredients"]],"strength": strength,"rxcui": product[0] if product else (lead.rxcui if lead.tty != "INN" else g["ingredients"][0][0]),"rxnorm_name": product[1] if product else None,"found_in": [lines[i] for i in sorted({f.line for f in found})],"first_line": found[0].line,"_rank": (-(bool(brand) + bool(strengths) + bool(product) + len(found)), found[0].line),})out.sort(key=lambda c: c.pop("_rank"))return out# ---- what else a label or prescription says (blueprint job B7) -------------------------------------------------------DIRECTION_START = re.compile(r"^\s*(take|apply|use|inhale|instil+|insert|dissolve|chew|swallow|place|spray|give|put|"r"rub|gargle|dilute|one|two|1|2)\b", re.I)DIRECTION_WORDS = re.compile(r"\b(times? (a|per) day|times daily|(once|twice|thrice) (a|per) day|daily|"r"every \d+ hours?|every (morning|night|evening|day)|when necessary|as needed|if needed|"r"as required|at night|in the morning|in the evening|at bedtime|before (bed|sleep)|"r"before (meals?|food|breakfast|lunch|dinner)|after (meals?|food|breakfast|lunch|dinner)|"r"with (meals?|food)|with or without (food|meals?)|on an empty stomach)\b", re.I)# pharmacy shorthand, upper case only ("ON" is also an ordinary word, so only right after the dose: "1 TAB ON")ABBREVIATION = re.compile(r"\b(BD|BID|TDS|TID|QDS|QID|OD|OM|PRN)\b|\b(?:TABS?|TABLETS?|CAPS?|CAPSULES?)\s+ON\b")QUANTITY = re.compile(r"\b(?:qty|quantity|dispensed)\s*[:.]?\s*(\d+)\s*([a-z]*)|\b(\d+)\s+"r"(?:(?!(?:mg|mcg|g|ml|iu)\b)[a-z\-]+\s+)?(tablets?|capsules?|caplets?|tabs?|caps?|sachets?)\b",re.I)DATE = re.compile(r"\b(\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4}|\d{1,2} (?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"r"[a-z]* \d{4}|\d{1,2}[/.\-]\d{4})\b", re.I)PERSONAL = re.compile(r"\b(name|patient|nric|fin|address|tel|phone|dob|date of birth)\b", re.I)def _field(value, line):return {"value": value, "line": line} if value else None# ---- a Singapore dispensing label, field by field --------------------------------------------------------------------# The pharmacy sticker on the bag or box: medicine and strength, quantity, then the instructions ("Take 1 tablet twice# a day after food"), often what it is for ("For high blood pressure") and cautions ("May cause drowsiness").# Everything is parsed from what is printed; a part that isn't printed stays None.NUMBER_WORDS = {"half": 0.5, "½": 0.5, "1/2": 0.5, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6,"once": 1, "twice": 2, "thrice": 3}DOSE_UNITS = {"tablet": "tablet", "tab": "tablet", "caplet": "tablet", "capsule": "capsule", "cap": "capsule","ml": "ml", "puff": "puff", "drop": "drop", "sachet": "sachet", "teaspoon": "teaspoon", "tsp": "teaspoon","patch": "patch", "spray": "spray", "suppository": "suppository", "lozenge": "lozenge","bottle": "bottle","tube": "tube", "box": "box", "inhaler": "inhaler"}_AMT = r"(\d+(?:\.\d+)?|½|1/2|half|one|two|three|four|five|six)"_UNIT = r"(tablets?|tabs?|caplets?|capsules?|caps?|ml|puffs?|drops?|sachets?|teaspoons?|tsps?|patch(?:es)?|sprays?|" \r"suppositor(?:y|ies)|lozenges?)"DOSE = re.compile(rf"\b{_AMT}(?:\s*(?:to|-)\s*{_AMT})?\s*{_UNIT}\b", re.I)FREQUENCY = [ # (pattern, times a day); "every 8 hours" is kept as every_hours, never turned into times a day(re.compile(r"\b(\d|one|two|three|four|five|six)\s*(?:times?|x)\s*(?:a|per|each|every)?\s*(?:day|daily)\b", re.I),None),(re.compile(r"\b(once|twice|thrice)\s*(?:a|per|each|every)?\s*(?:day|daily)\b", re.I), None),(re.compile(r"\b(?:every|each)\s+day\b|\bdaily\b", re.I), 1),(re.compile(r"\bevery\s+(?:morning|night|evening)\b", re.I), 1),(re.compile(r"\b(?:OD|QD)\b"), 1), (re.compile(r"\b(?:BD|BID)\b"), 2), (re.compile(r"\b(?:TDS|TID)\b"), 3),(re.compile(r"\b(?:QDS|QID)\b"), 4),(re.compile(r"\bOM\b|\b(?:TABS?|TABLETS?|CAPS?|CAPSULES?)\s+ON\b"), 1), # every morning, every night]EVERY_HOURS = re.compile(r"\bevery\s+(\d+(?:\.\d+)?)\s*(?:-\s*\d+\s*)?(?:hours?|hrs?)\b", re.I)AS_NEEDED = re.compile(r"\b(when necessary|as needed|if needed|when needed|as required|when required|if required|"r"if necessary)\b|\bPRN\b", re.I)TIMES_OF_DAY = [("morning", re.compile(r"\bmorning\b|\b(?:tabs?|tablets?|caps?|capsules?)\s+OM\b", re.I)),("afternoon", re.compile(r"\bafternoon\b", re.I)), ("evening", re.compile(r"\bevening\b", re.I)),("night", re.compile(r"\bnight\b|\b(?:tabs?|tablets?|caps?|capsules?)\s+ON\b", re.I)),("bedtime", re.compile(r"\bbedtime\b|\bbefore (?:going to )?(?:bed|sleep)\b", re.I))]FOOD = [("with_or_without_food", re.compile(r"\bwith or without (?:food|meals?)\b", re.I)),("empty_stomach", re.compile(r"\bon an empty stomach\b", re.I)),("before_food", re.compile(r"\bbefore (?:food|meals?|breakfast|lunch|dinner|eating)\b", re.I)),("after_food", re.compile(r"\bafter (?:food|meals?|breakfast|lunch|dinner|eating)\b", re.I)),("with_food", re.compile(r"\bwith (?:food|meals?|a meal|milk)\b", re.I))]DURATION = re.compile(r"\bfor\s+(\d+|one|two|three|four|five|six|seven)\s+(days?|weeks?|months?)\b", re.I)MAX_PER_DAY = re.compile(r"\b(?:not more than|no more than|do not (?:take|exceed) more than|max(?:imum)?(?: of)?)\s+"r"(\d+)\s*([a-z]+)?\s*(?:in|per|a|within)\s+(?:any\s+)?(24 hours|day)\b", re.I)INDICATION = re.compile(r"(?:^|\b)(?:indications?\s*[:\-]|(?:this medicine is |used |it is )?for|to (treat|relieve|"r"reduce|lower|prevent|control))\s*:?\s+([a-z][a-z0-9 ,/&()'\-]{2,60})", re.I)NOT_INDICATION = re.compile(r"^(?:external|oral|internal|\d|one|two|three|four|five|six|seven|the next|up to|a day|"r"a week|days?|weeks?|use only)\b", re.I)CAUTION = re.compile(r"\b(drows|alcohol|do not drive|operat\w* machine|complete the (?:whole|full|entire) course|"r"finish the course|swallow (?:it )?whole|do not (?:crush|chew|break|cut)|shake well|refrigerat|"r"fridge|store (?:below|in|at)|keep (?:in|away|out of)|protect from|external use|avoid|"r"do not take (?:with|together)|may (?:cause|colour|color|discolou?r|make)|stop (?:taking|if)|"r"sun ?light|sunburn|dizz|grapefruit)", re.I)CAUTION_START = re.compile(r"^\s*(caution|warning|note|precaution|important)\b", re.I)def _unit(word):"""'capsules' -> 'capsule', 'tabs' -> 'tablet', 'patches' -> 'patch', 'suppositories' -> 'suppository'."""w = word.lower()for candidate in (w, w[:-1] if w.endswith("s") else w, w[:-2] if w.endswith("es") else w,w[:-3] + "y" if w.endswith("ies") else w):if candidate in DOSE_UNITS:return DOSE_UNITS[candidate]return w or Nonedef _number(word):return NUMBER_WORDS.get(word.lower(), None) if not re.match(r"\d", word) else float(word)def parse_instructions(text):"""'Take 1 tablet 2 times a day after food' -> the instruction's parts: dose (amount, amount_max for '1-2', unit),times_per_day, every_hours, as_needed, times_of_day, food, duration, max_per_day. A part that isn't printed isNone (or [] / False); nothing is filled in from habit (every 8 hours stays every_hours)."""t = re.sub(r"\(s\)", "", text or "")dose = Nonem = DOSE.search(t)if m:unit = _unit(m.group(3))dose = {"amount": _number(m.group(1)), "amount_max": _number(m.group(2)) if m.group(2) else None,"unit": unit}times = Nonefor pattern, fixed in FREQUENCY:f = pattern.search(t)if f:times = fixed if fixed is not None else int(_number(f.group(1)))breakevery = EVERY_HOURS.search(t)food = next((name for name, p in FOOD if p.search(t)), None)duration = DURATION.search(t)most = MAX_PER_DAY.search(t)return {"dose": dose, "times_per_day": times, "every_hours": float(every.group(1)) if every else None,"as_needed": bool(AS_NEEDED.search(t)),"times_of_day": [name for name, p in TIMES_OF_DAY if p.search(t)],"food": food,"duration": f"{duration.group(1)} {duration.group(2).lower()}" if duration else None,"max_per_day": " ".join(x for x in (most.group(1), (most.group(2) or "").lower(), "in", most.group(3).lower())if x) if most else None,}def parse_quantity(value):"""'60 tab' -> (60.0, 'tablet'); '100 ml' -> (100.0, 'ml')."""m = re.match(r"(\d+(?:\.\d+)?)\s*([a-z]*)", value or "", re.I)if not m:return None, Noneunit = _unit(m.group(2))return float(m.group(1)), unitdef indication_of(line):"""'For high blood pressure' -> 'high blood pressure'; None for 'for external use', 'for 5 days', ..."""for m in INDICATION.finditer(line):what = m.group(2).strip(" .,;:-")if what and not NOT_INDICATION.match(what) and not AS_NEEDED.fullmatch(what):return f"{m.group(1).lower()} {what}" if m.group(1) else what # 'to lower cholesterol' -> 'lower ...'return Nonedef document_fields(lines, candidates):"""Per candidate, what the label prints about it, each value with the line it was read from; None when it isn'tprinted (never inferred). A candidate's block runs from its first line to the next candidate's (the first onealso gets the header lines above it: the dispensing date). Lines with personal details are never used."""starts = sorted({c["first_line"] for c in candidates})for c in candidates:i = starts.index(c["first_line"])lo = 0 if i == 0 else starts[i]hi = starts[i + 1] if i + 1 < len(starts) else len(lines)block = [(n, lines[n]) for n in range(lo, hi) if not PERSONAL.search(lines[n])]directions, quantity, date, expiry, indication, cautions = [], None, None, None, None, []for n, line in block:is_direction = n >= c["first_line"] and (DIRECTION_START.search(line) and (DIRECTION_WORDS.search(line) or ABBREVIATION.search(line)or DOSE.search(line))or (directions and directions[-1][0] == n - 1and (DIRECTION_WORDS.search(line) or ABBREVIATION.search(line) or MAX_PER_DAY.search(line))))if n >= c["first_line"] and line not in c["found_in"]:indication = indication or _field(indication_of(line), line)if is_direction:directions.append((n, line))cautions += [s.strip() for s in re.split(r"(?<=[.;!])\s+", line) if CAUTION.search(s)]continueif n >= c["first_line"] and line not in c["found_in"] and \(CAUTION.search(line) or CAUTION_START.match(line)) and not DATE.search(line):cautions.append(line.strip())continueq = QUANTITY.search(line)# an explicit "Qty:" also counts on the name's own line, or just above it (a tilted photo puts the right# end of "METFORMIN 500MG TABLET Qty: 60 TAB" a little higher, so it is read first)if q and quantity is None and (n >= c["first_line"] or q.group(1)) and \(line not in c["found_in"] or q.group(1)):number, unit = (q.group(1), q.group(2)) if q.group(1) else (q.group(3), q.group(4))quantity = _field(f"{number} {unit.lower()}".strip(), line)d = DATE.search(line)if d:if re.search(r"\bexp", line, re.I):expiry = expiry or _field(d.group(1), line)else:date = date or _field(d.group(1), line)form = dose_form([line for n, line in block if n >= c["first_line"]])text = " ".join(l for _, l in directions)if quantity:quantity["amount"], quantity["unit"] = parse_quantity(quantity["value"])c["fields"] = {"directions": _field(text, " / ".join(l for _, l in directions)),"instructions": {"text": text, "line": " / ".join(l for _, l in directions), **parse_instructions(text)}if directions else None,"indication": indication,"cautions": [{"value": s, "line": s} for s in dict.fromkeys(cautions)],"quantity": quantity,"dose_form": _field(form, next((l for n, l in block if n >= c["first_line"] and form andre.search(form[:5], l, re.I)), None)),"date": date,"expiry_date": expiry,}return candidates# ---- is this box one of my medicines? (blueprint job B9) -------------------------------------------------------------def _amounts(strength):"""'500 mg, 65 mg' or '500 MG / 65 MG' -> {(500.0, 'mg'), (65.0, 'mg')}."""return {(float(m.group(1).replace(",", ".")), m.group(2).lower().replace("µg", "mcg").replace("ug", "mcg"))for m in STRENGTH.finditer(strength or "")}def compare_with_list(candidate, medications):"""medications: the patient's list, each {"id", "name", "ingredients": {rxcui}, "strength": printed or None}.-> {"status", "medication_id", "message"}: a deterministic comparison of ingredients and strength, no model score.same_medicine same ingredients and strength (or the list gives no strength)different_strength same ingredients, another strengthcontains_listed a combination that includes a listed medicine's ingredientnot_on_list no ingredient in common"""have = {i["rxcui"] for i in candidate["ingredients"] if i.get("rxcui")}best = Nonefor med in medications:common = have & med["ingredients"]if not common:continueif common == have == med["ingredients"]:a, b = _amounts(candidate.get("strength")), _amounts(med.get("strength"))if a and b and a != b:status = "different_strength"message = (f"This says {candidate.get('strength')}; your list has {med['name']}. Check with your ""pharmacist.")else:status = "same_medicine"message = f"This matches your {med['name']}: the same medicine" + \(" and strength." if a and b else ". Check the strength printed on it.")return {"status": status, "medication_id": med["id"], "message": message}best = best or {"status": "contains_listed", "medication_id": med["id"],"message": f"This medicine shares an ingredient with your {med['name']} but is not the same. ""Check with your pharmacist."}return best or {"status": "not_on_list", "medication_id": None,"message": "This medicine isn't on your list. Check with your pharmacist."}
serving/app/evidence.py+22-4
serving/app/main.py+12-6
serving/app/schemas.py+34-1
serving/app/tools.py+96-95
src/epills/core/imprint/ocr.py+5
src/epills/core/label.py+510-368