markproof 0.2.0__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: markproof
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Python client for the Markproof API - EU AI Act Article 50 watermarking and verification.
5
5
  Author-email: Markproof <support@markproof.co>
6
6
  License-Expression: MIT
@@ -48,12 +48,23 @@ print(result.summary)
48
48
  ## API
49
49
 
50
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)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`.
51
+ - `client.mark(file, filename=None, generator_name=None, model_name=None, response_format=None, 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"` (the default for small images and audio) 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
53
  - `client.get_asset(asset_id)` → `Asset` — requires an API key on the same project that created the asset.
54
54
 
55
55
  All methods raise `MarkproofError` (with `.status` and `.body`) on a non-2xx response.
56
56
 
57
+ ### Video and large files (launches with video)
58
+
59
+ `mark` and `verify` also take `url=` (https, up to 25 MB) or `upload_id=` instead of `file`. Video, and any
60
+ file over about 4 MB, is sent through a direct upload automatically: the SDK asks the API for a signed
61
+ upload URL, PUTs the file straight to storage (up to 100 MB), then marks or verifies it by id. For these,
62
+ `response_format` defaults to `"url"`, because the marked file is too big to come back inline. Call
63
+ `client.upload(file, filename=None)` → `upload_id` to do the upload yourself; each upload can be used
64
+ once. `result.calls_used` says how many quota calls a mark used: 1 per image or audio file, one per
65
+ started second of video. Until video launches, the upload step fails with a 404 `MarkproofError`
66
+ saying so; pass `url=` for big files meanwhile.
67
+
57
68
  ## Batches and webhooks
58
69
 
59
70
  For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
@@ -1,69 +1,80 @@
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)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`.
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.
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=None, 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"` (the default for small images and audio) 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
+ ### Video and large files (launches with video)
39
+
40
+ `mark` and `verify` also take `url=` (https, up to 25 MB) or `upload_id=` instead of `file`. Video, and any
41
+ file over about 4 MB, is sent through a direct upload automatically: the SDK asks the API for a signed
42
+ upload URL, PUTs the file straight to storage (up to 100 MB), then marks or verifies it by id. For these,
43
+ `response_format` defaults to `"url"`, because the marked file is too big to come back inline. Call
44
+ `client.upload(file, filename=None)` → `upload_id` to do the upload yourself; each upload can be used
45
+ once. `result.calls_used` says how many quota calls a mark used: 1 per image or audio file, one per
46
+ started second of video. Until video launches, the upload step fails with a 404 `MarkproofError`
47
+ saying so; pass `url=` for big files meanwhile.
48
+
49
+ ## Batches and webhooks
50
+
51
+ For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
52
+
53
+ ```python
54
+ created = client.create_batch(
55
+ urls=["https://cdn.example.com/1.png", "https://cdn.example.com/2.png"], # and/or files=["a.png", (data, "b.wav")]
56
+ generator_name="your-app",
57
+ webhook_url="https://your-app.example.com/hooks/markproof", # optional
58
+ )
59
+ batch = client.wait_for_batch(created.batch_id) # or get_batch(...), or wait for the webhook
60
+ for item in batch.items:
61
+ print(item.index, item.status, item.file_url or item.error)
62
+ ```
63
+
64
+ - `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.
65
+ - `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`.
66
+ - `client.wait_for_batch(batch_id, interval=3.0, timeout=900, on_progress=None)` — polls until the batch is final.
67
+
68
+ Verify webhooks with the raw request body and your signing secret from the dashboard:
69
+
70
+ ```python
71
+ from markproof import verify_webhook_signature
72
+
73
+ ok = verify_webhook_signature(
74
+ request.get_data(), # the exact bytes received, not re-serialized JSON
75
+ request.headers.get("Markproof-Signature"),
76
+ os.environ["MARKPROOF_WEBHOOK_SECRET"],
77
+ )
78
+ ```
79
+
80
+ `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.
@@ -16,6 +16,9 @@ from .batches import Batch, CreatedBatch, _batch_from_api
16
16
  from .errors import MarkproofError
17
17
 
18
18
  DEFAULT_BASE_URL = "https://markproof.co/v1"
19
+ # Files bigger than this (and all video) go through a direct upload (POST /uploads) instead of
20
+ # the request body: the API's host caps request bodies at about 4.5 MB, multipart overhead included.
21
+ INLINE_UPLOAD_LIMIT = 4 * 1024 * 1024
19
22
 
20
23
  FileLike = Union[str, "os.PathLike[str]", bytes]
21
24
 
@@ -38,6 +41,9 @@ class MarkResult:
38
41
  # Populated when response_format="url". Short-lived (~1 hour) - download
39
42
  # promptly rather than caching it.
40
43
  file_url: Optional[str] = None
44
+ # Monthly-quota calls this mark used: 1 for an image or audio file, one per
45
+ # started second for video. None from servers that don't report it yet.
46
+ calls_used: Optional[int] = None
41
47
 
42
48
 
43
49
  @dataclass
@@ -93,6 +99,30 @@ def _kind_from_content_type(content_type: str) -> str:
93
99
  return "image"
94
100
 
95
101
 
