API Reference¶
Public API exported from the dicom_dre package.
DICOM De-identification & Redaction Engine (dicom-dre).
DICOM de-identification engine: metadata scrub, device-catalog filtering, pixel blanking, and JPEG-DCT scrubbing.
Public API: the engine entry point (deidentify_file), the
result type (DeidentifyResult / Outcome), the canonical profile builder
(build_profile), the concrete profile factories, the device catalog, and
the supporting value types.
- class dicom_dre.BatchItemResult(input_file, result)[source]¶
Bases:
objectResult of de-identifying one input within a batch run.
- Variables:
input_file (Path) – Path to the source DICOM file processed.
result (DeidentifyResult) – The de-identification result for that input.
- Parameters:
input_file (Path)
result (DeidentifyResult)
- input_file: Path¶
- result: DeidentifyResult¶
- class dicom_dre.ProfileSettings(uid_root='1.2.840.4267.32.', allowlist_csv='default.csv', hash_salt='NOSALT')[source]¶
Bases:
objectTyped build-time configuration for profile construction.
The type is frozen and picklable so it can be serialized and sent to worker processes via a
ProfileSpec.- Variables:
- Parameters:
- class dicom_dre.CatalogDecision(action, reason, scrub_regions=<factory>, matched_variant=None)[source]¶
Bases:
objectResult of evaluating a DICOM instance against the device catalog.
- Variables:
action (str) – One of “allow”, “deny”, or “scrub”.
reason (str) – Human-readable explanation for the decision.
scrub_regions (list[dicom_dre.scrub_region.ScrubRegion]) – Pixel regions to blank, as ScrubRegion instances.
matched_variant (dicom_dre.catalog.Variant | None) – The Variant that matched, if any.
- Parameters:
action (str)
reason (str)
scrub_regions (list[ScrubRegion])
matched_variant (Variant | None)
- scrub_regions: list[ScrubRegion]¶
- class dicom_dre.DeidParameters(patient_id=None, patient_name=None, accession_number=None, study_id=None, series_description=None, study_description=None, protocol_name=None, jitter=None)[source]¶
Bases:
objectImmutable per-patient de-identification parameters.
Each field records exactly what the caller supplied;
Nonemeans “not supplied” and the parameterized tag actions resolve placeholder defaults at write time. The type is hashable and picklable so it can be shared read-only across threads and serialized to worker processes.- Parameters:
- classmethod from_mapping(mapping)[source]¶
Build
DeidParametersfrom an uppercase-keyed parameter mapping.Reads the per-patient identity keys
PATIENT_ID,PATIENT_NAME,ACCESSION_NUMBER,STUDY_ID,SERIES_DESCRIPTION,STUDY_DESCRIPTION,PROTOCOL_NAME, andJITTER. Build-time settings (UID root, allowlist CSV, identifier-hash salt) are not accepted here; they belong todicom_dre.profiles.config.ProfileSettings.- Parameters:
mapping (Mapping[str, str]) – Parameter mapping with uppercase keys.
- Returns:
The parsed parameters.
- Raises:
ValueError – If
JITTERis present but not an integer, or if the mapping contains a key that is not a per-patient identity key.- Return type:
- class dicom_dre.DeidProfile(name, rules, keep_groups, remove_private, remove_curves, remove_overlays, remove_unspecified=False, preserve_dates=False, modifies_dates=False, allowlist_csv='default.csv', hash_salt=None, uid_root=None, uid_use_study_salt=False, date_override_tags=<factory>, preserved_private_specs=<factory>, emits_basic_profile=True, deid_options=<factory>, content_root_tags=<factory>)[source]¶
Bases:
objectImmutable de-identification profile binding tag rules and global flags.
- Parameters:
name (str)
rules (dict[BaseTag, TagAction])
remove_private (bool)
remove_curves (bool)
remove_overlays (bool)
remove_unspecified (bool)
preserve_dates (bool)
modifies_dates (bool)
allowlist_csv (str)
hash_salt (str | None)
uid_root (str | None)
uid_use_study_salt (bool)
date_override_tags (frozenset[BaseTag])
preserved_private_specs (frozenset[PrivateTagSpec])
emits_basic_profile (bool)
content_root_tags (frozenset[BaseTag])
- apply(ds, params, *, applied_options=frozenset({}))[source]¶
Apply all de-identification rules to a pydicom Dataset in place.
Per-patient values are read from
paramsat apply time.applied_optionscarries per-instance de-identification option codes the caller applied outside the profile rules (for example113101when the pipeline scrubbed burned-in pixel text); they are merged into the method code sequence alongside the profile-declareddeid_options.Phase 0: Validate the jitter and resolve a per-patient shift when unset. Phase 1: Insert a default SpecificCharacterSet when absent. Phase 2: Apply element-level rules. Phase 3: Shift preserved private dates flagged for jitter. Phase 4: Apply global removal rules (private, curves, overlays, unspecified). Phase 5: Emit the De-identification Method Code Sequence. Phase 6: Remove retired Group Length tags from all datasets. Phase 7: Correct VRs for elements read as OB/UN inside sequences.
- Parameters:
ds (Dataset)
params (DeidParameters)
- Return type:
None
- class dicom_dre.DeidentifyResult(outcome, output_file=None, was_decompressed=False, scrub_regions=<factory>, filter_reason=None, error=None, input_file=None, parameters=None, input_attributes=None, output_attributes=None)[source]¶
Bases:
objectResult of de-identifying a single DICOM file.
- Variables:
outcome (Outcome) – The terminal outcome kind.
output_file (Path | None) – Path to the de-identified file; None unless DEIDENTIFIED.
was_decompressed (bool) – Whether pixel data was decompressed during processing.
scrub_regions (frozenset[ScrubRegion]) – The pixel regions blanked during processing.
filter_reason (str | None) – Why the file was rejected; set only when FILTERED.
error (str | None) – The processing error; set only when QUARANTINED.
input_file (Path | None) – Path to the source DICOM file processed, when known.
parameters (DeidParameters | None) – The per-patient de-identification parameters applied; None when not supplied.
input_attributes (IndexAttributes | None) – Attribute snapshot of the input, when available.
output_attributes (IndexAttributes | None) – Attribute snapshot of the de-identified output; set only when DEIDENTIFIED.
- Parameters:
outcome (Outcome)
output_file (Path | None)
was_decompressed (bool)
scrub_regions (frozenset[ScrubRegion])
filter_reason (str | None)
error (str | None)
input_file (Path | None)
parameters (DeidParameters | None)
input_attributes (IndexAttributes | None)
output_attributes (IndexAttributes | None)
- scrub_regions: frozenset[ScrubRegion]¶
- parameters: DeidParameters | None¶
- input_attributes: IndexAttributes | None¶
- output_attributes: IndexAttributes | None¶
- classmethod deidentified(output_file, *, was_decompressed, scrub_regions, input_file=None, parameters=None, input_attributes=None, output_attributes=None)[source]¶
Build a successful (DEIDENTIFIED) result.
- Parameters:
output_file (Path)
was_decompressed (bool)
scrub_regions (frozenset[ScrubRegion])
input_file (Path | None)
parameters (DeidParameters | None)
input_attributes (IndexAttributes | None)
output_attributes (IndexAttributes | None)
- Return type:
- classmethod filtered(reason, *, input_file=None, parameters=None, input_attributes=None)[source]¶
Build a rejected (FILTERED) result.
- Parameters:
reason (str | None)
input_file (Path | None)
parameters (DeidParameters | None)
input_attributes (IndexAttributes | None)
- Return type:
- classmethod quarantined(error, *, input_file=None, parameters=None, input_attributes=None)[source]¶
Build a failed (QUARANTINED) result.
- Parameters:
error (str | None)
input_file (Path | None)
parameters (DeidParameters | None)
input_attributes (IndexAttributes | None)
- Return type:
- class dicom_dre.DeviceCatalog(devices, exclusions, default_action='deny')[source]¶
Bases:
objectEvaluates DICOM instances against a list of device rules and exclusions.
Devices are checked in declaration order; the first matching rule wins for all actions (“allow”, “deny”, and “scrub”). A matching “allow” or “scrub” device short-circuits evaluation and skips the exclusion rules, so its scrub regions come only from the device that matched. Exclusion rules act as a last-chance filter, applied only to instances that match no device rule.
- Parameters:
- class dicom_dre.DicomTags(values)[source]¶
Bases:
objectLightweight wrapper for reading DICOM attributes needed by the catalog.
Normalizes access so the matching engine does not interact with pydicom directly.
- get_list(keyword)[source]¶
Return the multi-valued tag as a list of strings.
Image Type, for example, is stored as
"ORIGINAL\PRIMARY\AXIAL".
- class dicom_dre.IndexAttributes(sop_instance_uid=None, study_instance_uid=None, series_instance_uid=None, sop_class_uid=None, accession_number=None, patient_id=None, study_id=None, transfer_syntax_uid=None, modality=None, modalities_in_study=None, manufacturer=None, manufacturer_model_name=None, secondary_capture_device_manufacturer_model_name=None, station_name=None, institution_name=None, institutional_department_name=None, study_description=None, series_description=None, protocol_name=None, derivation_description=None, body_part_examined=None, laterality=None, patient_position=None, conversion_type=None, image_type=None, software_versions=None, patient_name=None, patient_birth_date=None, patient_age=None, patient_sex=None, patient_size=None, patient_weight=None, ethnic_group=None, patient_identity_removed=None, confidentiality_code=None, referring_physician_name=None, requesting_physician=None, performing_physician_name=None, study_date=None, study_time=None, series_date=None, series_time=None, content_date=None, content_time=None, instance_number=None, series_number=None, number_of_frames=None, number_of_series_related_instances=None, number_of_study_related_instances=None, number_of_study_related_series=None, rows=None, columns=None, bits_allocated=None, bits_stored=None, high_bit=None, samples_per_pixel=None, pixel_representation=None, photometric_interpretation=None, burned_in_annotation=None, lossy_image_compression=None, procedure_code_sequence=None, retrieve_url=None)[source]¶
Bases:
objectTyped snapshot of standard DICOM attributes read from a dataset.
All fields are standard DICOM keywords.
Nonemeans the element is absent. Multi-valued attributes aretuple[str, ...]so the snapshot is hashable.- Parameters:
sop_instance_uid (str | None)
study_instance_uid (str | None)
series_instance_uid (str | None)
sop_class_uid (str | None)
accession_number (str | None)
patient_id (str | None)
study_id (str | None)
transfer_syntax_uid (str | None)
modality (str | None)
manufacturer (str | None)
manufacturer_model_name (str | None)
secondary_capture_device_manufacturer_model_name (str | None)
station_name (str | None)
institution_name (str | None)
institutional_department_name (str | None)
study_description (str | None)
series_description (str | None)
protocol_name (str | None)
derivation_description (str | None)
body_part_examined (str | None)
laterality (str | None)
patient_position (str | None)
conversion_type (str | None)
patient_name (str | None)
patient_birth_date (str | None)
patient_age (str | None)
patient_sex (str | None)
patient_size (str | None)
patient_weight (str | None)
ethnic_group (str | None)
patient_identity_removed (str | None)
confidentiality_code (str | None)
referring_physician_name (str | None)
requesting_physician (str | None)
performing_physician_name (str | None)
study_date (str | None)
study_time (str | None)
series_date (str | None)
series_time (str | None)
content_date (str | None)
content_time (str | None)
instance_number (int | None)
series_number (int | None)
number_of_frames (int | None)
number_of_series_related_instances (int | None)
number_of_study_related_instances (int | None)
number_of_study_related_series (int | None)
rows (int | None)
columns (int | None)
bits_allocated (int | None)
bits_stored (int | None)
high_bit (int | None)
samples_per_pixel (int | None)
pixel_representation (int | None)
photometric_interpretation (str | None)
burned_in_annotation (str | None)
lossy_image_compression (str | None)
procedure_code_sequence (str | None)
retrieve_url (str | None)
- classmethod from_dataset(ds)[source]¶
Extract a snapshot from an in-memory dataset (no I/O).
- Parameters:
ds (Dataset)
- Return type:
- class dicom_dre.Outcome(*values)[source]¶
Bases:
EnumTerminal outcome kind for a de-identification run.
- DEIDENTIFIED = 'deidentified'¶
- FILTERED = 'filtered'¶
- QUARANTINED = 'quarantined'¶
- exception dicom_dre.OutputPathCollisionError[source]¶
Bases:
ValueErrorTwo discovered inputs would be written to the same output path.
Raised before any file is written when
rename_to_sop_uidis disabled and the derived output paths are not unique (for example, two explicitly listed files that share a basename). With SOP-UID renaming the output names are unique by construction, so this is never raised.
- class dicom_dre.ProfileSpec(name, settings=<factory>)[source]¶
Bases:
objectPicklable description of a de-identification profile.
A bound
DeidProfilecannot cross a process boundary because its tag rules are closures. This spec contains the profile name and build-time configuration instead, so each worker process can rebuild the profile withdicom_dre.build_profile(). Per-patient identity values are not part of the spec; they are passed on aDeidParameters.- Variables:
name (str) – Profile name accepted by
dicom_dre.build_profile().settings (dicom_dre.profiles.config.ProfileSettings) – Build-time configuration (UID root, allowlist CSV, and identifier-hash salt).
- Parameters:
name (str)
settings (ProfileSettings)
- settings: ProfileSettings¶
- class dicom_dre.ScrubRegion(x, y, width, height)[source]¶
Bases:
objectA rectangular pixel region to blank, in (x, y, width, height) coordinates.
- classmethod from_string(value)[source]¶
Create a ScrubRegion from an ‘x,y,width,height’ string.
- Parameters:
value (str)
- Return type:
- class dicom_dre.TextRedactor(allowlist=None, delimiters=None, deny_regex_patterns=None, allow_regex_patterns=None, pii_prefixes=None, preserve_dates=False)[source]¶
Bases:
objectText redaction tool for PII and sensitive information.
This class provides functionality to redact words not present in an allowlist and text matching specific regex patterns that may contain sensitive information.
- Variables:
allowlist – Set of words that should not be redacted.
delimiters – List of characters used to split text into tokens.
regex_patterns – List of regex patterns to identify sensitive information.
allowlist_regex_patterns – List of regex patterns for tokens that should not be redacted.
- Parameters:
- static create_month_regex()[source]¶
Create a regex pattern to match month names (full and abbreviated).
- TIMEZONE_ABBREVIATIONS = ['UTC', 'GMT', 'EST', 'EDT', 'CST', 'CDT', 'MST', 'MDT', 'PST', 'PDT', 'AKST', 'AKDT', 'HST', 'HAST', 'HADT', 'AST', 'ADT', 'NST', 'NDT', 'BST', 'CET', 'CEST', 'EET', 'EEST', 'WET', 'WEST', 'IST', 'JST', 'KST', 'CST', 'HKT', 'SGT', 'ICT', 'WIB', 'AEST', 'AEDT', 'ACST', 'ACDT', 'AWST', 'NZST', 'NZDT', 'SAST', 'EAT', 'WAT', 'CAT']¶
- static create_date_regex()[source]¶
Create a regex pattern to match various date formats. Must include year.
- US_STATES = ['AL', 'Alabama', 'AK', 'Alaska', 'AZ', 'Arizona', 'AR', 'Arkansas', 'CA', 'California', 'CO', 'Colorado', 'CT', 'Connecticut', 'DE', 'Delaware', 'FL', 'Florida', 'GA', 'Georgia', 'HI', 'Hawaii', 'ID', 'Idaho', 'IL', 'Illinois', 'IN', 'Indiana', 'IA', 'Iowa', 'KS', 'Kansas', 'KY', 'Kentucky', 'LA', 'Louisiana', 'ME', 'Maine', 'MD', 'Maryland', 'MA', 'Massachusetts', 'MI', 'Michigan', 'MN', 'Minnesota', 'MS', 'Mississippi', 'MO', 'Missouri', 'MT', 'Montana', 'NE', 'Nebraska', 'NV', 'Nevada', 'NH', 'New Hampshire', 'NJ', 'New Jersey', 'NM', 'New Mexico', 'NY', 'New York', 'NC', 'North Carolina', 'ND', 'North Dakota', 'OH', 'Ohio', 'OK', 'Oklahoma', 'OR', 'Oregon', 'PA', 'Pennsylvania', 'RI', 'Rhode Island', 'SC', 'South Carolina', 'SD', 'South Dakota', 'TN', 'Tennessee', 'TX', 'Texas', 'UT', 'Utah', 'VT', 'Vermont', 'VA', 'Virginia', 'WA', 'Washington', 'WV', 'West Virginia', 'WI', 'Wisconsin', 'WY', 'Wyoming', 'DC', 'District of Columbia', 'PR', 'Puerto Rico', 'VI', 'Virgin Islands', 'GU', 'Guam', 'AS', 'American Samoa', 'MP', 'Northern Mariana Islands']¶
- DEFAULT_PII_PREFIXES = ['NRP', 'MRN', 'SSN']¶
- DEFAULT_TIME_DENY_REGEX_PATTERNS = ['(\\b(?:(?:2[0-3]|[01]?[0-9]):(?:[0-5][0-9])(?::(?:[0-5][0-9]))?\\s*(?:[AaPp][Mm])?)\\b)', '(\\b\\d{1,2}H\\d{1,2}M\\b)']¶
- DEFAULT_DENY_REGEX_PATTERNS = ['(\\b(?=.*[A-Fa-f])[0-9A-Fa-f]{6,}\\b)', '(\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b)', '(\\b[a-zA-Z][a-zA-Z0-9+.-]*://[^\\s/$.?#].[^\\s]*\\b)', '(\\b\\d{3}-?\\d{2}-?\\d{4}\\b)', '(\\b\\d{5}-\\d{4}\\b)', '(\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}\\b)', '(?i)(\\b(?:AL|Alabama|AK|Alaska|AZ|Arizona|AR|Arkansas|CA|California|CO|Colorado|CT|Connecticut|DE|Delaware|FL|Florida|GA|Georgia|HI|Hawaii|ID|Idaho|IL|Illinois|IN|Indiana|IA|Iowa|KS|Kansas|KY|Kentucky|LA|Louisiana|ME|Maine|MD|Maryland|MA|Massachusetts|MI|Michigan|MN|Minnesota|MS|Mississippi|MO|Missouri|MT|Montana|NE|Nebraska|NV|Nevada|NH|New Hampshire|NJ|New Jersey|NM|New Mexico|NY|New York|NC|North Carolina|ND|North Dakota|OH|Ohio|OK|Oklahoma|OR|Oregon|PA|Pennsylvania|RI|Rhode Island|SC|South Carolina|SD|South Dakota|TN|Tennessee|TX|Texas|UT|Utah|VT|Vermont|VA|Virginia|WA|Washington|WV|West Virginia|WI|Wisconsin|WY|Wyoming|DC|District of Columbia|PR|Puerto Rico|VI|Virgin Islands|GU|Guam|AS|American Samoa|MP|Northern Mariana Islands)(?:,)?\\s+\\d{5}\\b)']¶
- DEFAULT_ALLOW_REGEX_PATTERNS = ['^(?:[0]*\\d{1,5})$', '^0*(?:360|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])[\\u00b0\\u00ba]$', '^[xX]+$']¶
- DEFAULT_DELIMITERS = [' ', '<', '>', '(', ')', '{', '}', '|', '!', ';', ',', "'", '"', '*', '&', '?', '+', '/', ':', '=', '@', '.', '-', '$', '%', '\\', '_', '\n', '\r', '\t', ']', '[', '^', '#', '~', '`']¶
- redact_text(text, track_redacted=False, return_token_pairs=False)[source]¶
Redact words not in the allowlist and mask regex patterns.
- Parameters:
- Returns:
If track_redacted is False and return_token_pairs is False, returns redacted text. If track_redacted is True, returns tuple of (redacted text, set of redacted tokens). If return_token_pairs is True, returns tuple of (redacted text, list of token pairs).
- Return type:
str | tuple[str, set[str]] | tuple[str, list[tuple[str, str]]]
- load_allowlist_from_csv(allowlist_file)[source]¶
Load allowlist words from a CSV file.
- Parameters:
allowlist_file (str | Path) – Path to the CSV file containing allowed words.
- Raises:
ValueError – If the file cannot be read or is not in the expected format.
- Return type:
None
- class dicom_dre.Variant(rows=None, cols=None, sop_class_uid=None, software_versions=None, image_type=None, image_type_any=None, image_type_exclude=None, scrub_regions=<factory>)[source]¶
Bases:
objectA resolution or version variant within a device rule.
- Variables:
rows (int | None) – Required image row count, or None if unconstrained.
cols (int | None) – Required image column count, or None if unconstrained.
sop_class_uid (str | list[str] | None) – SOPClassUID pattern(s) for narrowing, or None if unconstrained.
software_versions (str | list[str] | None) – Software version pattern(s) for narrowing.
image_type (str | list[str] | None) – ImageType component(s) that all must appear.
image_type_any (str | list[str] | None) – ImageType component(s) where at least one must appear.
image_type_exclude (str | list[str] | None) – ImageType component(s) where none may appear.
scrub_regions (list[dicom_dre.scrub_region.ScrubRegion]) – Pixel regions to blank, as ScrubRegion instances.
- Parameters:
- scrub_regions: list[ScrubRegion]¶
- dicom_dre.build_profile(name, settings=None)[source]¶
Construct a patient-invariant
DeidProfilefor a named profile.- Parameters:
name (str) – Profile name, one of
"default","lds","lds-no-dob", or"strict".settings (ProfileSettings | None) – Optional build-time configuration. When omitted, the
ProfileSettingsdefaults apply.
- Returns:
A profile ready for
apply(ds, params).- Raises:
ValueError – If the name is unknown.
- Return type:
- dicom_dre.correct_implicit_vr_elements(ds)[source]¶
Correct VRs for elements pydicom decoded as OB or UN inside sequences.
Some DICOM files use implicit VR encoding inside explicit VR sequences. pydicom assigns VR=OB or VR=UN to these elements because the byte stream lacks VR information. This function resolves the correct VR from the DICOM data dictionary and re-decodes the raw bytes.
- Parameters:
ds (Dataset)
- Return type:
None
- dicom_dre.deidentify_file(input_file, output_file, *, profile, parameters, catalog=None, decompress=False, rename_to_sop_uid=True, dataset=None, highlight_blanked_pixels=False)[source]¶
De-identify a single DICOM file using the de-identification pipeline.
Runs the device catalog filter, pixel blanker, and metadata deidentifyr in sequence and returns a library-owned
DeidentifyResult.- Parameters:
input_file (Path) – Path to the PHI DICOM file.
output_file (Path) – Path to write the de-identified DICOM file.
profile (DeidProfile) – The bound de-identification profile to apply. Build one with
dicom_dre.build_profile()or the exported profile factories.parameters (DeidParameters) – Per-patient values applied to the dataset at apply time.
catalog (DeviceCatalog | None) – Device catalog for filtering and pixel-scrub decisions. Defaults to
dicom_dre.get_default_catalog().decompress (bool) – Whether to decompress encapsulated pixel data on output.
rename_to_sop_uid (bool) – Rename the output file to the new SOP Instance UID.
dataset (pydicom.Dataset | None) – Optional pre-read dataset to avoid re-opening
input_file. Used only when no pixel scrubbing is required; it is mutated and written out in place.highlight_blanked_pixels (bool) – Fill scrubbed regions with a visible color.
- Returns:
A
DeidentifyResultwhose outcome is DEIDENTIFIED, FILTERED, or QUARANTINED.- Return type:
- dicom_dre.deidentify_paths(sources, output_dir, *, profile=None, parameters=None, catalog=None, recursive=False, patterns=('*.dcm', '*.dicom'), decompress=False, rename_to_sop_uid=True, highlight_blanked_pixels=False, workers=1, profile_spec=None)[source]¶
De-identify every DICOM file discovered under
sources.Mirrors each source directory tree under
output_dir; explicitly listed files land flat inoutput_dir. Discovery and output-directory creation errors are turned intoQUARANTINEDresults so processing continues; the pipeline itself already quarantines its own internal errors.With
workers == 1(default) inputs are processed sequentially in discovery order. The profile is taken fromprofileif given, otherwise built once in this process fromprofile_spec. Withworkersgreater than one, inputs are dispatched to aconcurrent.futures.ProcessPoolExecutorand results are yielded as each worker completes (not in discovery order). A bound profile cannot be pickled, so parallel runs requireprofile_specand build the profile once per worker;profileis not built or used in that case.Because
profile_specis limited to whatdicom_dre.build_profile()can construct (the registered named profiles), parallel runs support only those profiles. An arbitrary hand-builtDeidProfilethat noprofile_speccan describe must be passed asprofileand run sequentially (workers == 1), since its rules cannot cross a process boundary.When
rename_to_sop_uidis disabled the derived output paths must be unique; if two inputs would be written to the same path the run fails fast withOutputPathCollisionErrorbefore any file is written.- Parameters:
sources (Sequence[Path]) – The source files and/or directories to process.
output_dir (Path) – Root directory under which de-identified files are written.
profile (DeidProfile | None) – The bound de-identification profile to apply. Optional; for a sequential run it is built from
profile_specwhen omitted, and it is ignored entirely for parallel runs.parameters (DeidParameters | None) – Per-patient values applied to every discovered file. Defaults to a
DeidParameterswith all placeholders when omitted.catalog (DeviceCatalog | None) – Device catalog for filtering and pixel-scrub decisions. Defaults to
dicom_dre.get_default_catalog().recursive (bool) – Whether to descend into subdirectories of directory sources.
patterns (Sequence[str]) – Filename glob patterns applied to directory-scan candidates.
decompress (bool) – Whether to decompress encapsulated pixel data on output.
rename_to_sop_uid (bool) – Rename each output file to its new SOP Instance UID.
highlight_blanked_pixels (bool) – Fill scrubbed regions with a visible color.
workers (int) – Number of worker processes.
1runs sequentially in-process.profile_spec (ProfileSpec | None) – Picklable profile description used to rebuild the profile in each worker. Required when
workersis greater than one, and used to build the sequential profile whenprofileis omitted.
- Yields:
One
BatchItemResultper discovered input. Ordered by discovery whenworkers == 1; ordered by completion whenworkers > 1.- Raises:
ValueError – If
workersis less than one, if neitherprofilenorprofile_specis provided for a sequential run, or ifworkersis greater than one without aprofile_spec.OutputPathCollisionError – If
rename_to_sop_uidis disabled and two inputs map to the same output path.
- Return type:
Iterator[BatchItemResult]
- dicom_dre.default_profile(settings=None, *, deid_method='DICOM-PS3.15E-Basic', preserve_dates=False)[source]¶
Construct a full PS3.15E de-identification profile.
The returned profile is a patient-invariant policy object. Per-patient identity values (PatientID, AccessionNumber, StudyID, PatientName, the free-text description overrides, and the date jitter) are supplied at apply time via
DeidParameters.When a caller supplies no PatientID, PatientName, or AccessionNumber, the original element value is hashed with
settings.hash_saltand the study identifier; PatientName reuses the PatientID hash. A fail-safe placeholder is written only when there is no value to hash.The free-text description fields accept a per-patient value that takes precedence; when it is
Nonethe engine redacts the corresponding element from the dataset at apply time usingsettings.allowlist_csv.preserve_datesselects a date-preserving redactor for the free-text fields and does not alter the profile’s date-jitter behavior.- Parameters:
settings (ProfileSettings | None)
deid_method (str)
preserve_dates (bool)
- Return type:
- dicom_dre.get_default_catalog()[source]¶
Return the default device catalog with all translated rules.
- Return type:
- dicom_dre.get_text_redactor(allowlist_csv, preserve_dates=False)[source]¶
Get or create a cached TextRedactor instance for the given allowlist.
- Parameters:
- Returns:
A cached TextRedactor instance configured with the allowlist
- Return type:
- Raises:
ValueError – If the allowlist CSV file does not exist at the specified path
- dicom_dre.jpeg_dct_accelerator_available()[source]¶
Report whether the JPEG DCT C accelerator is active.
Returns the effective runtime state used by the scrubber to select the fast path. When
Falsethe pure-Python entropy codec fallback is used, which is roughly 300x slower.This function is import-safe and side-effect-free: it does not raise and does not re-emit the missing-extension warning.
- Returns:
Trueif the compiled_jpeg_dct_accelextension is loaded and in use,Falseif the pure-Python fallback is active.- Return type:
- dicom_dre.jpeg_dct_accelerator_info()[source]¶
Return diagnostic details about the JPEG DCT C accelerator.
- dicom_dre.lds_no_dob_profile(settings=None)[source]¶
Construct an LDS-No-DOB profile. All dates kept except BirthDate/BirthTime.
- Parameters:
settings (ProfileSettings | None)
- Return type:
- dicom_dre.lds_profile(settings=None, *, deid_method='DICOM-PS3.15E-Basic-LDS')[source]¶
Construct an LDS profile. All dates are preserved via VR inspection.
- Parameters:
settings (ProfileSettings | None)
deid_method (str)
- Return type:
- dicom_dre.strict_profile(settings=None)[source]¶
Construct a strict profile.
Minimal metadata. Removes all unspecified elements. Date and datetime elements are removed entirely rather than date-shifted, so no jitter is applied; allow-listed time elements are retained. UIDs are re-derived without the study-ID salt. Per-patient identity values are supplied at apply time via
DeidParameters. When PatientID, PatientName, or AccessionNumber are not supplied, the original element value is hashed withsettings.hash_saltand the study identifier; PatientName reuses the PatientID hash.The free-text description fields take a per-patient value verbatim; when it is
Nonethey are redacted from the dataset usingsettings.allowlist_csvat apply time.KO and PR label subtrees, along with the PR rendering sequences that bind annotations to their images and define their geometry, are retained through
content_root_tags. The shared PHI-removal, date-removal, and free-text redaction rules are applied so those retained subtrees are de-identified: dates are removed entirely (not date-shifted), and the free-text label fields are redacted against the allowlist. Because the profile hashes UIDs without the study salt, references resolve within a single strict export but not against objects de-identified by another profile.- Parameters:
settings (ProfileSettings | None)
- Return type: