tracemark 0.1.0__tar.gz
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-0.1.0/PKG-INFO +12 -0
- tracemark-0.1.0/README.md +221 -0
- tracemark-0.1.0/pyproject.toml +34 -0
- tracemark-0.1.0/setup.cfg +4 -0
- tracemark-0.1.0/tests/test_api.py +21 -0
- tracemark-0.1.0/tests/test_image_fragile.py +43 -0
- tracemark-0.1.0/tests/test_image_fragile_formats.py +21 -0
- tracemark-0.1.0/tests/test_image_robust.py +304 -0
- tracemark-0.1.0/tests/test_payload.py +34 -0
- tracemark-0.1.0/tests/test_text_generative.py +163 -0
- tracemark-0.1.0/tests/test_text_invisible.py +33 -0
- tracemark-0.1.0/tests/test_text_lexical.py +114 -0
- tracemark-0.1.0/tracemark/__init__.py +9 -0
- tracemark-0.1.0/tracemark/_fragile_bits.py +67 -0
- tracemark-0.1.0/tracemark/api.py +61 -0
- tracemark-0.1.0/tracemark/core.py +64 -0
- tracemark-0.1.0/tracemark/data/lexicon_v1.json +1 -0
- tracemark-0.1.0/tracemark/image_fragile.py +65 -0
- tracemark-0.1.0/tracemark/image_robust.py +1948 -0
- tracemark-0.1.0/tracemark/payload.py +146 -0
- tracemark-0.1.0/tracemark/text_generative.py +298 -0
- tracemark-0.1.0/tracemark/text_invisible.py +94 -0
- tracemark-0.1.0/tracemark/text_lexical.py +714 -0
- tracemark-0.1.0/tracemark.egg-info/PKG-INFO +12 -0
- tracemark-0.1.0/tracemark.egg-info/SOURCES.txt +26 -0
- tracemark-0.1.0/tracemark.egg-info/dependency_links.txt +1 -0
- tracemark-0.1.0/tracemark.egg-info/requires.txt +7 -0
- tracemark-0.1.0/tracemark.egg-info/top_level.txt +1 -0
tracemark-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tracemark
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hide bytes in images or text and read them back (CS1302A group project)
|
|
5
|
+
Project-URL: Homepage, https://github.com/barebone-lab/tracemark
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Requires-Dist: numpy>=1.24
|
|
8
|
+
Requires-Dist: cryptography>=42
|
|
9
|
+
Requires-Dist: reedsolo<2,>=1.7
|
|
10
|
+
Requires-Dist: opencv-python-headless>=5.0.0.93
|
|
11
|
+
Provides-Extra: generative
|
|
12
|
+
Requires-Dist: mlx-lm>=0.31.3; extra == "generative"
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# TraceMark
|
|
2
|
+
|
|
3
|
+
> Every set of notes you sell carries an invisible signature that can be traced back to its buyer.
|
|
4
|
+
|
|
5
|
+
**English** | [中文](README.zh.md)
|
|
6
|
+
|
|
7
|
+
**CS1302A Project Documentation**
|
|
8
|
+
|
|
9
|
+
**TraceMark** is a Python watermarking and leak-tracing module for tutors, notes sellers, and small content creators. It cannot stop someone from copying a file, but when a copy is resold or leaked, it can answer one crucial question: **who was this copy originally issued to?**
|
|
10
|
+
|
|
11
|
+
| Item | Detail |
|
|
12
|
+
|---|---|
|
|
13
|
+
| Course | CS1302A Introduction to Computer Programming (2026/27 Semester A) |
|
|
14
|
+
| Team | 4 members (group85): Wing, Kay, Billy, Amos |
|
|
15
|
+
| Deadline | 22 November 2026 (Sunday), 23:59 |
|
|
16
|
+
| Document version | v0.3 (17 November 2026) |
|
|
17
|
+
| Implementation status | All five modes implemented (package version `0.1.0`); PyPI, JupyterHub install, and CLI still pending |
|
|
18
|
+
| Test status | 2026-11-16 local run: 84 passed, 2 skipped (131.83 s, Python 3.12.13); coverage not measured; design targets listed separately |
|
|
19
|
+
| Licence | Code MIT (planned); documentation CC BY 4.0 (planned) |
|
|
20
|
+
|
|
21
|
+
> **In one sentence:** TraceMark embeds an invisible buyer identifier into each copy of a teaching file and, after a leak, compares the file against candidate keys to produce a mode-specific score that must be checked against transaction records.
|
|
22
|
+
> **What it is not:** A DRM / encryption / automatic conviction tool.
|
|
23
|
+
> **Current state:** all five modes run locally; PyPI, JupyterHub, and the formal CLI are still being finished.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Documentation map
|
|
28
|
+
|
|
29
|
+
This README is available in both English and Chinese. The English version is the default entry point; the Chinese version is available at [README.zh.md](README.zh.md). The remaining technical documents are written in Traditional Chinese.
|
|
30
|
+
|
|
31
|
+
| Document | Content |
|
|
32
|
+
|---|---|
|
|
33
|
+
| **README.md** (this page) | Summary, installation and usage, five modes |
|
|
34
|
+
| [README.zh.md](README.zh.md) | Chinese README |
|
|
35
|
+
| [01-background.md](docs/01-background.md) | Background and problem, two ideas, literature review, design goals, references, glossary |
|
|
36
|
+
| [02-architecture-and-api.md](docs/02-architecture-and-api.md) | System architecture, public API, payload format, future work |
|
|
37
|
+
| [03-testing-and-evaluation.md](docs/03-testing-and-evaluation.md) | What has been tested, attack matrix, evaluation metrics, targets still to verify |
|
|
38
|
+
| [04-project-and-course.md](docs/04-project-and-course.md) | Team roles, schedule, milestones, risks, course mapping |
|
|
39
|
+
| [05-legal-ethics-and-appendix.md](docs/05-legal-ethics-and-appendix.md) | Legal position, ethics, technical limits, AI-use statement, acknowledgements, licence |
|
|
40
|
+
| [06-version-history.md](docs/06-version-history.md) | Version history |
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## 1. Summary
|
|
45
|
+
|
|
46
|
+
In Hong Kong, DSE notes, tutoring materials, and self-made revision notes have long circulated on second-hand platforms such as Carousell as PDFs, images, or printed copies. Producing a set of notes costs many hours; copying a PDF costs almost nothing. When a buyer resells the same file, uploads it to cloud storage, or shares it with friends, the original author loses not only one sale but also the pricing power and trust built around the material.
|
|
47
|
+
|
|
48
|
+
The traditional defence is a visible watermark such as “For the use of XXX only” printed on the PDF. It deters some buyers, but it can be cropped, covered, retyped after OCR, or removed by reformatting a screenshot. Once the visible mark is gone, the seller has no thread to follow. In other words, a visible watermark can deter but cannot trace.
|
|
49
|
+
|
|
50
|
+
**TraceMark** is designed to combat the lack of a paper trail. It embeds a separate identifier for each buyer and, when a file leaks, compares the content against candidate keys to report the most likely leaked version and a similarity score. The module provides four watermarking methods plus one generative mode:
|
|
51
|
+
|
|
52
|
+
1. **Fragile image mode** (`image_fragile`): modifies the least significant bit (LSB) of pixel channels. Capacity is high and the change is invisible; it is suitable for hiding data and verifying an extracted payload, but it does not localise tampering.
|
|
53
|
+
2. **Robust image mode** (`image_robust`): adds a key-dependent balance pattern to luminance, with pilot-block synchronisation, convolutional coding, and soft Viterbi decoding. It targets compression, cropping, rotation, and screenshots.
|
|
54
|
+
3. **Invisible text mode** (`text_invisible`): encodes bits with U+200B/U+2060 and marks frame boundaries with U+2063; a 64-byte payload adds 682 invisible characters.
|
|
55
|
+
4. **Lexical text mode** (`text_lexical`): carries signals through English synonym substitutions, using Reed–Solomon coding and equation solving; it requires candidates or a provider.
|
|
56
|
+
5. **Generative text mode** (`text_generative`): adds a statistical watermark during model generation; extraction and identification require the same tokenizer and target the Apple silicon MLX backend.
|
|
57
|
+
|
|
58
|
+
All five modes share the same `embed`, `extract`, and `identify` interface. `identify` returns `match`, `none`, or `ambiguous`, not a “probability that this person leaked the file”. TraceMark is positioned as **post-hoc tracing**, not DRM or encryption: it cannot prevent copying, but after a leak it can give the seller a technical lead that can be checked against transaction records.
|
|
59
|
+
|
|
60
|
+
This documentation set covers the problem background, the trade-off between two initial ideas, related work, system design, test results, course mapping, and limitations. **Unless a number is explicitly labelled as a measured result, it is a design target.**
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Quick start: install, import, and use
|
|
65
|
+
|
|
66
|
+
> **Status:** the PyPI release is still pending, and the JupyterHub install has not been verified. The instructions below focus on a local install. The package name is `tracemark`, and Python `>=3.10` is required.
|
|
67
|
+
|
|
68
|
+
### Install
|
|
69
|
+
|
|
70
|
+
| Method | Command | Status |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| PyPI | `pip install tracemark` | Not published by this project yet; wait for the release announcement |
|
|
73
|
+
| Local source | `git clone https://github.com/barebone-lab/tracemark.git`<br>`cd tracemark`<br>`python -m pip install .` | Available |
|
|
74
|
+
| Development mode | `python -m pip install -e .` | Available |
|
|
75
|
+
| Generative mode (optional) | `python -m pip install '.[generative]'` | Requires Apple silicon and MLX; downloads a model on first use |
|
|
76
|
+
|
|
77
|
+
Base dependencies are `numpy>=1.24`, `cryptography>=42`, `reedsolo>=1.7,<2`, and `opencv-python-headless>=5.0.0.93`. The generative optional dependency is `mlx-lm>=0.31.3`.
|
|
78
|
+
|
|
79
|
+
### Import
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from tracemark import embed, extract, identify
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Basic usage
|
|
86
|
+
|
|
87
|
+
The following example runs as written. `content` is text in memory, `payload` is `bytes`, and `key` is a non-empty `bytes` or `str`.
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from tracemark import embed, extract, identify
|
|
91
|
+
|
|
92
|
+
keys = {"buyer-001": "demo-key-001", "buyer-002": "demo-key-002"}
|
|
93
|
+
text = "This is a set of teaching notes. " * 20
|
|
94
|
+
marked = embed(
|
|
95
|
+
text,
|
|
96
|
+
b"BUYER-001",
|
|
97
|
+
keys["buyer-001"],
|
|
98
|
+
mode="text_invisible",
|
|
99
|
+
)
|
|
100
|
+
result = extract(marked, keys["buyer-001"], mode="text_invisible")
|
|
101
|
+
print(result.verified, result.payload) # True, b'BUYER-001'
|
|
102
|
+
|
|
103
|
+
who = identify(marked, keys, mode="text_invisible")
|
|
104
|
+
print(who.status, who.best) # match, buyer-001
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Image input is a NumPy `uint8` array (RGB, RGBA, or grayscale); `embed` returns a new image array or string and leaves the input unchanged. The API does not open or save files; file I/O is the caller's responsibility.
|
|
108
|
+
|
|
109
|
+
### Modes and options
|
|
110
|
+
|
|
111
|
+
| `mode` | `content` | Required data / options | Default profile |
|
|
112
|
+
|---|---|---|---|
|
|
113
|
+
| `image_fragile` | Image array | Non-empty `payload`; optional `bits_per_channel=1` or `2`, `use_alpha=False` | `standard` |
|
|
114
|
+
| `image_robust` | Image array | Short `payload` or `b''`; optional `strength=1.0`, `markers=False`, `marker_strength=0.4` | `compact` |
|
|
115
|
+
| `text_invisible` | Text | Non-empty `payload`; optional `copies=1` | `standard` |
|
|
116
|
+
| `text_lexical` | English text | `payload` or `b''`; exactly one of `provider=` or `candidates=` is required | `compact` |
|
|
117
|
+
| `text_generative` | Generation prompt | `payload=b''`, `model=`; optional `max_tokens=400`, `temperature=0.8`, `top_k=64`, `seed=` | No payload frame |
|
|
118
|
+
|
|
119
|
+
For `image_robust` and `text_lexical`, `payload=b''` means key-only: only a key-derived trace is left, a successful extraction returns `payload=b''`, and no separate hidden data can be recovered. Key-only `image_robust` requires `markers=False`.
|
|
120
|
+
|
|
121
|
+
### Return values and exceptions
|
|
122
|
+
|
|
123
|
+
- `ExtractResult`: `mode`, `verified`, `score`, `payload`, `details`.
|
|
124
|
+
- A wrong key or no watermark usually returns `verified=False`, `payload=None`, `score=0`; the reason is in `details`.
|
|
125
|
+
- `IdentifyResult`: `status`, `best`, `results`. `status` is `match` (exactly one key passes), `none` (all fail), or `ambiguous` (more than one key passes).
|
|
126
|
+
- `best` is the label with the highest score among passing candidates, or `None` if all fail. `results` is a dict from candidate label to `ExtractResult`, preserving candidate order; it is not a sorted list.
|
|
127
|
+
- Exceptions: `WatermarkError`, with subclasses `CapacityError` and `UnsupportedModeError`; invalid arguments may also raise `ValueError` or `TypeError`.
|
|
128
|
+
|
|
129
|
+
`score` is a within-mode quality/evidence indicator, not a probability that a person leaked the file. When a payload is present, verification uses an authentication tag; for key-only and generative modes, `verified=True` means the statistical threshold was met.
|
|
130
|
+
|
|
131
|
+
### Current limitations
|
|
132
|
+
|
|
133
|
+
- PyPI has not yet been published; the JupyterHub install and formal CLI remain unfinished. CLI commands are not available yet; use the Python API.
|
|
134
|
+
- v1 supports images (formats that can be converted to NumPy arrays, such as PNG/BMP) and text; PDF, video, and audio are not supported.
|
|
135
|
+
- A watermark is neither DRM nor encryption; an identification score is a lead, not a verdict.
|
|
136
|
+
- `text_lexical` currently supports only an English tokenizer and lexicon; Chinese synonym support may be available in the future.
|
|
137
|
+
- `text_generative` requires a model and tokenizer; the MLX backend downloads a model on first use. It is not an AI content detector.
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## 7. The five modes
|
|
142
|
+
|
|
143
|
+
### 7.1 Fragile image mode (`image_fragile`)
|
|
144
|
+
|
|
145
|
+
**Principle:** Payload bits are written into the least significant bit (LSB) of each pixel channel. The change is at most a few least-significant-bit levels and is almost invisible. Before embedding, a key-derived pseudorandom permutation spreads the bits across the image; extraction reverses the permutation with the same key. Each channel can carry one or two bits; RGBA preserves alpha by default.
|
|
146
|
+
|
|
147
|
+
**Capacity:** For a 1024×1024 RGB image with `standard` profile and one bit per channel, net capacity is **393,195 bytes** (after the 21-byte payload overhead).
|
|
148
|
+
|
|
149
|
+
**Robustness:** Suitable only for lossless formats and identical copies; JPEGs, scaling, cropping, and screenshots destroy the payload.
|
|
150
|
+
|
|
151
|
+
**Purpose:** To conceal data and verify a certain payload. It does **not** provide tamper localisation: there is no coordinate or heat map, and no integrity authentication of the whole carrier; a successful extraction does not prove that the image is unmodified.
|
|
152
|
+
|
|
153
|
+
**References:** van Schyndel et al. (1994); Yeung & Mintzer (1997).
|
|
154
|
+
|
|
155
|
+
### 7.2 Robust image mode (`image_robust`)
|
|
156
|
+
|
|
157
|
+
**Principle:** a key-dependent balance pattern is added to image luminance and tiled repeatedly. Pilot blocks provide synchronisation; autocorrelation and image contours estimate rotation, scale, and perspective. The payload uses a convolutional code, repetition, and soft Viterbi decoding; when a payload is present, an authentication tag verifies it.
|
|
158
|
+
|
|
159
|
+
**Markers:** `markers=False` by default, with no visible corner marks. `markers=True` adds eight ArUco markers at the four corners and four edge midpoints for harder reproduction cases; visibility is controlled by `marker_strength`.
|
|
160
|
+
|
|
161
|
+
**Capacity:** the default marker-free compact layout holds up to **27 bytes**; with full rate-1/2 error correction it holds up to **16 bytes**. Marker layouts hold **21/12 bytes** respectively. Longer payloads use weaker error correction and become less robust.
|
|
162
|
+
|
|
163
|
+
**Limits:** embedding requires the image's shorter side to be at least **400 px**. Success under cropping, rotation, compression, and reproduction depends on the image, payload, and distortion; report only measured cases and do not claim that “any attack can be recovered”.
|
|
164
|
+
|
|
165
|
+
**References:** Cox et al. (1997); Ge et al. (2023); Pramila et al. (2008).
|
|
166
|
+
|
|
167
|
+
### 7.3 Invisible text mode (`text_invisible`)
|
|
168
|
+
|
|
169
|
+
**Principle:** U+200B represents 0, U+2060 represents 1, and U+2063 marks the boundary of each frame. Each data character carries one bit; insertion points are allocated at safe text gaps so that combining characters and emoji are not split. The key protects the payload; it does not scramble insertion positions.
|
|
170
|
+
|
|
171
|
+
**Capacity:** the `standard` profile holds **64 bytes**; one copy adds `(64+21)*8+2 = 682` invisible characters.
|
|
172
|
+
|
|
173
|
+
**Robustness:** copy-paste usually preserves the characters; OCR, retyping, or platform filtering removes them. NFC/NFKC normalisation alone is not the same as platform filtering; the example still extracted after normalisation.
|
|
174
|
+
|
|
175
|
+
**Ethics:** zero-width characters can also hide malicious instructions or bypass review. This project supports defensive use only and discloses the technique in its documentation.
|
|
176
|
+
|
|
177
|
+
**References:** Ishtiaq et al. (2025); Kaushik & Bhardwaj (2021).
|
|
178
|
+
|
|
179
|
+
### 7.4 Lexical text mode (`text_lexical`)
|
|
180
|
+
|
|
181
|
+
**Principle:** The current tokenizer and lexicon are tailor-made for English; support for Chinese synonyms will soon be added. Embedding requires approved substitution candidates: `candidates=` is a sequence of `Substitution(start, end, original, replacement)`, where positions are indices into the original string and the class is imported from `tracemark.text_lexical`. Alternatively, `provider=` supplies `propose(text)` to return candidates; the provided `DeepSeekProvider` uses `DEEPSEEK_API_KEY`, sends sentences to DeepSeek, and double-checks the substitutions, which involves an external API and meaning-review limits.
|
|
182
|
+
|
|
183
|
+
**Extraction:** Only the text, the same public lexicon, and the key are needed; it does not depend on an AI reply or the original document. Encoding uses anchors, local addresses, Reed–Solomon coding, and equation solving, rather than the simplified description “each word pair independently carries one bit and identification uses the match ratio”.
|
|
184
|
+
|
|
185
|
+
**Capacity (measured on a specific sample, not a general guarantee):** The current 7,000-English-word sample can hide **3 bytes**; its 3,000-word prefix is insufficient under the specified setting; the 2,000-word key-only sample can identify the source but cannot hide the same 3-byte ID.
|
|
186
|
+
|
|
187
|
+
**Limits:** OCR readability depends on whether the actual vocabulary survives; rewriting, translation, and typo/omission changes can cause failure. AI candidate review does not guarantee that meaning is unchanged. With `return_details=True`, embedding returns `(marked_text, details)`, including the actual substitutions; by default it returns the marked text directly.
|
|
188
|
+
|
|
189
|
+
**References:** Atallah et al. (2001); Lu et al. (2009); Stamatatos (2009).
|
|
190
|
+
|
|
191
|
+
### 7.5 Generative text mode (`text_generative`)
|
|
192
|
+
|
|
193
|
+
**Principle:** a statistical watermark is added while the model generates text, giving the output a traceable signal. `payload=b''`; no payload frame is used. `model=` must provide a tokenizer, `decode`, `prompt_ids`, `logits`, and `eos_ids`. The provided implementation is `tracemark.text_generative.MLXModel` for Apple silicon; it downloads a model on first use.
|
|
194
|
+
|
|
195
|
+
**Extraction and identification:** `tokenizer=` is required and must match the one used during generation; `verified=True` means the statistical threshold was met, not that a fixed payload was decoded.
|
|
196
|
+
|
|
197
|
+
**Positioning:** This is a watermark generation tool, not an AI content detector. It does not decide whether a piece of text was generated by AI, and it does not claim compliance with Article 50 of the EU AI Act.
|
|
198
|
+
|
|
199
|
+
**References:** Kirchenbauer et al. (2023); Fernandez et al. (2023).
|
|
200
|
+
|
|
201
|
+
### 7.6 Comparison
|
|
202
|
+
|
|
203
|
+
**Table 5: trade-offs between the five modes**
|
|
204
|
+
|
|
205
|
+
| Mode | Carrier | Capacity | Invisibility | Robustness | Main attacks | Implementation effort |
|
|
206
|
+
|---|---|---|---:|---|---|---|
|
|
207
|
+
| `image_fragile` | Image | High (393,195 bytes @1024²) | High | Low | Compression, scaling, cropping | Low |
|
|
208
|
+
| `image_robust` | Image | Low (16–27 bytes) | High | Medium | Geometric transforms, strong compression, screenshots, reproduction | High |
|
|
209
|
+
| `text_invisible` | Text | Medium (64 bytes / 682 characters) | High (but detectable) | Medium | Normalisation, platform filtering, OCR | Low |
|
|
210
|
+
| `text_lexical` | English text | Low (3 bytes in the 7,000-word sample) | High | Low–medium | Rewriting, translation, typos, omissions | Medium–high |
|
|
211
|
+
| `text_generative` | Model-generated text | No fixed payload | Not applicable | Medium | Changing model/decoding settings | High |
|
|
212
|
+
|
|
213
|
+
The five modes are not mutually exclusive. In practice they can be combined: a robust image watermark can carry a buyer number, invisible characters can carry a transaction number, and a lexical watermark can provide an additional text lead. Layering raises the cost of removal but also changes more of the content; combined settings remain a design option for future evaluation.
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## About this documentation set
|
|
218
|
+
|
|
219
|
+
- This page is the English README and the default GitHub entry point; the Chinese version is available at [README.zh.md](README.zh.md).
|
|
220
|
+
- The other six technical documents are linked from the documentation map above and are written in Traditional Chinese.
|
|
221
|
+
- Document version: v0.3 (17 November 2026). Implementation facts are current to 16 November 2026; measured results and unverified targets are reported separately in [03-testing-and-evaluation.md](docs/03-testing-and-evaluation.md).
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "tracemark"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Hide bytes in images or text and read them back (CS1302A group project)"
|
|
5
|
+
requires-python = ">=3.10"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"numpy>=1.24",
|
|
8
|
+
"cryptography>=42",
|
|
9
|
+
"reedsolo>=1.7,<2",
|
|
10
|
+
"opencv-python-headless>=5.0.0.93",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Homepage = "https://github.com/barebone-lab/tracemark"
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
generative = [
|
|
18
|
+
"mlx-lm>=0.31.3",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["setuptools>=68"]
|
|
23
|
+
build-backend = "setuptools.build_meta"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools]
|
|
26
|
+
packages = ["tracemark", "tracemark.data"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.package-data]
|
|
29
|
+
"tracemark.data" = ["*.json"]
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = [
|
|
33
|
+
"pytest>=9.2.0",
|
|
34
|
+
]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pytest
|
|
4
|
+
import tracemark as wm
|
|
5
|
+
|
|
6
|
+
def test_identify_finds_recipient():
|
|
7
|
+
keys = {"alice": os.urandom(32), "bob": os.urandom(32), "carol": os.urandom(32)}
|
|
8
|
+
leak = wm.embed("Confidential memo. Do not share.", b"memo-42", keys["bob"], mode="text_invisible")
|
|
9
|
+
result = wm.identify(leak, keys, mode="text_invisible")
|
|
10
|
+
assert result.status == "match" and result.best == "bob"
|
|
11
|
+
assert result.results["bob"].payload == b"memo-42"
|
|
12
|
+
|
|
13
|
+
def test_identify_none(key, other_key):
|
|
14
|
+
leak = wm.embed("Some text here.", b"x", os.urandom(32), mode="text_invisible")
|
|
15
|
+
assert wm.identify(leak, [key, other_key], mode="text_invisible").status == "none"
|
|
16
|
+
|
|
17
|
+
def test_unknown_mode_and_payload_type(key):
|
|
18
|
+
with pytest.raises(wm.UnsupportedModeError):
|
|
19
|
+
wm.embed("text", b"x", key, mode="nope")
|
|
20
|
+
with pytest.raises(TypeError):
|
|
21
|
+
wm.embed("text", "not bytes", key, mode="text_invisible")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
import tracemark as wm
|
|
5
|
+
from tracemark import image_fragile as fr
|
|
6
|
+
|
|
7
|
+
rng = np.random.default_rng(1)
|
|
8
|
+
MODE = "image_fragile"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture
|
|
12
|
+
def image():
|
|
13
|
+
return rng.integers(0, 256, (512, 512, 3), dtype=np.uint8)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_roundtrip_large_payload(image, key):
|
|
17
|
+
secret = rng.integers(0, 256, 50_000, dtype=np.uint8).tobytes()
|
|
18
|
+
before = image.copy()
|
|
19
|
+
marked = wm.embed(image, secret, key, mode=MODE)
|
|
20
|
+
assert np.array_equal(image, before), "input must not be modified"
|
|
21
|
+
assert int(np.abs(marked.astype(int) - image).max()) <= 1
|
|
22
|
+
result = wm.extract(marked, key, mode=MODE)
|
|
23
|
+
assert result.verified and result.payload == secret and result.score == 1.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_rejections(image, key, other_key):
|
|
27
|
+
marked = wm.embed(image, b"ID7", key, mode=MODE)
|
|
28
|
+
assert not wm.extract(marked, other_key, mode=MODE).verified
|
|
29
|
+
assert not wm.extract(image, key, mode=MODE).verified
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_capacity_exact_and_exceeded(image, key):
|
|
33
|
+
cap = fr.capacity(image)
|
|
34
|
+
assert wm.extract(wm.embed(image, b"x" * cap, key, mode=MODE), key, mode=MODE).payload == b"x" * cap
|
|
35
|
+
with pytest.raises(wm.CapacityError):
|
|
36
|
+
wm.embed(image, b"x" * (cap + 1), key, mode=MODE)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_hide_whole_image_two_bits(image, key):
|
|
40
|
+
small = rng.integers(0, 256, (200, 200, 3), dtype=np.uint8)
|
|
41
|
+
result = wm.extract(wm.embed(image, small.tobytes(), key, mode=MODE, bits_per_channel=2), key, mode=MODE)
|
|
42
|
+
assert result.verified and result.details["bits_per_channel"] == 2
|
|
43
|
+
assert np.array_equal(np.frombuffer(result.payload, np.uint8).reshape(small.shape), small)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
import tracemark as wm
|
|
5
|
+
|
|
6
|
+
rng = np.random.default_rng(1)
|
|
7
|
+
MODE = "image_fragile"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_rgba_alpha_untouched_and_grayscale(key):
|
|
11
|
+
rgba = rng.integers(0, 256, (64, 64, 4), dtype=np.uint8)
|
|
12
|
+
marked = wm.embed(rgba, b"alpha", key, mode=MODE)
|
|
13
|
+
assert np.array_equal(marked[..., 3], rgba[..., 3])
|
|
14
|
+
assert wm.extract(marked, key, mode=MODE).payload == b"alpha"
|
|
15
|
+
gray = rng.integers(0, 256, (64, 64), dtype=np.uint8)
|
|
16
|
+
assert wm.extract(wm.embed(gray, b"g", key, mode=MODE), key, mode=MODE).payload == b"g"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_rejects_non_uint8(key):
|
|
20
|
+
with pytest.raises(TypeError):
|
|
21
|
+
wm.embed(np.zeros((8, 8), dtype=np.float32), b"x", key, mode=MODE)
|