tracemark 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tracemark/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """General-purpose digital watermarking: hide bytes in images or text, then read them back.
2
+
3
+ Modes: image_fragile, image_robust, text_invisible, text_lexical, text_generative.
4
+ """
5
+ from .api import embed, extract, identify
6
+ from .core import CapacityError, ExtractResult, IdentifyResult, UnsupportedModeError, WatermarkError
7
+
8
+ __all__ = ["embed", "extract", "identify", "ExtractResult", "IdentifyResult",
9
+ "WatermarkError", "CapacityError", "UnsupportedModeError"]
@@ -0,0 +1,67 @@
1
+ """Low-level bit and sample helpers for the fragile image watermark.
2
+
3
+ This module deliberately contains no public watermark API. It owns the
4
+ key-dependent sample order and the conversion between packed frame bytes and
5
+ the least-significant bits of image samples, so the public mode module can stay
6
+ focused on payload framing and result types.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
12
+
13
+ from . import payload as pl
14
+
15
+ ORDER_CONTEXT = "image_fragile/positions"
16
+
17
+
18
+ def check_image(image) -> np.ndarray:
19
+ """Return *image* as an array, rejecting unsupported dtypes/shapes."""
20
+ image = np.asarray(image)
21
+ if image.dtype != np.uint8:
22
+ raise TypeError("image must be a uint8 array")
23
+ if image.ndim not in (2, 3):
24
+ raise ValueError("image must be shaped (H, W) or (H, W, C)")
25
+ return image
26
+
27
+
28
+ def check_bpc(bpc: int) -> None:
29
+ """Validate the number of embedded bits per channel."""
30
+ if bpc not in (1, 2):
31
+ raise ValueError("bits_per_channel must be 1 or 2")
32
+
33
+
34
+ def sample_view(image: np.ndarray, use_alpha: bool) -> np.ndarray:
35
+ """Return the view whose samples carry the watermark.
36
+
37
+ RGBA images keep their alpha channel untouched unless *use_alpha* is true.
38
+ """
39
+ if image.ndim == 3 and image.shape[2] == 4 and not use_alpha:
40
+ return image[..., :3]
41
+ return image
42
+
43
+
44
+ def sample_order(key, total: int, count: int) -> np.ndarray:
45
+ """First *count* sample indices of a key-dependent permutation of range(total).
46
+
47
+ Sort keys are 32 random bits from AES-CTR with the index in the low bits, so
48
+ every key is unique and the order is identical on every platform.
49
+ """
50
+ stream = Cipher(algorithms.AES(pl.subkey(key, ORDER_CONTEXT)), modes.CTR(b"\0" * 16)).encryptor()
51
+ rand = np.frombuffer(stream.update(b"\0" * (4 * total)), dtype=">u4").astype(np.uint64)
52
+ sort_keys = (rand << np.uint64(32)) | np.arange(total, dtype=np.uint64)
53
+ if count < total:
54
+ head = np.argpartition(sort_keys, count)[:count]
55
+ else:
56
+ head = np.arange(total)
57
+ return head[np.argsort(sort_keys[head], kind="stable")]
58
+
59
+
60
+ def read_bits(flat: np.ndarray, key, bpc: int, nbytes: int) -> bytes | None:
61
+ """Read *nbytes* frame bytes from the low *bpc* bits of *flat* samples."""
62
+ needed = -(-nbytes * 8 // bpc)
63
+ if needed > flat.size:
64
+ return None
65
+ values = flat[sample_order(key, flat.size, needed)] & ((1 << bpc) - 1)
66
+ bits = ((values[:, None] >> np.arange(bpc - 1, -1, -1, dtype=np.uint8)) & 1).reshape(-1)[: nbytes * 8]
67
+ return np.packbits(bits.astype(np.uint8)).tobytes()
tracemark/api.py ADDED
@@ -0,0 +1,61 @@
1
+ """One entry point for every mode: embed, extract, identify.
2
+
3
+ from tracemark import embed, extract, identify
4
+ marked = embed(image, b"Student-123", key, mode="image_fragile")
5
+ result = extract(marked, key, mode="image_fragile") # ExtractResult
6
+ who = identify(leaked, {"alice": k1, "bob": k2}, mode="text_invisible")
7
+
8
+ Content is always passed and returned in memory (numpy arrays for images,
9
+ str for text); nothing is read from or written to disk. Extra keyword
10
+ arguments go to the chosen mode (see each module's embed/extract).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from importlib import import_module
15
+ from typing import Any, Iterable, Mapping
16
+
17
+ from .core import MODES, ExtractResult, IdentifyResult, UnsupportedModeError
18
+
19
+ _MODULES = {
20
+ "image_fragile": ".image_fragile",
21
+ "text_invisible": ".text_invisible",
22
+ "text_lexical": ".text_lexical",
23
+ "image_robust": ".image_robust",
24
+ "text_generative": ".text_generative",
25
+ }
26
+
27
+
28
+ def _module(mode: str):
29
+ if mode not in MODES:
30
+ raise UnsupportedModeError(f"unknown mode {mode!r}; choose from {MODES}")
31
+ if mode not in _MODULES:
32
+ raise UnsupportedModeError(f"mode {mode!r} is not implemented yet")
33
+ return import_module(_MODULES[mode], __package__)
34
+
35
+
36
+ def embed(content: Any, payload: bytes, key: bytes | str, *, mode: str, **options) -> Any:
37
+ """Return a watermarked copy of `content`. The input is not modified."""
38
+ if not isinstance(payload, (bytes, bytearray)):
39
+ raise TypeError("payload must be bytes; encode text or images to bytes first")
40
+ return _module(mode).embed(content, bytes(payload), key, **options)
41
+
42
+
43
+ def extract(content: Any, key: bytes | str, *, mode: str, **options) -> ExtractResult:
44
+ return _module(mode).extract(content, key, **options)
45
+
46
+
47
+ def identify(content: Any, keys: Mapping[Any, bytes | str] | Iterable[bytes | str], *, mode: str,
48
+ **options) -> IdentifyResult:
49
+ """Try every candidate key; report which one (if any) the content belongs to.
50
+
51
+ keys: {label: key} or a plain list (labels are then the list positions).
52
+ """
53
+ items = list(keys.items()) if isinstance(keys, Mapping) else list(enumerate(keys))
54
+ many = getattr(_module(mode), "extract_many", None) # shares key-independent work between keys
55
+ results: dict[Any, ExtractResult] = many(content, items, **options) if many else \
56
+ {label: extract(content, k, mode=mode, **options) for label, k in items}
57
+ verified = [label for label, r in results.items() if r.verified]
58
+ if not verified:
59
+ return IdentifyResult("none", None, results)
60
+ best = max(verified, key=lambda label: results[label].score)
61
+ return IdentifyResult("match" if len(verified) == 1 else "ambiguous", best, results)
tracemark/core.py ADDED
@@ -0,0 +1,64 @@
1
+ """Shared result types and errors used by every watermark mode."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+ MODES = ("image_fragile", "image_robust", "text_invisible", "text_lexical", "text_generative")
8
+
9
+
10
+ class WatermarkError(Exception):
11
+ """Base class for every error raised by this package."""
12
+
13
+
14
+ class CapacityError(WatermarkError):
15
+ """The content cannot hold the requested payload. Nothing is truncated."""
16
+
17
+
18
+ class UnsupportedModeError(WatermarkError):
19
+ """The requested mode does not exist or is not implemented yet."""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ExtractResult:
24
+ """Outcome of one extraction attempt.
25
+
26
+ verified: True only when the authentication tag matched the key.
27
+ score: 0.0 when not verified; otherwise 1.0 minus the share of the
28
+ error-correction margin that was used (1.0 = no errors seen).
29
+ payload: the hidden bytes, or None when not verified.
30
+ """
31
+
32
+ mode: str
33
+ verified: bool
34
+ score: float
35
+ payload: bytes | None = None
36
+ details: dict[str, Any] = field(default_factory=dict)
37
+
38
+ @staticmethod
39
+ def failed(mode: str, reason: str, **details: Any) -> "ExtractResult":
40
+ return ExtractResult(mode=mode, verified=False, score=0.0, payload=None, details={"reason": reason, **details})
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class IdentifyResult:
45
+ """Outcome of comparing one content against several candidate keys.
46
+
47
+ status: "match" exactly one key verified;
48
+ "none" no key verified;
49
+ "ambiguous" more than one key verified (should not happen with
50
+ distinct keys; treat as suspicious).
51
+ best: label of the best-scoring verified key, or None.
52
+ results: label -> ExtractResult for every candidate.
53
+ """
54
+
55
+ status: str
56
+ best: Any
57
+ results: dict[Any, ExtractResult]
58
+
59
+
60
+ def margin_score(corrected: int, correctable: int) -> float:
61
+ """Map 'errors corrected out of the correctable budget' to a score in (0, 1]."""
62
+ if correctable <= 0:
63
+ return 1.0 if corrected == 0 else 0.0
64
+ return max(0.0, 1.0 - corrected / (correctable + 1))