medfence 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- medfence-0.1.0/LICENSE +202 -0
- medfence-0.1.0/PKG-INFO +192 -0
- medfence-0.1.0/README.md +165 -0
- medfence-0.1.0/medfence/__init__.py +25 -0
- medfence-0.1.0/medfence/checks/__init__.py +0 -0
- medfence-0.1.0/medfence/checks/grounding.py +323 -0
- medfence-0.1.0/medfence/checks/refdata.py +214 -0
- medfence-0.1.0/medfence/contract.py +117 -0
- medfence-0.1.0/medfence/data/refdata_seed.json +39 -0
- medfence-0.1.0/medfence/normalize.py +142 -0
- medfence-0.1.0/medfence/py.typed +0 -0
- medfence-0.1.0/medfence/rulepack.py +54 -0
- medfence-0.1.0/medfence/verify.py +170 -0
- medfence-0.1.0/medfence.egg-info/PKG-INFO +192 -0
- medfence-0.1.0/medfence.egg-info/SOURCES.txt +27 -0
- medfence-0.1.0/medfence.egg-info/dependency_links.txt +1 -0
- medfence-0.1.0/medfence.egg-info/top_level.txt +1 -0
- medfence-0.1.0/pyproject.toml +82 -0
- medfence-0.1.0/setup.cfg +4 -0
- medfence-0.1.0/tests/test_aggregate.py +56 -0
- medfence-0.1.0/tests/test_audit_json.py +134 -0
- medfence-0.1.0/tests/test_contract.py +263 -0
- medfence-0.1.0/tests/test_golden_gate.py +37 -0
- medfence-0.1.0/tests/test_grounding.py +218 -0
- medfence-0.1.0/tests/test_metamorphic.py +60 -0
- medfence-0.1.0/tests/test_normalize.py +181 -0
- medfence-0.1.0/tests/test_properties.py +142 -0
- medfence-0.1.0/tests/test_refdata.py +140 -0
- medfence-0.1.0/tests/test_rulepack.py +67 -0
medfence-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
medfence-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: medfence
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic, fail-closed verification harness for clinical LLM outputs
|
|
5
|
+
Author-email: Debanit Panigrahi <d.panigrahi.nitrkl@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Debanitrkl/medfence
|
|
8
|
+
Project-URL: Repository, https://github.com/Debanitrkl/medfence
|
|
9
|
+
Project-URL: Issues, https://github.com/Debanitrkl/medfence/issues
|
|
10
|
+
Keywords: llm,verification,clinical,healthcare,hallucination,guardrails,fail-closed,prescription,grounding
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Healthcare Industry
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# medfence
|
|
29
|
+
|
|
30
|
+
[](https://github.com/Debanitrkl/medfence/actions/workflows/ci.yml)
|
|
31
|
+
|
|
32
|
+
**A deterministic, fail-closed verification harness for clinical LLM outputs.**
|
|
33
|
+
|
|
34
|
+
LLM extraction is entering clinical workflows (scribes, prescription digitization,
|
|
35
|
+
lab-report parsing) faster than verification infrastructure is being built. Known
|
|
36
|
+
failure modes include fabricated medications, silently altered dosages, mg→mcg unit
|
|
37
|
+
swaps, and invented frequencies. `medfence` is the fence between model output and
|
|
38
|
+
clinical action: pure-function, zero-dependency, every verdict backed by
|
|
39
|
+
machine-checkable evidence.
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from medfence import verify, Extraction, SourceDocument
|
|
43
|
+
|
|
44
|
+
report = verify(
|
|
45
|
+
Extraction(artifact_type="prescription", payload=llm_output),
|
|
46
|
+
SourceDocument(text=ocr_text, modality="ocr", ocr_confidence=0.91),
|
|
47
|
+
)
|
|
48
|
+
report.overall # Verdict.PASS | Verdict.FAIL | Verdict.ABSTAIN
|
|
49
|
+
report.coverage # fraction of payload fields actually verified
|
|
50
|
+
report.to_audit_json() # one hash-chained JSON line per verification
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## The three guarantees
|
|
54
|
+
|
|
55
|
+
1. **Deterministic.** No I/O, no clock, no model calls inside `verify()`. Identical
|
|
56
|
+
`(source, extraction, rulepack)` → bit-identical report. Verdicts are reproducible
|
|
57
|
+
by strangers; that is what makes them auditable.
|
|
58
|
+
2. **Fail-closed.** `ABSTAIN` is a first-class verdict, not an error state. "Couldn't
|
|
59
|
+
check" routes to a human exactly like `FAIL`; it never silently becomes `PASS`.
|
|
60
|
+
Unknown artifact types, missing reference data, low-confidence OCR → `ABSTAIN`.
|
|
61
|
+
3. **No finding without evidence.** Every verdict carries a source span, a reference
|
|
62
|
+
bundle key, or a rule id. A check that cannot produce evidence must abstain.
|
|
63
|
+
|
|
64
|
+
And one deliberate refusal: **medfence never judges clinical appropriateness.**
|
|
65
|
+
`dose_in_range` answers "does 500 mg paracetamol exist as a marketed product?",
|
|
66
|
+
never "should this patient take it?" Fidelity and referential validity are
|
|
67
|
+
mechanically decidable; clinical judgment is not, and pretending otherwise is how
|
|
68
|
+
verification tools become unlicensed medical devices.
|
|
69
|
+
|
|
70
|
+
## Check families (v0)
|
|
71
|
+
|
|
72
|
+
**Family G: span grounding ("no span, no claim")**
|
|
73
|
+
Every extracted value must align to a span in the source, *localized to its own
|
|
74
|
+
medication's line*, because whole-document matching invites cross-medication collisions
|
|
75
|
+
(a 250 mg on someone else's line must not ground your altered strength).
|
|
76
|
+
Numbers and units match exact-after-normalization only; fuzzy-matching a dosage
|
|
77
|
+
is how a fence approves a hallucination. `unit_integrity` catches the mg↔mcg
|
|
78
|
+
class specifically. Fully ungrounded medication objects fail `no_orphans`
|
|
79
|
+
(the fabricated-drug detector).
|
|
80
|
+
|
|
81
|
+
**Family R: reference validity**
|
|
82
|
+
Drug names, marketed strengths, dose forms, and frequency tokens are checked
|
|
83
|
+
against a versioned, content-hashed Indian drug bundle and a closed grammar of
|
|
84
|
+
prescription shorthand (OD, BD, TDS, 1-0-1, SOS, …). Fuzzy lookup is allowed for
|
|
85
|
+
retrieval; a weak hit is `ABSTAIN`, never `PASS`.
|
|
86
|
+
|
|
87
|
+
## Benchmark
|
|
88
|
+
|
|
89
|
+
100 documents: 20 synthetic Indian OPD prescriptions × (1 clean + 4 seeded-error
|
|
90
|
+
variants). Reproduce with `python scripts/make_golden.py && python scripts/benchmark.py`.
|
|
91
|
+
|
|
92
|
+
| error class | n | FAIL | ABSTAIN | PASS | caught | **false PASS** |
|
|
93
|
+
|--------------------|---:|-----:|--------:|-----:|-------:|---------------:|
|
|
94
|
+
| fabricated_drug | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
95
|
+
| unit_swap | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
96
|
+
| altered_strength | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
97
|
+
| invented_frequency | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
98
|
+
| clean | 20 | 0 | 0 | 20 | n/a | (100% clean-pass) |
|
|
99
|
+
|
|
100
|
+
**Read this honestly:** 100% on a synthetic golden set means the set is easy, not
|
|
101
|
+
that the fence is finished. The seeded errors are clean single-fault injections on
|
|
102
|
+
noise-free text. The numbers that matter will come from real, anonymized,
|
|
103
|
+
OCR-noisy prescriptions. Contributions of anonymized hard cases are the most
|
|
104
|
+
valuable thing you can send this project.
|
|
105
|
+
|
|
106
|
+
## What v0 deliberately does not do
|
|
107
|
+
|
|
108
|
+
- Drug-drug interaction checking (v1 candidate, behind an explicit opt-in)
|
|
109
|
+
- Patient-contextual dosing (age/weight/renal): the SaMD line; we stay below it
|
|
110
|
+
- Auto-correction: medfence flags, it never fixes
|
|
111
|
+
- LLM-as-judge fallback: if deterministic checks can't verify it, a human sees it
|
|
112
|
+
- STT/word-timestamp evidence (the `Evidence` type is designed for it; v0 is OCR/text)
|
|
113
|
+
- **Omission detection**: `verify()` checks payload→source fidelity, not
|
|
114
|
+
source→payload completeness: a medication silently *dropped* by the extractor is
|
|
115
|
+
not caught. This gap is encoded as a strict-xfail test so it stays visible.
|
|
116
|
+
|
|
117
|
+
## Reference bundle
|
|
118
|
+
|
|
119
|
+
v0 ships `refdata-2026.07.0-seed`: ~27 common Indian OPD molecules with brand
|
|
120
|
+
aliases, forms, and marketed strengths, a deliberately small, versioned
|
|
121
|
+
placeholder for a proper CDSCO + NLEM + Jan Aushadhi normalization pass. The
|
|
122
|
+
bundle is content-hashed and the hash is pinned into every report, so verdicts
|
|
123
|
+
remain reproducible as the data grows.
|
|
124
|
+
|
|
125
|
+
## Testing & validation
|
|
126
|
+
|
|
127
|
+
The suite is deliberately heavier than the library; for a verification tool,
|
|
128
|
+
the tests *are* the product claim. Beyond unit tests, three layers guard the
|
|
129
|
+
contract:
|
|
130
|
+
|
|
131
|
+
- **Property-based** (`tests/test_properties.py`, Hypothesis): `verify()` is
|
|
132
|
+
total, fail-closed, and non-mutating over arbitrary junk payloads; reports are
|
|
133
|
+
bit-identical; clean-by-construction cases PASS and any corruption of them
|
|
134
|
+
never does; mg/mcg canonicalization never merges; aggregation matches an
|
|
135
|
+
independent worst-of oracle and is order-invariant and monotone.
|
|
136
|
+
- **Metamorphic** (`tests/test_metamorphic.py`): ~700 guarded corruptions
|
|
137
|
+
(digit edits, magnitude shifts, unit swaps, real-but-absent drug insertion,
|
|
138
|
+
in-grammar frequency swaps, …) applied to every clean golden case at test
|
|
139
|
+
time; none may PASS. Same fault taxonomy as the golden set, one
|
|
140
|
+
implementation (`scripts/corruptions.py`), two depths.
|
|
141
|
+
- **Golden gate** (`tests/test_golden_gate.py`): the benchmark as hard
|
|
142
|
+
assertions; false-PASS == 0 and clean-pass == 100% fail the build, and the
|
|
143
|
+
committed golden set must match its generator exactly.
|
|
144
|
+
|
|
145
|
+
Known v0 limitations are encoded as `xfail(strict=True)` tests (duplicate
|
|
146
|
+
medication names, trailing punctuation on frequencies, omission detection):
|
|
147
|
+
executable documentation that flips to a build failure the day the limitation
|
|
148
|
+
is fixed.
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
uv sync --group dev
|
|
152
|
+
uv run pytest # full suite (~750 tests, <5 s)
|
|
153
|
+
uv run pytest -m golden # just the benchmark gate
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Project layout
|
|
157
|
+
|
|
158
|
+
```
|
|
159
|
+
medfence/
|
|
160
|
+
contract.py # types + fail-closed aggregation (the stable core)
|
|
161
|
+
normalize.py # deterministic text/unit/number normalization
|
|
162
|
+
rulepack.py # bundle loading, thresholds-as-versioned-data
|
|
163
|
+
checks/grounding.py # Family G
|
|
164
|
+
checks/refdata.py # Family R
|
|
165
|
+
verify.py # the single entrypoint
|
|
166
|
+
data/refdata_seed.json
|
|
167
|
+
scripts/make_golden.py # regenerate the golden set (deterministic, no RNG)
|
|
168
|
+
scripts/benchmark.py # the table above (exits 1 on any false PASS)
|
|
169
|
+
scripts/corruptions.py # shared fault operators (golden set + metamorphic grid)
|
|
170
|
+
tests/ # contract invariants, properties, metamorphic grid, golden gate
|
|
171
|
+
tests/schemas/ # JSON Schema for the audit report (the output contract)
|
|
172
|
+
docs/adr-001-*.md # the design record
|
|
173
|
+
docs/related-work.md # how this differs from LangExtract, Guardrails, etc.
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Design record & positioning
|
|
177
|
+
|
|
178
|
+
See `docs/adr-001-clinical-verification-contract-v0.md` for the full contract
|
|
179
|
+
spec, options considered, and the trade-off analysis (notably: why ABSTAIN
|
|
180
|
+
exists, why coverage is a first-class output, and where the SaMD line is drawn).
|
|
181
|
+
For how medfence relates to LangExtract, Guardrails AI, clinical
|
|
182
|
+
self-verification, and the rest of the landscape, see `docs/related-work.md`.
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
Apache-2.0.
|
|
187
|
+
|
|
188
|
+
## Quick demo
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
python3 demo.py # one prescription: PASS, FAIL (mcg swap + fabricated drug), ABSTAIN (low OCR)
|
|
192
|
+
```
|
medfence-0.1.0/README.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# medfence
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Debanitrkl/medfence/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
**A deterministic, fail-closed verification harness for clinical LLM outputs.**
|
|
6
|
+
|
|
7
|
+
LLM extraction is entering clinical workflows (scribes, prescription digitization,
|
|
8
|
+
lab-report parsing) faster than verification infrastructure is being built. Known
|
|
9
|
+
failure modes include fabricated medications, silently altered dosages, mg→mcg unit
|
|
10
|
+
swaps, and invented frequencies. `medfence` is the fence between model output and
|
|
11
|
+
clinical action: pure-function, zero-dependency, every verdict backed by
|
|
12
|
+
machine-checkable evidence.
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from medfence import verify, Extraction, SourceDocument
|
|
16
|
+
|
|
17
|
+
report = verify(
|
|
18
|
+
Extraction(artifact_type="prescription", payload=llm_output),
|
|
19
|
+
SourceDocument(text=ocr_text, modality="ocr", ocr_confidence=0.91),
|
|
20
|
+
)
|
|
21
|
+
report.overall # Verdict.PASS | Verdict.FAIL | Verdict.ABSTAIN
|
|
22
|
+
report.coverage # fraction of payload fields actually verified
|
|
23
|
+
report.to_audit_json() # one hash-chained JSON line per verification
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## The three guarantees
|
|
27
|
+
|
|
28
|
+
1. **Deterministic.** No I/O, no clock, no model calls inside `verify()`. Identical
|
|
29
|
+
`(source, extraction, rulepack)` → bit-identical report. Verdicts are reproducible
|
|
30
|
+
by strangers; that is what makes them auditable.
|
|
31
|
+
2. **Fail-closed.** `ABSTAIN` is a first-class verdict, not an error state. "Couldn't
|
|
32
|
+
check" routes to a human exactly like `FAIL`; it never silently becomes `PASS`.
|
|
33
|
+
Unknown artifact types, missing reference data, low-confidence OCR → `ABSTAIN`.
|
|
34
|
+
3. **No finding without evidence.** Every verdict carries a source span, a reference
|
|
35
|
+
bundle key, or a rule id. A check that cannot produce evidence must abstain.
|
|
36
|
+
|
|
37
|
+
And one deliberate refusal: **medfence never judges clinical appropriateness.**
|
|
38
|
+
`dose_in_range` answers "does 500 mg paracetamol exist as a marketed product?",
|
|
39
|
+
never "should this patient take it?" Fidelity and referential validity are
|
|
40
|
+
mechanically decidable; clinical judgment is not, and pretending otherwise is how
|
|
41
|
+
verification tools become unlicensed medical devices.
|
|
42
|
+
|
|
43
|
+
## Check families (v0)
|
|
44
|
+
|
|
45
|
+
**Family G: span grounding ("no span, no claim")**
|
|
46
|
+
Every extracted value must align to a span in the source, *localized to its own
|
|
47
|
+
medication's line*, because whole-document matching invites cross-medication collisions
|
|
48
|
+
(a 250 mg on someone else's line must not ground your altered strength).
|
|
49
|
+
Numbers and units match exact-after-normalization only; fuzzy-matching a dosage
|
|
50
|
+
is how a fence approves a hallucination. `unit_integrity` catches the mg↔mcg
|
|
51
|
+
class specifically. Fully ungrounded medication objects fail `no_orphans`
|
|
52
|
+
(the fabricated-drug detector).
|
|
53
|
+
|
|
54
|
+
**Family R: reference validity**
|
|
55
|
+
Drug names, marketed strengths, dose forms, and frequency tokens are checked
|
|
56
|
+
against a versioned, content-hashed Indian drug bundle and a closed grammar of
|
|
57
|
+
prescription shorthand (OD, BD, TDS, 1-0-1, SOS, …). Fuzzy lookup is allowed for
|
|
58
|
+
retrieval; a weak hit is `ABSTAIN`, never `PASS`.
|
|
59
|
+
|
|
60
|
+
## Benchmark
|
|
61
|
+
|
|
62
|
+
100 documents: 20 synthetic Indian OPD prescriptions × (1 clean + 4 seeded-error
|
|
63
|
+
variants). Reproduce with `python scripts/make_golden.py && python scripts/benchmark.py`.
|
|
64
|
+
|
|
65
|
+
| error class | n | FAIL | ABSTAIN | PASS | caught | **false PASS** |
|
|
66
|
+
|--------------------|---:|-----:|--------:|-----:|-------:|---------------:|
|
|
67
|
+
| fabricated_drug | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
68
|
+
| unit_swap | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
69
|
+
| altered_strength | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
70
|
+
| invented_frequency | 20 | 20 | 0 | 0 | 100% | **0%** |
|
|
71
|
+
| clean | 20 | 0 | 0 | 20 | n/a | (100% clean-pass) |
|
|
72
|
+
|
|
73
|
+
**Read this honestly:** 100% on a synthetic golden set means the set is easy, not
|
|
74
|
+
that the fence is finished. The seeded errors are clean single-fault injections on
|
|
75
|
+
noise-free text. The numbers that matter will come from real, anonymized,
|
|
76
|
+
OCR-noisy prescriptions. Contributions of anonymized hard cases are the most
|
|
77
|
+
valuable thing you can send this project.
|
|
78
|
+
|
|
79
|
+
## What v0 deliberately does not do
|
|
80
|
+
|
|
81
|
+
- Drug-drug interaction checking (v1 candidate, behind an explicit opt-in)
|
|
82
|
+
- Patient-contextual dosing (age/weight/renal): the SaMD line; we stay below it
|
|
83
|
+
- Auto-correction: medfence flags, it never fixes
|
|
84
|
+
- LLM-as-judge fallback: if deterministic checks can't verify it, a human sees it
|
|
85
|
+
- STT/word-timestamp evidence (the `Evidence` type is designed for it; v0 is OCR/text)
|
|
86
|
+
- **Omission detection**: `verify()` checks payload→source fidelity, not
|
|
87
|
+
source→payload completeness: a medication silently *dropped* by the extractor is
|
|
88
|
+
not caught. This gap is encoded as a strict-xfail test so it stays visible.
|
|
89
|
+
|
|
90
|
+
## Reference bundle
|
|
91
|
+
|
|
92
|
+
v0 ships `refdata-2026.07.0-seed`: ~27 common Indian OPD molecules with brand
|
|
93
|
+
aliases, forms, and marketed strengths, a deliberately small, versioned
|
|
94
|
+
placeholder for a proper CDSCO + NLEM + Jan Aushadhi normalization pass. The
|
|
95
|
+
bundle is content-hashed and the hash is pinned into every report, so verdicts
|
|
96
|
+
remain reproducible as the data grows.
|
|
97
|
+
|
|
98
|
+
## Testing & validation
|
|
99
|
+
|
|
100
|
+
The suite is deliberately heavier than the library; for a verification tool,
|
|
101
|
+
the tests *are* the product claim. Beyond unit tests, three layers guard the
|
|
102
|
+
contract:
|
|
103
|
+
|
|
104
|
+
- **Property-based** (`tests/test_properties.py`, Hypothesis): `verify()` is
|
|
105
|
+
total, fail-closed, and non-mutating over arbitrary junk payloads; reports are
|
|
106
|
+
bit-identical; clean-by-construction cases PASS and any corruption of them
|
|
107
|
+
never does; mg/mcg canonicalization never merges; aggregation matches an
|
|
108
|
+
independent worst-of oracle and is order-invariant and monotone.
|
|
109
|
+
- **Metamorphic** (`tests/test_metamorphic.py`): ~700 guarded corruptions
|
|
110
|
+
(digit edits, magnitude shifts, unit swaps, real-but-absent drug insertion,
|
|
111
|
+
in-grammar frequency swaps, …) applied to every clean golden case at test
|
|
112
|
+
time; none may PASS. Same fault taxonomy as the golden set, one
|
|
113
|
+
implementation (`scripts/corruptions.py`), two depths.
|
|
114
|
+
- **Golden gate** (`tests/test_golden_gate.py`): the benchmark as hard
|
|
115
|
+
assertions; false-PASS == 0 and clean-pass == 100% fail the build, and the
|
|
116
|
+
committed golden set must match its generator exactly.
|
|
117
|
+
|
|
118
|
+
Known v0 limitations are encoded as `xfail(strict=True)` tests (duplicate
|
|
119
|
+
medication names, trailing punctuation on frequencies, omission detection):
|
|
120
|
+
executable documentation that flips to a build failure the day the limitation
|
|
121
|
+
is fixed.
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
uv sync --group dev
|
|
125
|
+
uv run pytest # full suite (~750 tests, <5 s)
|
|
126
|
+
uv run pytest -m golden # just the benchmark gate
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Project layout
|
|
130
|
+
|
|
131
|
+
```
|
|
132
|
+
medfence/
|
|
133
|
+
contract.py # types + fail-closed aggregation (the stable core)
|
|
134
|
+
normalize.py # deterministic text/unit/number normalization
|
|
135
|
+
rulepack.py # bundle loading, thresholds-as-versioned-data
|
|
136
|
+
checks/grounding.py # Family G
|
|
137
|
+
checks/refdata.py # Family R
|
|
138
|
+
verify.py # the single entrypoint
|
|
139
|
+
data/refdata_seed.json
|
|
140
|
+
scripts/make_golden.py # regenerate the golden set (deterministic, no RNG)
|
|
141
|
+
scripts/benchmark.py # the table above (exits 1 on any false PASS)
|
|
142
|
+
scripts/corruptions.py # shared fault operators (golden set + metamorphic grid)
|
|
143
|
+
tests/ # contract invariants, properties, metamorphic grid, golden gate
|
|
144
|
+
tests/schemas/ # JSON Schema for the audit report (the output contract)
|
|
145
|
+
docs/adr-001-*.md # the design record
|
|
146
|
+
docs/related-work.md # how this differs from LangExtract, Guardrails, etc.
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Design record & positioning
|
|
150
|
+
|
|
151
|
+
See `docs/adr-001-clinical-verification-contract-v0.md` for the full contract
|
|
152
|
+
spec, options considered, and the trade-off analysis (notably: why ABSTAIN
|
|
153
|
+
exists, why coverage is a first-class output, and where the SaMD line is drawn).
|
|
154
|
+
For how medfence relates to LangExtract, Guardrails AI, clinical
|
|
155
|
+
self-verification, and the rest of the landscape, see `docs/related-work.md`.
|
|
156
|
+
|
|
157
|
+
## License
|
|
158
|
+
|
|
159
|
+
Apache-2.0.
|
|
160
|
+
|
|
161
|
+
## Quick demo
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
python3 demo.py # one prescription: PASS, FAIL (mcg swap + fabricated drug), ABSTAIN (low OCR)
|
|
165
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from .contract import (
|
|
2
|
+
Evidence,
|
|
3
|
+
Extraction,
|
|
4
|
+
Finding,
|
|
5
|
+
Severity,
|
|
6
|
+
SourceDocument,
|
|
7
|
+
Verdict,
|
|
8
|
+
VerificationReport,
|
|
9
|
+
)
|
|
10
|
+
from .rulepack import Rulepack, load_rulepack
|
|
11
|
+
from .verify import verify
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Evidence",
|
|
15
|
+
"Extraction",
|
|
16
|
+
"Finding",
|
|
17
|
+
"Rulepack",
|
|
18
|
+
"Severity",
|
|
19
|
+
"SourceDocument",
|
|
20
|
+
"Verdict",
|
|
21
|
+
"VerificationReport",
|
|
22
|
+
"load_rulepack",
|
|
23
|
+
"verify",
|
|
24
|
+
]
|
|
25
|
+
__version__ = "0.1.0"
|
|
File without changes
|