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: object

Result 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
class dicom_dre.ProfileSettings(uid_root='1.2.840.4267.32.', allowlist_csv='default.csv', hash_salt='NOSALT')[source]

Bases: object

Typed 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:
  • uid_root (str) – UID root prefix under which re-derived UIDs are hashed.

  • allowlist_csv (str) – Free-text redaction allowlist filename or absolute path.

  • hash_salt (str) – Salt applied when hashing PatientID, PatientName, and AccessionNumber.

Parameters:
  • uid_root (str)

  • allowlist_csv (str)

  • hash_salt (str)

uid_root: str
allowlist_csv: str
hash_salt: str
class dicom_dre.CatalogDecision(action, reason, scrub_regions=<factory>, matched_variant=None)[source]

Bases: object

Result of evaluating a DICOM instance against the device catalog.

Variables:
Parameters:
action: str
reason: str
scrub_regions: list[ScrubRegion]
matched_variant: Variant | None
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: object

Immutable per-patient de-identification parameters.

Each field records exactly what the caller supplied; None means “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:
  • patient_id (str | None)

  • patient_name (str | None)

  • accession_number (str | None)

  • study_id (str | None)

  • series_description (str | None)

  • study_description (str | None)

  • protocol_name (str | None)

  • jitter (int | None)

patient_id: str | None
patient_name: str | None
accession_number: str | None
study_id: str | None
series_description: str | None
study_description: str | None
protocol_name: str | None
jitter: int | None
classmethod from_mapping(mapping)[source]

Build DeidParameters from 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, and JITTER. Build-time settings (UID root, allowlist CSV, identifier-hash salt) are not accepted here; they belong to dicom_dre.profiles.config.ProfileSettings.

Parameters:

mapping (Mapping[str, str]) – Parameter mapping with uppercase keys.

Returns:

The parsed parameters.

Raises:

ValueError – If JITTER is present but not an integer, or if the mapping contains a key that is not a per-patient identity key.

Return type:

DeidParameters

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: object

Immutable de-identification profile binding tag rules and global flags.

Parameters:
name: str
rules: dict[BaseTag, TagAction]
keep_groups: frozenset[int]
remove_private: bool
remove_curves: bool
remove_overlays: bool
remove_unspecified: bool = False
preserve_dates: bool = False
modifies_dates: bool = False
allowlist_csv: str = 'default.csv'
hash_salt: str | None = None
uid_root: str | None = None
uid_use_study_salt: bool = False
date_override_tags: frozenset[BaseTag]
preserved_private_specs: frozenset[PrivateTagSpec]
emits_basic_profile: bool = True
deid_options: frozenset[str]
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 params at apply time. applied_options carries per-instance de-identification option codes the caller applied outside the profile rules (for example 113101 when the pipeline scrubbed burned-in pixel text); they are merged into the method code sequence alongside the profile-declared deid_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:
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: object

Result 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
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:
Return type:

DeidentifyResult

classmethod filtered(reason, *, input_file=None, parameters=None, input_attributes=None)[source]

Build a rejected (FILTERED) result.

Parameters:
Return type:

DeidentifyResult

classmethod quarantined(error, *, input_file=None, parameters=None, input_attributes=None)[source]

Build a failed (QUARANTINED) result.

Parameters:
Return type:

DeidentifyResult

property was_deidentified: bool

Whether the file was successfully deidentified.

property was_filtered: bool

Whether the file was rejected by the device catalog.

property was_quarantined: bool

Whether the file was quarantined due to a processing error.

property was_scrubbed: bool

Whether pixel data was scrubbed during processing.

class dicom_dre.DeviceCatalog(devices, exclusions, default_action='deny')[source]

Bases: object

Evaluates 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:
  • devices (list[DeviceRule]) – Ordered list of DeviceRule entries.

  • exclusions (list[ExclusionRule]) – List of ExclusionRule entries.

  • default_action (str) – Action when no device or exclusion matches.

property devices: list[DeviceRule]

The ordered device rules.

property exclusions: list[ExclusionRule]

The exclusion rules.

evaluate(tags)[source]

Evaluate a DICOM instance against the catalog.

Parameters:

tags (DicomTags) – Extracted DICOM tag values.

