Skip to main content

hansu

ci

Verify it, don't trust it. docs/HS2-format.md is a complete bitstream specification — enough that a third party can implement a decoder without reading this code. hansu/standalone.py is that third party: written from the document alone, and CI asserts the two decoders agree pixel for pixel on every test image.

A structural image codec — small files on graphics, screenshots and flat UI, plus a topology signature that other systems can query.

Thirty-second check:

pip install hansu
python -c "import hansu,numpy as np; d,r=hansu.encode(np.zeros((64,64,3),np.uint8)); print(len(d),'bytes for a blank 64x64 RGB')"

— small files on graphics, screenshots and flat UI, plus a topology signature that other systems can query.**

hansu (珩速) is an HS2 codec: MED-style prediction with a 250-context binary arithmetic coder, a palette route for few-colour images, banded streams for parallel / random-access decoding, and an RGBA path. It ships with a second, independently written decoder so the format can be verified rather than trusted.

Two things make it more than another compressor:

  • The bitstream is specified. docs/HS2-format.md is written to the level where a third party can implement a decoder without reading this code. hansu/standalone.py is exactly that: written from the document alone, and the test suite asserts the two agree pixel for pixel.
  • Images have signatures. hansu.signature(img) returns a JSON description of the image's structure — colour count, flatness, edge density, dominant periods, entropy, family — plus the codec's own result. Signatures are comparable, so you can build a library and search it by topology instead of by content hash.

Where it wins

Against WebP lossless, on 256×256 synthetic graphics (10 images):

image hansu WebP-LL ratio
blocks5 65 B 114 B 0.57×
icon 370 B 466 B 0.79×
blocks2 51 B 60 B 0.85×
chart 104 B 120 B 0.87×
circles 645 B 726 B 0.89×
checker8 128 B 142 B 0.90×
gradstep 98 B 106 B 0.92×
ui 238 B 240 B 0.99×
stripes4 86 B 82 B 1.05×
noise16 116 761 B 98 394 B 1.19×

Nine of ten beat WebP lossless; at 512² and 1024² graphics the margin grows (2.2×–3.0× on 5-colour blocks vs PNG).

† noise16 is the one entry that does not hold up. The 0.84× figure that appeared in earlier versions compared a very low-quality hansu setting (PSNR 9.4) against lossless WebP — not an equal-quality comparison. At the default setting (PSNR 33.49) it is 1.19×, i.e. larger. Noise is the case this codec is worst at, and the table now says so.

A correction on the lossy comparison. An earlier version of this README reported "2.4×–8× smaller than WebP q35". That compared hansu at q16 (≈36 dB) against WebP at q35 (≈30 dB) — different quality, so the number was wrong. At matched PSNR WebP is ahead on every page-type image. See docs/COMPARISON.md for the corrected study.

On 512×512 near-real pages (generated by benchmarks/make_set.py):

page hansu q16 PSNR WebP-LL WebP q35 ratio to LL* ratio to q35*
shot_ui 10 296 B 36.93 11 042 B 7 712 B 0.93× 1.34×
shot_icons 1 733 B 99.00 1 686 B 3 908 B 1.03× 0.44×
shot_text 29 470 B 43.99 15 056 B 35 442 B 1.96× 0.83×
shot_chart 1 658 B 41.74 1 354 B 2 148 B 1.22× 0.77×
shot_grad 5 665 B 34.81 5 292 B 3 538 B 1.07× 1.60×
shot_photo 159 264 B 34.28 443 376 B 9 302 B 0.36× 17.12×

Reading it: on pages made of flat blocks and sharp edges it holds up against lossless WebP and wins against q35; on anti-aliased text and photographs it loses, exactly as the boundaries below say.

An independent check on real images

The two tables above come from benchmarks/make_set.py — synthetic pages built for testing, not real screenshots. A separate run on 512² real inputs (six object renders, one UI screenshot, one text page, one photograph) at q=1:

input q=1 WebP-LL ratio
object render (chair) 94 338 B 67 476 B 1.40×
UI screenshot 25 030 B 9 610 B 2.60×
text page 52 974 B 8 538 B 6.20×
photograph 448 496 B 443 158 B 1.01×

Near-lossless on real images is larger than WebP lossless on everything except a photograph. Also note that q=1 is not a guarantee of pixel identity: on three of these inputs the maximum channel difference was 1. The synthetic tables describe a controlled testbed; they are not a claim about real pages.

v0.2.0 / v0.3.0 — tile palettes, then a 2-D index context

v0.2.0 gave every ts × ts tile its own local palette, grouped so tiles with similar colour sets share one, with the tile-id map arithmetic coded as side information. v0.3.0 then replaced the index plane's context (not its predictor, not the palettes): instead of gradients over labels, the context is the exact pair (left, top), up to (K+1)² ≤ 289 contexts, chosen per stream by trying both models and keeping the smaller one.

Measured against 0.1.1 on the same images:

image 0.1.1 v0.3.0 Δ of which index plane
icon 256² 370 B 286 B −22.7% 326 → 247 B (−24.2%)
circles 256² 645 B 426 B −34.0% 598 → 384 B (−35.8%)
ui 256² 238 B 196 B −17.6% 176 → 139 B (−21.0%)
checker8 1024² 874 B 263 B −69.9% 51 B
stripes4 1024² 225 B 163 B −27.6% 51 B
blocks5 256² 65 B 60 B −7.7% 18 B
chart 256² 104 B 99 B −4.8% 48 B
shot_icons 512² 2 418 B 1 733 B −28.3% 2 356 → 1 675 B

