Metadata-Version: 2.4
Name: traceless-watermark
Version: 0.1.0
Summary: Add and extract invisible image watermarks with Reed-Solomon error correction and optional GPU acceleration.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Requires-Dist: numpy>=2.5.2
Requires-Dist: opencv-python-headless>=5.0.0.93
Requires-Dist: pywavelets>=1.9.0
Requires-Dist: wgpu>=0.32.0 ; extra == 'gpu'
Requires-Python: >=3.12
Provides-Extra: gpu
Description-Content-Type: text/markdown

# Traceless Watermark for Python

`TracelessWatermark-Python` is a Python image-processing library for adding and extracting invisible watermarks.

This package uses the DWT-DCT-SVD implementation from ShieldMnt's Python [invisible-watermark](https://github.com/ShieldMnt/invisible-watermark) library and incorporates [Reed-Solomon error correction](https://github.com/tomerfiliba-org/reedsolomon).

Encoding and decoding work with NumPy image arrays. GPU mode uses WebGPU when available and falls back to the CPU path otherwise.

Traceless Watermark also includes libraries for iOS, Android, and browsers.

## Requirements

- Python 3.12 or later
- Optional WebGPU dependencies for the GPU implementation

## Usage

```python
import asyncio
import cv2

from traceless_watermark import TracelessWatermark, WatermarkSuccess

async def main():
    image = cv2.imread("input.jpg", cv2.IMREAD_COLOR)
    watermark = TracelessWatermark()
    watermark_text = "Example watermark"

    encode_result = await watermark.encode_text(image, watermark_text)

    if isinstance(encode_result, WatermarkSuccess):
        watermarked_image = encode_result.value
        cv2.imwrite("watermarked.png", watermarked_image)

        decode_result = await watermark.decode_text(
            watermarked_image,
            byte_count=len(watermark_text.encode("utf-8")),
        )

        if isinstance(decode_result, WatermarkSuccess):
            print(decode_result.value.payload)
        else:
            print("Decode failed:", decode_result.error)
    else:
        print("Encode failed:", encode_result.error)

asyncio.run(main())
```

## API

Traceless Watermark has the following methods used for encoding and decoding watermarks, and all move off the event loop thread to avoid blocking async callers.

Text-based APIs:

```python
async def encode_text(
    image: np.ndarray,
    text: str,
) -> WatermarkSuccess[np.ndarray] | WatermarkFailure[WatermarkEncodeError]

async def decode_text(
    image: np.ndarray,
    byte_count: int,
) -> WatermarkSuccess[DecodedPayload[str]] | WatermarkFailure[WatermarkDecodeError]
```

Byte-based APIs:

```python
async def encode_bytes(
    image: np.ndarray,
    payload: bytes,
) -> WatermarkSuccess[np.ndarray] | WatermarkFailure[WatermarkEncodeError]

async def decode_bytes(
    image: np.ndarray,
    byte_count: int,
) -> WatermarkSuccess[DecodedPayload[bytes]] | WatermarkFailure[WatermarkDecodeError]
```

Results are returned as `WatermarkSuccess(value)` or `WatermarkFailure(error)`. Decode success values contain a `DecodedPayload`; use `payload` for the recovered text or bytes, and `correction_usage` for the fraction of the Reed-Solomon correction budget used during recovery.

## Options

Options can be set when creating the `TracelessWatermark` object.

```python
watermark = TracelessWatermark(
    scales=ChannelScales(),
    block_size=WatermarkBlockSize.FOUR,
    correction_level=StandardWatermarkErrorCorrectionLevel.MEDIUM,
    execution_mode=WatermarkExecutionMode.GPU,
)
```

### Channel Scales

The scale controls how strongly the watermark is written into each YUV channel.

Using more channels can improve decode reliability, but costs more work.

```python
ChannelScales(y_channel=0, u_channel=36, v_channel=36) # Default values
```

Higher YUV color scale values improve watermark resilience at the cost of visual artifacting.

### Execution Mode

Switch between CPU and GPU environments when performing watermarks.

```python
WatermarkExecutionMode.CPU
WatermarkExecutionMode.GPU
WatermarkExecutionMode.REFERENCE
```

`GPU` uses WebGPU and is the default. When WebGPU is unavailable, it falls back to `CPU`. `REFERENCE` uses the local reference implementation for comparison and debugging.

### Error Correction

Error correction levels are provided for better watermark survivability.

```python
StandardWatermarkErrorCorrectionLevel.NONE
StandardWatermarkErrorCorrectionLevel.LOW
StandardWatermarkErrorCorrectionLevel.MEDIUM
StandardWatermarkErrorCorrectionLevel.QUARTILE
StandardWatermarkErrorCorrectionLevel.HIGH
CustomWatermarkErrorCorrectionLevel(recovery_rate)
```

The levels mimic QR code error correction levels. The default is `MEDIUM`.

### Block Size

Block size controls the squares used for embedding watermark bits.

```python
WatermarkBlockSize.FOUR
WatermarkBlockSize.EIGHT
```

`FOUR` is the recommended default. `EIGHT` is available for tuning and experiments.

## GPU Cold Starts

If you know the sizes of your images and watermark in advance, you can pass a buffer-pool reservation during warmup to reduce cold start latency.

```python
warm_up_result = await TracelessWatermark.warm_up(
    BufferPoolReservation(
        width=image_width,
        height=image_height,
        byte_count=len("Example watermark".encode("utf-8")),
        correction_level=StandardWatermarkErrorCorrectionLevel.MEDIUM, # Default parameter
    )
)
```

`warm_up` returns `WarmUpResult.Success`, `WarmUpResult.GpuUnavailable`, or `WarmUpResult.ReservationTooLarge`.

Call `clean_up()` when an app wants to release shared GPU resources:

```python
await TracelessWatermark.clean_up()
```

## Image Notes

- Images should be `np.uint8` arrays.
- Supported shapes are `(height, width, 3)` and `(height, width, 4)`.
- Channel order is BGR/BGRA, matching OpenCV.
- Decode length is the original UTF-8 byte length.
- Resizing, cropping, rotating, taking screenshots, or heavy recompression damages the signal.
- Higher-resolution images increase watermark capacity, but require more processing time and memory.
- Transparent images are not supported due to alpha premultiplication.
- Encoded output file sizes are typically larger than the source images.
- Cross-platform compatibility may still encounter edge cases.
- Currently Traceless Watermark is meant to watermark one image at a time.

## Development

See [PLATFORM_DETAILS.md](PLATFORM_DETAILS.md) for local setup, development environment tips, running the example app, and testing changes.

## License

Apache-2.0. See [`LICENSE`](LICENSE).
