Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

c5tools (Python)

Python port of the c5tools, a validator for COUNTER R5.0 and R5.1 reports and COUNTER API responses. The port is work in progress, see docs/REWRITE_PLAN.md. The PHP implementation in the repository root is the specification: the Python implementation must produce the same snapshots for the test corpus in tests/corpus as recorded in tests/expected (see tests/README.md).

Installation

The package is published on PyPI as c5tools (pre-releases until the switch from the PHP implementation, so pin the version or allow pre-releases):

pip install c5tools==0.9.0a1            # or: pip install --pre c5tools
poetry add c5tools@0.9.0a1              # Poetry
pip install "c5tools[server]==0.9.0a1"  # with the REST service

It needs Python 3.12 or newer and depends only on httpx and xlrd. The development version can be installed from the repository with pip install "c5tools @ git+https://github.com/Big-Dig-Data/c5tools@python#subdirectory=python".

Command Line Tools

The package installs two console scripts, the equivalents of the PHP scripts in demo:

c5tools-validate-file -f report.json            # validate a report file (JSON, CSV, TSV, xlsx, xls, ods)
c5tools-validate-file -f report.tsv -j          # also print the JSON representation of a usable report
c5tools-validate-file -f report.xlsx -x result.xlsx   # save the validation result as Excel file
c5tools-validate-api -u 'https://example.com/r51/reports/tr?customer_id=...&begin_date=...&end_date=...'

-m and -t print the memory and time used. The output is the PHP scripts' output, the exit code 0, 5 for invalid options and 255 for an unexpected error.

Library

See the library guide for validating report files, buffers and COUNTER API requests, reading the result (JSON, text, Excel) and the parsed report, and how errors are reported.

REST Service

The REST service has the JSON contract of the PHP service (public/index.php, public/file.php and public/api.php), as the optional extra c5tools[server] (Starlette, uvicorn):

Endpoint Request Response
GET / (/index.php) {"status": "OK", ...}
POST /file.php?extension=<json|csv|tsv|xlsx|xls|ods> (/file) the report file as body {"memory": <int>, "result": <CheckResult JSON>}
POST /api.php (/api) {"url": "<COUNTER API request URL>"} {"memory": <int>, "result": <CheckResult JSON>, "report": <response JSON, zlib (level 3) and base64> or null}