Nine-image flat-graphics family, mean saving: −23.2% at 256², −30.0% at 512², −53.0% at 1024². The route is lossless by construction and takes part in smallest-of, so it never enlarges a file.

The boundary that survived: the 2-D context loses on planes that are already nearly free (a checker at ts=64, where every context has to warm up), so the encoder keeps the legacy model there — smallest-of covers it, but it is a measured edge, not a bug.

A VP8L-style colour cache was implemented and rejected on numbers: on these planes the cache hits 99.98–99.99% of pixels, so a cache position must be coded almost every pixel and costs 2–200× the MED residual it replaces.

Where it does not

Honest boundaries, measured:

  • Photographs against WebP lossy: 19× larger. Do not use it for photos.
  • Anti-aliased text against WebP lossless: ~2× larger — grey ramps break index-plane prediction and the palette cannot pay for itself.
  • 1024² low-entropy images: banded mode costs 8×20 B of header; a whole-image path would be smaller (a known trade-off, not a bug).

The niche is real and narrow: flat graphics, icons, charts, UI, palette-like images — the same class where PNG/VP8L do worst.

Install

pip install hansu                 # pure Python backend (slow, correct)
python -m hansu.build_c           # optional: build the C backend (~100× faster)

Use

import numpy as np, hansu
from PIL import Image

img = np.array(Image.open("shot.png").convert("RGB"))
data, rec = hansu.encode(img, qy=16, qc=8)   # qy/qc = 1 → near-lossless
img2 = hansu.decode(data)                     # native decoder
img3 = hansu.decode_reference(data)           # independent decoder, same bytes

CLI:

hansu encode shot.png -o shot.hs2
hansu decode shot.hs2 -o shot.png
hansu sign  shot.png                     # topology signature as JSON
hansu lib   images/ -o library.json      # build a signature library
hansu query shot.png --lib library.json  # nearest by topology
hansu bench images/                      # batch encode, print a table
hansu info                               # backend + format version

Topology signatures

import hansu, json
sig = hansu.signature(img)
print(json.dumps(sig, indent=2))
{
  "size": [512, 512], "colors": 8, "palette_top16": [[245,246,250], [255,255,255], [59,130,246]],
  "flat_ratio": 0.983, "edge_density": 0.006,
  "period_x": 0, "period_y": 0, "gray_entropy": 1.63,
  "family": "flat-blocks",
  "codec": {"bytes": 2368, "psnr": 99.0, "route": "banded k=4", "version": 3}
}

Distance is a weighted Euclidean metric over [log2(colors)/16, flat_ratio, edge_density, has_period, entropy/8]. On a 16-image set, same-family pairs average 0.35 and cross-family 1.08 — a 3.1× separation.

Reproduce

python benchmarks/make_set.py                  # draws both sets, no assets needed
python benchmarks/bench.py benchmarks/set/set256
python benchmarks/bench.py benchmarks/set/set512

* These ratios are indicative only: the hansu column is its q16 setting (≈35 dB), so comparing it with WebP lossless (99 dB) or q35 (≈30 dB) is not an equal-quality comparison. docs/COMPARISON.md does the equal-quality study.

WebP numbers come from Pillow's encoder on the same pixels. If your Pillow builds a different WebP, the comparison columns move; the hansu column does not.

Architecture

img ──┬─ palette route ──┐
      │                  ├─ smaller wins ── HS2 stream
      └─ predictive route┘        │
         YCoCg-R → per-channel    ├─ banded variant (parallel decode)
         MED pred → 250 ctx AC    ├─ alpha plane
                                  └─ CRC32

Performance

C backend, 4 threads, single machine:

input encode+decode note
512² UI ~100 ms automatic route
1024² UI ~46 ms banded k=8, 8.7× vs single band

The pure-Python backend is the reference: same bits, roughly 60× slower.

Format

docs/HS2-format.md — 11 sections, normative, including the uint64 overflow note that a 32-bit arithmetic coder implementation will hit silently.

Status

Alpha, v0.1.0. What works: whole/banded encode, decode, alpha, CRC, palette and predictive routes, independent decoder, topology signatures, CLI, tests. What does not exist yet: HTTP service, language bindings other than Python, a real third-party implementation, registered media type.

Licence

MIT.

Metadata

Release files for hansu 0.3.0

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

Source distribution (sdist)

Source distribution for hansu 0.3.0
File Size Uploaded Provenance Actions
hansu-0.3.0.tar.gz 52.2 kB With provenance Details for hansu-0.3.0.tar.gz

Built distribution (wheel)

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

Total release size: 82.3 kB

Release files / hansu-0.3.0.tar.gz

Download URL hansu-0.3.0.tar.gz
Size 52.2 kB
Tags Source
SHA-256 checksum
How to use checksums
291661774b43df7b64f53a620e9af1c7f22a18194e1969f4bfde1eb2f9d7dce3
BLAKE2b-256 checksum
How to use checksums
cb139eb817ab91fc550aa9f898cb1376ea92ce83adfd87e69b286a2c56fc2c09
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 Nov 28, 2026.

Transparency log

Release files / hansu-0.3.0-py3-none-any.whl

Download URL hansu-0.3.0-py3-none-any.whl
Size 30.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
07e79e1a5ce4be1497eb622617fb1501deba22272cd1e29cb9ba9796b0ea0be2
BLAKE2b-256 checksum
How to use checksums
32b83fbd358a55a4d4adf82193db1a40dfad6b094ca203396a55eece315f15c8
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 Nov 28, 2026.

Transparency log

Security for hansu 0.3.0

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 hansu-0.3.0.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 Nov 28, 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.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files Full provenance

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