Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion .github/workflows/run_pytest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ jobs:
runs-on: ubuntu-latest
strategy:
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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ Whether you're extracting data from documents, performing ETL transformations, e
pip install stickler-eval
```

That installs the comparison engine, which is everything you need to score structured output: comparators, list matching, and per-field metrics. Optional features declare their own extras, so a default install stays light and does not pull a scientific-computing 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) |
| `[confidence]` | scikit-learn | Confidence calibration metrics (AUROC) |
| `[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
60 changes: 53 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,26 @@ 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 and nothing else. Peripheral modules (document
# splitting, HTML reporting, confidence metrics) declare their own extras
# below, so `pip install stickler-eval` does not pull a scientific-computing
# stack to compare two objects.
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"
]

Expand All @@ -43,6 +46,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 @@ -57,7 +69,9 @@ llm = [
# docs and examples landed in 1.14.0. On 1.0-1.13 __call__ swallows it via
# **kwargs, so no structured output is requested and the call fails later
# with AttributeError on .structured_output.
"strands-agents>=1.14.0,<=1.16.0"
"strands-agents>=1.14.0,<=1.16.0",
# LLMComparator renders its prompt with a jinja2 Template.
"jinja2>=3.1.6,<3.2.0",
]
bert = [
"evaluate>=0.4.0",
Expand All @@ -66,6 +80,29 @@ bert = [
]
semantic = [
"boto3>=1.28.0",
# SemanticComparator's cosine similarity uses scipy.spatial.
"scipy>=1.12.0,<2.0.0",
]
# Confidence calibration metrics (AUROC needs scikit-learn).
confidence = [
"scikit-learn>=1.7.2,<2.0.0",
]
# 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, for users who would rather not think about extras.
all = [
"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",
]

[project.urls]
Expand Down Expand Up @@ -103,8 +140,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
23 changes: 19 additions & 4 deletions src/stickler/comparators/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@
"""

import html
from typing import Any, Dict, Union

from jinja2 import Template
from typing import TYPE_CHECKING, Any, Dict, Union

from stickler.comparators.base import BaseComparator

if TYPE_CHECKING: # pragma: no cover - typing only
from jinja2 import Template

try:
from botocore.exceptions import NoCredentialsError
from strands import Agent
Expand Down Expand Up @@ -137,13 +138,27 @@ def _default_system_prompt(self) -> str:
"""
return "You are a helpful assistant that compares two values and determines if they are equivalent. Only return one word: 'true' or 'false'."

def _default_prompt_template(self) -> Template:
def _default_prompt_template(self) -> "Template":
"""Generate the default Jinja2 template for comparison prompts.

Returns:
Template: Jinja2 template that formats comparison prompts with values
and optional evaluation guidelines.

Raises:
ImportError: If jinja2 is not installed.
"""
# Imported here rather than at module scope: jinja2 is only needed to
# render this prompt, and a module-level import would put it on the
# `import stickler` path via the comparator registry.
try:
from jinja2 import Template
except ImportError as exc: # pragma: no cover - exercised by the extras gate
raise ImportError(
"LLMComparator requires jinja2. Install it with: "
'pip install "stickler-eval[llm]"'
) from exc

prompt_template = """
Compare these two values and determine if they are equivalent:

Expand Down
26 changes: 23 additions & 3 deletions src/stickler/comparators/semantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,34 @@
from functools import partial
from typing import Callable, Optional

from scipy import spatial

from stickler.comparators.base import BaseComparator
from stickler.comparators.utils import generate_bedrock_embedding

logger = logging.getLogger(__name__)


def _cosine_distance(x, y) -> float:
"""Cosine distance between two embedding vectors.

scipy is imported here rather than at module scope: ``SemanticComparator``
is a top-level export, so a module-level import would put scipy on the
``import stickler`` path for every user, including those who never compute
an embedding.

Raises:
ImportError: If scipy is not installed.
"""
try:
from scipy import spatial
except ImportError as exc: # pragma: no cover - exercised by the extras gate
raise ImportError(
"SemanticComparator's cosine similarity requires scipy. Install it "
'with: pip install "stickler-eval[semantic]"'
) from exc

return spatial.distance.cosine(x, y)


def _embedding_function_name(embedding_function: Callable) -> str:
"""Return a useful name for custom callables and functools.partial wrappers."""
if isinstance(embedding_function, partial):
Expand Down Expand Up @@ -48,7 +68,7 @@ class SemanticComparator(BaseComparator):
"""

SIMILARITY_FUNCTIONS = {
"cosine_similarity": lambda x, y: 1 - spatial.distance.cosine(x, y)
"cosine_similarity": lambda x, y: 1 - _cosine_distance(x, y)
}

def __init__(
Expand Down
22 changes: 16 additions & 6 deletions src/stickler/doc_split/packet_evaluation_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,22 @@
from typing import Any, Dict, List, Tuple, Union

import numpy as np
import pandas as pd
from scipy.stats import kendalltau
from sklearn.metrics import (
homogeneity_completeness_v_measure,
rand_score,
)

# pandas, scipy, and scikit-learn are only needed by this module, so they live
# behind the `docsplit` extra rather than in the core dependency set. Raise an
# actionable error naming the extra instead of a bare ModuleNotFoundError.
try:
import pandas as pd
from scipy.stats import kendalltau
from sklearn.metrics import (
homogeneity_completeness_v_measure,
rand_score,
)
except ImportError as exc: # pragma: no cover - exercised by the extras gate
raise ImportError(
"stickler.doc_split requires pandas, scipy, and scikit-learn. Install "
'them with: pip install "stickler-eval[docsplit]"'
) from exc

logger = logging.getLogger(__name__)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, field_validator
from sklearn.metrics import roc_auc_score


class ConfidencePair(BaseModel):
Expand Down Expand Up @@ -95,6 +94,18 @@ def name(self) -> str:
def compute(self, pairs: ConfidencePairs) -> Dict[str, Any]:
if not pairs or len(set(p.is_match for p in pairs)) < 2:
return {"value": None}
# Imported here, not at module scope: scikit-learn is the single
# heaviest optional dependency and AUROC is the only thing that needs
# it. A module-level import would put it on the `import stickler` path
# and force every user to install it.
try:
from sklearn.metrics import roc_auc_score
except ImportError as exc: # pragma: no cover - exercised by the extras gate
raise ImportError(
"AUROCMetric requires scikit-learn. Install it with: "
'pip install "stickler-eval[confidence]"'
) from exc

y_true = [1 if p.is_match else 0 for p in pairs]
y_scores = [p.confidence for p in pairs]
# float() defends against numpy scalars from future ndarray callers.
Expand Down
7 changes: 4 additions & 3 deletions src/stickler/utils/markdown_util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Any, Dict, List
from typing import TYPE_CHECKING, Any, Dict, List

import pandas as pd
if TYPE_CHECKING: # pragma: no cover - typing only
import pandas as pd


class MarkdownUtil:
Expand Down Expand Up @@ -84,7 +85,7 @@ def table_dict(
return table

@staticmethod
def table_df(df: pd.DataFrame) -> str:
def table_df(df: "pd.DataFrame") -> str:
"""
Creates a markdown table from a pandas DataFrame.

Expand Down
70 changes: 70 additions & 0 deletions tests/test_core_import_weight.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Guards that `import stickler` stays light.

The comparison engine needs only pydantic, rapidfuzz, munkres, numpy, and
python-dateutil. Everything heavier (pandas, scipy, scikit-learn, jinja2, and
the ML stack behind the optional comparators) belongs to a peripheral module
and lives behind an extra.

These tests fail if a module-level import puts one of those packages back on
the ``import stickler`` path. That regression is easy to introduce and silent:
the suite installs every extra, so the import still succeeds here while a
default install breaks for users.
"""

import subprocess
import sys

import pytest

# Packages that must not be imported as a side effect of `import stickler`,
# mapped to the extra that owns them.
FORBIDDEN_ON_CORE_PATH = {
"pandas": "docsplit / reporting",
"scipy": "semantic / docsplit",
"sklearn": "confidence / docsplit",
"jinja2": "llm",
"torch": "bert",
"transformers": "bert",
"strands": "llm",
"boto3": "semantic",
}


def _modules_after_importing_stickler() -> set:
"""Return sys.modules keys after a bare `import stickler`.

Runs in a subprocess so the already-imported state of this test session
(which has every extra installed) cannot mask a regression.
"""
code = "import sys, json; import stickler; print(json.dumps(sorted(sys.modules)))"
result = subprocess.run(
[sys.executable, "-c", code], capture_output=True, text=True, check=True
)
import json

return set(json.loads(result.stdout))


@pytest.mark.parametrize("package,owning_extra", sorted(FORBIDDEN_ON_CORE_PATH.items()))
def test_heavy_package_not_on_core_import_path(package, owning_extra):
"""A bare `import stickler` must not pull an extra's dependency."""
loaded = _modules_after_importing_stickler()
top_level = {m.split(".")[0] for m in loaded}
assert package not in top_level, (
f"`import stickler` loaded {package!r}, which belongs to the "
f"{owning_extra} extra. Move the import inside the function that needs "
f"it, or guard it with TYPE_CHECKING if it is only an annotation."
)


def test_core_import_stays_small():
"""Sanity bound on module count, to catch a broad new eager dependency.

The threshold is deliberately loose: it is a tripwire for something large
arriving on the core path, not a precise budget.
"""
loaded = _modules_after_importing_stickler()
assert len(loaded) < 900, (
f"`import stickler` now loads {len(loaded)} modules. Something heavy "
f"joined the core import path; check for a new module-level import."
)
Loading
Loading