Other methods get 405, an invalid api.php body 400 with {"error": ...}, a body larger than the maximum 413 with {"error": ...}. A file or a COUNTER API response that can't be validated is a fatal error in the result. Where PHP fails with an uncaught Error (and answers 500), the service answers 500 with {"error": "internal server error"} and logs the error. The bodies are PHP's byte for byte, except memory (the peak resident set size of the process) and the content type of the 400 responses (application/json instead of PHP's default text/html).

COUNTER API requests may only connect to public addresses: the host is resolved, every address is checked, and the connection is made to a checked address (no DNS rebinding); redirects are checked the same way. The timeouts are PHP's: 30 seconds to connect, 300 seconds for a request (see c5tools.api.guard).

Configuration (environment variables):

Variable Default Meaning
C5TOOLS_MAX_UPLOAD_SIZE 100M maximum request body size in bytes, with optional unit K, M, G (1024-based); 0 for unlimited
C5TOOLS_API_ALLOW_PRIVATE_ADDRESSES false true allows COUNTER API requests to private, loopback, link-local and other non-public addresses (no SSRF protection)
C5TOOLS_API_ALLOWED_NETWORKS comma-separated networks (CIDR) that COUNTER API requests may connect to although they aren't public, e.g. 10.1.2.0/24,fd00::/64
C5TOOLS_API_MAX_RESPONSE_SIZE 500M maximum size of a COUNTER API response (bytes received), like C5TOOLS_MAX_UPLOAD_SIZE
WEB_CONCURRENCY 1 number of worker processes (uvicorn)

Invalid values stop the service at startup. Run it with any ASGI server, e.g.

pip install "c5tools[server]==0.9.0a1"
uvicorn --factory c5tools.server:create_app --host 0.0.0.0 --port 8080
uv run --extra server uvicorn --factory c5tools.server:create_app --port 8080   # in python/, for development

Docker

Dockerfile builds a small image (multi-stage, python:3.12-slim, the dependencies from uv.lock, non-root user c5tools, port 8080, health check on /). In the repository root:

docker build -t c5tools-server python/
docker run --rm -p 8080:8080 -e WEB_CONCURRENCY=2 c5tools-server
curl -X POST --data-binary @tests/corpus/reports/r51/cop/TR_sample_r51.json 'http://localhost:8080/file.php?extension=json'
curl -X POST -d '{"url": "https://example.com/r51/status"}' http://localhost:8080/api.php

Behind a TLS-intercepting proxy, pass its CA certificates to the build with --secret id=ca-bundle,src=/path/to/ca-bundle.crt (and the proxy with --build-arg HTTPS_PROXY=...). The CI job docker builds the image and runs scripts/smoke_test_server.py, which posts corpus files to the running service and compares the results with tests/expected (uv run python scripts/smoke_test_server.py http://localhost:8080).

Development

Requires uv and Python 3.12 or newer. All commands are run in python/:

uv sync                                     # create .venv with the package and the dev tools
uv run pytest                               # unit tests and parity tests
uv run ruff check                           # lint
uv run ruff format --check                  # formatting (uv run ruff format to fix)
uv run mypy                                 # type check (strict)
uv run coverage run -m pytest && uv run coverage report   # branch coverage

Releases

The package is published to PyPI by the workflow .github/workflows/publish.yml when a tag python-v<version> is pushed. The workflow builds the sdist and the wheel (uv build --no-sources) on the self-hosted runner, checks that the tag matches the package version, checks the distributions with twine check --strict, installs the wheel into a new virtual environment and validates a corpus file with it, and uploads the distributions as artifact; a second job on a GitHub-hosted runner publishes them with PyPI's trusted publishing (pypa/gh-action-pypi-publish, OpenID Connect, no API token) in the GitHub environment pypi.

One-time setup:

  1. On pypi.org, log in with the account that should own the project, open Your account → Publishing and add a pending publisher (GitHub): PyPI project name c5tools, owner Big-Dig-Data, repository c5tools, workflow name publish.yml, environment name pypi. The first upload creates the project; the pending publisher becomes its trusted publisher. Add the co-maintainers to the project afterwards.
  2. In the GitHub repository, create the environment pypi (Settings → Environments). Recommended: required reviewers, so that every upload is approved, and a deployment tag rule python-v*.

Release:

  1. Set the version in src/c5tools/__init__.py (__version__, the single source of the version; PEP 440, e.g. 0.9.0a2, 0.9.0rc1, 1.0.0), update the version in the installation instructions above and in docs/guide.md, run uv lock (the lock file records the version), and commit.
  2. When CI is green for the commit, tag and push it: git tag python-v0.9.0a2 && git push origin python-v0.9.0a2.
  3. Approve the deployment in the workflow run if the environment requires it; check the release on https://pypi.org/project/c5tools/.

A version can't be uploaded twice: to fix a broken release, publish a new version (and yank the broken one on PyPI). To check the build locally: uv build --no-sources && uvx twine check --strict dist/*.

Configuration

The COUNTER configuration in src/c5tools/config/r50 and r51 is generated from the PHP configuration in src/config (requires php); don't edit the generated modules, change the PHP files and run

uv run python scripts/convert_config.py             # regenerate the modules
uv run python scripts/convert_config.py --check     # exit with 1 if they are not up to date (run in CI)

Check methods are referenced as functions in c5tools.checks (checkedCountryCode becomes checks.checked_country_code). Each check takes a c5tools.checks.CheckContext followed by the PHP arguments.

The ISBN range data in src/c5tools/isbn/ranges.py is generated from the nicebooks/isbn package in composer.lock (requires php and the Composer dependencies), so that ISBNs are hyphenated like RangeService::format; regenerate it when the package is updated:

uv run python scripts/convert_isbn_ranges.py             # regenerate the module
uv run python scripts/convert_isbn_ranges.py --check     # exit with 1 if it is not up to date (run in CI)

PHP Oracles

The scripts in tests/oracles run parts of the PHP implementation for differential tests. Oracles that need only PHP are run by the tests (skipped if php is missing, unless C5TOOLS_REQUIRE_PHP=1 is set as in CI): config-lookups.php by tests/test_config.py, php-functions.php (json_decode, finfo, fgetcsv, ...) by tests/test_readers_php.py, (strtotime, date, DateTime::createFromFormat) by tests/test_timelib_php.py, (preg_match, parse_url) by tests/test_checks_identifiers.py and (parse_str, rawurlencode) by tests/test_api.py. Oracles that need the Composer dependencies write fixtures that are committed:

php ../tests/oracles/check-result-roundtrip.php > tests/data/check-result-roundtrip.json
php ../tests/oracles/dump-cells.php --write          # tests/data/cell-grids (the PHP CI job runs --check)
php ../tests/oracles/format-values.php > tests/data/format-values.json
uv run python scripts/generate_reader_fixtures.py    # edge case spreadsheets in tests/data/spreadsheets

The field checks are compared with PHP call by call: checks.php runs the methods of src/traits/Checks.php on a host class that uses the traits, tests/check_oracle.py runs the same calls with the Python checks and compares the results (tests/test_checks_*.py). This oracle needs the Composer dependencies and runs on the fly (the CI job installs them; locally the tests are skipped without vendor/). The date checks depend on the current time; check-clock.php lets the oracle use the time of the call (CheckCall.now, CheckContext.now in Python). The test inputs include element values collected from the corpus:

uv run python scripts/collect_check_values.py            # tests/data/check-values.json (CI runs --check)

dump-cells.php dumps the cell grids of all tabular corpus files and of the edge cases in tests/data/spreadsheets as the validation sees them; tests/test_readers_tabular.py compares the readers with them. Regenerate the dumps when tabular corpus files are added or changed.

The report validation is compared with PHP on generated variants of the corpus samples: report-snapshots.php prints the snapshots of a list of report files (Snapshot::forReport), tests/test_report_php.py generates the variants of the JSON samples and tests/test_report_tabular_php.py those of the TSV samples (also written as xlsx, ods and CSV files) and compare them with the Python snapshots (on the fly, needs the Composer dependencies like the check oracle). Likewise the COUNTER API validation: api-snapshots.php prints the snapshots of API case files (Snapshot::forApi), tests/test_api_php.py generates request URLs, list and exception responses, reports checked against the request and variants of the corpus API cases; tests/test_api_client.py tests the CounterApiClient with the recorded responses.

The Excel output is compared by content: check-result-xlsx.php writes check results with CheckResult::saveXlsx and dumps the PHP and the Python file as the PhpSpreadsheet reader loads them (cells with data types and styles, merged cells, auto filter, frozen pane, column widths); tests/test_spreadsheet_php.py compares the check results of the corpus cases and generated values (on the fly, needs the Composer dependencies). tests/test_cli.py compares the command line tools with demo/validate_file.php and demo/validate_api.php (the API cases are served to both by a local HTTPS server with a self-signed certificate, made with openssl, see tests/https_server.py), and tests/test_server.py the REST service with the PHP service (php -S on a copy of public/).

file-response.php runs the code of public/file.php with a set current time (for the dates in the checks and the datetime of the result); tests/test_shadow.py compares its responses with c5tools.shadow.compare_file (around midnight and the turn of the year, and with the content-based reader choice), and scripts/shadow_case.py uses it to reproduce the differences of the shadow run (see the library guide).

Parity Harness

c5tools.testing.snapshot(case) creates the snapshot of a corpus case (e.g. reports/r51/cop/TR_sample_r51.json or api/r51/status-valid.json) in the format of tests/src/Snapshot.php. The parity report compares the snapshots of all corpus cases with the expected PHP snapshots:

uv run python -m c5tools.testing.parity                     # report as Markdown
uv run python -m c5tools.testing.parity --diff CASE [CASE ...]   # differences for single cases
uv run python -m c5tools.testing.parity --only reports/r51/  # report on the cases starting with a prefix
uv run python -m c5tools.testing.parity --update            # update tests/parity-matching.txt
uv run python -m c5tools.testing.parity --check             # exit with 1 if tests/parity-matching.txt is outdated

The report shows

  • the matching cases per corpus group (directory) and in total, and the cases with order-only differences, errors (exceptions other than NotImplementedError) and not implemented parts,
  • the matching messages per position prefix: .Report_Header and .Report_Items for JSON reports, header cells (rows 1-14) and body for tabular reports, and the case type (file name prefix: status, members, reports, report, exception, request, response) for API cases. Messages are matched per position regardless of their order, positions with the same messages in a different order are counted separately, since messages at the same position must be in the same order as in PHP.

Every corpus case matches (since stage 8b) without tolerated differences; test_parity.py checks that every case is in the list of matching cases. A case whose validation raises NotImplementedError (e.g. a spreadsheet feature the readers don't support, UnsupportedSpreadsheetError) counts as not implemented.

The CI job adds the report to the job summary.

Parity Tests and the List of Matching Cases

tests/test_parity.py runs every corpus case. tests/parity-matching.txt lists the cases that match: these must keep matching, all other cases are expected to fail (strict xfail). When a change makes more cases match, they fail as XPASS(strict) until the list is updated with --update, so commit the updated list with the change. A regression of a listed case fails the tests.

Tolerated Differences

Differences that can't or shouldn't be fixed are listed in src/c5tools/testing/tolerated.py with the case, the part of the snapshot (result, text, usable, json, crash or *) and the reason. A tolerated difference needs approval in the PR review, the goal is an empty list. The tests fail for entries that are no longer needed.

The corpus is found relative to the package (../tests); set C5TOOLS_TESTS_DIR to use another tests directory.

Metadata

Release files for c5tools 0.9.0a2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for c5tools 0.9.0a2
File Size Uploaded Provenance Actions
c5tools-0.9.0a2.tar.gz 259.9 kB With provenance Details for c5tools-0.9.0a2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for c5tools 0.9.0a2
File Interpreter ABI Platform Actions
c5tools-0.9.0a2-py3-none-any.whl Python 3 none any Details for c5tools-0.9.0a2-py3-none-any.whl

Total release size: 580.4 kB

Release files / c5tools-0.9.0a2.tar.gz

Download URL c5tools-0.9.0a2.tar.gz
Size 259.9 kB
Tags Source
SHA-256 checksum
How to use checksums
72cbdc20d4d4838c4d92abecfa700060930ad575b8764b431d44bb64a7cc40b3
BLAKE2b-256 checksum
How to use checksums
d8b4c3525daee35d0ac1171e446d577b93229b431ef17be54b8a582bbb812097
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / c5tools-0.9.0a2-py3-none-any.whl

Download URL c5tools-0.9.0a2-py3-none-any.whl
Size 320.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7f24a67eafa6f0e217ef57526860cbe2827cd1e17e37be3037b1fe6fb0054b73
BLAKE2b-256 checksum
How to use checksums
9005c0d3a6d29261d8e704d8a8c01f503b85b7d20c2fd3931442e82ce091df9d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for c5tools 0.9.0a2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for c5tools-0.9.0a2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page