Metadata-Version: 2.5
Name: imagecalculator
Version: 0.1.0
Summary: Progressive block-DCT image codec: truncate to the first k anti-diagonals, quantize per diagonal, decode at the reduced native size (Image Calculator / Frequency-Store)
Project-URL: Homepage, https://github.com/cangokmen/imagecalculator
Project-URL: Repository, https://github.com/cangokmen/imagecalculator
Project-URL: Issues, https://github.com/cangokmen/imagecalculator/issues
Author: Can Gokmen
License: MIT
License-File: LICENSE
Keywords: dct,image-compression,progressive-codec,tokens,vision-language-models
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: blosc<2,>=1.10
Requires-Dist: numpy>=1.24
Requires-Dist: pillow>=9.0
Requires-Dist: torch>=2.1
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Description-Content-Type: text/markdown

# imagecalculator

A progressive block-DCT image codec for sending images to vision models.

**Truncation reduces your token count.** Keep only the first `k` anti-diagonals
of each DCT block and decode them at the *reduced native size*: the model sees
fewer pixels, and pixel-priced APIs (Claude, GPT, Gemini) charge fewer image
tokens. Tokens scale with `(k/N)^2`.

**Truncation + the other optimizations reduce your wifi cost.** Per-diagonal
quantization, YCrCb with chroma subsampling, support-only (zero-free) storage
and blosc/zstd entropy coding shrink the bytes that leave the device for the
same pixels.

The two levers are independent: `keep` sets the pixel/token budget, the rest
sets bytes per pixel.

```python
import imagecalculator as ic

enc = ic.compress("photo.jpg", keep=8, quantization=20)   # 8 of 63 diagonals (block 32, 448 px)
enc.pixels            # (112, 112)  -> what the model will see
enc.token_estimate()  # ~17 tokens on Anthropic (vs ~268 for the full 448 px image)
enc.nbytes            # bytes over the air (.icf container)
enc.save("photo.icf")

img = ic.decompress(enc)                 # PIL image, 112 x 112, k-point inverse DCT per block
img = ic.decompress(enc, size=224)       # any S*m/N with m >= k
img = ic.decompress(enc, size="full")    # blurry full-size reconstruction (legacy behaviour)
```

### Sending it to Claude

```python
import os, anthropic, imagecalculator as ic

enc = ic.compress("photo.jpg", keep=8, quantization=20)
img = ic.decompress(enc)                                   # receiver side
client = anthropic.Anthropic()
r = client.messages.create(
    model="claude-opus-5-5", max_tokens=1024,
    messages=[{"role": "user", "content": [
        {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": ic.png_b64(img)}},
        {"type": "text", "text": "What color is the bus?"},
    ]}],
)
print("tokens:", r.usage.input_tokens, "(full image: ~268)")                      # tier 1: truncation
print("bytes over wifi:", enc.nbytes, "(original JPEG:", os.path.getsize("photo.jpg"), ")")  # tier 2
```

`examples/compress_for_claude.py` runs the same question at `keep = 4, 8, 16, 32`
and prints measured `usage.input_tokens` and bytes next to a Lanczos resize of
the original to the same pixel size.

### Honest framing

A `k`-point inverse DCT of the low corner is a near-ideal low-pass filter
followed by decimation. It carries the **same information as a good resize**
(Lanczos / area) to that size, not more. What the format adds: one encoding
serves every size, and bytes are competitive with a JPEG of the resized image.

## Per-diagonal control (the adaptivity knobs)

```python
# scalar step, a per-diagonal vector, or [[from, to, q], ...] bands tiling [0, max_diag)
enc = ic.compress("photo.jpg", keep=16, quantization=[[0, 8, 1], [8, 20, 10], [20, 63, 50]])

# anything else per diagonal: a hook on the un-rounded (3, n_d) coefficients
import torch
def dead_zone(d, coeffs):            # drop tiny high-frequency coefficients
    return coeffs if d < 8 else torch.where(coeffs.abs() < 30, torch.zeros_like(coeffs), coeffs)
pol = ic.DiagonalPolicy(keep=16, quantization=20, transform=dead_zone, clevel=9)
enc = ic.compress("photo.jpg", policy=pol)
```

## CLI

```
imagecalculator compress photo.jpg --keep 8 --quantization 20 [--block-size 32 --image-size 448] -o photo.icf
imagecalculator decompress photo.icf [--size native|full|224] -o photo.png
imagecalculator info photo.icf [--original photo.jpg]
```

`info` prints the config, then two lines: `tokens: 17 (full image 268, ...)` and
`bytes over the air: 6.1 KiB (original file 182 KiB, ...)`.

`compress` and `info` take `--provider anthropic | openai[:model] | google[:model]`
and `--detail` (OpenAI `detail`, Gemini `media_resolution`); the same arguments
go to `token_estimate()` / `EncodedImage.savings()`. Truncation only saves tokens
where cost scales with pixels: Anthropic, OpenAI patch models (gpt-5.2 and
later, gpt-4.1-mini; default `openai` = gpt-5.5) and Gemini 2.5 and earlier. Tile-priced OpenAI
models (gpt-4o, gpt-4.1, gpt-5.1) bill a 448 px image as one 512 px tile, and
Gemini 3/4 bill a fixed count per image (1120 by default), so `keep` doesn't
change their token count, only bytes.

## Install

```
pip install imagecalculator
```

`pip` pulls in a default torch build; to pick the CPU wheel (much smaller),
install torch from the PyTorch index first:

```
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install imagecalculator
```

From a checkout: `pip install -e ".[dev]"` and `OMP_NUM_THREADS=4 pytest -q`.

Dependencies: numpy, torch, blosc (1.x), Pillow.

On a shared machine with many cores, set `OMP_NUM_THREADS` (or
`torch.set_num_threads`) to a small number: the codec's tensors are small, and
32 contending OpenMP threads turn a 2 ms encode into seconds.

`quantization=1` stores the DCT coefficients as rounded integers (the
research "q1" stores); a full decode is within 2 levels of the input (one from
coefficient rounding, one from uint8 truncation), not bit-exact in pixel space.

## Compatibility with the research Frequency-Store

With no `transform`, `enc.payloads[d]` is byte-identical to the file
`img_<i>/diag_<d>.col` of a research dir store built with the same config, and
`decompress(enc, size="full")` reproduces the research reader's reconstruction
exactly.