102
+ _AUDIO_ONLY_BRANDS = {b"M4A ", b"M4B ", b"M4P ", b"F4A ", b"F4B "}
103
+
104
+
105
+ def _looks_like_video(data: bytes, content_type: str) -> bool:
106
+ """Video by MIME type, or by container (MP4/MOV/WebM), like the API's own sniff."""
107
+ if content_type.startswith("video/"):
108
+ return True
109
+ if len(data) < 12:
110
+ return False
111
+ box = data[4:8]
112
+ if box == b"ftyp":
113
+ return data[8:12] not in _AUDIO_ONLY_BRANDS
114
+ if box in (b"moov", b"mdat", b"wide", b"free", b"skip"):
115
+ return True
116
+ return data[:4] == b"\x1a\x45\xdf\xa3"
117
+
118
+
119
+ def _calls_used(value: object) -> Optional[int]:
120
+ try:
121
+ return int(value) if value is not None else None
122
+ except (TypeError, ValueError):
123
+ return None
124
+
125
+
96
126
  def _resolve_file(file: FileLike, filename: Optional[str]) -> tuple[bytes, str, str]:
97
127
  """Returns (data, filename, content_type)."""
98
128
  if isinstance(file, (bytes, bytearray)):
@@ -132,46 +162,99 @@ class Markproof:
132
162
  )
133
163
  raise MarkproofError(message, response.status_code, body)
134
164
 
165
+ def upload(self, file: FileLike, filename: Optional[str] = None) -> str:
166
+ """Uploads a file straight to Markproof's storage and returns its ``upload_id``.
167
+
168
+ For files over the ~4.5 MB request limit, video above all. ``mark()`` and
169
+ ``verify()`` do this automatically; call it yourself to upload once and then
170
+ pass ``upload_id=`` (each upload can be marked or verified once, and unused
171
+ uploads are deleted after 24 hours). Up to 100 MB.
172
+ """
173
+ data, _, content_type = _resolve_file(file, filename)
174
+ return self._upload_bytes(data, content_type)
175
+
176
+ def _upload_bytes(self, data: bytes, content_type: str) -> str:
177
+ response = self._session.post(f"{self._base_url}/uploads", headers=self._headers())
178
+ if response.status_code == 404:
179
+ raise MarkproofError(
180
+ "Direct uploads aren't available on this server yet: send files under ~4.5 MB, or pass url=.",
181
+ 404,
182
+ None,
183
+ )
184
+ self._raise_if_error(response)
185
+ body = response.json()
186
+ put = self._session.put(body["upload_url"], data=data, headers={"Content-Type": content_type})
187
+ if not put.ok:
188
+ raise MarkproofError(f"Upload failed (status {put.status_code}).", put.status_code, put.text)
189
+ return body["upload_id"]
190
+
135
191
  def mark(
136
192
  self,
137
- file: FileLike,
193
+ file: Optional[FileLike] = None,
138
194
  filename: Optional[str] = None,
139
195
  generator_name: Optional[str] = None,
140
196
  model_name: Optional[str] = None,
141
- response_format: str = "file",
197
+ response_format: Optional[str] = None,
142
198
  visible_label: Union[bool, str, None] = None,
143
199
  label_position: Optional[str] = None,
200
+ *,
201
+ url: Optional[str] = None,
202
+ upload_id: Optional[str] = None,
144
203
  ) -> MarkResult:
145
204
  """Watermarks (and, if the server has C2PA signing configured, signs) a file.
146
205
 
147
- response_format="file" (default) returns the marked bytes inline
148
- (result.file/result.content_type). "url" returns a short-lived
149
- signed download URL instead (result.file_url).
206
+ Pass exactly one of ``file`` (a path or bytes), ``url`` (https, up to 25 MB)
207
+ or ``upload_id`` (from ``upload()``). Video, and any file over ~4 MB, is
208
+ sent through a direct upload automatically.
209
+
210
+ response_format="file" returns the marked bytes inline
211
+ (result.file/result.content_type); "url" returns a short-lived signed
212
+ download URL instead (result.file_url). Default: "url" for video and
213
+ uploads (marked video is too big to return inline), "file" otherwise.
150
214
 
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,
215
+ visible_label (images only; the API returns 400 for audio and video): True
216
+ draws a visible "AI-generated" label (EU AI Act Art. 50(4)) before marking,
153
217
  or pass your own text (max 40 characters). label_position:
154
218
  "bottom-right" (default), "bottom-left", "top-right" or "top-left".
155
219
  """
156
- data, resolved_filename, content_type = _resolve_file(file, filename)
157
- form_data = {}
220
+ if sum(x is not None for x in (file, url, upload_id)) != 1:
221
+ raise ValueError("Pass exactly one of file, url or upload_id.")
222
+
223
+ fields: dict = {}
158
224
  if generator_name:
159
- form_data["generator_name"] = generator_name
225
+ fields["generator_name"] = generator_name
160
226
  if model_name:
161
- form_data["model_name"] = model_name
162
- if response_format == "url":
163
- form_data["response_format"] = "url"
227
+ fields["model_name"] = model_name
164
228
  if visible_label:
165
- form_data["visible_label"] = "true" if visible_label is True else visible_label
229
+ fields["visible_label"] = "true" if visible_label is True else visible_label
166
230
  if label_position:
