Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/run_pytest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@ jobs:
test:
runs-on: ubuntu-latest
strategy:
# Report every version's real outcome. With fail-fast on (the default),
# the first failing version cancels the other four, so a single red
# version hides whether the rest passed.
fail-fast: false
matrix:
python-version: ["3.12"]
# Every version `requires-python` claims to support, so the floor is
# enforced rather than asserted.
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]

steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
Expand Down
52 changes: 52 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,58 @@ Each release links to full notes on the

## [Unreleased]

### Added

- Support for Python 3.10 and 3.11, and testing through 3.14. `requires-python`
moves from `>=3.12` to `>=3.10`, with trove classifiers for 3.10-3.14 and a
CI matrix covering every version claimed, so the floor is enforced rather
than asserted ([#201](https://github.com/awslabs/stickler/issues/201))
- New extras that scope the peripheral modules: `semantic` (Bedrock
embeddings), `docsplit` (document packet splitting), `reporting` (HTML report
tables). `all` aggregates every extra except `bert`, whose ML stack is large
enough that installing it unasked is a surprise

### Changed

- **Breaking:** the peripheral modules now require their extra. `pandas`,
`scipy`, `scikit-learn`, and `jinja2` are no longer core dependencies, so
`pip install stickler-eval` installs the comparison engine and nothing else.
Code that used these without installing an extra now raises `ImportError`
naming the extra to install:

| what you were using | now needs |
|---|---|
| `stickler.doc_split` (raises at import) | `stickler-eval[docsplit]` |
| `MarkdownUtil.table_df()` | `stickler-eval[reporting]` |
| `LLMComparator(...)` | `stickler-eval[llm]` |
| `SemanticComparator` cosine similarity | `stickler-eval[semantic]` |

Confidence calibration metrics are **not** affected: `scikit-learn` stays in
the core dependency set because calibration is core functionality, not an
add-on. The `confidence` extra is now empty and kept only so existing pins
keep resolving.

`pip install "stickler-eval[all]"` restores everything except `bert`.

Only `stickler.doc_split` fails at import time; the rest fail at first use.
`SemanticComparator` still constructs on a core install and raises when the
similarity function runs
([#201](https://github.com/awslabs/stickler/issues/201))

- Optional comparators are now imported lazily. `import stickler` no longer
pulls a scientific-computing stack: 421 modules on a core install, down from
1664, with none of pandas, scipy, scikit-learn, jinja2, torch, transformers,
strands, or boto3 on the path. `scikit-learn` is a core dependency but its
import stays inside `AUROCMetric.compute()`, so it costs nothing at import
time. `BERTComparator` no longer loads its model at import time. Accessing an
optional comparator whose extra is missing raises `AttributeError`, so
`hasattr()` gating keeps working
([#187](https://github.com/awslabs/stickler/issues/187))

- Relaxed the `scikit-learn` floor from `>=1.8.0` to `>=1.7.2`. 1.8.0 requires
Python 3.11+, so the old floor made the 3.10 support above unresolvable. The
lock pins 1.7.2 below 3.11 and 1.8.0 above

## [0.6.0] - 2026-07-30

### Added
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ Whether you're extracting data from documents, performing ETL transformations, e
pip install stickler-eval
```

That installs the comparison engine and confidence calibration, which is everything you need to score structured output: comparators, list matching, per-field metrics, and calibration metrics (AUROC, Brier score, ECE, error capture at budget). Genuinely optional features declare their own extras, so a default install does not pull an ML stack:

| Extra | Adds | For |
|---|---|---|
| `[semantic]` | boto3, scipy | `SemanticComparator` (Bedrock embeddings) |
| `[llm]` | strands-agents, jinja2 | `LLMComparator` (LLM-as-judge comparison) |
| `[bert]` | evaluate, torch, bert-score | `BERTComparator` (BERTScore similarity) |
| `[docsplit]` | pandas, scipy, scikit-learn | Document packet splitting metrics |
| `[reporting]` | pandas | Confusion-matrix tables in HTML reports |
| `[all]` | all of the above except the ML stack | Convenience |

Importing a feature without its extra raises an error naming the extra to install.

## Already have a Pydantic model? Evaluate with zero config

If you have a plain [Pydantic](https://docs.pydantic.dev/) model (for example, the `response_model` a Strands agent produces structured output with), you can score it as-is. No `StructuredModel` subclass, no comparators, no thresholds, no schema. Stickler infers a sensible comparator and threshold per field from the model itself, then shows you exactly what it chose.
Expand Down
67 changes: 59 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,33 @@ classifiers = [
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries :: Python Modules",
]
requires-python = ">=3.12"
requires-python = ">=3.10"

# The comparison engine plus confidence calibration, which is core
# functionality rather than a peripheral add-on: knowing whether a model's
# self-reported confidence tracks correctness is part of evaluating it.
# Genuinely peripheral modules (document splitting, HTML reporting) declare
# their own extras below.
dependencies = [
"pydantic>=2.11.0,<3.0.0",
"rapidfuzz>=3.4.0,<4.0.0",
"munkres>=1.1.4",
"numpy>=1.26.0,<3.0.0",
"scipy>=1.12.0,<2.0.0",
"psutil>=5.9.6,<7.0.0",
"pandas>=2.1.1,<3.0.0",
"jsonschema>=4.17.3,<5.0.0",
"scikit-learn>=1.8.0,<2.0.0",
"jinja2>=3.1.6,<3.2.0",
"python-dateutil>=2.8.2,<3.0.0"
"python-dateutil>=2.8.2,<3.0.0",
# AUROC is the only metric that needs it; the other three calibration
# metrics are pure Python. Issue #216 replaces this with a numpy
# implementation, after which scikit-learn leaves the dependency set.
# Floor is 1.7.2 rather than 1.8.0 because 1.8.0 requires Python 3.11+.
"scikit-learn>=1.7.2,<2.0.0",
]

# pip-compatible extras (for `pip install -e ".[dev]"`)
Expand All @@ -43,6 +52,15 @@ dev = [
"pytest-xdist>=3.0.0",
"coverage>=7.0.0",
"beautifulsoup4>=4.14.2",
# Used by the memory-measurement assertions in the stress and deep-nesting
# tests. Not imported anywhere in src/.
"psutil>=5.9.6,<7.0.0",
# The suite exercises every optional module, so it needs every extra's
# dependencies even though they are not required at runtime.
"jinja2>=3.1.6,<3.2.0",
"pandas>=2.1.1,<3.0.0",
"scipy>=1.12.0,<2.0.0",
"scikit-learn>=1.7.2,<2.0.0",
"ruff>=0.14.10",
"mkdocs",
"mkdocs-material",
Expand All @@ -64,7 +82,9 @@ llm = [
# the newest release that existed when it was written. Capping at <2.0.0
# made stickler[llm] uninstallable alongside strands-agents-evals, which
# requires >=1.42.0.
"strands-agents>=1.14.0,<2.0.0"
"strands-agents>=1.14.0,<2.0.0",
# LLMComparator renders its prompt with a jinja2 Template.
"jinja2>=3.1.6,<3.2.0",
]
bert = [
"evaluate>=0.4.0",
Expand All @@ -73,6 +93,28 @@ bert = [
]
semantic = [
"boto3>=1.28.0",
# SemanticComparator's cosine similarity uses scipy.spatial.
"scipy>=1.12.0,<2.0.0",
]
# Confidence calibration is part of the core dependency set, so this extra is
# empty. Kept as a no-op so `pip install "stickler-eval[confidence]"` keeps
# working for anyone who already pinned it.
confidence = []
# Document packet splitting: clustering and agreement metrics.
docsplit = [
"pandas>=2.1.1,<3.0.0",
"scipy>=1.12.0,<2.0.0",
"scikit-learn>=1.7.2,<2.0.0",
]
# HTML reporting: ProcessEvaluation renders markdown tables from DataFrames.
reporting = [
"pandas>=2.1.1,<3.0.0",
]
# Everything except `bert`, whose ML stack (torch, transformers) is large
# enough that pulling it in unasked is a surprise. Written as self-referential
# extras so it cannot drift out of sync with the extras it aggregates.
all = [
"stickler-eval[llm,semantic,confidence,docsplit,reporting]",
]

[project.urls]
Expand Down Expand Up @@ -110,8 +152,17 @@ test = [
"pytest-xdist>=3.0.0",
"coverage>=7.0.0",
"beautifulsoup4>=4.14.2",
# Used by the memory-measurement assertions in the stress and deep-nesting
# tests. Not imported anywhere in src/.
"psutil>=5.9.6,<7.0.0",
# Used by examples/notebooks/Review_Efficiency_Exploration.ipynb.
"matplotlib>=3.8.0",
# The suite exercises every optional module, so it needs every extra's
# dependencies even though they are not required at runtime.
"jinja2>=3.1.6,<3.2.0",
"pandas>=2.1.1,<3.0.0",
"scipy>=1.12.0,<2.0.0",
"scikit-learn>=1.7.2,<2.0.0",
]
lint = [
"ruff>=0.14.10",
Expand Down
114 changes: 99 additions & 15 deletions src/stickler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
with configurable comparison strategies and detailed evaluation metrics.
"""

import importlib as _il
import importlib.util as _ilu
import sys as _sys

# Zero-config evaluation of vanilla pydantic models (no StructuredModel
# subclass or schema required). See stickler/auto/README.md.
from .auto import EvalResult, EvalSpec, eval_for, evaluate
Expand All @@ -14,7 +18,6 @@
from .comparators.exact import ExactComparator
from .comparators.fuzzy import FuzzyComparator
from .comparators.levenshtein import LevenshteinComparator
from .comparators.llm import STRANDS_AVAILABLE as _HAS_LLM
from .comparators.numeric import NumericComparator
from .comparators.semantic import SemanticComparator
from .comparators.structured import StructuredModelComparator
Expand All @@ -29,20 +32,101 @@
compare_structured_models,
)

# Optional: LLM comparator (requires strands-agents)
if _HAS_LLM:
from .comparators.llm import LLMComparator # noqa: F401

# Optional: BERT comparator (requires the `bert` extra: torch, bert-score,
# evaluate). Catch broad ImportError, not just ModuleNotFoundError: a
# version-skewed transitive dep (datasets/pyarrow/huggingface_hub) raises plain
# ImportError, and a broken optional extra must not take down `import stickler`.
try:
from .comparators.bert import BERTComparator # noqa: F401

_HAS_BERT = True
except ImportError:
_HAS_BERT = False
# Optional comparators are PROBED, not imported.
#
# Importing them here would put their dependencies on the `import stickler`
# path: strands-agents and boto3 for LLMComparator, and torch, transformers,
# datasets, and pandas for BERTComparator. That cost lands on every caller who
# installed an extra, even one who never touches the comparator, and it is
# seconds rather than milliseconds.
#
# `find_spec` answers "is the dependency installed?" without executing the
# module, so `__all__` stays accurate while the import is deferred to first
# attribute access via `__getattr__` below.

def _dependency_available(name: str) -> bool:
"""Whether an optional dependency can be imported, without importing it.

Checks ``sys.modules`` before the filesystem so a test that injects a mock
(see tests/common/comparators/conftest.py) is treated as available, which
``importlib.util.find_spec`` alone would not do.
"""
module = _sys.modules.get(name, False)
if module is not None and module is not False:
# Present in sys.modules, including a test-injected mock.
return True
if module is None:
# Explicitly blocked (sys.modules[name] = None), which is how tests
# simulate a missing dependency.
return False
try:
return _ilu.find_spec(name) is not None
except (ImportError, ValueError):
return False


# `_HAS_LLM`/`LLM_AVAILABLE` mean "strands-agents is installed", which is what
# gates __all__ and what tests/test_top_level_exports.py asserts. Note that the
# MODULE stickler.comparators.llm imports fine without strands (it degrades to
# STRANDS_AVAILABLE=False and raises at instantiation), so __getattr__ below
# does not gate on this flag for LLMComparator; only __all__ does.
_HAS_LLM = _dependency_available("strands")
_HAS_BERT = _dependency_available("evaluate")

# Optional comparator name -> (module, owning extra, whether it is available).
# Only available entries are resolvable, so `hasattr(stickler, "LLMComparator")`
# stays False when the extra is not installed, matching the behavior of the
# previous eager try/except gating.
_LAZY_COMPARATORS = {
"LLMComparator": (".comparators.llm", "llm", _HAS_LLM),
"BERTComparator": (".comparators.bert", "bert", _HAS_BERT),
}


def __getattr__(name: str):
"""Import optional comparators on first access (PEP 562).

`stickler.LLMComparator` and `from stickler import BERTComparator` both
route here, so the heavy import happens when the comparator is actually
used rather than at package import.

Raises:
AttributeError: If the name is unknown, or if it is an optional
comparator whose extra is not installed. Raising AttributeError
rather than ImportError keeps `hasattr()` False for a missing
extra, which is what the eager gating used to provide.
"""
entry = _LAZY_COMPARATORS.get(name)
if entry is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

module_path, extra, available = entry
if not available:
raise AttributeError(
f"module {__name__!r} has no attribute {name!r}: it requires the "
f"'{extra}' extra. Install it with: "
f'pip install "stickler-eval[{extra}]"'
)

try:
module = _il.import_module(module_path, __name__)
except ImportError as exc:
# Installed but broken (a version-skewed transitive dependency raising
# plain ImportError). Surface it here, at the point of use, rather than
# taking down `import stickler`.
raise ImportError(
f"{name} requires the '{extra}' extra, which is installed but "
f"failed to import. Original error: {exc}"
) from exc
value = getattr(module, name)
# Cache on the module so subsequent lookups skip __getattr__ entirely.
globals()[name] = value
return value


def __dir__() -> list:
"""Include lazily-available comparators in `dir(stickler)`."""
return sorted(set(globals()) | set(__all__))

__version__ = "0.6.0"
__all__ = [
Expand Down
Loading
Loading