Metadata-Version: 2.4
Name: hansu
Version: 0.3.0
Summary: A structural image codec (HS2) with topology signatures and an image-similarity index
Author: Zhi & Heng
License: MIT
Project-URL: Homepage, https://github.com/antlee160429-collab/hansu
Keywords: image,compression,codec,arithmetic-coding,palette,topology
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Requires-Dist: pillow>=9.0
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Dynamic: license-file

# hansu

![ci](https://github.com/antlee160429-collab/hansu/actions/workflows/ci.yml/badge.svg)

> **Verify it, don't trust it.** [`docs/HS2-format.md`](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:

```bash
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`](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`](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

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

## Use

```python
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:

```bash
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

```python
import hansu, json
sig = hansu.signature(img)
print(json.dumps(sig, indent=2))
```

```json
{
  "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

```bash
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`](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.
