API Reference

This section provides a detailed reference for all the modules, classes, and functions available in dartfx-unf.

Top-Level Interface

For most common tasks, you can use the functions re-exported at the package level.

dartfx-unf is a high-performance Python implementation of the Universal Number Fingerprint (UNF) v6 specification, built on the Polars engine.

The library provides tools to calculate system-independent digital signatures (fingerprints) for data objects, ensuring data integrity across different environments and formats.

Key Features

  • Column-level hashing: Fingerprint individual Polars Series.

  • File-level hashing: Supports CSV, Parquet, and TSV with automatic format detection.

  • Dataset-level hashing: Combine fingerprints from multiple files into a single hash.

  • Out-of-core processing: Efficiently handle massive datasets using streaming.

Public API

Quick Example

>>> from dartfx.unf import unf_file
>>> report = unf_file("data.parquet")
>>> print(report.result.unf)

Core Computation

The dartfx.unf.core module contains the main logic for file, dataset, and vector-level hashing.

Core UNF v6 computation – column, file, and dataset levels.

This module provides the three public entry-points of the library:

  • unf_column – compute the UNF of a single Polars Series.

  • unf_dataframe – compute the UNF of a Polars DataFrame.

  • unf_file – compute the UNF of a CSV or Parquet file.

  • unf_dataset – compute the combined UNF of multiple files.

  • unf_from_bytes – compute the UNF from raw file bytes.

  • unf_from_stream – compute the UNF from a file-like object.

For large files, unf_file automatically switches to streaming mode when the file size exceeds a fraction of available system memory. This can also be controlled explicitly via the streaming parameter.

dartfx.unf.core.unf_column(series: Series, params: UNFParameters | None = None, null_handling: Literal['null-as-null', 'null-as-string'] = 'null-as-null') → str[source]

Compute the UNF fingerprint of a single data vector (Polars Series).

This function implements the UNF v6 specification for individual vectors, including type-specific normalization (numeric rounding, string truncation, bit-field encoding, etc.) and SHA-256 hashing.

Parameters:
  • series (pl.Series) – A Polars Series containing the data to fingerprint. Supports all standard Polars dtypes including Integers, Floats, Strings (Utf8), Booleans, Dates, Datetimes, and Durations.

  • params (UNFParameters, optional) – Calculation parameters (digits, hash bits, etc.). If None, default UNF v6 settings are used (N=7, H=128, X=128).

  • null_handling (Literal["null-as-null", "null-as-string"], default "null-as-null") – If “null-as-string”, null values in string-like columns are normalized as empty strings (newline + null byte) instead of the UNF missing value representation (3 null bytes). This provides parity with the canonical Java Dataverse implementation’s CSV parsing behavior.

Returns:

The printable UNF v6 fingerprint string (e.g., UNF:6:Do5dfAoOOFt4FSj0JcByEw==).

Return type:

str

dartfx.unf.core.unf_dataframe(df: DataFrame, *, params: UNFParameters | None = None, label: str | None = None, null_handling: Literal['null-as-null', 'null-as-string'] = 'null-as-null') → UNFReport[source]

Compute the UNF fingerprint for a Polars DataFrame.

Implements the “combination” rule for dataframes: individual column hashes are sorted lexicographically and then hashed together to form the table-level fingerprint. This ensures that the UNF is invariant to column order.

Parameters:
  • df (pl.DataFrame) – The Polars DataFrame to fingerprint.

  • params (UNFParameters, optional) – Calculation parameters. Uses defaults if None.

  • label (str, optional) – A human-readable label or filename for the report.

  • null_handling (Literal["null-as-null", "null-as-string"], default "null-as-null") – If “null-as-string”, the implementation provides bit-for-bit parity with the canonical Java Dataverse CSV reader. Any column containing nulls is coerced to a string column, and those nulls are normalized as empty strings (nx00) instead of missing values (x00x00x00).

Returns:

A structured report containing the final UNF, individual column UNFs, and types.

Return type:

UNFReport

Examples

