invisimark 0.2.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.
- invisimark/__init__.py +6 -0
- invisimark/ai.py +402 -0
- invisimark/calibrate.py +191 -0
- invisimark/cli.py +458 -0
- invisimark/course.py +235 -0
- invisimark/detect.py +508 -0
- invisimark/embed.py +145 -0
- invisimark/keys.py +110 -0
- invisimark/media.py +136 -0
- invisimark/py.typed +0 -0
- invisimark/service.py +910 -0
- invisimark/site.py +201 -0
- invisimark/static/index.html +280 -0
- invisimark/static/site/app.js +184 -0
- invisimark/static/site/apple-touch-icon.png +0 -0
- invisimark/static/site/check.js +81 -0
- invisimark/static/site/favicon.svg +1 -0
- invisimark/static/site/layout.html +72 -0
- invisimark/static/site/og.png +0 -0
- invisimark/static/site/pages/about.html +24 -0
- invisimark/static/site/pages/check.html +33 -0
- invisimark/static/site/pages/eu-ai-act-marking.html +48 -0
- invisimark/static/site/pages/guides/find-who-leaked-your-video.html +50 -0
- invisimark/static/site/pages/guides/invisible-vs-visible-watermarks.html +32 -0
- invisimark/static/site/pages/guides/watermark-course-videos.html +41 -0
- invisimark/static/site/pages/guides.html +9 -0
- invisimark/static/site/pages/index.html +89 -0
- invisimark/static/site/pages/privacy.html +15 -0
- invisimark/static/site/pages/terms.html +15 -0
- invisimark/static/site/style.css +137 -0
- invisimark/tile.py +99 -0
- invisimark/web.py +290 -0
- invisimark-0.2.0.dist-info/METADATA +379 -0
- invisimark-0.2.0.dist-info/RECORD +37 -0
- invisimark-0.2.0.dist-info/WHEEL +4 -0
- invisimark-0.2.0.dist-info/entry_points.txt +3 -0
- invisimark-0.2.0.dist-info/licenses/LICENSE +202 -0
invisimark/__init__.py
ADDED
invisimark/ai.py
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
"""Marking AI-generated images and video, and checking for those marks.
|
|
2
|
+
|
|
3
|
+
Two layers, following Measure 1.1 of the EU Code of Practice on Transparency of AI-Generated Content:
|
|
4
|
+
|
|
5
|
+
* an imperceptible watermark derived from a key published here, so anyone can check for it without asking the provider;
|
|
6
|
+
* a signed, time-stamped C2PA manifest that declares the file AI-generated and names who made it.
|
|
7
|
+
|
|
8
|
+
The watermark is public on purpose, which has a cost: anyone can read it, copy it onto another file, or subtract it almost
|
|
9
|
+
perfectly (bench/results/ai-adversarial.md). A provider can add a second tile from a secret key, which survives the public tile
|
|
10
|
+
being subtracted, so it can still recognise its own output. That tile can be copied along with the public one, so it does not
|
|
11
|
+
prove origin. Only the C2PA signature does, for as long as the metadata survives. See docs/spec.md.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import datetime as dt
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import shutil
|
|
22
|
+
import tempfile
|
|
23
|
+
from dataclasses import asdict, dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from . import __version__, calibrate, detect, embed, keys, media
|
|
29
|
+
from .tile import DEFAULT, id_tile, pattern
|
|
30
|
+
|
|
31
|
+
AI_KEY = hashlib.sha256(b"invisimark.ai-marking.v1").digest()
|
|
32
|
+
AI_LABEL = "ai-generated"
|
|
33
|
+
PROVIDER_LABEL = "provider"
|
|
34
|
+
SCHEME = "invisimark-public-v1"
|
|
35
|
+
# Written into every signed manifest, so it must outlive any domain or hosted service: the public repository holds the
|
|
36
|
+
# specification and the reference detector, and it is never renamed or deleted. Changing it breaks the link in every file
|
|
37
|
+
# already marked, so treat a change as a migration.
|
|
38
|
+
DETECTOR = "https://github.com/Huckcity/invisimark"
|
|
39
|
+
|
|
40
|
+
IPTC = "http://cv.iptc.org/newscodes/digitalsourcetype/"
|
|
41
|
+
GENERATED = IPTC + "trainedAlgorithmicMedia"
|
|
42
|
+
MANIPULATED = IPTC + "compositeWithTrainedAlgorithmicMedia"
|
|
43
|
+
AI_SOURCE_TYPES = {GENERATED, MANIPULATED, IPTC + "compositeSynthetic", IPTC + "algorithmicMedia"}
|
|
44
|
+
DEFAULT_TIMESTAMPER = "http://timestamp.digicert.com"
|
|
45
|
+
MIME = {".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".tif": "image/tiff",
|
|
46
|
+
".tiff": "image/tiff", ".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime"}
|
|
47
|
+
VIDEO_OUTPUTS = {".mp4", ".m4v", ".mov"}
|
|
48
|
+
DEFAULT_RMS = 1.75 # chosen in bench/ai.py: see bench/results/ai.md
|
|
49
|
+
PARENT = "source"
|
|
50
|
+
# The search aligns on the whole public pattern, id tile included, so the id score at that alignment is not independent evidence
|
|
51
|
+
# and detect's own "gate plus a named candidate" rule does not apply. The alignment score alone decides. See bench/results/ai-null.txt.
|
|
52
|
+
PUBLIC_SURE = 8.0
|
|
53
|
+
PROVIDER_ALPHA = 2.0 # weight of the private tile beside the public pair, before the overall strength is applied
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class MarkError(RuntimeError):
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------------------------------------
|
|
61
|
+
# marking
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Signing:
|
|
66
|
+
"""A C2PA signing identity: a PEM certificate chain (leaf first) and its private key."""
|
|
67
|
+
|
|
68
|
+
cert: Path | str
|
|
69
|
+
key: Path | str
|
|
70
|
+
timestamper: str | None = DEFAULT_TIMESTAMPER
|
|
71
|
+
alg: str = "ES256"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class Marked:
|
|
76
|
+
output: str
|
|
77
|
+
sha256: str
|
|
78
|
+
strength: float
|
|
79
|
+
robust: bool | None # None when the strength was fixed, not measured on this file
|
|
80
|
+
signed: bool
|
|
81
|
+
provider_tile: bool
|
|
82
|
+
calibration: str = ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def ai_tile(provider_key: bytes | None = None) -> np.ndarray:
|
|
86
|
+
tile = pattern(AI_KEY, AI_LABEL, DEFAULT)
|
|
87
|
+
if provider_key:
|
|
88
|
+
tile = tile + PROVIDER_ALPHA * id_tile(provider_key, PROVIDER_LABEL, DEFAULT)
|
|
89
|
+
return tile
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _manifest(path: Path, *, generated: bool, provider: str | None, system: str | None, model: str | None) -> dict:
|
|
93
|
+
origin = {"provider": provider, "system": system, "model": model}
|
|
94
|
+
agent = {"softwareAgent": {"name": system}} if system else {}
|
|
95
|
+
if generated:
|
|
96
|
+
actions = [{"action": "c2pa.created", "digitalSourceType": GENERATED, **agent}]
|
|
97
|
+
else: # C2PA requires an edit to open its source first: _sign attaches that source as the ingredient named PARENT
|
|
98
|
+
actions = [{"action": "c2pa.opened", "parameters": {"ingredientIds": [PARENT]}},
|
|
99
|
+
{"action": "c2pa.edited", "digitalSourceType": MANIPULATED, **agent}]
|
|
100
|
+
return {
|
|
101
|
+
"claim_generator_info": [{"name": "invisimark", "version": __version__}],
|
|
102
|
+
"format": MIME[path.suffix.lower()],
|
|
103
|
+
"title": path.name,
|
|
104
|
+
"assertions": [
|
|
105
|
+
{"label": "c2pa.actions.v2", "data": {"actions": actions}},
|
|
106
|
+
{"label": "app.invisimark.marking", "data": {
|
|
107
|
+
"watermark": SCHEME, "detector": DETECTOR, **{k: v for k, v in origin.items() if v},
|
|
108
|
+
}},
|
|
109
|
+
],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _sign(src: Path, dst: Path, signing: Signing, manifest: dict, parent: Path | None) -> None:
|
|
114
|
+
import c2pa
|
|
115
|
+
|
|
116
|
+
with c2pa.Signer.from_info(c2pa.C2paSignerInfo(
|
|
117
|
+
signing.alg.encode(),
|
|
118
|
+
Path(signing.cert).read_bytes(), Path(signing.key).read_bytes(),
|
|
119
|
+
signing.timestamper.encode() if signing.timestamper else None,
|
|
120
|
+
)) as signer, c2pa.Builder(manifest) as builder:
|
|
121
|
+
if parent is not None:
|
|
122
|
+
with open(parent, "rb") as fh:
|
|
123
|
+
builder.add_ingredient({"title": parent.name, "relationship": "parentOf", "label": PARENT}, MIME[parent.suffix.lower()], fh)
|
|
124
|
+
builder.sign_file(src, dst, signer)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _has_manifest(path: Path) -> bool:
|
|
128
|
+
return read_manifest(path).get("present", False) if path.suffix.lower() in MIME else False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def mark(
|
|
132
|
+
src: Path | str, dst: Path | str, *, signing: Signing | None = None, generated: bool = True, provider: str | None = None,
|
|
133
|
+
system: str | None = None, model: str | None = None, strength: float | str = DEFAULT_RMS,
|
|
134
|
+
provider_key: bytes | None = None, crf: int = 18, log: Path | str | None = None,
|
|
135
|
+
) -> Marked:
|
|
136
|
+
"""Watermark `src` and, with `signing`, attach a signed manifest. Signing comes last, so its hash covers the final bytes."""
|
|
137
|
+
src, dst = Path(src), Path(dst)
|
|
138
|
+
if not src.is_file():
|
|
139
|
+
raise MarkError(f"{src}: no such file")
|
|
140
|
+
suffix = dst.suffix.lower()
|
|
141
|
+
is_image = media.is_image(src)
|
|
142
|
+
if signing and suffix not in MIME:
|
|
143
|
+
raise MarkError(f"{dst.name}: signed output must be one of {', '.join(sorted(MIME))}")
|
|
144
|
+
if not is_image and suffix not in VIDEO_OUTPUTS:
|
|
145
|
+
raise MarkError(f"{dst.name}: video output must be .mp4, .m4v or .mov")
|
|
146
|
+
if is_image and not media.is_image(dst):
|
|
147
|
+
raise MarkError(f"{dst.name}: image output must be an image format")
|
|
148
|
+
|
|
149
|
+
robust, note = None, ""
|
|
150
|
+
if strength == "auto":
|
|
151
|
+
cal = calibrate.calibrate(src, AI_KEY, label=AI_LABEL)
|
|
152
|
+
rms, robust, note = cal.rms, cal.passed, cal.summary()
|
|
153
|
+
else:
|
|
154
|
+
rms = float(strength)
|
|
155
|
+
tile = ai_tile(provider_key)
|
|
156
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
with tempfile.TemporaryDirectory(dir=dst.parent, prefix=".invisimark-") as tmp:
|
|
158
|
+
work = Path(tmp) / f"marked{suffix}"
|
|
159
|
+
if is_image:
|
|
160
|
+
embed.embed_image(src, work, AI_KEY, AI_LABEL, rms=rms, tile=tile)
|
|
161
|
+
else:
|
|
162
|
+
embed.embed_video(src, work, AI_KEY, AI_LABEL, rms=rms, crf=crf, tile=tile)
|
|
163
|
+
if signing:
|
|
164
|
+
# an edit always names its source; a generated file names one only to keep existing provenance (Measure 1.2)
|
|
165
|
+
parent = src if not generated or _has_manifest(src) else None
|
|
166
|
+
if parent is not None and src.suffix.lower() not in MIME:
|
|
167
|
+
raise MarkError(f"{src.name}: signing an edit needs a source in one of {', '.join(sorted(MIME))}")
|
|
168
|
+
signed = Path(tmp) / f"signed{suffix}"
|
|
169
|
+
_sign(work, signed, signing, _manifest(dst, generated=generated, provider=provider, system=system, model=model), parent)
|
|
170
|
+
work = signed
|
|
171
|
+
shutil.move(work, dst)
|
|
172
|
+
digest = keys.sha256_of(dst)
|
|
173
|
+
if log:
|
|
174
|
+
keys.record_issue(Path(log), kind="ai-mark", output_sha256=digest, watermark=SCHEME, signed=bool(signing), strength=rms)
|
|
175
|
+
return Marked(str(dst), digest, rms, robust, bool(signing), bool(provider_key), note)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ---------------------------------------------------------------------------------------------
|
|
179
|
+
# development certificates
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def dev_certificate(out_dir: Path | str, name: str = "Invisimark development certificate") -> Signing:
|
|
183
|
+
"""A throwaway CA and leaf that C2PA accepts structurally. Anything signed with it validates as untrusted, which is correct."""
|
|
184
|
+
from cryptography import x509
|
|
185
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
186
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
187
|
+
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
|
188
|
+
|
|
189
|
+
out = Path(out_dir)
|
|
190
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
now = dt.datetime.now(dt.UTC)
|
|
192
|
+
ca_key, leaf_key = ec.generate_private_key(ec.SECP256R1()), ec.generate_private_key(ec.SECP256R1())
|
|
193
|
+
|
|
194
|
+
def subject(cn: str) -> x509.Name:
|
|
195
|
+
return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "NOT TRUSTED")])
|
|
196
|
+
|
|
197
|
+
usage = {"content_commitment": False, "key_encipherment": False, "data_encipherment": False, "key_agreement": False,
|
|
198
|
+
"encipher_only": False, "decipher_only": False}
|
|
199
|
+
ca = (x509.CertificateBuilder().subject_name(subject(f"{name} CA")).issuer_name(subject(f"{name} CA"))
|
|
200
|
+
.public_key(ca_key.public_key()).serial_number(x509.random_serial_number())
|
|
201
|
+
.not_valid_before(now - dt.timedelta(minutes=5)).not_valid_after(now + dt.timedelta(days=825))
|
|
202
|
+
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
|
203
|
+
.add_extension(x509.KeyUsage(digital_signature=False, key_cert_sign=True, crl_sign=True, **usage), critical=True)
|
|
204
|
+
.add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), critical=False)
|
|
205
|
+
.sign(ca_key, hashes.SHA256()))
|
|
206
|
+
leaf = (x509.CertificateBuilder().subject_name(subject(name)).issuer_name(ca.subject)
|
|
207
|
+
.public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
|
|
208
|
+
.not_valid_before(now - dt.timedelta(minutes=5)).not_valid_after(now + dt.timedelta(days=397))
|
|
209
|
+
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|
210
|
+
.add_extension(x509.KeyUsage(digital_signature=True, key_cert_sign=False, crl_sign=False, **usage), critical=True)
|
|
211
|
+
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.EMAIL_PROTECTION]), critical=False)
|
|
212
|
+
.add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()), critical=False)
|
|
213
|
+
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
|
|
214
|
+
.sign(ca_key, hashes.SHA256()))
|
|
215
|
+
cert_path, key_path = out / "dev-chain.pem", out / "dev-key.pem"
|
|
216
|
+
cert_path.write_bytes(leaf.public_bytes(serialization.Encoding.PEM) + ca.public_bytes(serialization.Encoding.PEM))
|
|
217
|
+
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
218
|
+
with os.fdopen(fd, "wb") as fh:
|
|
219
|
+
fh.write(leaf_key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
|
|
220
|
+
return Signing(cert_path, key_path)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ---------------------------------------------------------------------------------------------
|
|
224
|
+
# checking
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _source_types(manifest: dict) -> list[str]:
|
|
228
|
+
found = []
|
|
229
|
+
for assertion in manifest.get("assertions", []):
|
|
230
|
+
if str(assertion.get("label", "")).startswith("c2pa.actions"):
|
|
231
|
+
for action in (assertion.get("data") or {}).get("actions", []):
|
|
232
|
+
if action.get("digitalSourceType"):
|
|
233
|
+
found.append(action["digitalSourceType"])
|
|
234
|
+
return found
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def read_manifest(path: Path | str, trust_anchors: str | None = None) -> dict:
|
|
238
|
+
"""What the file's C2PA manifest says. A file without one, or one we cannot parse, is reported as such and never raises."""
|
|
239
|
+
import c2pa
|
|
240
|
+
|
|
241
|
+
path = Path(path)
|
|
242
|
+
if path.suffix.lower() not in MIME:
|
|
243
|
+
return {"present": False, "note": "this file type is not checked for metadata"}
|
|
244
|
+
try:
|
|
245
|
+
# A file can name a URL for its manifest, and by default the reader fetches it. Files here are untrusted, so it never does.
|
|
246
|
+
settings = {"verify": {"remote_manifest_fetch": False}}
|
|
247
|
+
if trust_anchors:
|
|
248
|
+
settings = {"verify": {"remote_manifest_fetch": False, "verify_trust": True}, "trust": {"trust_anchors": trust_anchors}}
|
|
249
|
+
with c2pa.Context(c2pa.Settings.from_dict(settings)) as context, c2pa.Reader(path, context=context) as reader:
|
|
250
|
+
store = json.loads(reader.json())
|
|
251
|
+
state = reader.get_validation_state()
|
|
252
|
+
except c2pa.C2paError as exc:
|
|
253
|
+
missing = type(exc).__name__ in {"ManifestNotFound", "NotFound"} or "ManifestNotFound" in str(exc) or "JumbfNotFound" in str(exc)
|
|
254
|
+
return {"present": False} if missing else {"present": False, "unreadable": True, "note": "a manifest could not be read from this file"}
|
|
255
|
+
active = store.get("manifests", {}).get(store.get("active_manifest"), {})
|
|
256
|
+
if not active:
|
|
257
|
+
return {"present": False}
|
|
258
|
+
sig = active.get("signature_info") or {}
|
|
259
|
+
types = _source_types(active)
|
|
260
|
+
origin = next((a.get("data") or {} for a in active.get("assertions", []) if a.get("label") == "app.invisimark.marking"), {})
|
|
261
|
+
return {
|
|
262
|
+
"present": True,
|
|
263
|
+
"state": state, # Trusted (chains to a loaded list) | Valid | Invalid
|
|
264
|
+
"intact": state in {"Trusted", "Valid"},
|
|
265
|
+
"trusted": state == "Trusted",
|
|
266
|
+
"ai_declared": any(t in AI_SOURCE_TYPES for t in types),
|
|
267
|
+
"source_types": types,
|
|
268
|
+
"signer": sig.get("common_name") or sig.get("issuer"),
|
|
269
|
+
"issuer": sig.get("issuer"),
|
|
270
|
+
"signed_at": sig.get("time"),
|
|
271
|
+
"provider": origin.get("provider"),
|
|
272
|
+
"system": origin.get("system"),
|
|
273
|
+
"model": origin.get("model"),
|
|
274
|
+
"detector": origin.get("detector"),
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@dataclass
|
|
279
|
+
class Check:
|
|
280
|
+
sha256: str
|
|
281
|
+
watermark: dict = field(default_factory=dict)
|
|
282
|
+
metadata: dict = field(default_factory=dict)
|
|
283
|
+
ai_marked: bool = False
|
|
284
|
+
summary: list[str] = field(default_factory=list)
|
|
285
|
+
|
|
286
|
+
def public(self) -> dict:
|
|
287
|
+
return asdict(self)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def find_mark(frames: list[np.ndarray], provider_key: bytes | None = None) -> detect.Report:
|
|
291
|
+
"""Look for the public mark, or a provider's private tile. If the plain search misses it, try again allowing for a tilt or a
|
|
292
|
+
change of aspect ratio."""
|
|
293
|
+
tile = id_tile(provider_key, PROVIDER_LABEL, DEFAULT) if provider_key else ai_tile()
|
|
294
|
+
key, label = (provider_key, PROVIDER_LABEL) if provider_key else (AI_KEY, AI_LABEL)
|
|
295
|
+
rep = detect.detect_frames(frames, key, [label], search=tile)
|
|
296
|
+
if rep.sync_z >= PUBLIC_SURE:
|
|
297
|
+
return rep
|
|
298
|
+
_, geometry = detect.search_geometry(frames, tile)
|
|
299
|
+
again = detect.detect_frames(detect.rectify(frames, geometry), key, [label], scale_hint=1.0, search=tile)
|
|
300
|
+
return again if again.sync_z > rep.sync_z else rep
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def read_watermark(path: Path | str, provider_key: bytes | None = None, frames: int = 32) -> dict:
|
|
304
|
+
loaded = detect.load_frames(path, frames)
|
|
305
|
+
rep = find_mark(loaded)
|
|
306
|
+
id_z = rep.matches[0].z if rep.matches else 0.0
|
|
307
|
+
present = rep.sync_z >= PUBLIC_SURE
|
|
308
|
+
out = {"scheme": SCHEME, "present": present, "sync_score": round(rep.sync_z, 1), "id_score": round(id_z, 1),
|
|
309
|
+
"scale": round(rep.scale, 3), "reoriented": rep.orientation != 0}
|
|
310
|
+
if provider_key:
|
|
311
|
+
private = find_mark(loaded, provider_key).sync_z
|
|
312
|
+
out["provider_score"] = round(private, 1)
|
|
313
|
+
out["provider_verified"] = private >= PUBLIC_SURE
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _describe(wm: dict, meta: dict) -> tuple[bool, list[str]]:
|
|
318
|
+
lines = []
|
|
319
|
+
if wm.get("present"):
|
|
320
|
+
lines.append("Watermark: this file carries the public Invisimark AI-marking watermark. It says the file was marked as AI-generated "
|
|
321
|
+
"or AI-manipulated. It does not say by whom, and it can be copied onto another file.")
|
|
322
|
+
else:
|
|
323
|
+
lines.append("Watermark: the public Invisimark watermark was not found. Other providers use other watermarks, which this check cannot read.")
|
|
324
|
+
if wm.get("provider_verified"):
|
|
325
|
+
lines.append("Provider key: the private tile for the key you supplied is present. It can be copied along with the public mark, so it does not prove the file is yours.")
|
|
326
|
+
if not meta.get("present"):
|
|
327
|
+
if meta.get("unreadable"):
|
|
328
|
+
lines.append("Metadata: this file holds provenance data that could not be read.")
|
|
329
|
+
else:
|
|
330
|
+
lines.append("Metadata: no C2PA manifest found. Most platforms strip metadata when files are shared, so this says little on its own.")
|
|
331
|
+
else:
|
|
332
|
+
who = meta.get("signer") or "an unnamed signer"
|
|
333
|
+
if not meta.get("intact"):
|
|
334
|
+
lines.append(f"Metadata: a C2PA manifest from {who} is present, but its signature does not validate, so what it says cannot be relied on. "
|
|
335
|
+
"The file may have been changed after signing.")
|
|
336
|
+
else:
|
|
337
|
+
trust = "and chains to the C2PA trust list" if meta.get("trusted") else "but the certificate is not on the trust list used here, so the name is the signer's own claim"
|
|
338
|
+
claim = "It declares the file AI-generated or AI-manipulated." if meta.get("ai_declared") else "It does not declare the file AI-generated."
|
|
339
|
+
lines.append(f"Metadata: a C2PA manifest signed by {who}. The signature is intact, {trust}. {claim}")
|
|
340
|
+
ai_marked = bool(wm.get("present") or (meta.get("intact") and meta.get("ai_declared")))
|
|
341
|
+
if not ai_marked:
|
|
342
|
+
lines.append("No AI marking found. That does not mean a person made this file: marks can be missing, removed or in a format this check cannot read.")
|
|
343
|
+
return ai_marked, lines
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def check(path: Path | str, provider_key: bytes | None = None, trust_anchors: str | None = None, frames: int = 32) -> Check:
|
|
347
|
+
path = Path(path)
|
|
348
|
+
wm = read_watermark(path, provider_key, frames)
|
|
349
|
+
meta = read_manifest(path, trust_anchors)
|
|
350
|
+
ai_marked, lines = _describe(wm, meta)
|
|
351
|
+
return Check(keys.sha256_of(path), wm, meta, ai_marked, lines)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
# ---------------------------------------------------------------------------------------------
|
|
355
|
+
# signed detection results (Sub-measure 2.1.2: a hash of the content, an identifier of the detector, a timestamp)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def canonical(body: dict) -> bytes:
|
|
359
|
+
return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def report_keypair() -> tuple[str, str]:
|
|
363
|
+
"""A new Ed25519 pair for signing detection results, as (private hex, public hex)."""
|
|
364
|
+
from cryptography.hazmat.primitives import serialization
|
|
365
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
366
|
+
|
|
367
|
+
private = Ed25519PrivateKey.generate()
|
|
368
|
+
raw = private.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())
|
|
369
|
+
return raw.hex(), private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def public_key_of(private_hex: str) -> str:
|
|
373
|
+
from cryptography.hazmat.primitives import serialization
|
|
374
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
375
|
+
|
|
376
|
+
key = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(private_hex))
|
|
377
|
+
return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def signed_report(result: Check, private_hex: str, detector: str = DETECTOR) -> dict:
|
|
381
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
382
|
+
|
|
383
|
+
body = {
|
|
384
|
+
"type": "invisimark-detection-result", "version": 1, "detector": detector, "software": f"invisimark {__version__}",
|
|
385
|
+
"time": dt.datetime.now(dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), "content_sha256": result.sha256,
|
|
386
|
+
"ai_marked": result.ai_marked, "watermark": result.watermark, "metadata": result.metadata, "summary": result.summary,
|
|
387
|
+
}
|
|
388
|
+
signature = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(private_hex)).sign(canonical(body))
|
|
389
|
+
return {"result": body, "alg": "Ed25519", "public_key": public_key_of(private_hex), "signature": base64.b64encode(signature).decode()}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def verify_report(report: dict, public_hex: str | None = None) -> bool:
|
|
393
|
+
"""True when the signature matches the result, under `public_hex` if given. Without it only integrity is shown, not who signed."""
|
|
394
|
+
from cryptography.exceptions import InvalidSignature
|
|
395
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
396
|
+
|
|
397
|
+
try:
|
|
398
|
+
key = public_hex or report["public_key"]
|
|
399
|
+
Ed25519PublicKey.from_public_bytes(bytes.fromhex(key)).verify(base64.b64decode(report["signature"]), canonical(report["result"]))
|
|
400
|
+
return True
|
|
401
|
+
except (InvalidSignature, KeyError, ValueError, TypeError):
|
|
402
|
+
return False
|
invisimark/calibrate.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Closed-loop strength: find the weakest mark that still survives a panel of realistic mangling.
|
|
2
|
+
|
|
3
|
+
How much mark a picture can carry depends on the picture: texture hides it and lets it through the encoder, flat
|
|
4
|
+
animation and dark water do not. So instead of a fixed strength, mark an excerpt at a few strengths, push each
|
|
5
|
+
through the panel below, trace it, and keep the lowest strength whose worst case clears the detection thresholds
|
|
6
|
+
with room to spare. If even the ceiling does not, say so, because then the copy is only traceable when it is
|
|
7
|
+
shared without heavy compression.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import multiprocessing
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import cv2
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from . import detect, embed, media
|
|
23
|
+
from .detect import SYNC_GATE, id_threshold
|
|
24
|
+
|
|
25
|
+
LABEL = "\x00calibration"
|
|
26
|
+
GRID = (0.7, 0.85, 1.0, 1.2, 1.45, 1.75, 2.1, 2.6, 3.2)
|
|
27
|
+
START = 3 # index of the default strength
|
|
28
|
+
SYNC_NEED = SYNC_GATE + 1.0 # room above the gate; the candidate score supplies the rest of the evidence
|
|
29
|
+
ID_NEED = id_threshold(100) + 3.0
|
|
30
|
+
|
|
31
|
+
# (name, ffmpeg output args). The scale is measured from the result, not assumed.
|
|
32
|
+
PANEL: list[tuple[str, list[str]]] = [
|
|
33
|
+
("recompress", ["-c:v", "libx264", "-preset", "veryfast", "-crf", "32"]),
|
|
34
|
+
("half-size", ["-vf", "scale=trunc(iw/4)*2:trunc(ih/4)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "30"]),
|
|
35
|
+
("screen-capture", ["-vf", "scale=trunc(iw*0.37)*2:trunc(ih*0.37)*2,gblur=sigma=0.6",
|
|
36
|
+
"-c:v", "libx264", "-preset", "veryfast", "-crf", "28"]),
|
|
37
|
+
]
|
|
38
|
+
IMAGE_PANEL = ("jpeg50", "half+jpeg60", "chat-app")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Trial:
|
|
43
|
+
attack: str
|
|
44
|
+
sync_z: float
|
|
45
|
+
id_z: float
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def ok(self) -> bool:
|
|
49
|
+
return self.sync_z >= SYNC_NEED and self.id_z >= ID_NEED
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Calibration:
|
|
54
|
+
rms: float
|
|
55
|
+
passed: bool
|
|
56
|
+
trials: list[Trial] = field(default_factory=list)
|
|
57
|
+
tried: list[float] = field(default_factory=list)
|
|
58
|
+
|
|
59
|
+
def summary(self) -> str:
|
|
60
|
+
worst = min(self.trials, key=lambda t: min(t.sync_z / SYNC_NEED, t.id_z / ID_NEED)) if self.trials else None
|
|
61
|
+
head = f"strength {self.rms:g} ({'robust' if self.passed else 'WEAK: content cannot carry a sturdier mark'})"
|
|
62
|
+
if worst:
|
|
63
|
+
head += f"; tightest case {worst.attack}: sync z {worst.sync_z:.1f}, id z {worst.id_z:.1f}"
|
|
64
|
+
return head
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---------------------------------------------------------------------------------------------
|
|
68
|
+
# video
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _activity(frame: np.ndarray) -> float:
|
|
72
|
+
return float(embed.activity_mask(frame).mean())
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def pick_excerpt(src: Path, seconds: float = 5.0) -> tuple[float, float]:
|
|
76
|
+
"""A typical stretch: the one whose texture sits at the median of twelve samples."""
|
|
77
|
+
info = media.probe(src)
|
|
78
|
+
if info.duration <= seconds * 1.2:
|
|
79
|
+
return 0.0, info.duration
|
|
80
|
+
starts = np.linspace(0, info.duration - seconds, 12)
|
|
81
|
+
scores = []
|
|
82
|
+
for t in starts:
|
|
83
|
+
f = media.grab_gray(src, float(t + seconds / 2), info.width, info.height)
|
|
84
|
+
scores.append(_activity(f) if f is not None else 0.0)
|
|
85
|
+
order = np.argsort(scores)
|
|
86
|
+
return float(starts[order[len(order) // 2]]), seconds
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _one_attack(args: tuple[str, str, list[str], bytes, float, str]) -> Trial:
|
|
90
|
+
marked, name, ff_args, key, src_width, label = args
|
|
91
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
92
|
+
leaked = Path(tmp) / "leaked.mp4"
|
|
93
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", marked, *ff_args, "-an", str(leaked)], check=True)
|
|
94
|
+
hint = media.probe(leaked).width / src_width
|
|
95
|
+
rep = detect.detect(leaked, key, [label], scale_hint=hint)
|
|
96
|
+
return Trial(name, rep.sync_z, rep.matches[0].z if rep.matches else 0.0)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _evaluate_video(excerpt: Path, key: bytes, rms: float, width: int, workdir: Path, label: str = LABEL) -> list[Trial]:
|
|
100
|
+
marked = workdir / f"marked-{rms:g}.mp4"
|
|
101
|
+
embed.embed_video(excerpt, marked, key, label, rms=rms, preset="veryfast")
|
|
102
|
+
jobs = [(str(marked), name, args, key, float(width), label) for name, args in PANEL]
|
|
103
|
+
with ProcessPoolExecutor(len(jobs), mp_context=multiprocessing.get_context("spawn")) as pool:
|
|
104
|
+
return list(pool.map(_one_attack, jobs))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _search(evaluate) -> Calibration:
|
|
108
|
+
"""Lowest passing strength on the grid: start at the default, walk down while it keeps passing, else walk up."""
|
|
109
|
+
results: dict[int, list[Trial]] = {}
|
|
110
|
+
|
|
111
|
+
def passes(i: int) -> bool:
|
|
112
|
+
if i not in results:
|
|
113
|
+
results[i] = evaluate(GRID[i])
|
|
114
|
+
return all(t.ok for t in results[i])
|
|
115
|
+
|
|
116
|
+
if passes(START):
|
|
117
|
+
best = START
|
|
118
|
+
while best > 0 and passes(best - 1):
|
|
119
|
+
best -= 1
|
|
120
|
+
ok = True
|
|
121
|
+
else:
|
|
122
|
+
best, ok = len(GRID) - 1, False
|
|
123
|
+
for i in range(START + 1, len(GRID)):
|
|
124
|
+
if passes(i):
|
|
125
|
+
best, ok = i, True
|
|
126
|
+
break
|
|
127
|
+
passes(best)
|
|
128
|
+
return Calibration(rms=GRID[best], passed=ok, trials=results[best], tried=[GRID[i] for i in sorted(results)])
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def calibrate_video(src: Path | str, key: bytes, max_rms: float = 2.6, seconds: float = 5.0, label: str = LABEL) -> Calibration:
|
|
132
|
+
src = Path(src)
|
|
133
|
+
media.require_h264_encoder()
|
|
134
|
+
info = media.probe(src)
|
|
135
|
+
start, length = pick_excerpt(src, seconds)
|
|
136
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
137
|
+
work = Path(tmp)
|
|
138
|
+
excerpt = work / "excerpt.mp4"
|
|
139
|
+
subprocess.run(
|
|
140
|
+
["ffmpeg", "-v", "error", "-y", "-ss", f"{start:.2f}", "-t", f"{length:.2f}", "-i", str(src),
|
|
141
|
+
"-an", "-c:v", "libx264", "-crf", "12", "-preset", "veryfast", "-pix_fmt", "yuv420p", str(excerpt)],
|
|
142
|
+
check=True,
|
|
143
|
+
)
|
|
144
|
+
cal = _search(lambda rms: _evaluate_video(excerpt, key, rms, info.width, work, label))
|
|
145
|
+
return _cap(cal, max_rms)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _cap(cal: Calibration, max_rms: float) -> Calibration:
|
|
149
|
+
if cal.rms > max_rms:
|
|
150
|
+
return Calibration(rms=max_rms, passed=False, trials=cal.trials, tried=cal.tried)
|
|
151
|
+
return cal
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---------------------------------------------------------------------------------------------
|
|
155
|
+
# images
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _image_attack(img: np.ndarray, name: str) -> tuple[np.ndarray, float]:
|
|
159
|
+
def jpeg(x, q):
|
|
160
|
+
return cv2.imdecode(cv2.imencode(".jpg", x, [cv2.IMWRITE_JPEG_QUALITY, q])[1], cv2.IMREAD_COLOR)
|
|
161
|
+
|
|
162
|
+
if name == "jpeg50":
|
|
163
|
+
return jpeg(img, 50), 1.0
|
|
164
|
+
if name == "half+jpeg60":
|
|
165
|
+
return jpeg(cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA), 60), 0.5
|
|
166
|
+
return jpeg(cv2.resize(img, None, fx=0.75, fy=0.75, interpolation=cv2.INTER_AREA), 65), 0.75
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _evaluate_image(src: Path, key: bytes, rms: float, workdir: Path, label: str = LABEL) -> list[Trial]:
|
|
170
|
+
marked = workdir / f"marked-{rms:g}.png"
|
|
171
|
+
embed.embed_image(src, marked, key, label, rms=rms)
|
|
172
|
+
img = cv2.imread(str(marked), cv2.IMREAD_COLOR)
|
|
173
|
+
trials = []
|
|
174
|
+
for name in IMAGE_PANEL:
|
|
175
|
+
leaked, hint = _image_attack(img, name)
|
|
176
|
+
gray = cv2.cvtColor(leaked, cv2.COLOR_BGR2GRAY).astype(np.float32)
|
|
177
|
+
rep = detect.detect_frames([gray], key, [label], scale_hint=hint)
|
|
178
|
+
trials.append(Trial(name, rep.sync_z, rep.matches[0].z if rep.matches else 0.0))
|
|
179
|
+
return trials
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def calibrate_image(src: Path | str, key: bytes, max_rms: float = 2.6, label: str = LABEL) -> Calibration:
|
|
183
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
184
|
+
cal = _search(lambda rms: _evaluate_image(Path(src), key, rms, Path(tmp), label))
|
|
185
|
+
return _cap(cal, max_rms)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def calibrate(src: Path | str, key: bytes, max_rms: float = 2.6, label: str = LABEL) -> Calibration:
|
|
189
|
+
if media.is_image(src):
|
|
190
|
+
return calibrate_image(src, key, max_rms, label)
|
|
191
|
+
return calibrate_video(src, key, max_rms, label=label)
|