Metadata-Version: 2.4
Name: vcti-path-format
Version: 2.0.0
Summary: File format identification framework with heuristic evaluators and feature validators for Python
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-path-format
Project-URL: Changelog, https://github.com/vcollab/vcti-python-path-format/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: vcti-plugin-catalog>=2.0.0
Requires-Dist: vcti-lookup>=2.0.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# Path Format

File format identification framework with heuristic evaluators and feature validators for Python.

## Overview

`vcti-path-format` answers "what format is this file or folder, and how sure
are we?" Each format is a `FormatDescriptor` held in a `FormatRegistry`; the
descriptor's evaluator runs feature validators — magic bytes, extension, or
checks of your own — against a path. Validators are either *gates*, which
rule a format out when they fail, or *evidence*, which only lowers
confidence, and they are grouped into tiers of increasing cost so callers
can stop at cheap checks. `FormatIdentifier` evaluates a path against every
registered format and ranks the results on a five-level `MatchConfidence`
scale.

## Installation

```bash
pip install "vcti-path-format>=2.0.0"
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-path-format>=2.0.0",
]
```

---

## Quick Start

```python
from pathlib import Path
from vcti.pathformat.core import (
    FormatDescriptor,
    FormatIdentifier,
    FormatRegistry,
    HeuristicEvaluator,
    MatchConfidence,
    PathKind,
)

# Define a format descriptor with validators
hdf5_descriptor = FormatDescriptor(
    id="hdf5-file",
    name="HDF5 File",
    evaluator=(
        HeuristicEvaluator()
        .check_path_kind(PathKind.FILE)  # PRECONDITION: rules out directories
        .check_magic_bytes(b"\x89HDF\r\n\x1a\n")  # GATE
        .check_extension([".h5", ".hdf5", ".he5"])  # EVIDENCE
    ),
    attributes={"path_type": "file", "structure": "hdf5"},
)

# Register in a format registry
registry = FormatRegistry()
registry.register(hdf5_descriptor)

# Identify a file
identifier = FormatIdentifier(registry)
results = identifier.identify_file_format(Path("data.h5"))

for result in results:
    print(f"{result.descriptor.name}: {result.confidence.name}")

# Get best match above a confidence threshold
best = identifier.get_best_match(
    Path("data.h5"),
    min_confidence=MatchConfidence.LIKELY,
)
```

---

## Core Concepts

### FormatDescriptor

Extends `Descriptor[Evaluator]` from vcti-plugin-catalog. Wraps an evaluator
with format metadata and attributes.

### FormatRegistry

Extends `Registry[FormatDescriptor]`. Central catalog of known formats with
attribute-based filtering via `registry.lookup`.

### FormatIdentifier

Evaluates a path against all (or filtered) registered formats and returns
results sorted by confidence, then by descriptor `priority`.

### HeuristicEvaluator

Builder-pattern evaluator that runs feature validators and turns their
results into a confidence:

```python
from vcti.pathformat.core import HeuristicEvaluator, PathKind

evaluator = (
    HeuristicEvaluator()
    .check_path_kind(PathKind.FILE)            # PRECONDITION
    .check_magic_bytes(b"\x89PNG\r\n\x1a\n")   # GATE
    .check_extension([".png"])                 # EVIDENCE
)
```

Each validator plays a **role**:

| Role | Failure | Success |
|------|---------|---------|
| `PRECONDITION` | Rules the format out | No evidence — the format merely *applies* (e.g. "is a file") |
| `GATE` | Rules the format out | Strong evidence of a match (e.g. the signature) |
| `EVIDENCE` | Lowers confidence | Raises confidence |

A validator that cannot obtain evidence — the file cannot be read — returns
an *inconclusive* result instead of a failure: an inconclusive
PRECONDITION or GATE gives `CANT_EVALUATE`, not `CERTAINLY_NOT`.

**Confidence rules.** A failed PRECONDITION or GATE gives `CERTAINLY_NOT`,
an inconclusive one `CANT_EVALUATE`, and either stops evaluation. Otherwise
the evaluator's confidence policy decides. The default policy:

- All passed + GATE present -> `DEFINITE`
- GATE passed, some EVIDENCE failed -> `LIKELY`
- All passed + no GATE -> `LIKELY`
- Some EVIDENCE failed, no GATE -> `UNLIKELY`
- No GATE and no conclusive EVIDENCE -> `CANT_EVALUATE`

### Feature Validators

| Validator | Default role | Tier | Checks |
|-----------|--------------|------|--------|
| `PathKindValidator` | PRECONDITION | IDENTIFICATION | Path is a file, or a directory (`check_path_kind`) |
| `MagicBytesValidator` | GATE | IDENTIFICATION | File signature bytes (`check_magic_bytes`) |
| `ExtensionValidator` | EVIDENCE | IDENTIFICATION | File extension (`check_extension`) |

Every descriptor is evaluated against every path, so a file format also
meets directories and a directory format meets files. `check_path_kind()`
rules those out before any other check reads the path; it looks at the
filesystem, not at descriptor attributes.

Custom validators implement the `FeatureValidator` protocol — no base class
needed. See [docs/extending.md](docs/extending.md) for a worked example and
for when to return a failed versus an inconclusive result.

---