>>> import polars as pl
>>> from dartfx.unf import unf_dataframe
>>> df = pl.DataFrame({"a": [1, 2], "b": [3.5, 4.5]})
>>> report = unf_dataframe(df, label="my_table")
>>> print(report.result.unf)
UNF:6:L1XOn/hA9Y/p/v3N8XjH9A==
>>> # Inspect columns in the report
>>> for col in report.result.columns:
...     print(f"{col.name}: {col.unf}")
dartfx.unf.core.unf_dataset(paths: Sequence[str | Path], *, params: UNFParameters | None = None, label: str | None = None, streaming: bool | None = None, batch_size: int = 100000, infer_schema_length: int = 10000, schema: str | Path | dict[str, Any] | None = None, parse_dates: bool = True, detect_leading_zeros: bool = False, null_handling: Literal['null-as-null', 'null-as-string'] = 'null-as-null') → UNFReport[source]

Compute the combined UNF of multiple files (e.g. a partitioned dataset).

Equivalent to the UNF of a collection of files as per UNF v6 §IIb. Individual file fingerprints are computed, sorted lexicographically, and hashed.

Parameters:
  • paths (list of Path or str) – List of files to process.

  • params (UNFParameters, optional) – Common parameters for all files.

  • label (str, optional) – Label for the entire dataset.

  • streaming (bool, optional) – Whether to use streaming mode for individual files.

  • batch_size (int, optional) – Rows per batch for streaming.

  • infer_schema_length (int, optional) – Number of rows to scan for CSV schema inference. Use -1 to scan all rows.

  • schema (str, Path, dict, or None) – Optional schema specification to override type inference for all files. Same format as in unf_file().

  • parse_dates (bool, default True) – If True, attempt to auto-parse date and datetime columns in CSV files.

  • detect_leading_zeros (bool, default False) – If True, auto-detect columns with leading zeros (e.g. ‘01’) and treat them as strings to preserve the zeros. Disabled by default.

  • null_handling (Literal["null-as-null", "null-as-string"], default "null-as-null") – If “null-as-string”, the implementation provides bit-for-bit parity with the canonical Java Dataverse CSV reader. Any column containing nulls is coerced to a string column, and those nulls are normalized as empty strings (nx00) instead of missing values (x00x00x00).

Returns:

A report containing the dataset-level UNF and a collection of file-level results.

Return type:

UNFReport

Examples

>>> from dartfx.unf import unf_dataset
>>> files = ["part-1.parquet", "part-2.parquet"]
>>> ds_report = unf_dataset(files, label="Version_1")
>>> print(f"Unified UNF: {ds_report.result.unf}")
dartfx.unf.core.unf_file(path: str | Path, *, params: UNFParameters | None = None, label: str | None = None, streaming: bool | None = None, batch_size: int = 100000, infer_schema_length: int = 10000, schema: str | Path | dict[str, Any] | None = None, parse_dates: bool = True, detect_leading_zeros: bool = False, null_handling: Literal['null-as-null', 'null-as-string'] = 'null-as-null') → UNFReport[source]

Compute the UNF fingerprint for a CSV or Parquet data file.

This is the main entry point for file-based fingerprinting. It handles schema inference, format detection, and performance optimization based on file size.

Parameters:
  • path (str or Path) – Path to a CSV or Parquet data file.

  • params (UNFParameters, optional) – Normalization parameters (digits, characters, hash_bits, truncate).

  • label (str, optional) – Human-readable label for the file in the report.

  • streaming (bool, optional) – If True, force streaming mode (process in batches, constant memory). If False, force in-memory mode. If None (the default), auto-detect based on file size vs. available system memory.

  • batch_size (int) – Number of rows per batch in streaming mode (default 100 000).

  • infer_schema_length (int) – Number of rows to scan for CSV schema inference (default 10 000). Use -1 to scan all rows.

  • schema (str, Path, dict, or None) – Optional schema specification to override type inference. Can be: - Path to a JSON Schema file - Inline JSON Schema string - Dictionary mapping column names to JSON Schema type names User-specified types take precedence over inferred types.

  • parse_dates (bool, default True) – If True, attempt to auto-parse date and datetime columns in CSV files.

  • detect_leading_zeros (bool, default False) – If True, auto-detect columns with leading zeros (e.g. ‘01’) and treat them as strings to preserve the zeros. Disabled by default.

  • null_handling (Literal["null-as-null", "null-as-string"], default "null-as-null") – If “null-as-string”, the implementation provides bit-for-bit parity with the canonical Java Dataverse CSV reader. Any column containing nulls is coerced to a string column, and those nulls are normalized as empty strings (nx00) instead of missing values (x00x00x00).

Returns:

A structured report containing column-level and file-level UNFs.

Return type:

UNFReport

Raises:

ValueError – If the file format is not supported or schema is invalid.

Examples

>>> # With schema file
>>> report = unf_file("data.csv", schema="schema.json")
>>>
>>> # With inline schema
>>> schema_json = '{"properties": {"age": {"type": "integer"}}}'
>>> report = unf_file("data.csv", schema=schema_json)
>>>
>>> # With dictionary
>>> report = unf_file("data.csv", schema={"age": "integer", "name": "string"})
dartfx.unf.core.unf_from_bytes(data: bytes, format: str, *, params: UNFParameters | None = None, label: str | None = None, parse_dates: bool = True) → UNFReport[source]

Compute the UNF from raw file bytes.

Parameters:
  • data (bytes) – The raw bytes of a CSV or Parquet file.

  • format (str) – Either “csv” or “parquet”.

  • params (UNFParameters, optional) – Calculation parameters.

  • label (str, optional) – A human-readable label for the report.

  • parse_dates (bool, default True) – If True, attempt to auto-parse date and datetime columns in CSV datasets.

Returns:

A structured UNF report.

Return type:

UNFReport

dartfx.unf.core.unf_from_stream(stream: BinaryIO, format: str, *, params: UNFParameters | None = None, label: str | None = None, parse_dates: bool = True) → UNFReport[source]

Compute the UNF from a file-like object.

Parameters:
  • stream (BinaryIO) – A file-like object (e.g. from open(..., 'rb') or BytesIO).

  • format (str) – Either “csv” or “parquet”.

  • params (UNFParameters, optional) – Calculation parameters.

  • label (str, optional) – A human-readable label for the report.

  • parse_dates (bool, default True) – If True, attempt to auto-parse date and datetime columns in CSV streams.

Returns:

A structured UNF report.

Return type:

UNFReport

Configuration & Parameters

Use UNFParameters to control the precision and behavior of the fingerprinting algorithm.

UNF calculation parameters.

class dartfx.unf.parameters.UNFParameters(digits: int = 7, characters: int = 128, hash_bits: int = 128, truncate: bool = False)[source]

Bases: object

Parameters controlling the Universal Number Fingerprint (UNF) v6 calculation.

This class encapsulates all the optional parameters defined in the UNF v6 specification. When non-default values are used, they are automatically encoded into the resulting UNF header string (e.g., UNF:6:N9:...).

Examples

>>> from dartfx.unf.parameters import UNFParameters
>>> # Standard v6 defaults
>>> params = UNFParameters()
>>> print(params.header)
UNF:6:
>>> # High precision (9 digits) and larger hash (256 bits)
>>> params = UNFParameters(digits=9, hash_bits=256)
>>> print(params.header)
UNF:6:N9,H256:
>>> # Use truncation (R1) mode
>>> params = UNFParameters(truncate=True)
>>> print(params.header)
UNF:6:R1:
characters: int = 128
digits: int = 7
hash_bits: int = 128
property header: str

Build the UNF header string, e.g. UNF:6: or UNF:6:N9,H256:.

property is_default: bool

Return True if all parameters are at their default values.

truncate: bool = False

Reporting & Results

The dartfx.unf.report module provides the structured models used to represent the output of a UNF calculation.

Structured report model for UNF results.

class dartfx.unf.report.ColumnResult(name: str, type: str = '', unf: str = '')[source]

Bases: object

UNF result for a single column (vector).

name: str
type: str = ''
unf: str = ''
class dartfx.unf.report.DatasetResult(type: str = 'dataset', label: str = '', unf: str = '', entries: list[FileResult] = <factory>)[source]

Bases: object

UNF result for a dataset (multiple files).

entries: list[FileResult]
label: str = ''
type: str = 'dataset'
unf: str = ''
class dartfx.unf.report.FileResult(type: str = 'file', label: str = '', unf: str = '', columns: list[ColumnResult] = <factory>)[source]

Bases: object

UNF result for a single file (data frame).

columns: list[ColumnResult]
label: str = ''
type: str = 'file'
unf: str = ''
class dartfx.unf.report.UNFReport(result: FileResult | DatasetResult, params: UNFParameters = <factory>, timestamp: str = '', unf_version: str = '6', options: dict[str, ~typing.Any]=<factory>)[source]

Bases: object

A structured report containing the final results of a UNF calculation.