167
- form_data["label_position"] = label_position
168
-
169
- response = self._session.post(
170
- f"{self._base_url}/mark",
171
- headers=self._headers(),
172
- files={"file": (resolved_filename, data, content_type)},
173
- data=form_data,
174
- )
231
+ fields["label_position"] = label_position
232
+
233
+ if file is not None:
234
+ data, resolved_filename, content_type = _resolve_file(file, filename)
235
+ # Video, and anything too big for one request, goes through an upload. Its marked
236
+ # file would be too big to come back inline as well, hence "url" by default.
237
+ direct = _looks_like_video(data, content_type) or len(data) > INLINE_UPLOAD_LIMIT
238
+ response_format = response_format or ("url" if direct else "file")
239
+ if direct:
240
+ upload_id = self._upload_bytes(data, content_type)
241
+ else:
242
+ if response_format == "url":
243
+ fields["response_format"] = "url"
244
+ response = self._session.post(
245
+ f"{self._base_url}/mark",
246
+ headers=self._headers(),
247
+ files={"file": (resolved_filename, data, content_type)},
248
+ data=fields,
249
+ )
250
+ if file is None or upload_id is not None:
251
+ response_format = response_format or ("url" if upload_id is not None else "file")
252
+ source = {"upload_id": upload_id} if upload_id is not None else {"url": url}
253
+ response = self._session.post(
254
+ f"{self._base_url}/mark",
255
+ headers=self._headers(),
256
+ json={**source, **fields, "response_format": response_format},
257
+ )
175
258
  self._raise_if_error(response)
176
259
 
177
260
  if response_format == "url":
@@ -184,6 +267,7 @@ class Markproof:
184
267
  c2pa_manifest_label=body.get("c2pa_manifest_label"),
185
268
  watermark_robust=body.get("watermark_robust"),
186
269
  file_url=body["file_url"],
270
+ calls_used=_calls_used(body.get("calls_used", response.headers.get("x-calls-used"))),
187
271
  )
188
272
 
189
273
  response_content_type = response.headers.get("content-type", "")
@@ -196,16 +280,38 @@ class Markproof:
196
280
  watermark_robust={"true": True, "false": False}.get(response.headers.get("x-watermark-robust", "")),
197
281
  content_type=response_content_type,
198
282
  file=response.content,
283
+ calls_used=_calls_used(response.headers.get("x-calls-used")),
199
284
  )
200
285
 
201
- def verify(self, file: FileLike, filename: Optional[str] = None) -> VerifyResult:
202
- """Checks a file for our watermark and/or a C2PA manifest."""
203
- data, resolved_filename, content_type = _resolve_file(file, filename)
204
- response = self._session.post(
205
- f"{self._base_url}/verify",
206
- headers=self._headers(),
207
- files={"file": (resolved_filename, data, content_type)},
208
- )
286
+ def verify(
287
+ self,
288
+ file: Optional[FileLike] = None,
289
+ filename: Optional[str] = None,
290
+ *,
291
+ url: Optional[str] = None,
292
+ upload_id: Optional[str] = None,
293
+ ) -> VerifyResult:
294
+ """Checks a file for our watermark and/or a C2PA manifest.
295
+
296
+ Pass exactly one of ``file``, ``url`` (https, up to 25 MB) or ``upload_id``.
297
+ Video and files over ~4 MB (marked audio, for example, comes back as WAV)
298
+ go through a direct upload automatically.
299
+ """
300
+ if sum(x is not None for x in (file, url, upload_id)) != 1:
301
+ raise ValueError("Pass exactly one of file, url or upload_id.")
302
+ if file is not None:
303
+ data, resolved_filename, content_type = _resolve_file(file, filename)
304
+ if _looks_like_video(data, content_type) or len(data) > INLINE_UPLOAD_LIMIT:
305
+ upload_id = self._upload_bytes(data, content_type)
306
+ else:
307
+ response = self._session.post(
308
+ f"{self._base_url}/verify",
309
+ headers=self._headers(),
310
+ files={"file": (resolved_filename, data, content_type)},
311
+ )
312
+ if file is None or upload_id is not None:
313
+ source = {"upload_id": upload_id} if upload_id is not None else {"url": url}
314
+ response = self._session.post(f"{self._base_url}/verify", headers=self._headers(), json=source)
209
315
  self._raise_if_error(response)
210
316
  body = response.json()
