fhir-lite 0.5.0__py3-none-any.whl

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.
fhir_lite/__init__.py ADDED
@@ -0,0 +1,242 @@
1
+ """
2
+ FHIR Lite: Ultra-lightweight, zero-dependency FHIR library for Python.
3
+
4
+ Uses PEP 562 lazy module loading to ensure sub-millisecond cold starts
5
+ and minimal baseline memory footprint in serverless environments.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ from typing import TYPE_CHECKING
12
+
13
+ __version__ = "0.5.0"
14
+
15
+ _MOD_RESOURCES = ".resources"
16
+ _MOD_CLIENT = ".client"
17
+ _MOD_SERIALIZER = ".serializer"
18
+ _MOD_NDJSON = ".ndjson"
19
+ _MOD_TYPES = ".types"
20
+ _MOD_VERSION = ".version"
21
+ _MOD_FHIRPATH = ".fhirpath"
22
+ _MOD_ANONYMIZE = ".anonymize"
23
+
24
+ # Mapping from public symbols to their internal modules for lazy loading
25
+ _SUBMODULE_MAP = {
26
+ # Resources
27
+ "FHIRResource": _MOD_RESOURCES,
28
+ "Patient": _MOD_RESOURCES,
29
+ "Observation": _MOD_RESOURCES,
30
+ "Bundle": _MOD_RESOURCES,
31
+ "Practitioner": _MOD_RESOURCES,
32
+ "Encounter": _MOD_RESOURCES,
33
+ "Condition": _MOD_RESOURCES,
34
+ "MedicationRequest": _MOD_RESOURCES,
35
+ "Medication": _MOD_RESOURCES,
36
+ "OperationOutcome": _MOD_RESOURCES,
37
+ "Reference": _MOD_RESOURCES,
38
+ # Client
39
+ "FHIRClient": _MOD_CLIENT,
40
+ "FHIRError": _MOD_CLIENT,
41
+ # Serializer
42
+ "json_to_xml": _MOD_SERIALIZER,
43
+ "xml_to_json": _MOD_SERIALIZER,
44
+ "dict_to_xml": _MOD_SERIALIZER,
45
+ "xml_to_dict": _MOD_SERIALIZER,
46
+ "safe_fromstring": _MOD_SERIALIZER,
47
+ # NDJSON
48
+ "iter_ndjson": _MOD_NDJSON,
49
+ "write_ndjson": _MOD_NDJSON,
50
+ "loads_ndjson": _MOD_NDJSON,
51
+ "dumps_ndjson": _MOD_NDJSON,
52
+ # TypedDicts (fhir_lite.types)
53
+ "ExtensionDict": _MOD_TYPES,
54
+ "CodingDict": _MOD_TYPES,
55
+ "CodeableConceptDict": _MOD_TYPES,
56
+ "ReferenceDict": _MOD_TYPES,
57
+ "QuantityDict": _MOD_TYPES,
58
+ "PeriodDict": _MOD_TYPES,
59
+ "IdentifierDict": _MOD_TYPES,
60
+ "HumanNameDict": _MOD_TYPES,
61
+ "ContactPointDict": _MOD_TYPES,
62
+ "AddressDict": _MOD_TYPES,
63
+ "MetaDict": _MOD_TYPES,
64
+ "BundleEntryDict": _MOD_TYPES,
65
+ "BundleEntryRequestDict": _MOD_TYPES,
66
+ "BundleEntryResponseDict": _MOD_TYPES,
67
+ "DosageDict": _MOD_TYPES,
68
+ "NarrativeDict": _MOD_TYPES,
69
+ "IssueDict": _MOD_TYPES,
70
+ # Version API (fhir_lite.version)
71
+ "FHIRVersion": _MOD_VERSION,
72
+ "get_fhir_version": _MOD_VERSION,
73
+ "set_fhir_version": _MOD_VERSION,
74
+ "fhir_version_context": _MOD_VERSION,
75
+ "normalize_field": _MOD_VERSION,
76
+ "get_version_info": _MOD_VERSION,
77
+ # FHIRPath (fhir_lite.fhirpath)
78
+ "evaluate_fhirpath": _MOD_FHIRPATH,
79
+ "FHIRPathError": _MOD_FHIRPATH,
80
+ # Anonymization (fhir_lite.anonymize)
81
+ "DeidConfig": _MOD_ANONYMIZE,
82
+ "anonymize": _MOD_ANONYMIZE,
83
+ }
84
+
85
+
86
+ def from_json(json_str: str):
87
+ """Parse a FHIR JSON string into the appropriate FHIRResource instance."""
88
+ from .resources import FHIRResource
89
+ return FHIRResource.from_json(json_str)
90
+
91
+
92
+ def from_xml(xml_str: str):
93
+ """Parse a FHIR XML string into the appropriate FHIRResource instance."""
94
+ from .resources import FHIRResource
95
+ return FHIRResource.from_xml(xml_str)
96
+
97
+
98
+ def __getattr__(name: str):
99
+ """PEP 562 lazy loading: imports submodules on-demand when accessed."""
100
+ submodule = _SUBMODULE_MAP.get(name)
101
+ if submodule is not None:
102
+ mod = importlib.import_module(submodule, __package__)
103
+ val = getattr(mod, name)
104
+ globals()[name] = val
105
+ return val
106
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
107
+
108
+
109
+ def __dir__():
110
+ return __all__
111
+
112
+
113
+ __all__ = [
114
+ # Resources
115
+ "FHIRResource",
116
+ "Patient",
117
+ "Observation",
118
+ "Bundle",
119
+ "Practitioner",
120
+ "Encounter",
121
+ "Condition",
122
+ "MedicationRequest",
123
+ "Medication",
124
+ "OperationOutcome",
125
+ "Reference",
126
+ # Client
127
+ "FHIRClient",
128
+ "FHIRError",
129
+ # Convenience parsers
130
+ "from_json",
131
+ "from_xml",
132
+ # Serializer
133
+ "json_to_xml",
134
+ "xml_to_json",
135
+ "dict_to_xml",
136
+ "xml_to_dict",
137
+ "safe_fromstring",
138
+ # NDJSON
139
+ "iter_ndjson",
140
+ "write_ndjson",
141
+ "loads_ndjson",
142
+ "dumps_ndjson",
143
+ # TypedDicts (fhir_lite.types)
144
+ "ExtensionDict",
145
+ "CodingDict",
146
+ "CodeableConceptDict",
147
+ "ReferenceDict",
148
+ "QuantityDict",
149
+ "PeriodDict",
150
+ "IdentifierDict",
151
+ "HumanNameDict",
152
+ "ContactPointDict",
153
+ "AddressDict",
154
+ "MetaDict",
155
+ "BundleEntryDict",
156
+ "BundleEntryRequestDict",
157
+ "BundleEntryResponseDict",
158
+ "DosageDict",
159
+ "NarrativeDict",
160
+ "IssueDict",
161
+ # Version API (fhir_lite.version)
162
+ "FHIRVersion",
163
+ "get_fhir_version",
164
+ "set_fhir_version",
165
+ "fhir_version_context",
166
+ "normalize_field",
167
+ "get_version_info",
168
+ # FHIRPath (fhir_lite.fhirpath)
169
+ "evaluate_fhirpath",
170
+ "FHIRPathError",
171
+ # Anonymization (fhir_lite.anonymize)
172
+ "DeidConfig",
173
+ "anonymize",
174
+ ]
175
+
176
+
177
+ if TYPE_CHECKING:
178
+ from .resources import (
179
+ FHIRResource,
180
+ Patient,
181
+ Observation,
182
+ Bundle,
183
+ Practitioner,
184
+ Encounter,
185
+ Condition,
186
+ MedicationRequest,
187
+ Medication,
188
+ OperationOutcome,
189
+ Reference,
190
+ )
191
+ from .client import (
192
+ FHIRClient,
193
+ FHIRError,
194
+ )
195
+ from .serializer import (
196
+ json_to_xml,
197
+ xml_to_json,
198
+ dict_to_xml,
199
+ xml_to_dict,
200
+ safe_fromstring,
201
+ )
202
+ from .ndjson import (
203
+ iter_ndjson,
204
+ write_ndjson,
205
+ loads_ndjson,
206
+ dumps_ndjson,
207
+ )
208
+ from .types import (
209
+ ExtensionDict,
210
+ CodingDict,
211
+ CodeableConceptDict,
212
+ ReferenceDict,
213
+ QuantityDict,
214
+ PeriodDict,
215
+ IdentifierDict,
216
+ HumanNameDict,
217
+ ContactPointDict,
218
+ AddressDict,
219
+ MetaDict,
220
+ BundleEntryDict,
221
+ BundleEntryRequestDict,
222
+ BundleEntryResponseDict,
223
+ DosageDict,
224
+ NarrativeDict,
225
+ IssueDict,
226
+ )
227
+ from .version import (
228
+ FHIRVersion,
229
+ get_fhir_version,
230
+ set_fhir_version,
231
+ fhir_version_context,
232
+ normalize_field,
233
+ get_version_info,
234
+ )
235
+ from .fhirpath import (
236
+ evaluate_fhirpath,
237
+ FHIRPathError,
238
+ )
239
+ from .anonymize import (
240
+ DeidConfig,
241
+ anonymize,
242
+ )
fhir_lite/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Executable entrypoint for `python -m fhir_lite`.
2
+ """
3
+
4
+ import sys
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
fhir_lite/anonymize.py ADDED
@@ -0,0 +1,310 @@
1
+ """HIPAA Safe Harbor De-identification and Sanitization for FHIR.
2
+
3
+ Compliant with 45 CFR § 164.514(b)(2) (Safe Harbor Method), eliminating
4
+ the 18 protected health information (PHI) identifiers while preserving
5
+ clinical data integrity for analytics, machine learning, and research.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import datetime
12
+ import hashlib
13
+ import re
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Union
16
+
17
+ # Common FHIR date fields that may link to individuals
18
+ COMMON_DATE_FIELDS = {
19
+ "birthDate",
20
+ "deceasedDateTime",
21
+ "deceasedDate",
22
+ "effectiveDateTime",
23
+ "authoredOn",
24
+ "issued",
25
+ "recordedDate",
26
+ "occurrenceDateTime",
27
+ "onsetDateTime",
28
+ "abatementDateTime",
29
+ "date",
30
+ }
31
+
32
+
33
+ @dataclass
34
+ class DeidConfig:
35
+ """Configuration for HIPAA Safe Harbor de-identification.
36
+
37
+ Attributes
38
+ ----------
39
+ remove_names : bool
40
+ Whether to remove patient and practitioner names (default: True).
41
+ name_placeholder : str | None
42
+ If provided, sets name to [{"use": "anonymous", "family": name_placeholder}].
43
+ If None, removes the name field entirely (default: "ANONYMOUS").
44
+ remove_telecom : bool
45
+ Whether to remove phone, email, fax, and contact points (default: True).
46
+ remove_addresses : bool
47
+ Whether to remove addresses (default: True).
48
+ keep_state_and_country : bool
49
+ If True and remove_addresses is True, retains state and country while
50
+ removing street lines, cities, and zip codes (default: False).
51
+ remove_identifiers : bool
52
+ Whether to remove SSN, MRN, driver licenses, and account IDs (default: True).
53
+ pseudonymize_id : bool
54
+ Whether to replace resource IDs with deterministic SHA-256 hashes (default: False).
55
+ salt : str
56
+ Salt used for deterministic hashing (default: "").
57
+ remove_photos : bool
58
+ Whether to remove biometric and face images (default: True).
59
+ remove_narratives : bool
60
+ Whether to remove text.div free-text clinical notes that may leak PHI (default: True).
61
+ date_handling : str
62
+ Method for handling dates: "year_only", "shift", "remove", or "preserve" (default: "year_only").
63
+ date_shift_days : int
64
+ Days to shift dates when date_handling == "shift" (can be negative or positive) (default: 0).
65
+ remove_extensions : bool
66
+ Whether to strip custom extensions (default: False).
67
+ """
68
+ remove_names: bool = True
69
+ name_placeholder: Optional[str] = "ANONYMOUS"
70
+ remove_telecom: bool = True
71
+ remove_addresses: bool = True
72
+ keep_state_and_country: bool = False
73
+ remove_identifiers: bool = True
74
+ pseudonymize_id: bool = False
75
+ salt: str = ""
76
+ remove_photos: bool = True
77
+ remove_narratives: bool = True
78
+ date_handling: str = "year_only" # "year_only", "shift", "remove", "preserve"
79
+ date_shift_days: int = 0
80
+ remove_extensions: bool = False
81
+
82
+
83
+ # Regex for ISO date matching (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS...)
84
+ _ISO_DATE_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2}))?")
85
+
86
+
87
+ def _hash_id(original_id: str, salt: str = "") -> str:
88
+ h = hashlib.sha256((original_id + salt).encode("utf-8")).hexdigest()
89
+ return f"anon-{h[:12]}"
90
+
91
+
92
+ def _transform_date_string(val: str, config: DeidConfig) -> Optional[str]:
93
+ if config.date_handling == "preserve":
94
+ return val
95
+ elif config.date_handling == "remove":
96
+ return None
97
+
98
+ m = _ISO_DATE_RE.match(val)
99
+ if not m:
100
+ # If it's already just a year e.g. "1980", preserve it
101
+ if re.match(r"^\d{4}$", val):
102
+ return val
103
+ return None if config.date_handling == "remove" else val
104
+
105
+ year = m.group(1)
106
+
107
+ if config.date_handling == "year_only":
108
+ return f"{year}-01-01"
109
+
110
+ elif config.date_handling == "shift":
111
+ try:
112
+ month = int(m.group(2))
113
+ day = int(m.group(3))
114
+ hour = int(m.group(4) or 0)
115
+ minute = int(m.group(5) or 0)
116
+ second = int(m.group(6) or 0)
117
+
118
+ dt = datetime.datetime(int(year), month, day, hour, minute, second)
119
+ shifted = dt + datetime.timedelta(days=config.date_shift_days)
120
+
121
+ if m.group(4) is not None:
122
+ return shifted.strftime("%Y-%m-%dT%H:%M:%SZ")
123
+ return shifted.strftime("%Y-%m-%d")
124
+ except Exception:
125
+ return f"{year}-01-01"
126
+
127
+ return val
128
+
129
+
130
+ def _sanitize_dates_in_dict(data: dict, config: DeidConfig) -> None:
131
+ for key, val in list(data.items()):
132
+ if key in COMMON_DATE_FIELDS and isinstance(val, str):
133
+ transformed = _transform_date_string(val, config)
134
+ if transformed is None:
135
+ del data[key]
136
+ else:
137
+ data[key] = transformed
138
+ elif key == "period" and isinstance(val, dict):
139
+ for p_key in ("start", "end"):
140
+ if p_key in val and isinstance(val[p_key], str):
141
+ tr = _transform_date_string(val[p_key], config)
142
+ if tr is None:
143
+ del val[p_key]
144
+ else:
145
+ val[p_key] = tr
146
+ elif isinstance(val, dict):
147
+ _sanitize_dates_in_dict(val, config)
148
+ elif isinstance(val, list):
149
+ for item in val:
150
+ if isinstance(item, dict):
151
+ _sanitize_dates_in_dict(item, config)
152
+
153
+
154
+ def _anonymize_single_resource(data: dict, config: DeidConfig, id_map: Optional[dict[str, str]] = None) -> dict:
155
+ """Anonymize a single FHIR resource dictionary according to HIPAA Safe Harbor."""
156
+ # 1. Names
157
+ if config.remove_names:
158
+ if "name" in data:
159
+ if config.name_placeholder:
160
+ data["name"] = [{"use": "anonymous", "family": config.name_placeholder}]
161
+ else:
162
+ del data["name"]
163
+
164
+ # 2. Telecom (phone, email, fax, url)
165
+ if config.remove_telecom and "telecom" in data:
166
+ del data["telecom"]
167
+
168
+ # 3. Addresses
169
+ if config.remove_addresses and "address" in data:
170
+ if config.keep_state_and_country and isinstance(data["address"], list):
171
+ safe_addresses = []
172
+ for addr in data["address"]:
173
+ if isinstance(addr, dict):
174
+ safe_addr = {
175
+ k: addr[k]
176
+ for k in ("state", "country", "use")
177
+ if k in addr
178
+ }
179
+ if safe_addr:
180
+ safe_addresses.append(safe_addr)
181
+ if safe_addresses:
182
+ data["address"] = safe_addresses
183
+ else:
184
+ del data["address"]
185
+ else:
186
+ del data["address"]
187
+
188
+ # 4. Identifiers (MRN, SSN, licenses, account numbers)
189
+ if config.remove_identifiers and "identifier" in data:
190
+ del data["identifier"]
191
+
192
+ # 5. Photos / Biometrics
193
+ if config.remove_photos and "photo" in data:
194
+ del data["photo"]
195
+
196
+ # 6. Narratives (text.div free-text)
197
+ if config.remove_narratives and "text" in data:
198
+ del data["text"]
199
+
200
+ # 7. Contacts (Patient.contact, Encounter.participant, etc.)
201
+ if "contact" in data and isinstance(data["contact"], list):
202
+ for c in data["contact"]:
203
+ if isinstance(c, dict):
204
+ if config.remove_names and "name" in c:
205
+ del c["name"]
206
+ if config.remove_telecom and "telecom" in c:
207
+ del c["telecom"]
208
+ if config.remove_addresses and "address" in c:
209
+ del c["address"]
210
+
211
+ # 8. Extensions
212
+ if config.remove_extensions:
213
+ data.pop("extension", None)
214
+ data.pop("modifierExtension", None)
215
+
216
+ # 9. Dates
217
+ _sanitize_dates_in_dict(data, config)
218
+
219
+ # 10. ID Pseudonymization
220
+ if config.pseudonymize_id and "id" in data:
221
+ old_id = data["id"]
222
+ new_id = _hash_id(old_id, config.salt)
223
+ data["id"] = new_id
224
+ if id_map is not None:
225
+ rtype = data.get("resourceType", "Resource")
226
+ id_map[f"{rtype}/{old_id}"] = f"{rtype}/{new_id}"
227
+ id_map[old_id] = new_id
228
+
229
+ return data
230
+
231
+
232
+ def _update_bundle_references(bundle_data: dict, id_map: dict[str, str]) -> None:
233
+ """Replace old reference URIs with new pseudonymized ones inside bundle entries."""
234
+ def _traverse(node: Any) -> None:
235
+ if isinstance(node, dict):
236
+ if "reference" in node and isinstance(node["reference"], str):
237
+ ref = node["reference"]
238
+ if ref in id_map:
239
+ node["reference"] = id_map[ref]
240
+ else:
241
+ # Check relative e.g. Patient/123
242
+ for old_ref, new_ref in id_map.items():
243
+ if ref == old_ref or ref.endswith(f"/{old_ref}"):
244
+ node["reference"] = new_ref
245
+ break
246
+ for v in node.values():
247
+ _traverse(v)
248
+ elif isinstance(node, list):
249
+ for item in node:
250
+ _traverse(item)
251
+
252
+ _traverse(bundle_data)
253
+
254
+
255
+ def anonymize(
256
+ resource_or_data: Any,
257
+ config: Optional[DeidConfig] = None,
258
+ in_place: bool = False,
259
+ ) -> Any:
260
+ """Anonymize a FHIR resource or Bundle in compliance with HIPAA Safe Harbor.
261
+
262
+ Parameters
263
+ ----------
264
+ resource_or_data : Any
265
+ FHIRResource instance or dictionary.
266
+ config : DeidConfig, optional
267
+ De-identification options (uses strict Safe Harbor defaults if None).
268
+ in_place : bool, default False
269
+ Whether to modify the resource in place or return a deep copy.
270
+
271
+ Returns
272
+ -------
273
+ Any
274
+ The sanitized resource instance or dictionary.
275
+ """
276
+ cfg = config or DeidConfig()
277
+
278
+ is_fhir_resource = hasattr(resource_or_data, "data") and isinstance(resource_or_data.data, dict)
279
+ data = resource_or_data.data if is_fhir_resource else resource_or_data
280
+
281
+ if not isinstance(data, dict):
282
+ raise TypeError(f"Expected FHIRResource or dict, got {type(resource_or_data).__name__}")
283
+
284
+ working_data = data if in_place else copy.deepcopy(data)
285
+
286
+ id_map: dict[str, str] = {}
287
+
288
+ # Check if resource is a Bundle
289
+ if working_data.get("resourceType") == "Bundle" and "entry" in working_data:
290
+ entries = working_data.get("entry", [])
291
+ if isinstance(entries, list):
292
+ for entry in entries:
293
+ if isinstance(entry, dict) and "resource" in entry and isinstance(entry["resource"], dict):
294
+ _anonymize_single_resource(entry["resource"], cfg, id_map=id_map)
295
+
296
+ if cfg.pseudonymize_id and id_map:
297
+ _update_bundle_references(working_data, id_map)
298
+ else:
299
+ _anonymize_single_resource(working_data, cfg, id_map=id_map)
300
+
301
+ if is_fhir_resource:
302
+ if in_place:
303
+ return resource_or_data
304
+ cls = resource_or_data.__class__
305
+ return cls(working_data)
306
+
307
+ return working_data
308
+
309
+
310
+ __all__ = ["DeidConfig", "anonymize"]