This class wraps the final fingerprint (which can be a file-level result or a dataset-level result), the parameters used for the calculation, and a timestamp. It provides built-in methods for serializing the results to standard JSON formats that comply with the project’s JSON schema.

Examples

>>> from dartfx.unf import unf_file
>>> report = unf_file("data.parquet")
>>> # Save as a validated JSON file
>>> with open("report.json", "w") as f:
...     f.write(report.to_json(validate=True))
>>> # Get just the top-level UNF
>>> print(report.result.unf)
UNF:6:Do5dfAoOOFt4FSj0JcByEw==
options: dict[str, Any]
params: UNFParameters
result: FileResult | DatasetResult
timestamp: str = ''
to_dict(*, validate: bool = False) → dict[str, Any][source]

Serialize the report to a plain dict matching the JSON schema.

If validate is True, the resulting dict is validated against the bundled unf.schema.json using the jsonschema library.

to_json(indent: int = 2, *, validate: bool = False) → str[source]

Serialize the report to a JSON string.

unf_version: str = '6'

Normalization Logic

Internal functions responsible for spec-compliant data normalization.

Normalization of individual values according to UNF v6 specification.

This module handles section Ia of the specification: - Numeric normalization (Ia.1) - String normalization (Ia.2) - Boolean normalization (Ia.3) - Date/Time normalization (Ia.5) - Missing value encoding (Ia.6)

dartfx.unf.normalize.normalize_bit_field(value: bytes) → bytes[source]

Normalize a bit field value per UNF v6 spec §Ia.4.

Normalization steps: 1. Convert to big-endian form (implicit in binary input). 2. Truncate leading zero bits. 3. Align to a byte boundary (minimise bytes needed). 4. Base64 encode the result. 5. Append terminator.

dartfx.unf.normalize.normalize_boolean(value: bool) → bytes[source]

Normalize a boolean value per UNF v6 spec §Ia.3.

Booleans are treated as numeric 1 (True) or 0 (False).

dartfx.unf.normalize.normalize_date(value: date) → bytes[source]

Normalize a date value per UNF v6 spec §Ia.5a.

Format: YYYY-MM-DD, zero-padded.

Parameters:

value (datetime.date) – The date value to normalize.

Returns:

The normalized byte representation including the terminator.

Return type:

bytes

dartfx.unf.normalize.normalize_datetime(value: datetime) → bytes[source]

Normalize a combined date+time value per UNF v6 spec §Ia.5c.

Format: YYYY-MM-DDThh:mm:ss[.fffff][Z]

If the datetime is timezone-aware, it is converted to UTC and a Z suffix is appended. Partial dates are prohibited in combined date and time values.

Parameters:

value (datetime.datetime) – The datetime value to normalize.

Returns:

The normalized byte representation including the terminator.

Return type:

bytes

dartfx.unf.normalize.normalize_duration(value: timedelta) → bytes[source]

Normalize a duration/interval value per UNF v6 spec §Ia.5d.

Durations are represented as the total number of seconds, normalized as a numeric value. This is a pragmatic interpretation since the spec dropped formal duration support but Polars Duration columns still need handling.

Parameters:

value (datetime.timedelta) – The duration value to normalize.

Returns:

The normalized byte representation including the terminator.

Return type:

bytes

dartfx.unf.normalize.normalize_missing() → bytes[source]

Return the missing value representation per UNF v6 spec §Ia.6.

Missing values are encoded as 3 null bytes with NO terminator.

dartfx.unf.normalize.normalize_numeric(value: float | int, digits: int = 7, *, truncate: bool = False) → bytes[source]

Normalize a single numeric value per UNF v6 spec §Ia.1.

Parameters:
  • value (float or int) – The numeric value to normalize.

  • digits (int) – Number of significant digits (N).

  • truncate (bool) – If True, truncate instead of rounding (R1 mode).

Returns:

The normalized byte representation including the terminator.

Return type:

bytes

dartfx.unf.normalize.normalize_string(value: str, max_chars: int = 128) → bytes[source]

Normalize a character string per UNF v6 spec §Ia.2.

Encode as UTF-8, truncate to max_chars characters, then add the newline + null terminator.

Parameters:
  • value (str) – The string value to normalize.

  • max_chars (int) – Maximum number of characters to keep (X).

Returns:

The normalized byte representation.

Return type:

bytes

dartfx.unf.normalize.normalize_time(value: time) → bytes[source]