211
317
  return VerifyResult(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: markproof
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Python client for the Markproof API - EU AI Act Article 50 watermarking and verification.
5
5
  Author-email: Markproof <support@markproof.co>
6
6
  License-Expression: MIT
@@ -48,12 +48,23 @@ print(result.summary)
48
48
  ## API
49
49
 
50
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)` → `VerifyResult` — `watermark`/`c2pa` detection results, `matched_asset` if the watermark matches a record in Markproof's database, and a human-readable `summary`.
51
+ - `client.mark(file, filename=None, generator_name=None, model_name=None, response_format=None, 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"` (the default for small images and audio) 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
53
  - `client.get_asset(asset_id)` → `Asset` — requires an API key on the same project that created the asset.
54
54
 
55
55
  All methods raise `MarkproofError` (with `.status` and `.body`) on a non-2xx response.
56
56
 
57
+ ### Video and large files (launches with video)
58
+
59
+ `mark` and `verify` also take `url=` (https, up to 25 MB) or `upload_id=` instead of `file`. Video, and any
60
+ file over about 4 MB, is sent through a direct upload automatically: the SDK asks the API for a signed
61
+ upload URL, PUTs the file straight to storage (up to 100 MB), then marks or verifies it by id. For these,
62
+ `response_format` defaults to `"url"`, because the marked file is too big to come back inline. Call
63
+ `client.upload(file, filename=None)` → `upload_id` to do the upload yourself; each upload can be used
64
+ once. `result.calls_used` says how many quota calls a mark used: 1 per image or audio file, one per
65
+ started second of video. Until video launches, the upload step fails with a 404 `MarkproofError`
66
+ saying so; pass `url=` for big files meanwhile.
67
+
57
68
  ## Batches and webhooks
58
69
 
59
70
  For volume, queue many files at once instead of calling `mark` per file. Each item counts as one mark.
@@ -13,4 +13,5 @@ markproof.egg-info/requires.txt
13
13
  markproof.egg-info/top_level.txt
14
14
  tests/test_batches.py
15
15
  tests/test_client.py
16
+ tests/test_uploads.py
16
17
  tests/test_webhooks.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "markproof"
7
- version = "0.2.0"
7
+ version = "0.4.0"
8
8
  description = "Python client for the Markproof API - EU AI Act Article 50 watermarking and verification."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,249 +1,278 @@
1
- import pytest
2
- import responses
3
-
4
- from markproof import Markproof, MarkproofError
5
-
6
- API_KEY = "lt_test_abc123"
7
- BASE_URL = "http://localhost:3000/api/v1"
8
-
9
-
10
- @pytest.fixture
11
- def client():
12
- return Markproof(api_key=API_KEY, base_url=BASE_URL)
13
-
14
-
15
- def test_requires_api_key():
16
- with pytest.raises(ValueError, match="api_key is required"):
17
- Markproof(api_key="")
18
-
19
-
20
- def test_strips_trailing_slash():
21
- client = Markproof(api_key=API_KEY, base_url="http://localhost:3000/api/v1/")
22
- assert client._base_url == "http://localhost:3000/api/v1"
23
-
24
-
25
- @responses.activate
26
- def test_mark_parses_binary_response_and_headers(client):
27
- file_bytes = b"\x01\x02\x03\x04"
28
- responses.add(
29
- responses.POST,
30
- f"{BASE_URL}/mark",
31
- body=file_bytes,
32
- status=200,
33
- content_type="image/png",
34
- headers={
35
- "x-asset-id": "asset-1",
36
- "x-watermark-code": "ABC12345",
37
- "x-verify-url": "https://markproof.co/v/ABC12345",
38
- "x-c2pa-manifest-label": "urn:c2pa:xyz",
39
- },
40
- )
41
-
42
- result = client.mark(file_bytes, filename="test.png")
43
-
44
- assert result.content_type == "image/png"
45
- assert result.asset_id == "asset-1"
46
- assert result.watermark_code == "ABC12345"
47
- assert result.kind == "image"
48
- assert result.verify_url == "https://markproof.co/v/ABC12345"
49
- assert result.c2pa_manifest_label == "urn:c2pa:xyz"
50
- assert result.file == file_bytes
51
-
52
- sent = responses.calls[0].request
53
- assert sent.headers["Authorization"] == f"Bearer {API_KEY}"
54
-
55
-
56
- @responses.activate
57
- def test_mark_requires_filename_for_raw_bytes(client):
58
- with pytest.raises(ValueError, match="filename is required"):
59
- client.mark(b"abc")
60
-
61
-
62
- @responses.activate
63
- def test_mark_detects_audio_from_content_type(client):
64
- responses.add(
65
- responses.POST,
66
- f"{BASE_URL}/mark",
67
- body=b"\x00",
68
- status=200,
69
- content_type="audio/wav",
70
- headers={
71
- "x-asset-id": "a",
72
- "x-watermark-code": "b",
73
- "x-verify-url": "c",
74
- },
75
- )
76
- result = client.mark(b"fake-wav-bytes", filename="test.wav")
77
- assert result.content_type == "audio/wav"
78
- assert result.kind == "audio"
79
- # Audio isn't self-checked, so the API omits the header.
80
- assert result.watermark_robust is None
81
-
82
-
83
- @responses.activate
84
- def test_mark_parses_watermark_robust_header(client):
85
- responses.add(
86
- responses.POST,
87
- f"{BASE_URL}/mark",
88
- body=b"\x00",
89
- status=200,
90
- content_type="image/png",
91
- headers={"x-asset-id": "a", "x-watermark-code": "b", "x-verify-url": "c", "x-watermark-robust": "false"},
92
- )
93
- assert client.mark(b"img", filename="x.png").watermark_robust is False
94
-
95
-
96
- @responses.activate
97
- def test_mark_raises_markproof_error_with_server_message(client):
98
- responses.add(
99
- responses.POST,
100
- f"{BASE_URL}/mark",
101
- json={"error": "Monthly quota exceeded (10/10)."},
102
- status=429,
103
- )
104
- with pytest.raises(MarkproofError) as exc_info:
105
- client.mark(b"abc", filename="test.png")
106
- assert exc_info.value.status == 429
107
- assert str(exc_info.value) == "Monthly quota exceeded (10/10)."
108
-
109
-
110
- @responses.activate
111
- def test_mark_with_response_format_url(client):
112
- responses.add(
113
- responses.POST,
114
- f"{BASE_URL}/mark",
115
- json={
116
- "asset_id": "asset-1",
117
- "watermark_code": "ABC12345",
118
- "kind": "image",
119
- "verify_url": "https://markproof.co/v/ABC12345",
120
- "c2pa_manifest_label": "urn:c2pa:xyz",
121
- "file_url": "https://storage.example/signed-url",
122
- },
123
- status=200,
124
- )
125
- result = client.mark(b"abc", filename="test.png", response_format="url")
126
-
127
- assert result.file_url == "https://storage.example/signed-url"
128
- assert result.file is None
129
- assert result.asset_id == "asset-1"
130
-
131
- sent = responses.calls[0].request
132
- assert b'name="response_format"' in sent.body
133
-
134
-
135
- def _ok_image_response():
136
- responses.add(
137
- responses.POST,
138
- f"{BASE_URL}/mark",
139
- body=b"\x00",
140
- status=200,
141
- content_type="image/png",
142
- headers={"x-asset-id": "a", "x-watermark-code": "b", "x-verify-url": "c"},
143
- )
144
-
145
-
146
- @responses.activate
147
- def test_mark_sends_visible_label_true_and_position(client):
148
- _ok_image_response()
149
- client.mark(b"img", filename="x.png", visible_label=True, label_position="top-left")
150
- body = responses.calls[0].request.body
151
- assert b'name="visible_label"\r\n\r\ntrue\r\n' in body
152
- assert b'name="label_position"\r\n\r\ntop-left\r\n' in body
153
-
154
-
155
- @responses.activate
156
- def test_mark_sends_custom_visible_label(client):
157
- _ok_image_response()
158
- client.mark(b"img", filename="x.png", visible_label="Généré par IA")
159
- body = responses.calls[0].request.body
160
- assert 'name="visible_label"\r\n\r\nGénéré par IA\r\n'.encode() in body
161
- assert b'name="label_position"' not in body
162
-
163
-
164
- @responses.activate
165
- def test_mark_omits_label_fields_by_default(client):
166
- _ok_image_response()
167
- client.mark(b"img", filename="x.png", label_position="top-left")
168
- body = responses.calls[0].request.body
169
- assert b'name="visible_label"' not in body
170
- assert b'name="label_position"' not in body
171
-
172
-
173
- @responses.activate
174
- def test_verify_converts_snake_case_response(client):
175
- responses.add(
176
- responses.POST,
177
- f"{BASE_URL}/verify",
178
- json={
179
- "watermark": {"detected": True, "watermark_code": "ABC12345", "confidence": None},
180
- "c2pa": {"present": True, "signature_valid": True, "trusted": False, "manifest_label": "urn:c2pa:xyz"},
181
- "matched_asset": {
182
- "id": "asset-1",
183
- "watermark_code": "ABC12345",
184
- "kind": "image",
185
- "generator_name": "midjourney",
186
- "model_name": "v7",
187
- "c2pa_manifest_label": "urn:c2pa:xyz",
188
- "created_at": "2026-10-25T00:00:00Z",
189
- },
190
- "summary": "Watermark detected code ABC12345, matches our record.",
191
- },
192
- status=200,
193
- )
194
- result = client.verify(b"abc", filename="test.png")
195
-
196
- assert result.watermark.detected is True
197
- assert result.watermark.watermark_code == "ABC12345"
198
- assert result.c2pa.trusted is False
199
- assert result.matched_asset is not None
200
- assert result.matched_asset.generator_name == "midjourney"
201
-
202
-
203
- @responses.activate
204
- def test_verify_handles_no_matched_asset(client):
205
- responses.add(
206
- responses.POST,
207
- f"{BASE_URL}/verify",
208
- json={
209
- "watermark": {"detected": False, "watermark_code": None, "confidence": None},
210
- "c2pa": {"present": False, "signature_valid": None, "trusted": None, "manifest_label": None},
211
- "matched_asset": None,
212
- "summary": "No watermark detected.",
213
- },
214
- status=200,
215
- )
216
- result = client.verify(b"abc", filename="test.png")
217
- assert result.matched_asset is None
218
-
219
-
220
- @responses.activate
221
- def test_get_asset(client):
222
- responses.add(
223
- responses.GET,
224
- f"{BASE_URL}/assets/asset-1",
225
- json={
226
- "id": "asset-1",
227
- "watermark_code": "ABC12345",
228
- "kind": "image",
229
- "generator_name": None,
230
- "model_name": None,
231
- "c2pa_manifest_label": None,
232
- "created_at": "2026-10-25T00:00:00Z",
233
- },
234
- status=200,
235
- )
236
- asset = client.get_asset("asset-1")
237
- assert asset.id == "asset-1"
238
-
239
-
240
- @responses.activate
241
- def test_get_asset_url_encodes_id(client):
242
- responses.add(
243
- responses.GET,
244
- f"{BASE_URL}/assets/weird%2Fid",
245
- json={"error": "Not found."},
246
- status=404,
247
- )
248
- with pytest.raises(MarkproofError):
249
- client.get_asset("weird/id")
1
+ import json
2
+
3
+ import pytest
4
+ import responses
5
+
6
+ from markproof import Markproof, MarkproofError
7
+
8
+ API_KEY = "lt_test_abc123"
9
+ BASE_URL = "http://localhost:3000/api/v1"
10
+
11
+
12
+ @pytest.fixture
13
+ def client():
14
+ return Markproof(api_key=API_KEY, base_url=BASE_URL)
15
+
16
+
17
+ def test_requires_api_key():
18
+ with pytest.raises(ValueError, match="api_key is required"):
19
+ Markproof(api_key="")
20
+
21
+
22
+ def test_strips_trailing_slash():
23
+ client = Markproof(api_key=API_KEY, base_url="http://localhost:3000/api/v1/")
24
+ assert client._base_url == "http://localhost:3000/api/v1"
25
+
26
+
27
+ @responses.activate
28
+ def test_mark_parses_binary_response_and_headers(client):
29
+ file_bytes = b"\x01\x02\x03\x04"
30
+ responses.add(
31
+ responses.POST,
32
+ f"{BASE_URL}/mark",
33
+ body=file_bytes,
34
+ status=200,
35
+ content_type="image/png",
36
+ headers={
37
+ "x-asset-id": "asset-1",
38
+ "x-watermark-code": "ABC12345",
39
+ "x-verify-url": "https://markproof.co/v/ABC12345",
40
+ "x-c2pa-manifest-label": "urn:c2pa:xyz",
41
+ },
42
+ )
43
+
44
+ result = client.mark(file_bytes, filename="test.png")
45
+
46
+ assert result.content_type == "image/png"
47
+ assert result.asset_id == "asset-1"
48
+ assert result.watermark_code == "ABC12345"
49
+ assert result.kind == "image"
50
+ assert result.verify_url == "https://markproof.co/v/ABC12345"
51
+ assert result.c2pa_manifest_label == "urn:c2pa:xyz"
52
+ assert result.file == file_bytes
53
+
54
+ sent = responses.calls[0].request
55
+ assert sent.headers["Authorization"] == f"Bearer {API_KEY}"
56
+
57
+
58
+ @responses.activate
59
+ def test_mark_requires_filename_for_raw_bytes(client):
60
+ with pytest.raises(ValueError, match="filename is required"):
61
+ client.mark(b"abc")
62
+
63
+
64
+ @responses.activate
65
+ def test_mark_detects_audio_from_content_type(client):
66
+ responses.add(
67
+ responses.POST,
68
+ f"{BASE_URL}/mark",
69
+ body=b"\x00",
70
+ status=200,
71
+ content_type="audio/wav",
72
+ headers={
73
+ "x-asset-id": "a",
74
+ "x-watermark-code": "b",
75
+ "x-verify-url": "c",
76
+ },
77
+ )
78
+ result = client.mark(b"fake-wav-bytes", filename="test.wav")
79
+ assert result.content_type == "audio/wav"
80
+ assert result.kind == "audio"
81
+ # Audio isn't self-checked, so the API omits the header.
82
+ assert result.watermark_robust is None
83
+
84
+
85
+ @responses.activate
86
+ def test_mark_parses_watermark_robust_header(client):
87
+ responses.add(
88
+ responses.POST,
89
+ f"{BASE_URL}/mark",
90
+ body=b"\x00",
91
+ status=200,
92
+ content_type="image/png",
93
+ headers={"x-asset-id": "a", "x-watermark-code": "b", "x-verify-url": "c", "x-watermark-robust": "false"},
94
+ )
95
+ assert client.mark(b"img", filename="x.png").watermark_robust is False
96
+
97
+
98
+ @responses.activate
99
+ def test_mark_raises_markproof_error_with_server_message(client):
100
+ responses.add(
101
+ responses.POST,
102
+ f"{BASE_URL}/mark",
103
+ json={"error": "Monthly quota exceeded (10/10)."},
104
+ status=429,
105
+ )
106
+ with pytest.raises(MarkproofError) as exc_info:
107
+ client.mark(b"abc", filename="test.png")
108
+ assert exc_info.value.status == 429
109
+ assert str(exc_info.value) == "Monthly quota exceeded (10/10)."
110
+
111
+
112
+ @responses.activate
113
+ def test_mark_with_response_format_url(client):
114
+ responses.add(
115
+ responses.POST,
116
+ f"{BASE_URL}/mark",
117
+ json={
118
+ "asset_id": "asset-1",
119
+ "watermark_code": "ABC12345",
120
+ "kind": "image",
121
+ "verify_url": "https://markproof.co/v/ABC12345",
122
+ "c2pa_manifest_label": "urn:c2pa:xyz",
123
+ "file_url": "https://storage.example/signed-url",
124
+ },
125
+ status=200,
126
+ )
127
+ result = client.mark(b"abc", filename="test.png", response_format="url")
128
+
129
+ assert result.file_url == "https://storage.example/signed-url"
130
+ assert result.file is None
131
+ assert result.asset_id == "asset-1"
132
+
133
+ sent = responses.calls[0].request
134
+ assert b'name="response_format"' in sent.body
135
+
136
+
137
+ def _ok_image_response():
138
+ responses.add(
139
+ responses.POST,
140
+ f"{BASE_URL}/mark",
141
+ body=b"\x00",
142
+ status=200,
143
+ content_type="image/png",
144
+ headers={"x-asset-id": "a", "x-watermark-code": "b", "x-verify-url": "c"},
145
+ )
146
+
147
+
148
+ @responses.activate
149
+ def test_mark_sends_visible_label_true_and_position(client):
150
+ _ok_image_response()
151
+ client.mark(b"img", filename="x.png", visible_label=True, label_position="top-left")
152
+ body = responses.calls[0].request.body
153
+ assert b'name="visible_label"\r\n\r\ntrue\r\n' in body
154
+ assert b'name="label_position"\r\n\r\ntop-left\r\n' in body
155
+
156
+
157
+ @responses.activate
158
+ def test_mark_sends_custom_visible_label(client):
159
+ _ok_image_response()
160
+ client.mark(b"img", filename="x.png", visible_label="Généré par IA")
161
+ body = responses.calls[0].request.body
162
+ assert 'name="visible_label"\r\n\r\nGénéré par IA\r\n'.encode() in body
163
+ assert b'name="label_position"' not in body
164
+
165
+
166
+ @responses.activate
167
+ def test_mark_omits_label_fields_by_default(client):
168
+ _ok_image_response()
169
+ client.mark(b"img", filename="x.png", label_position="top-left")
170
+ body = responses.calls[0].request.body
171
+ assert b'name="visible_label"' not in body
172
+ assert b'name="label_position"' not in body
173
+
174
+
175
+ @responses.activate
176
+ def test_verify_converts_snake_case_response(client):
177
+ responses.add(
178
+ responses.POST,
179
+ f"{BASE_URL}/verify",
180
+ json={
181
+ "watermark": {"detected": True, "watermark_code": "ABC12345", "confidence": None},
182
+ "c2pa": {"present": True, "signature_valid": True, "trusted": False, "manifest_label": "urn:c2pa:xyz"},
183
+ "matched_asset": {
184
+ "id": "asset-1",
185
+ "watermark_code": "ABC12345",
186
+ "kind": "image",
187
+ "generator_name": "midjourney",
188
+ "model_name": "v7",
189
+ "c2pa_manifest_label": "urn:c2pa:xyz",
190
+ "created_at": "2026-10-25T00:00:00Z",
191
+ },
192
+ "summary": "Watermark detected code ABC12345, matches our record.",
193
+ },
194
+ status=200,
195
+ )
196
+ result = client.verify(b"abc", filename="test.png")
197
+
198
+ assert result.watermark.detected is True
199
+ assert result.watermark.watermark_code == "ABC12345"
200
+ assert result.c2pa.trusted is False
201
+ assert result.matched_asset is not None
202
+ assert result.matched_asset.generator_name == "midjourney"
203
+
204
+
205
+ @responses.activate
206
+ def test_verify_handles_no_matched_asset(client):
207
+ responses.add(
208
+ responses.POST,
209
+ f"{BASE_URL}/verify",
210
+ json={
211
+ "watermark": {"detected": False, "watermark_code": None, "confidence": None},
212
+ "c2pa": {"present": False, "signature_valid": None, "trusted": None, "manifest_label": None},
213
+ "matched_asset": None,
214
+ "summary": "No watermark detected.",
215
+ },
216
+ status=200,
217
+ )
218
+ result = client.verify(b"abc", filename="test.png")
219
+ assert result.matched_asset is None
220
+
221
+
222
+ @responses.activate
223
+ def test_verify_by_url_sends_json(client):
224
+ responses.add(
225
+ responses.POST,
226
+ f"{BASE_URL}/verify",
227
+ json={
228
+ "watermark": {"detected": True, "watermark_code": None, "confidence": 0.98},
229
+ "c2pa": {"present": True, "signature_valid": True, "trusted": False, "manifest_label": "urn:c2pa:x"},
230
+ "matched_asset": None,
231
+ "summary": "Watermark detected.",
232
+ },
233
+ status=200,
234
+ )
235
+ result = client.verify(url="https://cdn.example.com/a.wav")
236
+ sent = responses.calls[0].request
237
+ assert sent.headers["Content-Type"] == "application/json"
238
+ assert json.loads(sent.body) == {"url": "https://cdn.example.com/a.wav"}
239
+ assert result.watermark.confidence == 0.98
240
+
241
+
242
+ def test_verify_needs_exactly_one_input(client):
243
+ with pytest.raises(ValueError):
244
+ client.verify()
245
+ with pytest.raises(ValueError):
246
+ client.verify(b"abc", url="https://cdn.example.com/a.wav")
247
+
248
+
249
+ @responses.activate
250
+ def test_get_asset(client):
251
+ responses.add(
252
+ responses.GET,
253
+ f"{BASE_URL}/assets/asset-1",
254
+ json={
255
+ "id": "asset-1",
256
+ "watermark_code": "ABC12345",
257
+ "kind": "image",
258
+ "generator_name": None,
259
+ "model_name": None,
260
+ "c2pa_manifest_label": None,
261
+ "created_at": "2026-10-25T00:00:00Z",
262
+ },
263
+ status=200,
264
+ )
265
+ asset = client.get_asset("asset-1")
266
+ assert asset.id == "asset-1"
267
+
268
+
269
+ @responses.activate
270
+ def test_get_asset_url_encodes_id(client):
271
+ responses.add(
272
+ responses.GET,
273
+ f"{BASE_URL}/assets/weird%2Fid",
274
+ json={"error": "Not found."},
275
+ status=404,
276
+ )
277
+ with pytest.raises(MarkproofError):
278
+ client.get_asset("weird/id")
@@ -0,0 +1,153 @@
1
+ import json
2
+
3
+ import pytest
4
+ import responses
5
+
6
+ from markproof import Markproof, MarkproofError
7
+ from markproof.client import INLINE_UPLOAD_LIMIT
8
+
9
+ API_KEY = "lt_test_abc123"
10
+ BASE_URL = "http://localhost:3000/api/v1"
11
+ UPLOAD_URL = "https://storage.example/upload/sign/tool1-uploads/p/u?token=t"
12
+ UPLOAD_ID = "3f2b8c1e-9a4d-4c7e-8b21-5d6f7a8b9c0d"
13
+ MP4 = b"\x00\x00\x00\x18ftypisom\x00\x00\x02\x00isomiso2" + b"\x00" * 64
14
+ MARKED_URL_BODY = {
15
+ "asset_id": "asset-1",
16
+ "watermark_code": "ABC12345",
17
+ "kind": "video",
18
+ "verify_url": "https://markproof.co/v/ABC12345",
19
+ "c2pa_manifest_label": "urn:c2pa:xyz",
20
+ "watermark_robust": True,
21
+ "file_url": "https://storage.example/signed",
22
+ "calls_used": 6,
23
+ }
24
+
25
+
26
+ @pytest.fixture
27
+ def client():
28
+ return Markproof(api_key=API_KEY, base_url=BASE_URL)
29
+
30
+
31
+ def _upload_routes():
32
+ responses.add(
33
+ responses.POST,
34
+ f"{BASE_URL}/uploads",
35
+ json={"upload_id": UPLOAD_ID, "upload_url": UPLOAD_URL, "upload_method": "PUT"},
36
+ status=201,
37
+ )
38
+ responses.add(responses.PUT, UPLOAD_URL, status=200)
39
+
40
+
41
+ @responses.activate
42
+ def test_upload_starts_puts_and_returns_the_id(client):
43
+ _upload_routes()
44
+ assert client.upload(MP4, filename="clip.mp4") == UPLOAD_ID
45
+
46
+ start, put = responses.calls[0].request, responses.calls[1].request
47
+ assert start.headers["Authorization"] == f"Bearer {API_KEY}"
48
+ assert put.body == MP4
49
+ assert put.headers["Content-Type"] == "video/mp4"
50
+ assert "Authorization" not in put.headers # the signed URL is the credential
51
+
52
+
53
+ @responses.activate
54
+ def test_mark_sends_video_through_an_upload_and_defaults_to_url(client):
55
+ _upload_routes()
56
+ responses.add(responses.POST, f"{BASE_URL}/mark", json=MARKED_URL_BODY, status=200)
57
+
58
+ result = client.mark(MP4, filename="clip.mp4", generator_name="kling")
59
+
60
+ assert result.kind == "video"
61
+ assert result.file_url == "https://storage.example/signed"
62
+ assert result.calls_used == 6
63
+ body = json.loads(responses.calls[2].request.body)
64
+ assert body == {"upload_id": UPLOAD_ID, "generator_name": "kling", "response_format": "url"}
65
+
66
+
67
+ @responses.activate
68
+ def test_video_is_sniffed_even_without_a_video_filename(client):
69
+ _upload_routes()
70
+ responses.add(responses.POST, f"{BASE_URL}/mark", json=MARKED_URL_BODY, status=200)
71
+ client.mark(MP4, filename="render.bin")
72
+ assert [c.request.method for c in responses.calls] == ["POST", "PUT", "POST"]
73
+
74
+
75
+ @responses.activate
76
+ def test_large_images_go_through_an_upload_too(client):
77
+ _upload_routes()
78
+ responses.add(responses.POST, f"{BASE_URL}/mark", json={**MARKED_URL_BODY, "kind": "image", "calls_used": 1}, status=200)
79
+ big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (INLINE_UPLOAD_LIMIT + 1)
80
+
81
+ result = client.mark(big, filename="big.png")
82
+
83
+ assert result.calls_used == 1
84
+ assert json.loads(responses.calls[2].request.body)["response_format"] == "url"
85
+
86
+
87
+ @responses.activate
88
+ def test_small_images_stay_inline_and_read_x_calls_used(client):
89
+ responses.add(
90
+ responses.POST,
91
+ f"{BASE_URL}/mark",
92
+ body=b"\x00",
93
+ status=200,
94
+ content_type="image/png",
95
+ headers={"x-asset-id": "a", "x-watermark-code": "b", "x-verify-url": "c", "x-calls-used": "1"},
96
+ )
97
+ result = client.mark(b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00", filename="a.png")
98
+ assert result.calls_used == 1
99
+ assert len(responses.calls) == 1
100
+
101
+
102
+ @responses.activate
103
+ def test_mark_by_url_and_by_upload_id(client):
104
+ responses.add(responses.POST, f"{BASE_URL}/mark", json=MARKED_URL_BODY, status=200)
105
+ responses.add(responses.POST, f"{BASE_URL}/mark", json=MARKED_URL_BODY, status=200)
106
+
107
+ client.mark(url="https://cdn.example.com/clip.mp4", response_format="url")
108
+ client.mark(upload_id=UPLOAD_ID)
109
+
110
+ assert json.loads(responses.calls[0].request.body) == {"url": "https://cdn.example.com/clip.mp4", "response_format": "url"}
111
+ assert json.loads(responses.calls[1].request.body) == {"upload_id": UPLOAD_ID, "response_format": "url"}
112
+
113
+
114
+ def test_mark_needs_exactly_one_source(client):
115
+ with pytest.raises(ValueError, match="exactly one"):
116
+ client.mark()
117
+ with pytest.raises(ValueError, match="exactly one"):
118
+ client.mark(b"x", filename="a.png", url="https://x")
119
+
120
+
121
+ @responses.activate
122
+ def test_uploads_not_live_yet_gives_a_clear_error(client):
123
+ responses.add(responses.POST, f"{BASE_URL}/uploads", json={"error": "Not found."}, status=404)
124
+ with pytest.raises(MarkproofError, match="aren't available") as err:
125
+ client.mark(MP4, filename="clip.mp4")
126
+ assert err.value.status == 404
127
+
128
+
129
+ @responses.activate
130
+ def test_a_failed_put_raises(client):
131
+ responses.add(responses.POST, f"{BASE_URL}/uploads", json={"upload_id": UPLOAD_ID, "upload_url": UPLOAD_URL}, status=201)
132
+ responses.add(responses.PUT, UPLOAD_URL, status=400, body="too big")
133
+ with pytest.raises(MarkproofError, match="Upload failed"):
134
+ client.upload(MP4, filename="clip.mp4")
135
+
136
+
137
+ @responses.activate
138
+ def test_verify_uploads_video_and_verifies_by_id(client):
139
+ _upload_routes()
140
+ responses.add(
141
+ responses.POST,
142
+ f"{BASE_URL}/verify",
143
+ json={
144
+ "watermark": {"detected": True, "watermark_code": "ABC12345", "confidence": 0.98},
145
+ "c2pa": {"present": False, "signature_valid": None, "trusted": None, "manifest_label": None},
146
+ "matched_asset": None,
147
+ "summary": "Watermark detected code ABC12345.",
148
+ },
149
+ status=200,
150
+ )
151
+ result = client.verify(MP4, filename="clip.mp4")
152
+ assert result.watermark.watermark_code == "ABC12345"
153
+ assert json.loads(responses.calls[2].request.body) == {"upload_id": UPLOAD_ID}
File without changes
File without changes
File without changes