markproof 0.1.0__tar.gz → 0.3.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.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: markproof
3
+ Version: 0.3.0
4
+ Summary: Python client for the Markproof API - EU AI Act Article 50 watermarking and verification.
5
+ Author-email: Markproof <support@markproof.co>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://markproof.co
8
+ Project-URL: Documentation, https://markproof.co/docs
9
+ Keywords: eu-ai-act,article-50,watermark,c2pa,content-credentials,ai-generated,provenance
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Multimedia :: Graphics
13
+ Classifier: Topic :: Multimedia :: Sound/Audio
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.31
18
+ Dynamic: license-file
19
+
20
+ # markproof
21
+
22
+ Python client for the [Markproof](https://markproof.co) API — EU AI Act Article 50 watermarking and verification in one call. Thin wrapper over `requests`.
23
+
24
+ > **Is your AI output Article 50-ready?** Drop a file into the [free checker](https://markproof.co/check) (no signup) to see whether it carries a watermark and signed Content Credentials.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install markproof
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from markproof import Markproof
36
+
37
+ client = Markproof(api_key="lt_live_...")
38
+
39
+ marked = client.mark("generated.png", generator_name="my-app", model_name="my-model-v1")
40
+ print(marked.watermark_code, marked.verify_url)
41
+ with open("generated-marked.png", "wb") as f:
42
+ f.write(marked.file)
43
+
44
+ result = client.verify("generated-marked.png")
45
+ print(result.summary)
46
+ ```
47
+
48
+ ## API
49
+
50
+ - `Markproof(api_key, base_url=DEFAULT_BASE_URL)` — `base_url` defaults to the production API; override for local dev.
51
+ - `client.mark(file, filename=None, generator_name=None, model_name=None, response_format="file", visible_label=None, label_position=None)` → `MarkResult` — `file` is a path (`str`/`os.PathLike`) or raw `bytes` (in which case `filename` is required). `response_format="file"` (default) returns the marked bytes inline (`result.file`/`result.content_type`); `"url"` returns a short-lived signed download URL instead (`result.file_url`, ~1 hour — download promptly rather than caching it). Either way you also get `asset_id`, `watermark_code`, `verify_url`, `c2pa_manifest_label`. `visible_label` (images only): `True` draws a visible "AI-generated" label (EU AI Act Art. 50(4)) before marking, or pass your own text (max 40 characters); `label_position` picks the corner (`"bottom-right"` default, `"bottom-left"`, `"top-right"`, `"top-left"`).
52
+ - `client.verify(file, filename=None)` or `client.verify(url=...)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`. Direct uploads are limited to about 4.5 MB; pass a public `url` (up to 25 MB) for bigger files, such as marked audio, which comes back as WAV (e.g. a batch item's `file_url`).
53
+ - `client.get_asset(asset_id)` → `Asset` — requires an API key on the same project that created the asset.
54
+
55
+ All methods raise `MarkproofError` (with `.status` and `.body`) on a non-2xx response.
56
+
57
+ ## Batches and webhooks
58
+
59
+ For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
60
+
61
+ ```python
62
+ created = client.create_batch(
63
+ urls=["https://cdn.example.com/1.png", "https://cdn.example.com/2.png"], # and/or files=["a.png", (data, "b.wav")]
64
+ generator_name="your-app",
65
+ webhook_url="https://your-app.example.com/hooks/markproof", # optional
66
+ )
67
+ batch = client.wait_for_batch(created.batch_id) # or get_batch(...), or wait for the webhook
68
+ for item in batch.items:
69
+ print(item.index, item.status, item.file_url or item.error)
70
+ ```
71
+
72
+ - `client.create_batch(files=None, urls=None, generator_name=None, model_name=None, webhook_url=None)` → `CreatedBatch` — files go up in one multipart request (keep the total under ~4.5 MB; use `urls` for more). Max items per batch: 10 Free, 100 Indie, 1,000 Pro.
73
+ - `client.get_batch(batch_id)` → `Batch` — `status` (`queued`/`processing`/`completed`/`partial`/`failed`), `counts`, and `items` with `asset_id`, `watermark_code`, `verify_url`, `file_url` (signed, ~1 hour; call again for a fresh one) or `error`.
74
+ - `client.wait_for_batch(batch_id, interval=3.0, timeout=900, on_progress=None)` — polls until the batch is final.
75
+
76
+ Verify webhooks with the raw request body and your signing secret from the dashboard:
77
+
78
+ ```python
79
+ from markproof import verify_webhook_signature
80
+
81
+ ok = verify_webhook_signature(
82
+ request.get_data(), # the exact bytes received, not re-serialized JSON
83
+ request.headers.get("Markproof-Signature"),
84
+ os.environ["MARKPROOF_WEBHOOK_SECRET"],
85
+ )
86
+ ```
87
+
88
+ `parse_webhook_event(...)` does the same and returns the `batch.completed` event, raising `WebhookSignatureError` if the signature doesn't match. Event `id`s are stable across retries, so use them to drop duplicates.
@@ -0,0 +1,69 @@
1
+ # markproof
2
+
3
+ Python client for the [Markproof](https://markproof.co) API — EU AI Act Article 50 watermarking and verification in one call. Thin wrapper over `requests`.
4
+
5
+ > **Is your AI output Article 50-ready?** Drop a file into the [free checker](https://markproof.co/check) (no signup) to see whether it carries a watermark and signed Content Credentials.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install markproof
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ from markproof import Markproof
17
+
18
+ client = Markproof(api_key="lt_live_...")
19
+
20
+ marked = client.mark("generated.png", generator_name="my-app", model_name="my-model-v1")
21
+ print(marked.watermark_code, marked.verify_url)
22
+ with open("generated-marked.png", "wb") as f:
23
+ f.write(marked.file)
24
+
25
+ result = client.verify("generated-marked.png")
26
+ print(result.summary)
27
+ ```
28
+
29
+ ## API
30
+
31
+ - `Markproof(api_key, base_url=DEFAULT_BASE_URL)` — `base_url` defaults to the production API; override for local dev.
32
+ - `client.mark(file, filename=None, generator_name=None, model_name=None, response_format="file", visible_label=None, label_position=None)` → `MarkResult` — `file` is a path (`str`/`os.PathLike`) or raw `bytes` (in which case `filename` is required). `response_format="file"` (default) returns the marked bytes inline (`result.file`/`result.content_type`); `"url"` returns a short-lived signed download URL instead (`result.file_url`, ~1 hour — download promptly rather than caching it). Either way you also get `asset_id`, `watermark_code`, `verify_url`, `c2pa_manifest_label`. `visible_label` (images only): `True` draws a visible "AI-generated" label (EU AI Act Art. 50(4)) before marking, or pass your own text (max 40 characters); `label_position` picks the corner (`"bottom-right"` default, `"bottom-left"`, `"top-right"`, `"top-left"`).
33
+ - `client.verify(file, filename=None)` or `client.verify(url=...)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`. Direct uploads are limited to about 4.5 MB; pass a public `url` (up to 25 MB) for bigger files, such as marked audio, which comes back as WAV (e.g. a batch item's `file_url`).
34
+ - `client.get_asset(asset_id)` → `Asset` — requires an API key on the same project that created the asset.
35
+
36
+ All methods raise `MarkproofError` (with `.status` and `.body`) on a non-2xx response.
37
+
38
+ ## Batches and webhooks
39
+
40
+ For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
41
+
42
+ ```python
43
+ created = client.create_batch(
44
+ urls=["https://cdn.example.com/1.png", "https://cdn.example.com/2.png"], # and/or files=["a.png", (data, "b.wav")]
45
+ generator_name="your-app",
46
+ webhook_url="https://your-app.example.com/hooks/markproof", # optional
47
+ )
48
+ batch = client.wait_for_batch(created.batch_id) # or get_batch(...), or wait for the webhook
49
+ for item in batch.items:
50
+ print(item.index, item.status, item.file_url or item.error)
51
+ ```
52
+
53
+ - `client.create_batch(files=None, urls=None, generator_name=None, model_name=None, webhook_url=None)` → `CreatedBatch` — files go up in one multipart request (keep the total under ~4.5 MB; use `urls` for more). Max items per batch: 10 Free, 100 Indie, 1,000 Pro.
54
+ - `client.get_batch(batch_id)` → `Batch` — `status` (`queued`/`processing`/`completed`/`partial`/`failed`), `counts`, and `items` with `asset_id`, `watermark_code`, `verify_url`, `file_url` (signed, ~1 hour; call again for a fresh one) or `error`.
55
+ - `client.wait_for_batch(batch_id, interval=3.0, timeout=900, on_progress=None)` — polls until the batch is final.
56
+
57
+ Verify webhooks with the raw request body and your signing secret from the dashboard:
58
+
59
+ ```python
60
+ from markproof import verify_webhook_signature
61
+
62
+ ok = verify_webhook_signature(
63
+ request.get_data(), # the exact bytes received, not re-serialized JSON
64
+ request.headers.get("Markproof-Signature"),
65
+ os.environ["MARKPROOF_WEBHOOK_SECRET"],
66
+ )
67
+ ```
68
+
69
+ `parse_webhook_event(...)` does the same and returns the `batch.completed` event, raising `WebhookSignatureError` if the signature doesn't match. Event `id`s are stable across retries, so use them to drop duplicates.
@@ -0,0 +1,29 @@
1
+ from .batches import Batch, BatchItem, BatchWebhook, CreatedBatch
2
+ from .client import Asset, C2paResult, MarkResult, Markproof, VerifyResult, WatermarkResult
3
+ from .errors import MarkproofError
4
+ from .webhooks import (
5
+ SIGNATURE_HEADER,
6
+ BatchCompletedEvent,
7
+ WebhookSignatureError,
8
+ parse_webhook_event,
9
+ verify_webhook_signature,
10
+ )
11
+
12
+ __all__ = [
13
+ "Markproof",
14
+ "MarkproofError",
15
+ "MarkResult",
16
+ "VerifyResult",
17
+ "WatermarkResult",
18
+ "C2paResult",
19
+ "Asset",
20
+ "Batch",
21
+ "BatchItem",
22
+ "BatchWebhook",
23
+ "CreatedBatch",
24
+ "BatchCompletedEvent",
25
+ "WebhookSignatureError",
26
+ "SIGNATURE_HEADER",
27
+ "parse_webhook_event",
28
+ "verify_webhook_signature",
29
+ ]
@@ -0,0 +1,97 @@
1
+ """Batch result types for Markproof.create_batch / get_batch / wait_for_batch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import List, Optional
7
+
8
+ FINAL_BATCH_STATUSES = frozenset({"completed", "partial", "failed"})
9
+
10
+
11
+ @dataclass
12
+ class CreatedBatch:
13
+ batch_id: str
14
+ status: str
15
+ item_count: int
16
+
17
+
18
+ @dataclass
19
+ class BatchItem:
20
+ index: int # 0-based position in the submission: files first, then urls
21
+ status: str # "queued" | "processing" | "completed" | "failed"
22
+ filename: Optional[str] = None
23
+ source_url: Optional[str] = None
24
+ asset_id: Optional[str] = None
25
+ watermark_code: Optional[str] = None
26
+ kind: Optional[str] = None
27
+ verify_url: Optional[str] = None
28
+ watermark_robust: Optional[bool] = None
29
+ c2pa_manifest_label: Optional[str] = None
30
+ # Signed, ~1 hour. Call get_batch again for a fresh link; the file is kept 30 days.
31
+ file_url: Optional[str] = None
32
+ error: Optional[str] = None
33
+
34
+
35
+ @dataclass
36
+ class BatchWebhook:
37
+ url: str
38
+ status: Optional[str] # "pending" | "delivered" | "failed"
39
+ attempts: int
40
+ last_status: Optional[int]
41
+ delivered_at: Optional[str]
42
+
43
+
44
+ @dataclass
45
+ class Batch:
46
+ id: str
47
+ status: str # "queued" | "processing" | "completed" | "partial" | "failed"
48
+ created_at: str
49
+ completed_at: Optional[str]
50
+ generator_name: Optional[str]
51
+ model_name: Optional[str]
52
+ counts: dict
53
+ webhook: Optional[BatchWebhook]
54
+ items: List[BatchItem] = field(default_factory=list)
55
+
56
+ @property
57
+ def done(self) -> bool:
58
+ return self.status in FINAL_BATCH_STATUSES
59
+
60
+
61
+ def _batch_from_api(body: dict) -> Batch:
62
+ webhook = body.get("webhook")
63
+ return Batch(
64
+ id=body["id"],
65
+ status=body["status"],
66
+ created_at=body["created_at"],
67
+ completed_at=body.get("completed_at"),
68
+ generator_name=body.get("generator_name"),
69
+ model_name=body.get("model_name"),
70
+ counts=body.get("counts", {}),
71
+ webhook=BatchWebhook(
72
+ url=webhook["url"],
73
+ status=webhook.get("status"),
74
+ attempts=webhook.get("attempts", 0),
75
+ last_status=webhook.get("last_status"),
76
+ delivered_at=webhook.get("delivered_at"),
77
+ )
78
+ if webhook
79
+ else None,
80
+ items=[
81
+ BatchItem(
82
+ index=item["index"],
83
+ status=item["status"],
84
+ filename=item.get("filename"),
85
+ source_url=item.get("source_url"),
86
+ asset_id=item.get("asset_id"),
87
+ watermark_code=item.get("watermark_code"),
88
+ kind=item.get("kind"),
89
+ verify_url=item.get("verify_url"),
90
+ watermark_robust=item.get("watermark_robust"),
91
+ c2pa_manifest_label=item.get("c2pa_manifest_label"),
92
+ file_url=item.get("file_url"),
93
+ error=item.get("error"),
94
+ )
95
+ for item in body.get("items", [])
96
+ ],
97
+ )
@@ -4,13 +4,15 @@ from __future__ import annotations
4
4
 
5
5
  import mimetypes
6
6
  import os
7
+ import time
7
8
  from dataclasses import dataclass
8
9
  from pathlib import Path
9
- from typing import Optional, Union
10
+ from typing import Callable, Optional, Sequence, Union
10
11
  from urllib.parse import quote
11
12
 
12
13
  import requests
13
14
 
15
+ from .batches import Batch, CreatedBatch, _batch_from_api
14
16
  from .errors import MarkproofError
15
17
 
16
18
  DEFAULT_BASE_URL = "https://markproof.co/v1"
@@ -22,12 +24,13 @@ FileLike = Union[str, "os.PathLike[str]", bytes]
22
24
  class MarkResult:
23
25
  asset_id: str
24
26
  watermark_code: str
25
- kind: str # "image" | "audio"
27
+ kind: str # "image" | "audio" | "video"
26
28
  verify_url: str
27
29
  c2pa_manifest_label: Optional[str]
28
- # Images only (None for audio): whether the watermark passed Markproof's
29
- # robustness self-check. False for rare, very smooth images - the file is
30
- # still marked and signed, but rely on the C2PA manifest for it.
30
+ # Images and video (None for audio): whether the watermark passed
31
+ # Markproof's robustness self-check. False for rare, very smooth or
32
+ # featureless content - the file is still marked and signed, but rely on
33
+ # the C2PA manifest for it.
31
34
  watermark_robust: Optional[bool] = None
32
35
  # Exactly one pair is populated, matching the requested response_format.
33
36
  content_type: Optional[str] = None
@@ -83,6 +86,13 @@ def _asset_from_api(body: dict) -> Asset:
83
86
  )
84
87
 
85
88
 
89
+ def _kind_from_content_type(content_type: str) -> str:
90
+ for kind in ("audio", "video"):
91
+ if content_type.startswith(kind + "/"):
92
+ return kind
93
+ return "image"
94
+
95
+
86
96
  def _resolve_file(file: FileLike, filename: Optional[str]) -> tuple[bytes, str, str]:
87
97
  """Returns (data, filename, content_type)."""
88
98
  if isinstance(file, (bytes, bytearray)):
@@ -129,12 +139,19 @@ class Markproof:
129
139
  generator_name: Optional[str] = None,
130
140
  model_name: Optional[str] = None,
131
141
  response_format: str = "file",
142
+ visible_label: Union[bool, str, None] = None,
143
+ label_position: Optional[str] = None,
132
144
  ) -> MarkResult:
133
145
  """Watermarks (and, if the server has C2PA signing configured, signs) a file.
134
146
 
135
147
  response_format="file" (default) returns the marked bytes inline
136
148
  (result.file/result.content_type). "url" returns a short-lived
137
149
  signed download URL instead (result.file_url).
150
+
151
+ visible_label (images only; the API returns 400 for audio): True draws
152
+ a visible "AI-generated" label (EU AI Act Art. 50(4)) before marking,
153
+ or pass your own text (max 40 characters). label_position:
154
+ "bottom-right" (default), "bottom-left", "top-right" or "top-left".
138
155
  """
139
156
  data, resolved_filename, content_type = _resolve_file(file, filename)
140
157
  form_data = {}
@@ -144,6 +161,10 @@ class Markproof:
144
161
  form_data["model_name"] = model_name
145
162
  if response_format == "url":
146
163
  form_data["response_format"] = "url"
164
+ if visible_label:
165
+ form_data["visible_label"] = "true" if visible_label is True else visible_label
166
+ if label_position:
167
+ form_data["label_position"] = label_position
147
168
 
148
169
  response = self._session.post(
149
170
  f"{self._base_url}/mark",
@@ -169,7 +190,7 @@ class Markproof:
169
190
  return MarkResult(
170
191
  asset_id=response.headers.get("x-asset-id", ""),
171
192
  watermark_code=response.headers.get("x-watermark-code", ""),
172
- kind="audio" if response_content_type.startswith("audio/") else "image",
193
+ kind=_kind_from_content_type(response_content_type),
173
194
  verify_url=response.headers.get("x-verify-url", ""),
174
195
  c2pa_manifest_label=response.headers.get("x-c2pa-manifest-label"),
175
196
  watermark_robust={"true": True, "false": False}.get(response.headers.get("x-watermark-robust", "")),
@@ -177,14 +198,26 @@ class Markproof:
177
198
  file=response.content,
178
199
  )
179
200
 
180
- def verify(self, file: FileLike, filename: Optional[str] = None) -> VerifyResult:
181
- """Checks a file for our watermark and/or a C2PA manifest."""
182
- data, resolved_filename, content_type = _resolve_file(file, filename)
183
- response = self._session.post(
184
- f"{self._base_url}/verify",
185
- headers=self._headers(),
186
- files={"file": (resolved_filename, data, content_type)},
187
- )
201
+ def verify(
202
+ self, file: Optional[FileLike] = None, filename: Optional[str] = None, *, url: Optional[str] = None
203
+ ) -> VerifyResult:
204
+ """Checks a file for our watermark and/or a C2PA manifest.
205
+
206
+ Pass ``url`` instead of ``file`` for anything over ~4.5 MB (the
207
+ direct-upload limit), e.g. marked audio, which comes back as WAV;
208
+ URLs up to 25 MB work.
209
+ """
210
+ if (file is None) == (url is None):
211
+ raise ValueError("Pass exactly one of file or url.")
212
+ if url is not None:
213
+ response = self._session.post(f"{self._base_url}/verify", headers=self._headers(), json={"url": url})
214
+ else:
215
+ data, resolved_filename, content_type = _resolve_file(file, filename)
216
+ response = self._session.post(
217
+ f"{self._base_url}/verify",
218
+ headers=self._headers(),
219
+ files={"file": (resolved_filename, data, content_type)},
220
+ )
188
221
  self._raise_if_error(response)
189
222
  body = response.json()
190
223
  return VerifyResult(
@@ -208,3 +241,72 @@ class Markproof:
208
241
  response = self._session.get(f"{self._base_url}/assets/{quote(asset_id, safe='')}", headers=self._headers())
209
242
  self._raise_if_error(response)
210
243
  return _asset_from_api(response.json())
244
+
245
+ def create_batch(
246
+ self,
247
+ files: Optional[Sequence[FileLike]] = None,
248
+ urls: Optional[Sequence[str]] = None,
249
+ generator_name: Optional[str] = None,
250
+ model_name: Optional[str] = None,
251
+ webhook_url: Optional[str] = None,
252
+ ) -> CreatedBatch:
253
+ """Queues many files for marking and returns at once; see get_batch / wait_for_batch.
254
+
255
+ ``files`` are paths (or ``(bytes, filename)`` tuples), sent in one
256
+ multipart request - keep the total under ~4.5 MB, or pass ``urls``
257
+ (https, up to 25 MB each) for Markproof to fetch. ``webhook_url``
258
+ receives a signed ``batch.completed`` event; check it with
259
+ ``markproof.verify_webhook_signature``.
260
+ """
261
+ files = list(files or [])
262
+ urls = list(urls or [])
263
+ if not files and not urls:
264
+ raise ValueError("create_batch needs at least one file or url.")
265
+
266
+ fields = {"generator_name": generator_name, "model_name": model_name, "webhook_url": webhook_url}
267
+ fields = {k: v for k, v in fields.items() if v}
268
+ if files:
269
+ parts = []
270
+ for f in files:
271
+ data, filename, content_type = (
272
+ _resolve_file(f[0], f[1]) if isinstance(f, tuple) else _resolve_file(f, None)
273
+ )
274
+ parts.append(("file", (filename, data, content_type)))
275
+ response = self._session.post(
276
+ f"{self._base_url}/batches",
277
+ headers=self._headers(),
278
+ files=parts,
279
+ data=[*fields.items(), *(("url", u) for u in urls)],
280
+ )
281
+ else:
282
+ response = self._session.post(
283
+ f"{self._base_url}/batches", headers=self._headers(), json={"urls": urls, **fields}
284
+ )
285
+ self._raise_if_error(response)
286
+ body = response.json()
287
+ return CreatedBatch(batch_id=body["batch_id"], status=body["status"], item_count=body["item_count"])
288
+
289
+ def get_batch(self, batch_id: str) -> Batch:
290
+ """A batch's status and per-item results, with fresh signed download URLs."""
291
+ response = self._session.get(f"{self._base_url}/batches/{quote(batch_id, safe='')}", headers=self._headers())
292
+ self._raise_if_error(response)
293
+ return _batch_from_api(response.json())
294
+
295
+ def wait_for_batch(
296
+ self,
297
+ batch_id: str,
298
+ interval: float = 3.0,
299
+ timeout: float = 15 * 60,
300
+ on_progress: Optional[Callable[[Batch], None]] = None,
301
+ ) -> Batch:
302
+ """Polls get_batch until the batch is completed, partial or failed. Raises MarkproofError on timeout."""
303
+ deadline = time.monotonic() + timeout
304
+ while True:
305
+ batch = self.get_batch(batch_id)
306
+ if on_progress:
307
+ on_progress(batch)
308
+ if batch.done:
309
+ return batch
310
+ if time.monotonic() + interval > deadline:
311
+ raise MarkproofError(f"Batch {batch_id} did not finish in time (status {batch.status}).", 0, None)
312
+ time.sleep(interval)
@@ -0,0 +1,87 @@
1
+ """Verify Markproof webhook signatures. See https://markproof.co/docs#webhooks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import time
9
+ from typing import Optional, Union
10
+
11
+ from .batches import Batch, _batch_from_api
12
+
13
+ SIGNATURE_HEADER = "Markproof-Signature"
14
+ DEFAULT_TOLERANCE_SECONDS = 300
15
+
16
+
17
+ class WebhookSignatureError(Exception):
18
+ """Raised by parse_webhook_event when the signature doesn't verify."""
19
+
20
+
21
+ def _to_bytes(payload: Union[str, bytes, bytearray]) -> bytes:
22
+ return payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
23
+
24
+
25
+ def verify_webhook_signature(
26
+ payload: Union[str, bytes, bytearray],
27
+ header: Optional[str],
28
+ secret: str,
29
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
30
+ now: Optional[int] = None,
31
+ ) -> bool:
32
+ """Checks a webhook's Markproof-Signature header.
33
+
34
+ ``payload`` must be the raw request body exactly as received (e.g.
35
+ ``request.get_data()`` in Flask, ``await request.body()`` in FastAPI),
36
+ not re-serialized JSON. The signature is HMAC-SHA256 of
37
+ ``f"{t}.{body}"`` keyed with your ``whsec_...`` secret, and ``t`` must
38
+ be within ``tolerance_seconds`` of now (replay protection).
39
+ """
40
+ if not header or not secret:
41
+ return False
42
+ timestamp: Optional[int] = None
43
+ signatures = []
44
+ for part in header.split(","):
45
+ key, _, value = part.strip().partition("=")
46
+ if key == "t" and value.isdigit():
47
+ timestamp = int(value)
48
+ elif key == "v1" and value:
49
+ signatures.append(value)
50
+ if timestamp is None or not signatures:
51
+ return False
52
+
53
+ current = int(time.time()) if now is None else now
54
+ if abs(current - timestamp) > tolerance_seconds:
55
+ return False
56
+
57
+ signed = str(timestamp).encode("ascii") + b"." + _to_bytes(payload)
58
+ expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest().encode("ascii")
59
+ # Compare as bytes: compare_digest raises on non-ASCII str input, and a header is untrusted.
60
+ return any(hmac.compare_digest(expected, sig.lower().encode("utf-8")) for sig in signatures)
61
+
62
+
63
+ class BatchCompletedEvent:
64
+ """A verified ``batch.completed`` event. ``id`` is stable across retries - use it to drop duplicates."""
65
+
66
+ def __init__(self, id: str, type: str, created: int, data: Batch):
67
+ self.id = id
68
+ self.type = type
69
+ self.created = created
70
+ self.data = data
71
+
72
+ def __repr__(self) -> str:
73
+ return f"BatchCompletedEvent(id={self.id!r}, type={self.type!r}, status={self.data.status!r})"
74
+
75
+
76
+ def parse_webhook_event(
77
+ payload: Union[str, bytes, bytearray],
78
+ header: Optional[str],
79
+ secret: str,
80
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
81
+ now: Optional[int] = None,
82
+ ) -> BatchCompletedEvent:
83
+ """Verifies the signature, then parses the event. Raises WebhookSignatureError if it doesn't verify."""
84
+ if not verify_webhook_signature(payload, header, secret, tolerance_seconds, now):
85
+ raise WebhookSignatureError("Invalid Markproof webhook signature.")
86
+ body = json.loads(_to_bytes(payload))
87
+ return BatchCompletedEvent(id=body["id"], type=body["type"], created=body["created"], data=_batch_from_api(body["data"]))
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: markproof
3
+ Version: 0.3.0
4
+ Summary: Python client for the Markproof API - EU AI Act Article 50 watermarking and verification.
5
+ Author-email: Markproof <support@markproof.co>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://markproof.co
8
+ Project-URL: Documentation, https://markproof.co/docs
9
+ Keywords: eu-ai-act,article-50,watermark,c2pa,content-credentials,ai-generated,provenance
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Multimedia :: Graphics
13
+ Classifier: Topic :: Multimedia :: Sound/Audio
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.31
18
+ Dynamic: license-file
19
+
20
+ # markproof
21
+
22
+ Python client for the [Markproof](https://markproof.co) API — EU AI Act Article 50 watermarking and verification in one call. Thin wrapper over `requests`.
23
+
24
+ > **Is your AI output Article 50-ready?** Drop a file into the [free checker](https://markproof.co/check) (no signup) to see whether it carries a watermark and signed Content Credentials.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install markproof
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from markproof import Markproof
36
+
37
+ client = Markproof(api_key="lt_live_...")
38
+
39
+ marked = client.mark("generated.png", generator_name="my-app", model_name="my-model-v1")
40
+ print(marked.watermark_code, marked.verify_url)
41
+ with open("generated-marked.png", "wb") as f:
42
+ f.write(marked.file)
43
+
44
+ result = client.verify("generated-marked.png")
45
+ print(result.summary)
46
+ ```
47
+
48
+ ## API
49
+
50
+ - `Markproof(api_key, base_url=DEFAULT_BASE_URL)` — `base_url` defaults to the production API; override for local dev.
51
+ - `client.mark(file, filename=None, generator_name=None, model_name=None, response_format="file", visible_label=None, label_position=None)` → `MarkResult` — `file` is a path (`str`/`os.PathLike`) or raw `bytes` (in which case `filename` is required). `response_format="file"` (default) returns the marked bytes inline (`result.file`/`result.content_type`); `"url"` returns a short-lived signed download URL instead (`result.file_url`, ~1 hour — download promptly rather than caching it). Either way you also get `asset_id`, `watermark_code`, `verify_url`, `c2pa_manifest_label`. `visible_label` (images only): `True` draws a visible "AI-generated" label (EU AI Act Art. 50(4)) before marking, or pass your own text (max 40 characters); `label_position` picks the corner (`"bottom-right"` default, `"bottom-left"`, `"top-right"`, `"top-left"`).
52
+ - `client.verify(file, filename=None)` or `client.verify(url=...)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`. Direct uploads are limited to about 4.5 MB; pass a public `url` (up to 25 MB) for bigger files, such as marked audio, which comes back as WAV (e.g. a batch item's `file_url`).
53
+ - `client.get_asset(asset_id)` → `Asset` — requires an API key on the same project that created the asset.
54
+
55
+ All methods raise `MarkproofError` (with `.status` and `.body`) on a non-2xx response.
56
+
57
+ ## Batches and webhooks
58
+
59
+ For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
60
+
61
+ ```python
62
+ created = client.create_batch(
63
+ urls=["https://cdn.example.com/1.png", "https://cdn.example.com/2.png"], # and/or files=["a.png", (data, "b.wav")]
64
+ generator_name="your-app",
65
+ webhook_url="https://your-app.example.com/hooks/markproof", # optional
66
+ )
67
+ batch = client.wait_for_batch(created.batch_id) # or get_batch(...), or wait for the webhook
68
+ for item in batch.items:
69
+ print(item.index, item.status, item.file_url or item.error)
70
+ ```
71
+
72
+ - `client.create_batch(files=None, urls=None, generator_name=None, model_name=None, webhook_url=None)` → `CreatedBatch` — files go up in one multipart request (keep the total under ~4.5 MB; use `urls` for more). Max items per batch: 10 Free, 100 Indie, 1,000 Pro.
73
+ - `client.get_batch(batch_id)` → `Batch` — `status` (`queued`/`processing`/`completed`/`partial`/`failed`), `counts`, and `items` with `asset_id`, `watermark_code`, `verify_url`, `file_url` (signed, ~1 hour; call again for a fresh one) or `error`.
74
+ - `client.wait_for_batch(batch_id, interval=3.0, timeout=900, on_progress=None)` — polls until the batch is final.
75
+
76
+ Verify webhooks with the raw request body and your signing secret from the dashboard:
77
+
78
+ ```python
79
+ from markproof import verify_webhook_signature
80
+
81
+ ok = verify_webhook_signature(
82
+ request.get_data(), # the exact bytes received, not re-serialized JSON
83
+ request.headers.get("Markproof-Signature"),
84
+ os.environ["MARKPROOF_WEBHOOK_SECRET"],
85
+ )
86
+ ```
87
+
88
+ `parse_webhook_event(...)` does the same and returns the `batch.completed` event, raising `WebhookSignatureError` if the signature doesn't match. Event `id`s are stable across retries, so use them to drop duplicates.