Normalize a time value per UNF v6 spec §Ia.5b.

Format: hh:mm:ss[.fffff][Z]

If the time has timezone information, it is converted to UTC and a Z suffix is appended.

Parameters:

value (datetime.time) – The time value to normalize.

Returns:

The normalized byte representation including the terminator.

Return type:

bytes

Internal Utilities

SHA-256 hashing and UNF fingerprint generation (spec §Ib and §II).

dartfx.unf.hasher.combine_unfs(unf_strings: list[str], params: UNFParameters | None = None) → str[source]

Combine multiple UNF strings into a single UNF (spec §IIa / §IIb).

Implements the combination algorithm for higher-level UNF objects:

  1. Strip the UNF:6: header from each individual UNF, keeping only the base64 hash component.

  2. Sort the stripped hashes in POSIX locale order (byte-level).

  3. Apply the UNF character-string algorithm (UTF-8 encode, terminate with \n\0, concatenate, SHA-256 hash).

Note

The UNF v6 specification text says to sort “the printable UTF-8 representations of the individual UNFs”, which could be read as using the full UNF:6:... strings. However, the canonical Java reference implementation (UnfDigest.addUNFs in the Dataverse UNF library) strips the header before combining. This implementation follows the Java behaviour to ensure interoperability with the Dataverse ecosystem and all existing UNF signatures produced by it.

See: https://github.com/IQSS/UNF (UnfDigest.addUNFs)

Parameters:
  • unf_strings (list[str]) – List of printable UNF strings to combine (e.g. ["UNF:6:abc==", "UNF:6:xyz=="]).

  • params (UNFParameters, optional) – Calculation parameters. Uses defaults if not provided.

Returns:

The combined UNF string.

Return type:

str

dartfx.unf.hasher.compute_unf_hash(concatenated: bytes, params: UNFParameters | None = None) → str[source]

Compute the UNF fingerprint from a concatenated byte string.

This implements spec §Ib: 1. Compute SHA-256 of the concatenated normalized values. 2. Truncate the hash to H bits (default 128). 3. Encode the result in base64. 4. Prepend the UNF header.

Parameters:
  • concatenated (bytes) – The concatenated, normalized byte representations of all vector elements.

  • params (UNFParameters, optional) – Calculation parameters. Uses defaults if not provided.

Returns:

The printable UNF string, e.g. UNF:6:Do5dfAoOOFt4FSj0JcByEw==.

Return type:

str

dartfx.unf.hasher.finalize_hash(hasher: hashlib._Hash, params: UNFParameters | None = None) → str[source]

Produce a UNF string from an in-progress SHA-256 hasher.

This is the incremental counterpart of compute_unf_hash(). Feed normalized bytes into the hasher via hasher.update(chunk) across one or more batches, then call this function once to obtain the final UNF string.

Parameters:
  • hasher (hashlib._Hash) – A SHA-256 hash object (from hashlib.sha256()).

  • params (UNFParameters, optional) – Calculation parameters. Uses defaults if not provided.

Returns:

The printable UNF string.

Return type:

str

System memory utilities for streaming decision-making.

Provides platform-aware memory detection and a heuristic to decide whether a file should be processed in-memory or via streaming.

dartfx.unf.memory.get_available_memory() → int[source]

Estimate available system memory in bytes.

Strategy (in order of preference):

  1. Linux /proc/meminfo – reads MemAvailable, which accounts for caches and buffers and is the most accurate indicator of how much memory a new process can use.

  2. Windows kernel32.GlobalMemoryStatusEx – returns available physical memory via the Win32 API (no external dependencies).

  3. os.sysconf – available on macOS and Linux; returns total physical memory (not currently-free memory, but still useful as an upper bound).

  4. Fallback – assume 4 GB.

Returns:

Estimated available memory in bytes.

Return type:

int

dartfx.unf.memory.should_stream(file_path: Path, *, memory_fraction: float = 0.25) → bool[source]

Decide whether a file should be processed via streaming.

The heuristic compares the on-disk file size against a configurable fraction of available memory. Because in-memory representations (especially for CSV) can be several times larger than the raw file, the default fraction is conservative (25 %).

Parameters:
  • file_path (Path) – Path to the data file.

  • memory_fraction (float) – Fraction of available memory above which streaming is triggered. Default is 0.25 (25 %).

Returns:

True if streaming is recommended.

Return type:

bool