#!/usr/bin/env python3 """Lot Report v1 validator (reference implementation, Python 3.8+, standard library only). Usage: python3 lot_report_validate.py lots.json # a local file python3 lot_report_validate.py https://example.com/.well-known/lots.json python3 lot_report_validate.py --check-documents lots.json # also download each # report and compare SHA-256 Exit status: 0 = valid (warnings allowed), 1 = errors found, 2 = could not read input. Spec: https://lodgepeptides.com/lot-report/ Licence: CC0 1.0 (public domain dedication). """ import sys, json, re, hashlib, datetime, urllib.request SCHEMA_URL = "https://lodgepeptides.com/lot-report/v1/schema.json" VERSION = "1.0.0" # ---------------------------------------------------------------- schema subset # A small JSON Schema 2020-12 evaluator covering exactly the keywords the # Lot Report v1 schema uses. If the full schema file sits next to this script # it is used; otherwise the embedded copy (identical) is used. def _load_schema(): import os p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "schema.json") try: with open(p, encoding="utf-8") as f: return json.load(f) except OSError: return json.loads(_EMBEDDED_SCHEMA) _DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") _DATETIME = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$") def _type_ok(v, t): return { "object": isinstance(v, dict), "array": isinstance(v, list), "string": isinstance(v, str), "number": isinstance(v, (int, float)) and not isinstance(v, bool), "integer": isinstance(v, int) and not isinstance(v, bool), "boolean": isinstance(v, bool), "null": v is None, }[t] def _format_ok(v, fmt): if fmt == "date": if not _DATE.match(v): return False try: datetime.date.fromisoformat(v); return True except ValueError: return False if fmt == "date-time": if not _DATETIME.match(v): return False try: datetime.datetime.fromisoformat(v.replace("Z", "+00:00").replace("z", "+00:00")); return True except ValueError: return False if fmt == "uri": return bool(re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:[^\s]*$", v)) return True def _validate(inst, sch, root, path, errs): if sch is True: return if "$ref" in sch: ref = sch["$ref"]; assert ref.startswith("#/$defs/") _validate(inst, root["$defs"][ref[8:]], root, path, errs) t = sch.get("type") if t and not _type_ok(inst, t): errs.append((path, f"must be of type {t}")); return if "const" in sch and inst != sch["const"]: errs.append((path, f"must equal {sch['const']!r}")) if "enum" in sch and inst not in sch["enum"]: errs.append((path, "must be one of: " + ", ".join(map(str, sch["enum"])))) if isinstance(inst, str): if len(inst) < sch.get("minLength", 0): errs.append((path, "must not be empty")) if "maxLength" in sch and len(inst) > sch["maxLength"]: errs.append((path, f"must be at most {sch['maxLength']} characters")) if "pattern" in sch and not re.search(sch["pattern"], inst): errs.append((path, f"must match pattern {sch['pattern']}")) if "format" in sch and not _format_ok(inst, sch["format"]): errs.append((path, f"must be a valid {sch['format']}")) if isinstance(inst, (int, float)) and not isinstance(inst, bool): if "minimum" in sch and inst < sch["minimum"]: errs.append((path, f"must be >= {sch['minimum']}")) if "maximum" in sch and inst > sch["maximum"]: errs.append((path, f"must be <= {sch['maximum']}")) if isinstance(inst, list): if len(inst) < sch.get("minItems", 0): errs.append((path, f"must have at least {sch['minItems']} item(s)")) if "items" in sch: for i, v in enumerate(inst): _validate(v, sch["items"], root, f"{path}/{i}", errs) for sub in sch.get("allOf", []): _validate(inst, sub, root, path, errs) if "if" in sch: probe = []; _validate(inst, sch["if"], root, path, probe) branch = sch.get("then") if not probe else sch.get("else") if branch: _validate(inst, branch, root, path, errs) if isinstance(inst, dict): if len(inst) < sch.get("minProperties", 0): errs.append((path, "must not be empty")) for k in sch.get("required", []): if k not in inst: errs.append((path, f"missing required property '{k}'")) props = sch.get("properties", {}); pats = sch.get("patternProperties", {}) for k, v in inst.items(): matched = False if k in props: _validate(v, props[k], root, f"{path}/{k}", errs); matched = True for p, s in pats.items(): if re.search(p, k): _validate(v, s, root, f"{path}/{k}", errs); matched = True if not matched: ap = sch.get("additionalProperties", True) if ap is False: errs.append((f"{path}/{k}", "is not a recognised property (use an x- prefix for extensions)")) elif isinstance(ap, dict): _validate(v, ap, root, f"{path}/{k}", errs) # ---------------------------------------------------------------- semantic lint def lint(doc): """Checks a schema cannot express. Returns (errors, warnings) lists of (path, message).""" E, W = [], [] if not isinstance(doc, dict) or not isinstance(doc.get("lots"), list): return E, W updated = None try: updated = datetime.datetime.fromisoformat(str(doc.get("updated", "")).replace("Z", "+00:00")).date() except ValueError: pass if doc.get("$schema") not in (None, SCHEMA_URL): W.append(("/$schema", f"expected {SCHEMA_URL}")) pub = doc.get("publisher") or {} if isinstance(pub, dict) and not pub.get("contact"): W.append(("/publisher", "no contact for corrections")) seen = {} def https(path, url): if isinstance(url, str) and url.startswith("http://"): W.append((path, "use https")) if isinstance(pub, dict): https("/publisher/url", pub.get("url")) for i, lot in enumerate(doc["lots"]): lp = f"/lots/{i}" if not isinstance(lot, dict): continue prod = lot.get("product") or {} key = (str(lot.get("lot", "")).strip().upper(), str(prod.get("name", "")).strip().lower()) if key in seen: E.append((lp + "/lot", f"duplicate lot '{lot.get('lot')}' for the same product (first at {seen[key]})")) else: seen[key] = lp https(lp + "/lot_url", lot.get("lot_url")); https(lp + "/product/url", prod.get("url")) claim = prod.get("label_claim") if isinstance(prod, dict) else None comp_claims = {c.get("name"): c.get("label_claim") for c in (prod.get("components") or []) if isinstance(c, dict)} if claim and comp_claims and all(isinstance(v, dict) for v in comp_claims.values()): units = {v.get("unit") for v in comp_claims.values()} if units == {claim.get("unit")}: s = sum(v.get("value", 0) for v in comp_claims.values()) if abs(s - claim.get("value", 0)) > 0.005 * max(1, claim.get("value", 0)): W.append((lp + "/product", f"component label claims sum to {s:g} but label_claim is {claim.get('value'):g}")) ids = set() for j, t in enumerate(lot.get("tests") or []): tp = f"{lp}/tests/{j}" if not isinstance(t, dict): continue ver0 = t.get("verification") if isinstance(t.get("verification"), dict) else {} rid = (str((t.get("lab") or {}).get("name", "")), t.get("report_id") or ver0.get("code") or ver0.get("url")) if rid in ids: W.append((tp + "/report_id", "same report listed twice for this lot")) ids.add(rid) https(tp + "/lab/url", (t.get("lab") or {}).get("url")) d = t.get("dates") or {} seq = [(k, d.get(k)) for k in ("received", "analyzed", "issued") if isinstance(d.get(k), str) and _format_ok(d.get(k), "date")] for (k1, v1), (k2, v2) in zip(seq, seq[1:]): if v2 < v1: E.append((tp + "/dates", f"{k2} ({v2}) is before {k1} ({v1})")) if updated: for k, v in seq: if datetime.date.fromisoformat(v) > updated: E.append((tp + f"/dates/{k}", f"{v} is after the document's updated date")) reference = "results" not in t # a pointer to the lab's own record: no figures to check doc_ = t.get("document") if reference: pass elif not doc_: W.append((tp, "no link to the original report document")) elif isinstance(doc_, dict): https(tp + "/document/url", doc_.get("url")) if not doc_.get("sha256"): W.append((tp + "/document", "no sha256: later edits to the file cannot be detected")) ver = t.get("verification") if not ver: W.append((tp, "no verification link or code: readers must trust the publisher's copy")) elif isinstance(ver, dict): https(tp + "/verification/url", ver.get("url")) if reference: continue r = t.get("results") or {} if not isinstance(r, dict): continue if "purity_percent" in r and not r.get("purity_basis"): W.append((tp + "/results", "purity_percent without purity_basis: say what the percentage is a fraction of")) if r.get("purity_percent") == 100: W.append((tp + "/results/purity_percent", "exactly 100%: check the reporting limit and rounding")) nc, fa = r.get("net_content"), r.get("fill_accuracy_percent") if isinstance(nc, dict) and isinstance(claim, dict): if nc.get("unit") != claim.get("unit"): W.append((tp + "/results/net_content", f"unit {nc.get('unit')} differs from label_claim unit {claim.get('unit')}")) elif isinstance(fa, (int, float)) and claim.get("value"): calc = nc["value"] / claim["value"] * 100 if abs(calc - fa) > 0.15: E.append((tp + "/results/fill_accuracy_percent", f"{fa} does not match net_content / label_claim x 100 = {calc:.1f}")) comps = r.get("components") or [] for k, c in enumerate(comps): if not isinstance(c, dict): continue cc = comp_claims.get(c.get("name")) cnc, cfa = c.get("net_content"), c.get("fill_accuracy_percent") if comp_claims and c.get("name") not in comp_claims: W.append((f"{tp}/results/components/{k}/name", f"'{c.get('name')}' is not one of product.components")) if isinstance(cc, dict) and isinstance(cnc, dict) and isinstance(cfa, (int, float)) and cc.get("value") and cc.get("unit") == cnc.get("unit"): calc = cnc["value"] / cc["value"] * 100 if abs(calc - cfa) > 0.15: E.append((f"{tp}/results/components/{k}/fill_accuracy_percent", f"{cfa} does not match {calc:.1f}")) if comps and isinstance(nc, dict) and all(isinstance((c or {}).get("net_content"), dict) and c["net_content"].get("unit") == nc.get("unit") for c in comps): s = sum(c["net_content"]["value"] for c in comps) if abs(s - nc["value"]) > 0.02 + 0.001 * nc["value"]: E.append((tp + "/results/net_content", f"components sum to {s:.2f} {nc.get('unit')}, total says {nc['value']}")) en = r.get("endotoxin") if isinstance(en, dict) and en.get("below_loq") and en.get("qualifier") != "<": E.append((tp + "/results/endotoxin", "below_loq is true but qualifier is not '<'")) if t.get("type") == "endotoxin" and not isinstance(en, dict): E.append((tp + "/results", "type is endotoxin but there is no endotoxin result")) if t.get("type") in ("purity", "purity_and_content") and "purity_percent" not in r and not comps: W.append((tp + "/results", "purity test without purity_percent")) return E, W def check_documents(doc, out): bad = 0 for i, lot in enumerate(doc.get("lots", [])): for j, t in enumerate(lot.get("tests", [])): d = t.get("document") or {} if not d.get("url") or not d.get("sha256"): continue try: req = urllib.request.Request(d["url"], headers={"User-Agent": "lot-report-validator/1.0"}) h = hashlib.sha256(urllib.request.urlopen(req, timeout=30).read()).hexdigest() except Exception as e: out.append(("WARN", f"/lots/{i}/tests/{j}/document", f"could not download: {e}")); continue if h != d["sha256"]: bad += 1; out.append(("ERROR", f"/lots/{i}/tests/{j}/document", f"sha256 mismatch: file is {h}")) return bad def validate(doc): """Returns (errors, warnings). Each is a list of (json_pointer, message).""" errs = [] _validate(doc, _load_schema(), _load_schema(), "", errs) E, W = lint(doc) return errs + E, W def main(argv): args = [a for a in argv[1:] if not a.startswith("--")] if len(args) != 1: print(__doc__.strip()); return 2 src = args[0] try: if re.match(r"^https?://", src): req = urllib.request.Request(src, headers={"User-Agent": "lot-report-validator/1.0"}) raw = urllib.request.urlopen(req, timeout=30).read().decode("utf-8") else: raw = open(src, encoding="utf-8").read() doc = json.loads(raw) except Exception as e: print(f"could not read {src}: {e}"); return 2 errs, warns = validate(doc) extra = [] if "--check-documents" in argv and not errs: check_documents(doc, extra) errs += [(p, m) for lvl, p, m in extra if lvl == "ERROR"] warns += [(p, m) for lvl, p, m in extra if lvl == "WARN"] for p, m in errs: print(f"ERROR {p or '/'}: {m}") for p, m in warns: print(f"WARN {p or '/'}: {m}") n = len(doc.get("lots", [])) if isinstance(doc, dict) and isinstance(doc.get("lots"), list) else 0 print(f"{'INVALID' if errs else 'VALID'}: {n} lot(s), {len(errs)} error(s), {len(warns)} warning(s)") return 1 if errs else 0 _EMBEDDED_SCHEMA = r'''{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://lodgepeptides.com/lot-report/v1/schema.json","title":"Lot Report v1","description":"An open, machine-readable format for publishing laboratory test results per production lot. Specification: https://lodgepeptides.com/lot-report/ . This schema is dedicated to the public domain under CC0 1.0.","type":"object","required":["lot_report_version","publisher","updated","lots"],"properties":{"$schema":{"type":"string","format":"uri","description":"URL of the schema this document claims to follow."},"lot_report_version":{"type":"string","pattern":"^1\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$","description":"Version of the Lot Report specification the document follows (SemVer, major version 1)."},"publisher":{"$ref":"#/$defs/publisher"},"updated":{"type":"string","format":"date-time","description":"When this document was last changed (RFC 3339)."},"license":{"type":"string","minLength":1,"description":"Licence for the data in this document: an SPDX identifier or a URL."},"lots":{"type":"array","items":{"$ref":"#/$defs/lot"}}},"patternProperties":{"^x-":true},"additionalProperties":false,"$defs":{"https_url":{"type":"string","format":"uri","pattern":"^https?://"},"date":{"type":"string","format":"date"},"quantity":{"type":"object","required":["value","unit"],"properties":{"value":{"type":"number","minimum":0},"unit":{"type":"string","enum":["g","mg","mcg","ng","IU","mL","mg/mL","mcg/mL","%"]}},"additionalProperties":false},"publisher":{"type":"object","required":["name","url"],"properties":{"name":{"type":"string","minLength":1},"url":{"$ref":"#/$defs/https_url"},"contact":{"type":"string","minLength":3,"description":"An email address or a URL where corrections can be sent."}},"patternProperties":{"^x-":true},"additionalProperties":false},"product":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1},"url":{"$ref":"#/$defs/https_url"},"sku":{"type":"string"},"label_claim":{"$ref":"#/$defs/quantity"},"form":{"type":"string","enum":["lyophilized_powder","solution","capsule","tablet","other"]},"components":{"type":"array","minItems":2,"items":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1},"label_claim":{"$ref":"#/$defs/quantity"},"cas":{"type":"string","pattern":"^[0-9]{2,7}-[0-9]{2}-[0-9]$"}},"additionalProperties":false}}},"patternProperties":{"^x-":true},"additionalProperties":false},"lot":{"type":"object","required":["lot","product","status","tests"],"properties":{"lot":{"type":"string","minLength":1,"maxLength":64,"description":"The lot or batch number exactly as printed on the label."},"product":{"$ref":"#/$defs/product"},"status":{"type":"string","enum":["current","previous","withdrawn","recalled"]},"lot_url":{"$ref":"#/$defs/https_url"},"label_details":{"type":"object","additionalProperties":{"type":"string"},"description":"Free-form identifying marks on the container, e.g. {\"cap_colour\": \"pink\"}."},"tests":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/test"}},"notes":{"type":"string"}},"patternProperties":{"^x-":true},"additionalProperties":false},"test":{"type":"object","required":["type","lab"],"properties":{"type":{"type":"string","enum":["purity","content","purity_and_content","identity","endotoxin","sterility","heavy_metals","residual_solvents","water_content","counter_ion","other"]},"lab":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1,"description":"The laboratory that issued the report."},"url":{"$ref":"#/$defs/https_url"},"performed_by":{"type":"string","description":"The laboratory that ran the analysis, if different from the issuer."},"accreditation":{"type":"string","description":"Accreditation standard and certificate number, if any, e.g. \"ISO/IEC 17025:2017, cert. 1234.01\"."}},"additionalProperties":false},"sample_submitted_by":{"type":"string","enum":["publisher","supplier","manufacturer","customer","independent","unknown"],"description":"Who sent the sample to the lab, in relation to the publisher."},"report_id":{"type":"string","minLength":1},"sample_id":{"type":"string"},"method":{"type":"string","minLength":1,"description":"Short technique name, e.g. \"HPLC-MS/MS\" or \"Kinetic chromogenic LAL\"."},"method_detail":{"type":"string","description":"Wavelength, column, compendial reference or other conditions."},"dates":{"type":"object","minProperties":1,"properties":{"received":{"$ref":"#/$defs/date"},"analyzed":{"$ref":"#/$defs/date"},"issued":{"$ref":"#/$defs/date"}},"additionalProperties":false},"results":{"$ref":"#/$defs/results"},"document":{"type":"object","required":["url"],"properties":{"url":{"$ref":"#/$defs/https_url"},"sha256":{"type":"string","pattern":"^[a-f0-9]{64}$"},"media_type":{"type":"string"}},"additionalProperties":false},"verification":{"type":"object","minProperties":1,"properties":{"url":{"$ref":"#/$defs/https_url"},"code":{"type":"string"}},"additionalProperties":false}},"patternProperties":{"^x-":true},"additionalProperties":false,"allOf":[{"if":{"type":"object","required":["results"],"properties":{"results":true}},"then":{"type":"object","required":["report_id","method","dates"],"properties":{"report_id":true,"method":true,"dates":true}},"else":{"type":"object","required":["verification"],"properties":{"verification":{"type":"object","required":["url"],"properties":{"url":true}}}}}]},"component_result":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1},"purity_percent":{"type":"number","minimum":0,"maximum":100},"net_content":{"$ref":"#/$defs/quantity"},"fill_accuracy_percent":{"type":"number","minimum":0}},"additionalProperties":false},"results":{"type":"object","minProperties":1,"properties":{"purity_percent":{"type":"number","minimum":0,"maximum":100},"purity_qualifier":{"type":"string","enum":["=",">=","<"],"default":"="},"purity_basis":{"type":"string","description":"What the percentage is a fraction of, e.g. \"HPLC peak area, 214 nm\"."},"net_content":{"$ref":"#/$defs/quantity"},"fill_accuracy_percent":{"type":"number","minimum":0},"identity":{"type":"string","enum":["conforms","does_not_conform","not_tested"]},"identity_detail":{"type":"string"},"endotoxin":{"type":"object","required":["qualifier","value","unit"],"properties":{"qualifier":{"type":"string","enum":["=","<",">"]},"value":{"type":"number","minimum":0},"unit":{"type":"string","enum":["EU/mg","EU/vial","EU/mL"]},"below_loq":{"type":"boolean"}},"additionalProperties":false},"components":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/component_result"}},"summary":{"type":"string"}},"patternProperties":{"^x-":true},"additionalProperties":false}}}''' if __name__ == "__main__": sys.exit(main(sys.argv))