Returns:

A CatalogDecision with action, reason, and scrub regions.

Return type:

CatalogDecision

class dicom_dre.DicomTags(values)[source]

Bases: object

Lightweight wrapper for reading DICOM attributes needed by the catalog.

Normalizes access so the matching engine does not interact with pydicom directly.

Parameters:

values (dict[str, str])

get(keyword)[source]

Return the string value for keyword, or "" if absent.

Parameters:

keyword (str)

Return type:

str

as_dict()[source]

Return the tag values as a plain dict copy.

Return type:

dict[str, str]

get_list(keyword)[source]

Return the multi-valued tag as a list of strings.

Image Type, for example, is stored as "ORIGINAL\PRIMARY\AXIAL".

Parameters:

keyword (str)

Return type:

list[str]

get_int(keyword)[source]

Return the integer value for keyword, or None if absent/non-numeric.

Parameters:

keyword (str)

Return type:

int | None

classmethod from_dataset(ds)[source]

Build from an existing pydicom Dataset.

Parameters:

ds (pydicom.Dataset)

Return type:

DicomTags

classmethod from_file(path)[source]

Read a DICOM file and extract catalog-relevant tags.

Parameters:

path (Path)

Return type:

DicomTags

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: object

Typed snapshot of standard DICOM attributes read from a dataset.

