theapk-ghostprint 0.1.1__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.
ghostprint/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """ghostprint — two-layer invisible watermark for 3D-printed parts (v0.1.1).
2
+
3
+ Layer 1 (L1): G-code micro-watermark (printer_id + job_seq + timestamp).
4
+ Layer 2 (L2): geometric steganography (order_id -> vertex perturbations).
5
+
6
+ The implementation lives in :mod:`ghostprint.core`; the tag/verify CLIs
7
+ live in tag-print.py / verify-print.py (repo clone layout), and
8
+ :mod:`ghostprint.cli` exposes the ``ghostprint`` console script.
9
+
10
+ Version matches ``theapk-ghostprint`` in pyproject.toml (0.1.1).
11
+ """
12
+
13
+ from .core import * # noqa: F401,F403
14
+ from .core import ( # noqa: F401
15
+ GhostprintManifest,
16
+ L1_PREAMBLE,
17
+ L1_SCHEME_VERSION,
18
+ L2_AMPLITUDE_MAX_MM,
19
+ L2_AMPLITUDE_MIN_MM,
20
+ file_sha256,
21
+ l1_babysteps_to_payload,
22
+ l1_decode_payload,
23
+ l1_encode_payload,
24
+ l1_extract_from_gcode,
25
+ l1_payload_to_babysteps,
26
+ l1_rewrite_gcode,
27
+ l2_order_hash,
28
+ l2_perturb_vertices,
29
+ l2_recover_deltas,
30
+ l2_recover_order,
31
+ l2_verify_match,
32
+ )
33
+
34
+ __version__ = "0.1.1"
ghostprint/cli.py ADDED
@@ -0,0 +1,117 @@
1
+ """ghostprint — console-script CLI for the two-layer 3D-print watermark.
2
+
3
+ Verbs (wrapping the repo's tag-print.py / verify-print.py):
4
+ ghostprint tag <tag-print.py arguments>
5
+ ghostprint verify <master.stl> <tagged.stl> [--order-id ...]
6
+ (also accepts decode-stl / decode-gcode subverbs)
7
+ ghostprint decode-gcode <FILE.gcode>
8
+ ghostprint self-test
9
+
10
+ v0.1.1 limitation: the CLI loads the sibling tag-print.py / verify-print.py
11
+ from a repo clone (documented install path: `pip install -e .` from the
12
+ git checkout). If the sibling scripts are missing (installed from a
13
+ wheel), main() fails cleanly with exit code 2.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import importlib.util
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import List, Optional
22
+
23
+ _SRC_DIR = Path(__file__).resolve().parents[1] # <repo>/src (package lives in src/)
24
+ _REPO_ROOT = _SRC_DIR.parent # <repo>/ (sibling scripts live here)
25
+ _TAG_PRINT = _REPO_ROOT / "tag-print.py"
26
+ _VERIFY_PRINT = _REPO_ROOT / "verify-print.py"
27
+
28
+ _VERIFY_SUBVERBS = ("decode-gcode", "decode-stl", "self-test")
29
+
30
+
31
+ def _load_sibling(module_name: str, path: Path):
32
+ """Load a sibling repo script by absolute path (same house pattern as
33
+ landing/serve.py). Returns None when the script is missing, so the
34
+ installed-from-wheel case can fail cleanly in main()."""
35
+ if not path.exists():
36
+ return None
37
+ src = str(_SRC_DIR)
38
+ if src not in sys.path:
39
+ sys.path.insert(0, src)
40
+ spec = importlib.util.spec_from_file_location(module_name, path)
41
+ assert spec is not None and spec.loader is not None, f"cannot load {path}"
42
+ module = importlib.util.module_from_spec(spec)
43
+ sys.modules[module_name] = module
44
+ spec.loader.exec_module(module)
45
+ return module
46
+
47
+
48
+ def _verify_argv(rest: List[str]) -> List[str]:
49
+ """Map `ghostprint verify ...` onto verify-print.py's argv.
50
+
51
+ Two-positional form (MASTER TAGGED — the README promise order) is
52
+ translated — decode-stl spells the master as --master. Everything else
53
+ passes through unchanged, and a leading verify-print.py subverb
54
+ (decode-gcode / decode-stl / self-test) is routed as-is.
55
+ """
56
+ if rest and rest[0] in _VERIFY_SUBVERBS:
57
+ return rest
58
+ if rest and rest[0].startswith("-"):
59
+ # Flags-first ordering (--amplitude X / --manifest m.json BEFORE the
60
+ # positionals) can't be translated positionally: pass through and let
61
+ # decode-stl's argparse produce its clean required-argument error.
62
+ return ["decode-stl"] + rest
63
+ if len(rest) >= 2 and not rest[1].startswith("-"):
64
+ # README promise order: MASTER first, TAGGED second; decode-stl
65
+ # spells the master as --master and takes the TAGGED path as its
66
+ # suspect positional (so <tagged>.manifest.json auto-discovery
67
+ # keys on the tagged file).
68
+ return ["decode-stl", rest[1], "--master", rest[0]] + rest[2:]
69
+ return ["decode-stl"] + rest
70
+
71
+
72
+ def build_parser() -> argparse.ArgumentParser:
73
+ ap = argparse.ArgumentParser(
74
+ prog="ghostprint",
75
+ description="ghostprint — two-layer invisible watermark for 3D-printed parts",
76
+ )
77
+ sub = ap.add_subparsers(dest="cmd", required=True)
78
+
79
+ tag = sub.add_parser("tag", help="tag an STL: invisible fingerprint encoder (tag-print.py arguments)")
80
+ tag.add_argument("tag_args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
81
+
82
+ verify = sub.add_parser("verify", help="compare a TAGGED part against a "
83
+ "MASTER (arguments: MASTER TAGGED; "
84
+ "or decode-stl/decode-gcode subverbs)")
85
+ verify.add_argument("verify_args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
86
+
87
+ dg = sub.add_parser("decode-gcode", help="recover the L1 (printer+job+ts) payload from a G-code file")
88
+ dg.add_argument("decode_gcode_args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
89
+
90
+ sub.add_parser("self-test", help="generate a cube, tag, decode both layers, assert round-trip")
91
+ return ap
92
+
93
+
94
+ def main(argv: Optional[List[str]] = None) -> int:
95
+ ap = build_parser()
96
+ args = ap.parse_args(argv)
97
+
98
+ tag_mod = _load_sibling("gp_tag_print", _TAG_PRINT)
99
+ verify_mod = _load_sibling("gp_verify_print", _VERIFY_PRINT)
100
+ if tag_mod is None or verify_mod is None:
101
+ print("ghostprint CLI verbs require a repo clone for now — reinstall from git",
102
+ file=sys.stderr)
103
+ return 2
104
+
105
+ if args.cmd == "tag":
106
+ return tag_mod.main(args.tag_args)
107
+ if args.cmd == "verify":
108
+ return verify_mod.main(_verify_argv(args.verify_args))
109
+ if args.cmd == "decode-gcode":
110
+ return verify_mod.main(["decode-gcode"] + args.decode_gcode_args)
111
+ if args.cmd == "self-test":
112
+ return verify_mod.main(["self-test"])
113
+ ap.error(f"unknown command: {args.cmd}") # unreachable: subparsers are required
114
+
115
+
116
+ if __name__ == "__main__":
117
+ sys.exit(main())
ghostprint/core.py ADDED
@@ -0,0 +1,461 @@
1
+ """
2
+ ghostprint_core — invisible 3D-print fingerprinting.
3
+
4
+ Two independent layers, both round-trip verifiable:
5
+
6
+ L1. G-code micro-watermark — printer_id + job_id + timestamp encoded as
7
+ sub-resolution Z-babysteps at print-start. Recovered by parsing the
8
+ .gcode file. Survives anything that does not round-trip Z to mm.
9
+
10
+ L2. Geometric steganography — order_id hash spread as vertex perturbations
11
+ with an amplitude within the allowed range 0.005-0.020 mm (see
12
+ L2_AMPLITUDE_MIN_MM / L2_AMPLITUDE_MAX_MM; per-vertex deltas stay at
13
+ or below the chosen amplitude, below typical 0.04 mm nozzle X/Y
14
+ resolution). Recovered by diffing the suspect STL against the master.
15
+ IMPORTANT: standard slicers re-mesh, so this layer survives only on
16
+ a no-slicer path or against the original master STL. The encoder
17
+ emits a manifest that pairs master STL with order_id so a verifier
18
+ with access to the master can always recover order_id.
19
+
20
+ The two layers are independent. L1 alone proves "printer N printed something
21
+ at time T" (assuming the .gcode is the artifact under test). L2 alone proves
22
+ "this object was the one tagged for order Z" (assuming you have the master).
23
+ Together they pin both provenance (which printer) and instance (which order).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import base64
29
+ import hashlib
30
+ import struct
31
+ import time
32
+ import zlib
33
+ from dataclasses import asdict, dataclass
34
+ from typing import Iterable, List, Optional, Sequence, Tuple
35
+
36
+ import numpy as np
37
+ from stl import mesh as stl_mesh
38
+
39
+
40
+ # --- Wire format -----------------------------------------------------------
41
+
42
+ # L1 payload layout (12 bytes, then CRC32 in 4 more bytes -> 16 bytes raw,
43
+ # base32-encoded into a string prefixed "GP1:"):
44
+ # bytes 0..2 printer_id (24 bits)
45
+ # bytes 3..5 job_seq (24 bits, sequence-per-printer)
46
+ # bytes 6..9 unix_ts (32 bits, full second precision)
47
+ # bytes 10..11 scheme (16 bits, currently always 0x0001)
48
+
49
+ L1_SCHEME_VERSION = 1
50
+ L1_PREAMBLE = "GP1"
51
+
52
+ # Allowed L2 perturbation amplitude range (min, max), in mm. The encoder
53
+ # rejects an --amplitude outside this window; this is NOT a per-vertex
54
+ # envelope (actual per-vertex deltas stay at or below the chosen amplitude).
55
+ L2_AMPLITUDE_MIN_MM = 0.005
56
+ L2_AMPLITUDE_MAX_MM = 0.020
57
+
58
+
59
+ # --- L1: G-code micro-watermark -------------------------------------------
60
+
61
+ def l1_encode_payload(printer_id: int, job_seq: int, ts_unix: int) -> bytes:
62
+ """Pack 12 bytes: printer_id(3) | job_seq(3) | ts_unix(4) | scheme(2)."""
63
+ if not (0 <= printer_id < (1 << 24)):
64
+ raise ValueError(f"printer_id out of range: {printer_id}")
65
+ if not (0 <= job_seq < (1 << 24)):
66
+ raise ValueError(f"job_seq out of range: {job_seq}")
67
+ if not (0 <= ts_unix < (1 << 32)):
68
+ raise ValueError(f"ts_unix out of range: {ts_unix}")
69
+ payload = struct.pack(">I", printer_id)[1:] # 3 bytes, big-endian
70
+ payload += struct.pack(">I", job_seq)[1:] # 3 bytes
71
+ payload += struct.pack(">I", ts_unix) # 4 bytes
72
+ payload += struct.pack(">H", L1_SCHEME_VERSION) # 2 bytes
73
+ assert len(payload) == 12
74
+ return payload
75
+
76
+
77
+ def l1_decode_payload(payload: bytes) -> Tuple[int, int, int]:
78
+ """Inverse of encode. Returns (printer_id, job_seq, ts_unix)."""
79
+ if len(payload) != 12:
80
+ raise ValueError(f"payload must be 12 bytes, got {len(payload)}")
81
+ printer_id = struct.unpack(">I", b"\x00" + payload[0:3])[0]
82
+ job_seq = struct.unpack(">I", b"\x00" + payload[3:6])[0]
83
+ ts_unix = struct.unpack(">I", payload[6:10])[0]
84
+ scheme = struct.unpack(">H", payload[10:12])[0]
85
+ if scheme != L1_SCHEME_VERSION:
86
+ raise ValueError(f"unknown scheme version: {scheme}")
87
+ return printer_id, job_seq, ts_unix
88
+
89
+
90
+ def l1_payload_to_babysteps(payload: bytes, base_z: float = 0.20) -> List[Tuple[float, int]]:
91
+ """
92
+ Map payload bytes + 4 CRC bytes to a sequence of (z_offset_mm, bit)
93
+ moves. Each bit produces a G1 Z move whose sign encodes the bit:
94
+ bit=1 -> +amplitude mm above base_z
95
+ bit=0 -> -amplitude mm below base_z
96
+ Amplitude is 0.010 mm — within a single 0.04 mm layer band, so
97
+ physically invisible on the finished part but recoverable from
98
+ the G-code text.
99
+ """
100
+ crc = zlib.crc32(payload) & 0xFFFFFFFF
101
+ bits: List[int] = []
102
+ for byte in payload:
103
+ for i in range(7, -1, -1):
104
+ bits.append((byte >> i) & 1)
105
+ for i in range(31, -1, -1):
106
+ bits.append((crc >> i) & 1)
107
+ out: List[Tuple[float, int]] = []
108
+ for b in bits:
109
+ z = base_z + (b * 2 - 1) * 0.010
110
+ out.append((z, b))
111
+ return out
112
+
113
+
114
+ def l1_babysteps_to_payload(steps: Sequence[Tuple[float, Optional[int]]],
115
+ expected_len: int = 12,
116
+ base_z: float = 0.20) -> bytes:
117
+ """Inverse: recover payload bytes from the (z_offset, bit) tuples.
118
+ `expected_len` is the payload length in bytes (8 default, 12 for v1.1+).
119
+ We read enough steps to cover expected_len*8 + 32 CRC bits."""
120
+ total_data_bits = expected_len * 8
121
+ total_bits = total_data_bits + 32
122
+ if len(steps) < total_bits:
123
+ raise ValueError(f"need >= {total_bits} babysteps, got {len(steps)}")
124
+ bits: List[int] = []
125
+ for z, b in steps[:total_bits]:
126
+ if b is not None and b in (0, 1):
127
+ bits.append(b)
128
+ else:
129
+ # Sign of (z - base_z) tells us the bit.
130
+ bits.append(1 if z > base_z else 0)
131
+ data_bits = bits[:total_data_bits]
132
+ crc_bits = bits[total_data_bits:total_bits]
133
+ payload = bytearray()
134
+ for i in range(0, total_data_bits, 8):
135
+ byte = 0
136
+ for j in range(8):
137
+ byte = (byte << 1) | data_bits[i + j]
138
+ payload.append(byte)
139
+ expected_crc = zlib.crc32(bytes(payload)) & 0xFFFFFFFF
140
+ got_crc = 0
141
+ for i in range(0, 32, 8):
142
+ byte = 0
143
+ for j in range(8):
144
+ byte = (byte << 1) | crc_bits[i + j]
145
+ got_crc = (got_crc << 8) | byte
146
+ if got_crc != expected_crc:
147
+ raise ValueError(f"CRC mismatch: got {got_crc:#010x}, expected {expected_crc:#010x}")
148
+ return bytes(payload)
149
+
150
+
151
+ def l1_rewrite_gcode(gcode: str, printer_id: int, job_seq: int, ts_unix: int,
152
+ inject_after: str = "; ghostprint-anchor") -> str:
153
+ """
154
+ Splice the L1 watermark block into a G-code string immediately after
155
+ the first line containing `inject_after` (or at the top if missing).
156
+ The block is bracketed by `; --- ghostprint begin/end ---` comments
157
+ and includes a human-readable `; GP1: <base32>` line for redundant
158
+ recovery.
159
+ """
160
+ payload = l1_encode_payload(printer_id, job_seq, ts_unix)
161
+ b32 = base64.b32encode(
162
+ payload + struct.pack(">I", zlib.crc32(payload) & 0xFFFFFFFF)
163
+ ).decode().replace("=", "")
164
+
165
+ steps = l1_payload_to_babysteps(payload)
166
+ out_lines: List[str] = []
167
+ out_lines.append("; --- ghostprint begin ---")
168
+ out_lines.append(f"; GP1: {L1_PREAMBLE}:{b32}")
169
+ out_lines.append(f"; printer_id={printer_id} job_seq={job_seq} ts_unix={ts_unix}")
170
+ out_lines.append("; G1 X0 Y0 F6000 ; park for watermark")
171
+ cur_x = 0.0
172
+ for z, bit in steps:
173
+ cur_x += 0.5
174
+ out_lines.append(f"G1 X{cur_x:.3f} Y0 Z{z:.4f} F6000")
175
+ out_lines.append("G1 X0 Y0 Z0.2 F6000 ; park done")
176
+ out_lines.append("; --- ghostprint end ---")
177
+ block = "\n".join(out_lines)
178
+
179
+ if inject_after in gcode:
180
+ return gcode.replace(inject_after, inject_after + "\n" + block, 1)
181
+ return f"; {inject_after}\n" + block + "\n" + gcode
182
+
183
+
184
+ def l1_extract_from_gcode(gcode: str) -> dict:
185
+ """
186
+ Recover the L1 watermark from a G-code string.
187
+ Strategy 1: regex the `; GP1: ...` comment.
188
+ Strategy 2: scan the watermark block for Z babysteps and sign-decode.
189
+ """
190
+ import re
191
+ m = re.search(r";\s*GP1:\s*GP1:([A-Z2-7]+)", gcode)
192
+ if m:
193
+ b32 = m.group(1)
194
+ pad = (-len(b32)) % 8
195
+ raw = base64.b32decode(b32 + "=" * pad)
196
+ if len(raw) != 16:
197
+ raise ValueError(f"GP1 base32 wrong length: {len(raw)} (expected 16)")
198
+ payload, crc = raw[:12], struct.unpack(">I", raw[12:16])[0]
199
+ if zlib.crc32(payload) & 0xFFFFFFFF != crc:
200
+ raise ValueError("GP1 CRC mismatch")
201
+ printer_id, job_seq, ts_unix = l1_decode_payload(payload)
202
+ return {
203
+ "printer_id": printer_id,
204
+ "job_seq": job_seq,
205
+ "ts_unix": ts_unix,
206
+ "ts_iso": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts_unix)),
207
+ "source": "comment",
208
+ }
209
+ m2 = re.search(
210
+ r";\s*---\s*ghostprint begin\s*---\s*\n(.*?);\s*---\s*ghostprint end\s*---",
211
+ gcode, re.DOTALL,
212
+ )
213
+ if not m2:
214
+ raise ValueError("no GP1 watermark found in gcode")
215
+ block = m2.group(1)
216
+ steps: List[Tuple[float, Optional[int]]] = []
217
+ in_park_done = False
218
+ for line in block.splitlines():
219
+ line = line.strip()
220
+ # Skip the "park done" trailing line (Z0.2 return-to-park) — it's
221
+ # part of the block envelope, not a watermark bit.
222
+ if "park done" in line:
223
+ in_park_done = True
224
+ continue
225
+ if in_park_done:
226
+ continue
227
+ if line.startswith("G1 ") and "Z" in line:
228
+ for tok in line.split():
229
+ if tok.startswith("Z"):
230
+ try:
231
+ z = float(tok[1:])
232
+ except ValueError:
233
+ continue
234
+ steps.append((z, None))
235
+ break
236
+ if not steps:
237
+ raise ValueError("ghostprint block present but no Z moves found")
238
+ payload = l1_babysteps_to_payload(steps, expected_len=12)
239
+ printer_id, job_seq, ts_unix = l1_decode_payload(payload)
240
+ return {
241
+ "printer_id": printer_id,
242
+ "job_seq": job_seq,
243
+ "ts_unix": ts_unix,
244
+ "ts_iso": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts_unix)),
245
+ "source": "babysteps",
246
+ }
247
+
248
+
249
+ # --- L2: geometric steganography ------------------------------------------
250
+
251
+ def l2_order_hash(order_id: str, master_seed: bytes = b"ghostprint-v1") -> bytes:
252
+ """Domain-separated 32-byte hash of order_id (BLAKE2b)."""
253
+ return hashlib.blake2b(
254
+ master_seed + b"\x00" + order_id.encode("utf-8"),
255
+ digest_size=32,
256
+ ).digest()
257
+
258
+
259
+ def _predict_delta(master_face: np.ndarray, f_idx: int, v_idx: int,
260
+ h_byte: int, amplitude: float) -> np.ndarray:
261
+ """
262
+ Re-derive the per-vertex perturbation axis (in the encoder's
263
+ deterministic order) so a verifier can predict it. Returns the
264
+ (3,) displacement vector the encoder would have applied.
265
+ """
266
+ n = np.cross(master_face[1] - master_face[0], master_face[2] - master_face[0])
267
+ nn = np.linalg.norm(n)
268
+ if nn < 1e-12:
269
+ return np.zeros(3)
270
+ n /= nn
271
+ ax = int(np.argmax(np.abs(n)))
272
+ axis = np.zeros(3)
273
+ axis[ax] = 1.0
274
+ axis = axis - n * (axis @ n)
275
+ an = np.linalg.norm(axis)
276
+ if an < 1e-6:
277
+ axis = np.array([1.0, 0.0, 0.0])
278
+ else:
279
+ axis /= an
280
+ sign = 1.0 if (h_byte & 0x80) else -1.0
281
+ frac = 0.5 + (h_byte & 0x7F) / 255.0 * 0.5
282
+ return np.round(axis * (sign * amplitude * frac), 4)
283
+
284
+
285
+ def l2_perturb_vertices(master: "stl_mesh.Mesh", order_id: str,
286
+ amplitude: float = 0.012) -> "stl_mesh.Mesh":
287
+ """
288
+ Return a NEW Mesh whose vertices are perturbed by ±amplitude mm
289
+ (within [L2_AMPLITUDE_MIN_MM, L2_AMPLITUDE_MAX_MM]) along a
290
+ deterministic per-vertex axis driven by the order hash. The axis
291
+ is the world axis with smallest dot to the face normal, then
292
+ projected to be tangent to the face. Shared vertices on triangle
293
+ boundaries move coherently (de-duped by coordinate).
294
+ """
295
+ if amplitude < L2_AMPLITUDE_MIN_MM or amplitude > L2_AMPLITUDE_MAX_MM:
296
+ raise ValueError(
297
+ f"amplitude {amplitude} out of safe range "
298
+ f"[{L2_AMPLITUDE_MIN_MM}, {L2_AMPLITUDE_MAX_MM}] mm"
299
+ )
300
+ h = l2_order_hash(order_id)
301
+ out = stl_mesh.Mesh(np.copy(master.data))
302
+ q = 6 # 1 µm coordinate dedup
303
+ seen: dict = {} # (x,y,z) rounded -> delta
304
+ # CRITICAL: predict against the UNPERTURBED master, not the live
305
+ # out.vectors view, because we mutate out.vectors in place below and
306
+ # that would distort face normals on subsequent vertices of the same
307
+ # face, breaking the deterministic per-vertex axis.
308
+ for f_idx in range(out.vectors.shape[0]):
309
+ master_face = master.vectors[f_idx]
310
+ for v_idx in range(3):
311
+ key = tuple(np.round(master_face[v_idx], q))
312
+ if key not in seen:
313
+ h_byte = h[(f_idx * 3 + v_idx) % 32]
314
+ seen[key] = _predict_delta(master_face, f_idx, v_idx, h_byte, amplitude)
315
+ out.vectors[f_idx, v_idx] = master_face[v_idx] + seen[key]
316
+ return out
317
+
318
+
319
+ def l2_recover_order(suspect: "stl_mesh.Mesh", master: "stl_mesh.Mesh",
320
+ amplitude: float = 0.012,
321
+ candidates: Optional[Iterable[str]] = None) -> Optional[str]:
322
+ """
323
+ Recover order_id by diffing suspect vs master.
324
+
325
+ With `candidates`: score each by cosine similarity between observed
326
+ deltas and predicted (axis, sign, fraction) under that candidate's
327
+ hash. The encoder de-dups shared vertices — the FIRST (face, vert)
328
+ occurrence defines the delta; all subsequent occurrences inherit it.
329
+ The verifier reproduces that exact ordering. Returns the best
330
+ candidate if score >= 0.99, else None.
331
+
332
+ Without `candidates`: returns None. (For exact match against a
333
+ single candidate, use l2_verify_match.)
334
+ """
335
+ if suspect.vectors.shape != master.vectors.shape:
336
+ raise ValueError(
337
+ f"shape mismatch: suspect {suspect.vectors.shape} vs master {master.vectors.shape}"
338
+ )
339
+
340
+ # Build the encoder-faithful (f, v) -> delta mapping for this master.
341
+ q = 6
342
+ primary: dict = {} # key -> (f_idx, v_idx)
343
+ deltas_by_key: dict = {}
344
+ for f_idx in range(master.vectors.shape[0]):
345
+ for v_idx in range(3):
346
+ key = tuple(np.round(master.vectors[f_idx, v_idx], q))
347
+ d = suspect.vectors[f_idx, v_idx] - master.vectors[f_idx, v_idx]
348
+ if key not in primary:
349
+ primary[key] = (f_idx, v_idx)
350
+ deltas_by_key[key] = d
351
+
352
+ if candidates is None:
353
+ return None
354
+
355
+ best: Optional[str] = None
356
+ best_score = -1.0
357
+ for cand in candidates:
358
+ h = l2_order_hash(cand)
359
+ score = 0.0
360
+ n = 0
361
+ for key, (pf, pv) in primary.items():
362
+ h_byte = h[(pf * 3 + pv) % 32]
363
+ predicted = _predict_delta(master.vectors[pf], pf, pv, h_byte, amplitude)
364
+ obs = deltas_by_key[key]
365
+ dn = np.linalg.norm(obs)
366
+ if dn < 1e-9:
367
+ score += 0.5
368
+ else:
369
+ pn = np.linalg.norm(predicted)
370
+ if pn < 1e-9:
371
+ score += 0.0
372
+ else:
373
+ cos = float(obs @ predicted / (dn * pn))
374
+ score += max(0.0, cos)
375
+ n += 1
376
+ score /= max(1, n)
377
+ if score > best_score:
378
+ best_score = score
379
+ best = cand
380
+ if best_score < 0.99:
381
+ return None
382
+ return best
383
+
384
+
385
+ def l2_recover_deltas(suspect: "stl_mesh.Mesh", master: "stl_mesh.Mesh") -> np.ndarray:
386
+ """
387
+ Return the (N*3, 3) array of per-vertex deltas (suspect - master),
388
+ flattened in (face, vertex) iteration order. Used by the round-trip
389
+ test to assert exact match against the encoder's prediction.
390
+ """
391
+ if suspect.vectors.shape != master.vectors.shape:
392
+ raise ValueError(
393
+ f"shape mismatch: suspect {suspect.vectors.shape} vs master {master.vectors.shape}"
394
+ )
395
+ return (suspect.vectors - master.vectors).reshape(-1, 3)
396
+
397
+
398
+ def l2_verify_match(suspect: "stl_mesh.Mesh", master: "stl_mesh.Mesh",
399
+ order_id: str, amplitude: float = 0.012) -> bool:
400
+ """
401
+ Verify that a suspect STL matches a candidate order_id exactly (within
402
+ 1e-4 mm — the encoder's rounding precision).
403
+
404
+ Mirrors the encoder's de-dup: the first time a vertex coordinate is
405
+ seen, its perturbation is computed from THAT (face, vert) index.
406
+ Subsequent shared vertices inherit the same delta.
407
+ """
408
+ h = l2_order_hash(order_id)
409
+ q = 6
410
+ seen: dict = {} # (x,y,z) -> delta
411
+ for f_idx in range(master.vectors.shape[0]):
412
+ face = master.vectors[f_idx]
413
+ for v_idx in range(3):
414
+ key = tuple(np.round(face[v_idx], q))
415
+ if key not in seen:
416
+ h_byte = h[(f_idx * 3 + v_idx) % 32]
417
+ seen[key] = _predict_delta(face, f_idx, v_idx, h_byte, amplitude)
418
+ predicted = np.asarray(seen[key], dtype=np.float64)
419
+ # Compare in float64: STL stores float32, so on large parts the
420
+ # saved-vertex quantization error (up to ~half-ulp of the
421
+ # coordinate, ~3e-5 mm at 600 mm) exceeds any tighter tolerance.
422
+ # The encoder grid is the rounding in _predict_delta —
423
+ # np.round(delta, 4) — i.e. deltas live on a 1e-4 mm grid, so
424
+ # 1e-4 is the correct tolerance.
425
+ observed = (suspect.vectors[f_idx, v_idx].astype(np.float64)
426
+ - master.vectors[f_idx, v_idx].astype(np.float64))
427
+ if not np.allclose(observed, predicted, atol=1e-4, rtol=0.0):
428
+ return False
429
+ return True
430
+
431
+
432
+ # --- Manifest --------------------------------------------------------------
433
+
434
+ @dataclass
435
+ class GhostprintManifest:
436
+ """Sidecar JSON describing what was tagged and how to verify it."""
437
+ order_id: str
438
+ printer_id: int
439
+ job_seq: int
440
+ ts_unix: int
441
+ l1_gcode_watermark: bool
442
+ l2_geom_stego: bool
443
+ l2_amplitude_mm: float
444
+ master_stl_sha256: str
445
+ tagged_stl_sha256: Optional[str]
446
+ scheme_version: int = L1_SCHEME_VERSION
447
+
448
+ def to_dict(self):
449
+ return asdict(self)
450
+
451
+ @classmethod
452
+ def from_dict(cls, d):
453
+ return cls(**d)
454
+
455
+
456
+ def file_sha256(path: str) -> str:
457
+ h = hashlib.sha256()
458
+ with open(path, "rb") as f:
459
+ for chunk in iter(lambda: f.read(65536), b""):
460
+ h.update(chunk)
461
+ return h.hexdigest()
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.4
2
+ Name: theapk-ghostprint
3
+ Version: 0.1.1
4
+ Summary: Two-layer invisible watermark for 3D-printed parts (forensics, not DRM)
5
+ Author: theapk llc
6
+ License: PolyForm Noncommercial License 1.0.0
7
+
8
+ Copyright (c) 2026 theapk llc
9
+
10
+ This source code is licensed under the PolyForm Noncommercial License
11
+ 1.0.0, a copy of which is reproduced below.
12
+
13
+ ---
14
+
15
+ # PolyForm Noncommercial License 1.0.0
16
+
17
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
18
+
19
+ ## Terms
20
+
21
+ ### 1. Purpose
22
+
23
+ This license gives you permission to use this software for any
24
+ noncommercial purpose. Commercial use requires a separate license
25
+ from the copyright holder.
26
+
27
+ ### 2. Copyright
28
+
29
+ The copyright holder retains all copyright and related rights to
30
+ the software.
31
+
32
+ ### 3. Grant of Rights
33
+
34
+ Subject to the terms and conditions of this license, the copyright
35
+ holder grants you a worldwide, royalty-free, non-exclusive,
36
+ non-transferable, non-sublicensable license to:
37
+
38
+ 1. Use, copy, modify, merge, and distribute copies of the software,
39
+ for noncommercial purposes only.
40
+
41
+ 2. Install and operate the software for your own personal,
42
+ educational, or research use.
43
+
44
+ 3. Contribute modifications back to the project under the same
45
+ license.
46
+
47
+ ### 4. Noncommercial Use
48
+
49
+ "Noncommercial use" means use that is not primarily intended for
50
+ or directed toward commercial advantage or monetary compensation.
51
+ Examples of noncommercial use include:
52
+
53
+ - Personal projects and hobbies
54
+ - Educational use in schools, universities, and courses
55
+ - Academic research
56
+ - Testing and evaluation
57
+ - Contributing to the open-source project itself
58
+
59
+ ### 5. Commercial Use
60
+
61
+ "Commercial use" means any use that is primarily intended for or
62
+ directed toward commercial advantage or monetary compensation.
63
+ Examples of commercial use include:
64
+
65
+ - Selling the software or derivatives thereof
66
+ - Offering the software as a paid or ad-supported service
67
+ - Using the software in a commercial print farm or production
68
+ environment
69
+ - Embedding the software in a commercial product
70
+ - Using the software internally by a business to generate revenue
71
+
72
+ For commercial use, contact theapk llc to obtain a commercial
73
+ license: https://theapk.com or support@theapk.com
74
+
75
+ ### 6. Conditions
76
+
77
+ You must include a copy of this license with every copy of the
78
+ software you distribute. You must include the copyright notice
79
+ above in all copies.
80
+
81
+ ### 7. No Warranty
82
+
83
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
84
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
85
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
86
+ NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
87
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
88
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
89
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
90
+ Requires-Python: >=3.10
91
+ Description-Content-Type: text/markdown
92
+ License-File: LICENSE
93
+ Requires-Dist: numpy>=1.24
94
+ Requires-Dist: numpy-stl>=3.0
95
+ Requires-Dist: trimesh>=4.0
96
+ Provides-Extra: test
97
+ Requires-Dist: pytest>=7.0; extra == "test"
98
+ Dynamic: license-file
99
+
100
+ # ghostprint
101
+
102
+ > Two-layer invisible watermark for 3D-printed parts.
103
+ > Forensics, not DRM. Free for noncommercial use + hosted web version.
104
+
105
+ [![PolyForm Noncommercial](https://img.shields.io/badge/license-PolyForm%20NC-blue.svg)](LICENSE)
106
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)]()
107
+ [![tests](https://github.com/theapk/ghostprint/actions/workflows/test.yml/badge.svg)](https://github.com/theapk/ghostprint/actions/workflows/test.yml)
108
+
109
+ ---
110
+
111
+ ## What it does
112
+
113
+ Once a 3D-print customer has the STL, you can't stop them from copying it forever. What you can do is prove the part they printed came from your STL.
114
+
115
+ ghostprint adds two independent invisible watermarks to your workflow:
116
+
117
+ - **Layer 1 — G-code watermark.** A 12-byte payload (printer + job + timestamp) encoded into sub-resolution Z-babysteps at the start of a sliced G-code file, duplicated in a `;` comment block. It lives in the G-code, not the STL. Recover it from a sliced file with `python verify-print.py decode-gcode <file.gcode>` (prints printer/job/timestamp JSON). Survives any slicer that doesn't strip comments.
118
+ - **Layer 2 — Geometric steganography.** Per-vertex perturbation whose amplitude the tagger picks inside the allowed ±0.005–0.020 mm range (default 0.012 mm), driven by a BLAKE2b hash of the order ID. Smaller than a typical 0.04 mm nozzle X/Y resolution. Translation-invariant. **Not** invariant under rotation or rescaling, and it does **not** survive re-meshing (standard slicers re-mesh).
119
+
120
+ Later, if a suspect part shows up, drop the original STL back in and ghostprint tells you whether it matches.
121
+
122
+ ## Demo
123
+
124
+ ![demo](demo.gif)
125
+
126
+ *Above: the hosted drag-drop web flow — the server runs the same tagging code and produces both layers there. In the CLI, L1 lives in G-code, not the STL (see the real CLI outputs in Use).*
127
+
128
+ ## Install
129
+
130
+ Not on PyPI yet. Install from the repo:
131
+
132
+ ```bash
133
+ git clone https://github.com/theapk/ghostprint.git
134
+ cd ghostprint
135
+ python3 -m venv .venv
136
+ source .venv/bin/activate
137
+
138
+ pip install -r requirements.txt # CLI scripts: tag-print.py, verify-print.py
139
+ # or, for the `ghostprint` console command:
140
+ pip install -e .
141
+ ```
142
+
143
+ The `ghostprint` command exposes four verbs: `tag`, `verify`, `decode-gcode`, `self-test`.
144
+
145
+ ## Use
146
+
147
+ ```bash
148
+ # Tag an STL with order metadata
149
+ python tag-print.py master.stl \
150
+ --order-id ORDER-2026-0001 \
151
+ --printer bambucco-1 \
152
+ --job-seq 42 \
153
+ --out tagged.stl
154
+
155
+ # → writes tagged.stl + tagged.stl.manifest.json (plain JSON, unsigned —
156
+ # bookkeeping only; the watermark itself is the proof).
157
+ # L1 needs G-code: add --sliced-gcode your.gcode (splice into existing
158
+ # slices) or --emit-gcode (standalone watermarked G-code).
159
+ # `ghostprint tag` takes the same arguments.
160
+
161
+ # Later, verify a tagged part against its master (master first, tagged
162
+ # second — matching the original `ghostprint verify master.stl tagged.stl`
163
+ # promise; the sidecar manifest is auto-discovered next to the tagged part):
164
+ ghostprint verify master.stl tagged.stl
165
+ # … per-vertex diff report …
166
+ # → ✅ L2 match: order_id=ORDER-2026-0001 printer_id=15777188
167
+ # printer_id is the 24-bit ID hashed from the printer name, supplied by
168
+ # the sidecar manifest; no match line without it (pass --order-id instead).
169
+
170
+ # Recover the L1 layer from a G-code file — separate from STL verify,
171
+ # because L1 lives in the G-code, not the STL:
172
+ python verify-print.py decode-gcode tagged.gcode
173
+ # → {"printer_id": 15777188, "job_seq": 42, "ts_unix": 1795119073,
174
+ # "ts_iso": "2026-11-19T20:11:13Z", "source": "comment"}
175
+ ```
176
+
177
+ ## Drag-drop web version
178
+
179
+ If you don't want to install Python, there's a hosted version:
180
+
181
+ **👉 https://ghostprint.theapk.com**
182
+
183
+ Three steps. No account required for the free tier. The web version uses the same CLI underneath — `tag-print.py` is the source of truth.
184
+
185
+ ## Pricing (hosted version)
186
+
187
+ | Tier | Price | What you get |
188
+ |---|---|---|
189
+ | CLI | **Free** | Python, no upload, no tracking. Free for noncommercial use; commercial use requires a license. |
190
+ | Maker | $9/mo | Drag-drop web tool, hold master STLs in your account |
191
+ | Studio | $49/mo | Unlimited tags, multi-printer fleet dashboard, API access |
192
+
193
+ ## Architecture
194
+
195
+ ```
196
+ ┌──────────────────┐
197
+ master.stl ───▶ │ │
198
+ │ tag-print.py │ ───▶ tagged.stl + <out>.manifest.json
199
+ --order-id ──▶ │ │ (plain JSON, unsigned)
200
+ --printer ──▶ │ │
201
+ --job-seq ──▶ │ │
202
+ └──────────────────┘
203
+
204
+ suspect.stl ─┐
205
+ ├──▶ verify ───▶ ✅ / ❌ + extracted metadata
206
+ master.stl ──┘
207
+ ```
208
+
209
+ Both layers are written by `tag-print.py`. L1 needs G-code: give it `--sliced-gcode` (splice the watermark into existing slices) or `--emit-gcode` (standalone watermarked G-code); with neither, the L1 parameters are recorded in the manifest only. No network, no GPU. The L2 loop is pure Python — tagging a 50 MB STL takes ~1 min today; a vectorized fast path is planned.
210
+
211
+ ## What it's not
212
+
213
+ - **Not DRM.** Can't stop someone from copying. Can't stop someone from stripping the watermark.
214
+ - **Not encryption.** Anyone with the original STL can extract the watermark. That's the point.
215
+ - **Not visible.** L2 perturbs vertices below typical print resolution; L1 rides inside the G-code text. Neither shows up on the part.
216
+
217
+ It's forensics. Think "document fingerprinting", not "encryption".
218
+
219
+ ## Limitations
220
+
221
+ - L1 requires the G-code, not the STL. If the slicer strips `;` comments (very rare), only L2 survives.
222
+ - L2 is translation-invariant only. It does **not** survive rotation, rescaling, or re-meshing (standard slicers re-mesh — verify against the original master or a no-slicer path). Large temperature warp can shift vertices beyond the perturbation amplitude and break the match.
223
+ - No support for AMF, 3MF, or OBJ yet. PRs welcome.
224
+
225
+ ## License
226
+
227
+ PolyForm Noncommercial 1.0.0 — free for personal, educational, and research use. Commercial use (selling the software, offering it as a paid service, using it in a commercial print farm) requires a separate license from theapk llc. See [LICENSE](LICENSE) for full terms.
228
+
229
+ ## Author
230
+
231
+ Ian Schwartz — [@studiozeroseven](https://github.com/studiozeroseven) — [theapk llc](https://theapk.com)
232
+
233
+ ---
234
+
235
+ **If you're selling 3D prints and want to catch knockoffs, this is for you.**
@@ -0,0 +1,9 @@
1
+ ghostprint/__init__.py,sha256=eh5QTTNPiSFToRy14LHQLSAxhXNaP7c3IPiG6Qeddo4,992
2
+ ghostprint/cli.py,sha256=O3uJLEyvLEMh3iZU_0YsUzrp_6DrL4XfmQO8TqlO-AM,4976
3
+ ghostprint/core.py,sha256=x8zQl0hxt8lHkvq288K2bKiX-eCXVm0CxCQXqtKE8gM,18257
4
+ theapk_ghostprint-0.1.1.dist-info/licenses/LICENSE,sha256=p7tIJBmPkkvlT61avR4Tr9B9sRSe2XEmQ02PAf0_hr4,2657
5
+ theapk_ghostprint-0.1.1.dist-info/METADATA,sha256=Kvo8umaGcc56Ij7uXDEvjoe8zqlP487mD8CRecCiUK0,10298
6
+ theapk_ghostprint-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ theapk_ghostprint-0.1.1.dist-info/entry_points.txt,sha256=yjmX8R5qg4B58mSuawBru2kgz_VsUf8i-JV1iHIHj1M,51
8
+ theapk_ghostprint-0.1.1.dist-info/top_level.txt,sha256=F7E-7Vue8zMMmXDnpeLWoiKesLvjM-2FAAWKYeSdNpg,11
9
+ theapk_ghostprint-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ghostprint = ghostprint.cli:main
@@ -0,0 +1,84 @@
1
+ PolyForm Noncommercial License 1.0.0
2
+
3
+ Copyright (c) 2026 theapk llc
4
+
5
+ This source code is licensed under the PolyForm Noncommercial License
6
+ 1.0.0, a copy of which is reproduced below.
7
+
8
+ ---
9
+
10
+ # PolyForm Noncommercial License 1.0.0
11
+
12
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
13
+
14
+ ## Terms
15
+
16
+ ### 1. Purpose
17
+
18
+ This license gives you permission to use this software for any
19
+ noncommercial purpose. Commercial use requires a separate license
20
+ from the copyright holder.
21
+
22
+ ### 2. Copyright
23
+
24
+ The copyright holder retains all copyright and related rights to
25
+ the software.
26
+
27
+ ### 3. Grant of Rights
28
+
29
+ Subject to the terms and conditions of this license, the copyright
30
+ holder grants you a worldwide, royalty-free, non-exclusive,
31
+ non-transferable, non-sublicensable license to:
32
+
33
+ 1. Use, copy, modify, merge, and distribute copies of the software,
34
+ for noncommercial purposes only.
35
+
36
+ 2. Install and operate the software for your own personal,
37
+ educational, or research use.
38
+
39
+ 3. Contribute modifications back to the project under the same
40
+ license.
41
+
42
+ ### 4. Noncommercial Use
43
+
44
+ "Noncommercial use" means use that is not primarily intended for
45
+ or directed toward commercial advantage or monetary compensation.
46
+ Examples of noncommercial use include:
47
+
48
+ - Personal projects and hobbies
49
+ - Educational use in schools, universities, and courses
50
+ - Academic research
51
+ - Testing and evaluation
52
+ - Contributing to the open-source project itself
53
+
54
+ ### 5. Commercial Use
55
+
56
+ "Commercial use" means any use that is primarily intended for or
57
+ directed toward commercial advantage or monetary compensation.
58
+ Examples of commercial use include:
59
+
60
+ - Selling the software or derivatives thereof
61
+ - Offering the software as a paid or ad-supported service
62
+ - Using the software in a commercial print farm or production
63
+ environment
64
+ - Embedding the software in a commercial product
65
+ - Using the software internally by a business to generate revenue
66
+
67
+ For commercial use, contact theapk llc to obtain a commercial
68
+ license: https://theapk.com or support@theapk.com
69
+
70
+ ### 6. Conditions
71
+
72
+ You must include a copy of this license with every copy of the
73
+ software you distribute. You must include the copyright notice
74
+ above in all copies.
75
+
76
+ ### 7. No Warranty
77
+
78
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
79
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
80
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
81
+ NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
82
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
83
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
84
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ ghostprint