-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
787 lines (672 loc) · 24.4 KB
/
client.py
File metadata and controls
787 lines (672 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
"""
Main Capture SDK client.
"""
from __future__ import annotations
import json
import mimetypes
from pathlib import Path
from typing import Any
from urllib.parse import urlencode
import httpx
from .crypto import create_integrity_proof, sha256, sign_integrity_proof
from .errors import CaptureError, ValidationError, create_api_error
from .types import (
Asset,
AssetSearchOptions,
AssetSearchResult,
AssetTree,
CaptureOptions,
Commit,
FileInput,
License,
NftRecord,
NftSearchResult,
RegisterOptions,
SimilarMatch,
UpdateOptions,
)
DEFAULT_BASE_URL = "https://api.numbersprotocol.io/api/v3"
HISTORY_API_URL = "https://e23hi68y55.execute-api.us-east-1.amazonaws.com/default/get-commits-storage-backend-jade-near"
MERGE_TREE_API_URL = "https://us-central1-numbers-protocol-api.cloudfunctions.net/get-full-asset-tree"
ASSET_SEARCH_API_URL = "https://us-central1-numbers-protocol-api.cloudfunctions.net/asset-search"
NFT_SEARCH_API_URL = "https://eofveg1f59hrbn.m.pipedream.net"
# Common MIME types by extension
MIME_TYPES: dict[str, str] = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"webp": "image/webp",
"svg": "image/svg+xml",
"mp4": "video/mp4",
"webm": "video/webm",
"mov": "video/quicktime",
"mp3": "audio/mpeg",
"wav": "audio/wav",
"pdf": "application/pdf",
"json": "application/json",
"txt": "text/plain",
}
def _get_mime_type(filename: str) -> str:
"""Detects MIME type from filename extension."""
ext = Path(filename).suffix.lower().lstrip(".")
if ext in MIME_TYPES:
return MIME_TYPES[ext]
# Try system mimetypes
mime_type, _ = mimetypes.guess_type(filename)
return mime_type or "application/octet-stream"
def _normalize_file(
file_input: FileInput,
options: RegisterOptions | None = None,
) -> tuple[bytes, str, str]:
"""
Normalizes various file input types to a common format.
Returns:
Tuple of (data, filename, mime_type)
"""
# 1. String path
if isinstance(file_input, str):
path = Path(file_input)
if not path.exists():
raise ValidationError(f"File not found: {file_input}")
data = path.read_bytes()
filename = path.name
mime_type = _get_mime_type(filename)
return data, filename, mime_type
# 2. Path object
if isinstance(file_input, Path):
if not file_input.exists():
raise ValidationError(f"File not found: {file_input}")
data = file_input.read_bytes()
filename = file_input.name
mime_type = _get_mime_type(filename)
return data, filename, mime_type
# 3. bytes or bytearray
if isinstance(file_input, bytes | bytearray):
if not options or not options.filename:
raise ValidationError("filename is required for binary input")
data = bytes(file_input)
filename = options.filename
mime_type = _get_mime_type(filename)
return data, filename, mime_type
raise ValidationError(f"Unsupported file input type: {type(file_input)}")
def _to_asset(response: dict[str, Any]) -> Asset:
"""Converts API response to Asset type."""
return Asset(
nid=response["id"],
filename=response["asset_file_name"],
mime_type=response["asset_file_mime_type"],
caption=response.get("caption"),
headline=response.get("headline"),
)
class Capture:
"""
Main Capture SDK client.
Example:
>>> from numbersprotocol_capture import Capture
>>> capture = Capture(token="your-api-token")
>>> asset = capture.register("./photo.jpg", caption="My photo")
>>> print(asset.nid)
"""
def __init__(
self,
token: str | None = None,
*,
testnet: bool = False,
base_url: str | None = None,
options: CaptureOptions | None = None,
):
"""
Initialize the Capture client.
Args:
token: Authentication token for API access.
testnet: Use testnet environment (default: False).
base_url: Custom base URL (overrides testnet setting).
options: CaptureOptions object (alternative to individual args).
"""
if options:
token = options.token
testnet = options.testnet
base_url = options.base_url
if not token:
raise ValidationError("token is required")
if base_url is not None and not base_url.startswith("https://"):
raise ValidationError("base_url must use HTTPS")
self._token = token
self._testnet = testnet
self._base_url = base_url or DEFAULT_BASE_URL
self._client = httpx.Client(timeout=30.0)
def __enter__(self) -> Capture:
return self
def __exit__(self, *args: Any) -> None:
self.close()
def close(self) -> None:
"""Close the HTTP client."""
self._client.close()
def _request(
self,
method: str,
url: str,
*,
data: dict[str, Any] | None = None,
files: dict[str, Any] | None = None,
json_body: dict[str, Any] | None = None,
nid: str | None = None,
) -> dict[str, Any]:
"""Makes an authenticated API request."""
headers = {"Authorization": f"token {self._token}"}
try:
if files:
response = self._client.request(
method,
url,
headers=headers,
data=data,
files=files,
)
elif json_body:
headers["Content-Type"] = "application/json"
response = self._client.request(
method,
url,
headers=headers,
json=json_body,
)
else:
response = self._client.request(
method,
url,
headers=headers,
data=data,
)
except httpx.RequestError as e:
raise create_api_error(0, f"Network error: {e}", nid) from e
if not response.is_success:
message = f"API request failed with status {response.status_code}"
try:
error_data = response.json()
message = error_data.get("detail") or error_data.get("message") or message
except Exception:
pass
raise create_api_error(response.status_code, message, nid)
result: dict[str, Any] = response.json()
return result
def register(
self,
file: FileInput,
*,
filename: str | None = None,
caption: str | None = None,
headline: str | None = None,
public_access: bool = True,
sign: dict[str, str] | None = None,
options: RegisterOptions | None = None,
) -> Asset:
"""
Registers a new asset.
Args:
file: File to register (path, Path, bytes, or bytearray).
filename: Filename (required for bytes/bytearray inputs).
caption: Brief description of the asset.
headline: Asset title (max 25 characters).
public_access: Pin to public IPFS gateway (default: True).
sign: Signing configuration with 'private_key' key.
options: RegisterOptions object (alternative to individual args).
Returns:
Registered Asset information.
Example:
>>> # File path
>>> asset = capture.register("./photo.jpg")
>>>
>>> # With options
>>> asset = capture.register(
... "./photo.jpg",
... caption="My photo",
... headline="Demo"
... )
>>>
>>> # Binary data
>>> asset = capture.register(
... image_bytes,
... filename="image.png"
... )
"""
# Build options from args if not provided
if options is None:
from .types import SignOptions
sign_opts = SignOptions(private_key=sign["private_key"]) if sign else None
options = RegisterOptions(
filename=filename,
caption=caption,
headline=headline,
public_access=public_access,
sign=sign_opts,
)
# Validate headline length
if options.headline and len(options.headline) > 25:
raise ValidationError("headline must be 25 characters or less")
# Normalize file input
data, file_name, mime_type = _normalize_file(file, options)
if len(data) == 0:
raise ValidationError("file cannot be empty")
# Build form data
form_data: dict[str, Any] = {
"public_access": str(options.public_access).lower(),
}
if options.caption:
form_data["caption"] = options.caption
if options.headline:
form_data["headline"] = options.headline
# Handle signing if private key provided
if options.sign and options.sign.private_key:
proof_hash = sha256(data)
proof = create_integrity_proof(proof_hash, mime_type)
signature = sign_integrity_proof(proof, options.sign.private_key)
proof_dict = {
"proof_hash": proof.proof_hash,
"asset_mime_type": proof.asset_mime_type,
"created_at": proof.created_at,
}
form_data["signed_metadata"] = json.dumps(proof_dict)
sig_dict = {
"proofHash": signature.proof_hash,
"provider": signature.provider,
"signature": signature.signature,
"publicKey": signature.public_key,
"integritySha": signature.integrity_sha,
}
form_data["signature"] = json.dumps([sig_dict])
files = {"asset_file": (file_name, data, mime_type)}
response = self._request(
"POST",
f"{self._base_url}/assets/",
data=form_data,
files=files,
)
return _to_asset(response)
def update(
self,
nid: str,
*,
caption: str | None = None,
headline: str | None = None,
commit_message: str | None = None,
custom_metadata: dict[str, Any] | None = None,
options: UpdateOptions | None = None,
) -> Asset:
"""
Updates an existing asset's metadata.
Args:
nid: Numbers ID of the asset to update.
caption: Updated description.
headline: Updated title (max 25 characters).
commit_message: Description of the changes.
custom_metadata: Custom metadata fields.
options: UpdateOptions object (alternative to individual args).
Returns:
Updated Asset information.
Example:
>>> updated = capture.update(
... asset.nid,
... caption="Updated caption",
... commit_message="Fixed typo in caption"
... )
"""
if not nid:
raise ValidationError("nid is required")
# Build options from args if not provided
if options is None:
options = UpdateOptions(
caption=caption,
headline=headline,
commit_message=commit_message,
custom_metadata=custom_metadata,
)
if options.headline and len(options.headline) > 25:
raise ValidationError("headline must be 25 characters or less")
form_data: dict[str, Any] = {}
if options.caption is not None:
form_data["caption"] = options.caption
if options.headline is not None:
form_data["headline"] = options.headline
if options.commit_message:
form_data["commit_message"] = options.commit_message
if options.custom_metadata:
form_data["nit_commit_custom"] = json.dumps(options.custom_metadata)
response = self._request(
"PATCH",
f"{self._base_url}/assets/{nid}/",
data=form_data,
nid=nid,
)
return _to_asset(response)
def get(self, nid: str) -> Asset:
"""
Retrieves a single asset by NID.
Args:
nid: Numbers ID of the asset.
Returns:
Asset information.
Example:
>>> asset = capture.get("bafybei...")
>>> print(f"Filename: {asset.filename}")
>>> print(f"Caption: {asset.caption}")
"""
if not nid:
raise ValidationError("nid is required")
response = self._request(
"GET",
f"{self._base_url}/assets/{nid}/",
nid=nid,
)
return _to_asset(response)
def get_history(self, nid: str) -> list[Commit]:
"""
Retrieves the commit history of an asset.
Args:
nid: Numbers ID of the asset.
Returns:
List of Commit objects.
Example:
>>> history = capture.get_history("bafybei...")
>>> for commit in history:
... print(f"Action: {commit.action}")
... print(f"Author: {commit.author}")
"""
if not nid:
raise ValidationError("nid is required")
params = {"nid": nid}
if self._testnet:
params["testnet"] = "true"
url = f"{HISTORY_API_URL}?{urlencode(params)}"
headers = {
"Content-Type": "application/json",
}
try:
response = self._client.get(url, headers=headers)
except httpx.RequestError as e:
raise create_api_error(0, f"Network error: {e}", nid) from e
if not response.is_success:
raise create_api_error(
response.status_code,
"Failed to fetch asset history",
nid,
)
data = response.json()
return [
Commit(
asset_tree_cid=c["assetTreeCid"],
tx_hash=c["txHash"],
author=c["author"],
committer=c["committer"],
timestamp=c["timestampCreated"],
action=c["action"],
)
for c in data["commits"]
]
def get_asset_tree(self, nid: str) -> AssetTree:
"""
Retrieves the merged asset tree containing full provenance data.
Combines all commits in chronological order.
Args:
nid: Numbers ID of the asset.
Returns:
Merged AssetTree.
Example:
>>> tree = capture.get_asset_tree(asset.nid)
>>> print(f"Creator: {tree.creator_name}")
>>> print(f"Created at: {tree.created_at}")
"""
if not nid:
raise ValidationError("nid is required")
# First, get the commit history
commits = self.get_history(nid)
if len(commits) == 0:
raise CaptureError("No commits found for asset", "NO_COMMITS", 404)
# Prepare the request body for merging
commit_data = [
{
"assetTreeCid": c.asset_tree_cid,
"timestampCreated": c.timestamp,
}
for c in commits
]
headers = {
"Content-Type": "application/json",
}
try:
response = self._client.post(
MERGE_TREE_API_URL,
headers=headers,
json=commit_data,
)
except httpx.RequestError as e:
raise create_api_error(0, f"Network error: {e}", nid) from e
if not response.is_success:
raise create_api_error(
response.status_code,
"Failed to merge asset trees",
nid,
)
data = response.json()
merged = data.get("mergedAssetTree", data)
# Map known fields and put the rest in extra
known_fields = {
"assetCid",
"assetSha256",
"creatorName",
"creatorWallet",
"createdAt",
"locationCreated",
"caption",
"headline",
"license",
"mimeType",
"nftRecord",
"usedBy",
"integrityCid",
"digitalSourceType",
"miningPreference",
"generatedBy",
}
extra = {k: v for k, v in merged.items() if k not in known_fields}
# Parse license field - can be object or string
license_data = merged.get("license")
license_obj = None
if isinstance(license_data, dict):
license_obj = License(
name=license_data.get("name"),
document=license_data.get("document"),
)
elif isinstance(license_data, str):
# Backwards compatibility: treat string as license name
license_obj = License(name=license_data)
return AssetTree(
asset_cid=merged.get("assetCid"),
asset_sha256=merged.get("assetSha256"),
creator_name=merged.get("creatorName"),
creator_wallet=merged.get("creatorWallet"),
created_at=merged.get("createdAt"),
location_created=merged.get("locationCreated"),
caption=merged.get("caption"),
headline=merged.get("headline"),
license=license_obj,
mime_type=merged.get("mimeType"),
nft_record=merged.get("nftRecord"),
used_by=merged.get("usedBy"),
integrity_cid=merged.get("integrityCid"),
digital_source_type=merged.get("digitalSourceType"),
mining_preference=merged.get("miningPreference"),
generated_by=merged.get("generatedBy"),
extra=extra,
)
def search_asset(
self,
*,
file_url: str | None = None,
file: FileInput | None = None,
nid: str | None = None,
threshold: float | None = None,
sample_count: int | None = None,
options: AssetSearchOptions | None = None,
) -> AssetSearchResult:
"""
Searches for similar assets using image similarity.
Args:
file_url: URL of the file to search.
file: File to search (path, Path, bytes, or bytearray).
nid: Numbers ID of an existing asset to search.
threshold: Similarity threshold (0-1, lower means more similar).
sample_count: Number of results to return.
options: AssetSearchOptions object (alternative to individual args).
Returns:
Search results with precise match and similar assets.
Example:
>>> # Search by file URL
>>> result = capture.search_asset(file_url="https://example.com/image.jpg")
>>>
>>> # Search by NID
>>> result = capture.search_asset(nid="bafybei...")
>>>
>>> # Search by file with options
>>> result = capture.search_asset(
... file="./photo.jpg",
... threshold=0.5,
... sample_count=10
... )
"""
# Build options from args if not provided
if options is None:
options = AssetSearchOptions(
file_url=file_url,
file=file,
nid=nid,
threshold=threshold,
sample_count=sample_count,
)
# Validate that at least one input source is provided
if not options.file_url and not options.file and not options.nid:
raise ValidationError(
"Must provide file_url, file, or nid for asset search"
)
# Validate threshold
if options.threshold is not None and (
options.threshold < 0 or options.threshold > 1
):
raise ValidationError("threshold must be between 0 and 1")
# Validate sample_count
if options.sample_count is not None and (
options.sample_count < 1
or not isinstance(options.sample_count, int)
):
raise ValidationError("sample_count must be a positive integer")
form_data: dict[str, Any] = {}
# Add input source
files_data: dict[str, Any] | None = None
if options.file_url:
form_data["url"] = options.file_url
elif options.nid:
form_data["nid"] = options.nid
elif options.file:
data, filename, mime_type = _normalize_file(options.file)
files_data = {"file": (filename, data, mime_type)}
# Add optional parameters
if options.threshold is not None:
form_data["threshold"] = str(options.threshold)
if options.sample_count is not None:
form_data["sample_count"] = str(options.sample_count)
# Verify Engine API requires token in Authorization header, not form data
headers = {"Authorization": f"token {self._token}"}
try:
if files_data:
response = self._client.post(
ASSET_SEARCH_API_URL,
headers=headers,
data=form_data,
files=files_data,
)
else:
response = self._client.post(
ASSET_SEARCH_API_URL,
headers=headers,
data=form_data,
)
except httpx.RequestError as e:
raise create_api_error(0, f"Network error: {e}") from e
if not response.is_success:
message = f"Asset search failed with status {response.status_code}"
try:
error_data = response.json()
message = (
error_data.get("message")
or error_data.get("error")
or message
)
except Exception:
pass
raise create_api_error(response.status_code, message)
data = response.json()
# Map response to our type
similar_matches = [
SimilarMatch(nid=m["nid"], distance=m["distance"])
for m in data.get("similar_matches", [])
]
return AssetSearchResult(
precise_match=data.get("precise_match", ""),
input_file_mime_type=data.get("input_file_mime_type", ""),
similar_matches=similar_matches,
order_id=data.get("order_id", ""),
)
def search_nft(self, nid: str) -> NftSearchResult:
"""
Searches for NFTs across multiple blockchains that match an asset.
Args:
nid: Numbers ID of the asset to search for.
Returns:
NFT records found across different chains.
Example:
>>> result = capture.search_nft("bafybei...")
>>> for nft in result.records:
... print(f"Found on {nft.network}: {nft.contract}#{nft.token_id}")
"""
if not nid:
raise ValidationError("nid is required for NFT search")
headers = {
"Content-Type": "application/json",
"Authorization": f"token {self._token}",
}
try:
response = self._client.post(
NFT_SEARCH_API_URL,
headers=headers,
json={"nid": nid},
)
except httpx.RequestError as e:
raise create_api_error(0, f"Network error: {e}", nid) from e
if not response.is_success:
message = f"NFT search failed with status {response.status_code}"
try:
error_data = response.json()
message = (
error_data.get("message")
or error_data.get("error")
or message
)
except Exception:
pass
raise create_api_error(response.status_code, message, nid)
data = response.json()
# Map response to our type
records = [
NftRecord(
token_id=r["token_id"],
contract=r["contract"],
network=r["network"],
owner=r.get("owner"),
)
for r in data.get("records", [])
]
return NftSearchResult(
records=records,
order_id=data.get("order_id", ""),
)