All fields are standard DICOM keywords. None means the element is absent. Multi-valued attributes are tuple[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)

  • modalities_in_study (tuple[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)

  • image_type (tuple[str, ...] | None)

  • software_versions (tuple[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)

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
modalities_in_study: tuple[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
image_type: tuple[str, ...] | None
software_versions: tuple[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
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:

IndexAttributes

classmethod from_file(path)[source]

Read a DICOM file and extract a snapshot.

Uses stop_before_pixels=True because none of the captured attributes require pixel data.

Parameters:

path (Path)

Return type:

IndexAttributes

class dicom_dre.Outcome(*values)[source]

Bases: Enum

Terminal outcome kind for a de-identification run.

DEIDENTIFIED = 'deidentified'
FILTERED = 'filtered'
QUARANTINED = 'quarantined'
exception dicom_dre.OutputPathCollisionError[source]

Bases: ValueError

Two discovered inputs would be written to the same output path.

Raised before any file is written when rename_to_sop_uid is 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: object

Picklable description of a de-identification profile.

A bound DeidProfile cannot 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 with dicom_dre.build_profile(). Per-patient identity values are not part of the spec; they are passed on a DeidParameters.

Variables:
Parameters:
name: str
settings: ProfileSettings
class dicom_dre.ScrubRegion(x, y, width, height)[source]

Bases: object

A rectangular pixel region to blank, in (x, y, width, height) coordinates.

Parameters:
x: int
y: int
width: int
height: int
classmethod from_tuple(values)[source]

Create a ScrubRegion from an (x, y, width, height) tuple.

Parameters:

values (tuple[int, int, int, int])

Return type:

ScrubRegion

classmethod from_string(value)[source]

Create a ScrubRegion from an ‘x,y,width,height’ string.

Parameters:

value (str)

Return type:

ScrubRegion

to_tuple()[source]

Return the region as an (x, y, width, height) tuple.

Return type:

tuple[int, int, int, int]

to_string()[source]

Return the region as an ‘x,y,width,height’ string.

Return type:

str

class dicom_dre.TextRedactor(allowlist=None, delimiters=None, deny_regex_patterns=None, allow_regex_patterns=None, pii_prefixes=None, preserve_dates=False)[source]

Bases: object

Text 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:
  • allowlist (set[str] | None)

  • delimiters (list[str] | None)

  • deny_regex_patterns (list[str] | None)

  • allow_regex_patterns (list[str] | None)

  • pii_prefixes (list[str] | None)

  • preserve_dates (bool)

static create_month_regex()[source]

Create a regex pattern to match month names (full and abbreviated).

Return type:

Pattern[str]

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_timezone_regex()[source]

Create a regex pattern to match timezone abbreviations.

Return type:

Pattern[str]

static create_year_regex()[source]

Create a regex pattern to match 4-digit years.

Return type:

Pattern[str]

static create_date_regex()[source]

Create a regex pattern to match various date formats. Must include year.

Return type:

Pattern[str]

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:
  • text (str) – The input text to redact.

  • track_redacted (bool) – If True, return set of redacted tokens. Default is False.

  • return_token_pairs (bool) – If True, return list of (original_token, redacted_token) pairs.

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: object

A 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:
rows: int | None
cols: int | None
sop_class_uid: str | list[str] | None
software_versions: str | list[str] | None
image_type: str | list[str] | None
image_type_any: str | list[str] | None
image_type_exclude: str | list[str] | None
scrub_regions: list[ScrubRegion]
dicom_dre.build_profile(name, settings=None)[source]

Construct a patient-invariant DeidProfile for 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 ProfileSettings defaults apply.

Returns:

A profile ready for apply(ds, params).

Raises:

ValueError – If the name is unknown.

Return type:

DeidProfile

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 DeidentifyResult whose outcome is DEIDENTIFIED, FILTERED, or QUARANTINED.

Return type:

DeidentifyResult

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 in output_dir. Discovery and output-directory creation errors are turned into QUARANTINED results 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 from profile if given, otherwise built once in this process from profile_spec. With workers greater than one, inputs are dispatched to a concurrent.futures.ProcessPoolExecutor and results are yielded as each worker completes (not in discovery order). A bound profile cannot be pickled, so parallel runs require profile_spec and build the profile once per worker; profile is not built or used in that case.

Because profile_spec is limited to what dicom_dre.build_profile() can construct (the registered named profiles), parallel runs support only those profiles. An arbitrary hand-built DeidProfile that no profile_spec can describe must be passed as profile and run sequentially (workers == 1), since its rules cannot cross a process boundary.

When rename_to_sop_uid is disabled the derived output paths must be unique; if two inputs would be written to the same path the run fails fast with OutputPathCollisionError before 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_spec when omitted, and it is ignored entirely for parallel runs.

  • parameters (DeidParameters | None) – Per-patient values applied to every discovered file. Defaults to a DeidParameters with 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. 1 runs sequentially in-process.

  • profile_spec (ProfileSpec | None) – Picklable profile description used to rebuild the profile in each worker. Required when workers is greater than one, and used to build the sequential profile when profile is omitted.

Yields:

One BatchItemResult per discovered input. Ordered by discovery when workers == 1; ordered by completion when workers > 1.

Raises:
  • ValueError – If workers is less than one, if neither profile nor profile_spec is provided for a sequential run, or if workers is greater than one without a profile_spec.

  • OutputPathCollisionError – If rename_to_sop_uid is 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_salt and 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 None the engine redacts the corresponding element from the dataset at apply time using settings.allowlist_csv. preserve_dates selects a date-preserving redactor for the free-text fields and does not alter the profile’s date-jitter behavior.

Parameters:
Return type:

DeidProfile

dicom_dre.get_default_catalog()[source]

Return the default device catalog with all translated rules.

Return type:

DeviceCatalog

dicom_dre.get_text_redactor(allowlist_csv, preserve_dates=False)[source]

Get or create a cached TextRedactor instance for the given allowlist.

Parameters:
  • allowlist_csv (str) – Filename of the allowlist CSV (e.g. “default.csv”) under allow_lists/.

  • preserve_dates (bool) – If True, dates and times in free text are kept intact. Used for HIPAA limited datasets where date elements are permitted.

Returns:

A cached TextRedactor instance configured with the allowlist

Return type:

TextRedactor

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 False the 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:

True if the compiled _jpeg_dct_accel extension is loaded and in use, False if the pure-Python fallback is active.

Return type:

bool

dicom_dre.jpeg_dct_accelerator_info()[source]

Return diagnostic details about the JPEG DCT C accelerator.

Returns:

A mapping with at least the key "available" (bool). When the accelerator is loaded, "path" holds the extension module file path if it can be determined.

Return type:

dict[str, object]

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:

DeidProfile

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:
Return type:

DeidProfile

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 with settings.hash_salt and the study identifier; PatientName reuses the PatientID hash.

The free-text description fields take a per-patient value verbatim; when it is None they are redacted from the dataset using settings.allowlist_csv at 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:

DeidProfile