## Deciding What Counts

Which evidence matters is a property of the format, so the descriptor's
author decides it:

- **`role=`** on any builder method overrides a validator's default role —
  e.g. make an extension a GATE for a format it defines.
- **`policy=`** on `HeuristicEvaluator` replaces the default confidence
  policy with a function of the results.
- **`priority=`** on `FormatDescriptor` ranks formats that reach the same
  confidence — e.g. CGNS above the plain HDF5 it is built on.

```python
from vcti.pathformat.core import FormatDescriptor, HeuristicEvaluator, ValidatorRole

erf_descriptor = FormatDescriptor(
    id="erfh5",
    name="ERF HDF5",
    evaluator=(
        HeuristicEvaluator()
        .check_magic_bytes(b"\x89HDF\r\n\x1a\n")
        .check_extension([".erfh5"], role=ValidatorRole.GATE)
    ),
    priority=10,  # wins over a generic HDF5 descriptor when both match
)
```

Why the package leaves these choices to you is in
[docs/design.md](docs/design.md); writing a policy is in
[docs/extending.md](docs/extending.md).

---

## Validation Tiers

Control evaluation depth with `max_tier`:

| Tier | Cost | Examples |
|------|------|---------|
| `IDENTIFICATION` | Cheap | Path kind, magic bytes, file extension |
| `STRUCTURE` | Medium | Schema validation, header parsing |
| `SEMANTIC` | Expensive | Content analysis, business logic |

```python
from vcti.pathformat.core import ValidationTier

# Only run cheap checks
results = identifier.identify_file_format(path, max_tier=ValidationTier.IDENTIFICATION)
```

---

## Evaluator Caching

Each `HeuristicEvaluator` caches its reports, keyed by the resolved path,
its modification time and size, and `max_tier`, so a changed file is
evaluated afresh. `HeuristicEvaluator(cache_size=0)` disables the cache,
`evaluate(path, use_cache=False)` bypasses it once, and `cache_info()` /
`clear_cache()` inspect and reset it. Sizing, the cases the key cannot see
(an edit inside an evaluated directory) and thread safety are in
[docs/production-guide.md](docs/production-guide.md).

---

## Pre-filtering with Rules

```python
from vcti.lookup import Rule

# Only evaluate formats with structure="hdf5"
results = identifier.identify_file_format(
    path,
    rules=[Rule("structure", "==", "hdf5")],
)
```

---

## Error Handling

A path that cannot be identified raises a standard exception, so one
`except (ValueError, OSError)` covers it:

| Exception | When |
|-----------|------|
| `FileNotFoundError` (an `OSError`) | Path does not exist; `.filename` holds the path |
| `UnsupportedPathError` (a `ValueError`) | Path is neither a regular file nor a directory, e.g. a socket or named pipe; `.path` holds the path |

An unreadable file is not an error either: `MagicBytesValidator` reports
it as inconclusive, so the formats it gates come out `CANT_EVALUATE` rather
than ruled out.

```python
try:
    results = identifier.identify_file_format(path)
except (ValueError, OSError) as e:
    print(f"Cannot identify {path}: {e}")
```

A format whose evaluator fails does not stop the others. Its result is
`CANT_EVALUATE`, the error is attached as `result.error`, and a WARNING is
logged:

```python
for result in identifier.identify_file_format(path):
    if result.error is not None:
        print(f"{result.descriptor.id} failed: {result.error}")
```

Pass `strict=True` to `identify_file_format()` or `get_best_match()` to
raise the error instead — useful in the tests of a descriptor package.

Errors from evaluation itself derive from `EvaluatorError`. All exception
classes are importable from `vcti.pathformat.core`:

| Exception | When |
|-----------|------|
| `EvaluatorError` | Base class for evaluator errors |
| `ValidationError` | A validator raised an unexpected exception; raised by `FormatIdentifier` only with `strict=True` |
| `InvalidValidatorError` | Invalid validator or arguments passed to a builder method |

---

## Ecosystem

This package is the identification engine in a three-repo system:

| Package | Role |
|---------|------|
| **vcti-path-format** | Framework: evaluators, validators, registry, identifier |
| [vcti-path-format-attributes](https://pypi.org/project/vcti-path-format-attributes/) | Vocabulary: standardized attribute enums |
| [vcti-path-format-descriptors](https://pypi.org/project/vcti-path-format-descriptors/) | Built-in format definitions (HDF5, CAX, etc.) |

---

## Dependencies

- [vcti-plugin-catalog](https://pypi.org/project/vcti-plugin-catalog/) (>=2.0.0) — descriptor/registry framework
- [vcti-lookup](https://pypi.org/project/vcti-lookup/) (>=2.0.0) — attribute-based filtering

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| See practical, real-world usage | [docs/patterns.md](docs/patterns.md) |
| Understand the architecture and design decisions | [docs/design.md](docs/design.md) |
| Run it in a long-lived or multi-threaded service | [docs/production-guide.md](docs/production-guide.md) |
| See how the related path-format repositories fit together | [docs/ecosystem.md](docs/ecosystem.md) |
| Navigate and understand the source | [docs/source-guide.md](docs/source-guide.md) |
| Add custom validators or evaluators | [docs/extending.md](docs/extending.md) |
