simlir 0.1.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.
- simlir-0.1.0/LICENSE +1 -0
- simlir-0.1.0/PKG-INFO +47 -0
- simlir-0.1.0/README.md +32 -0
- simlir-0.1.0/pyproject.toml +26 -0
- simlir-0.1.0/setup.cfg +4 -0
- simlir-0.1.0/src/simlir/__init__.py +22 -0
- simlir-0.1.0/src/simlir/client.py +195 -0
- simlir-0.1.0/src/simlir/contract.py +3 -0
- simlir-0.1.0/src/simlir/errors.py +32 -0
- simlir-0.1.0/src/simlir/models.py +216 -0
- simlir-0.1.0/src/simlir/py.typed +0 -0
- simlir-0.1.0/src/simlir.egg-info/PKG-INFO +47 -0
- simlir-0.1.0/src/simlir.egg-info/SOURCES.txt +15 -0
- simlir-0.1.0/src/simlir.egg-info/dependency_links.txt +1 -0
- simlir-0.1.0/src/simlir.egg-info/top_level.txt +1 -0
- simlir-0.1.0/tests/test_client.py +87 -0
- simlir-0.1.0/tests/test_pypi_metadata.spec.py +17 -0
simlir-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Release candidate only. Not licensed for redistribution. Final public license requires legal approval.
|
simlir-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: simlir
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed Python client for the simlir public product API
|
|
5
|
+
Author: simlir engineering
|
|
6
|
+
License: Release candidate only. Not licensed for redistribution. Final public license requires legal approval.
|
|
7
|
+
|
|
8
|
+
Keywords: product data,product search,shopping api,gtin,sku,ai
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
|
|
16
|
+
# simlir
|
|
17
|
+
|
|
18
|
+
The typed Python client for the simlir public product API is intended for publication on PyPI as `simlir` version `0.1.0` under Apache-2.0. The SDK is open source; installing it does not provide free access to the Simlir service. API access still requires a Simlir account, API key, and any applicable credits or plan entitlement. See [`docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md`](../../docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md) for the public artefact scope and service boundary.
|
|
19
|
+
|
|
20
|
+
## Local verification
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python -m compileall -q src
|
|
24
|
+
python -m unittest discover -s tests -p 'test_*.py'
|
|
25
|
+
python -m pip wheel --no-deps --no-build-isolation --wheel-dir /tmp/simlir-python-sdk-wheel .
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Intended consumer API
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from simlir import Simlir
|
|
32
|
+
|
|
33
|
+
client = Simlir(api_key="sk_...")
|
|
34
|
+
result = client.search(query="wireless headphones", market="GB", limit=10)
|
|
35
|
+
for product in result.results:
|
|
36
|
+
print(product.title, product.price.amount, product.price.retailer)
|
|
37
|
+
|
|
38
|
+
exact = client.lookup(identifier="5051234567890", type="gtin", market="GB")
|
|
39
|
+
visual = client.search_by_image(
|
|
40
|
+
image_url="https://example.com/product.jpg",
|
|
41
|
+
market="GB",
|
|
42
|
+
query="a slim fridge freezer with a front water dispenser for a small flat",
|
|
43
|
+
)
|
|
44
|
+
product = client.get_product(id=result.results[0].id)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The dataclass response models are generated from the pinned public API shape and include the source contract hash in the package boundary. The SDK uses Python’s standard library HTTP client, validates markets, UUIDs, API keys, price ranges, hosted HTTPS image URLs, and optional context, bounds timeouts/retries/response size, and never logs credentials, query strings, request bodies, or response bodies. Image-only calls remain supported.
|
simlir-0.1.0/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# simlir
|
|
2
|
+
|
|
3
|
+
The typed Python client for the simlir public product API is intended for publication on PyPI as `simlir` version `0.1.0` under Apache-2.0. The SDK is open source; installing it does not provide free access to the Simlir service. API access still requires a Simlir account, API key, and any applicable credits or plan entitlement. See [`docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md`](../../docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md) for the public artefact scope and service boundary.
|
|
4
|
+
|
|
5
|
+
## Local verification
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m compileall -q src
|
|
9
|
+
python -m unittest discover -s tests -p 'test_*.py'
|
|
10
|
+
python -m pip wheel --no-deps --no-build-isolation --wheel-dir /tmp/simlir-python-sdk-wheel .
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Intended consumer API
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from simlir import Simlir
|
|
17
|
+
|
|
18
|
+
client = Simlir(api_key="sk_...")
|
|
19
|
+
result = client.search(query="wireless headphones", market="GB", limit=10)
|
|
20
|
+
for product in result.results:
|
|
21
|
+
print(product.title, product.price.amount, product.price.retailer)
|
|
22
|
+
|
|
23
|
+
exact = client.lookup(identifier="5051234567890", type="gtin", market="GB")
|
|
24
|
+
visual = client.search_by_image(
|
|
25
|
+
image_url="https://example.com/product.jpg",
|
|
26
|
+
market="GB",
|
|
27
|
+
query="a slim fridge freezer with a front water dispenser for a small flat",
|
|
28
|
+
)
|
|
29
|
+
product = client.get_product(id=result.results[0].id)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The dataclass response models are generated from the pinned public API shape and include the source contract hash in the package boundary. The SDK uses Python’s standard library HTTP client, validates markets, UUIDs, API keys, price ranges, hosted HTTPS image URLs, and optional context, bounds timeouts/retries/response size, and never logs credentials, query strings, request bodies, or response bodies. Image-only calls remain supported.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68,<77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "simlir"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Typed Python client for the simlir public product API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
authors = [{ name = "simlir engineering" }]
|
|
13
|
+
keywords = ["product data", "product search", "shopping api", "gtin", "sku", "ai"]
|
|
14
|
+
classifiers = ["Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python :: 3"]
|
|
15
|
+
dependencies = []
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
|
19
|
+
|
|
20
|
+
[tool.setuptools.package-data]
|
|
21
|
+
simlir = ["py.typed"]
|
|
22
|
+
|
|
23
|
+
[tool.simlir.release]
|
|
24
|
+
publication_enabled = true
|
|
25
|
+
contract_version = "1.0.0"
|
|
26
|
+
contract_source_sha256 = "6d0c1f9c60ef7de7d49429c35d051c7b8283d0f47bed8d23a16a7621eda9bfc0"
|
simlir-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Typed Python client for the simlir public API release candidate."""
|
|
2
|
+
|
|
3
|
+
from .client import Simlir
|
|
4
|
+
from .errors import SimlirApiError, SimlirError
|
|
5
|
+
from .models import (
|
|
6
|
+
ApiProduct,
|
|
7
|
+
ImageSearchResponse,
|
|
8
|
+
LookupResponse,
|
|
9
|
+
ProductResponse,
|
|
10
|
+
SearchResponse,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"ApiProduct",
|
|
15
|
+
"ImageSearchResponse",
|
|
16
|
+
"LookupResponse",
|
|
17
|
+
"ProductResponse",
|
|
18
|
+
"SearchResponse",
|
|
19
|
+
"Simlir",
|
|
20
|
+
"SimlirApiError",
|
|
21
|
+
"SimlirError",
|
|
22
|
+
]
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from urllib.parse import urlencode, urlsplit, urlunsplit
|
|
12
|
+
from uuid import UUID
|
|
13
|
+
|
|
14
|
+
from .contract import PUBLIC_API_BASE_URL
|
|
15
|
+
from .errors import SimlirApiError, SimlirError, error_code_for_status
|
|
16
|
+
from .models import ImageSearchResponse, LookupResponse, ProductResponse, SearchResponse
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger("simlir")
|
|
19
|
+
RETRYABLE_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
|
|
20
|
+
MAX_RESPONSE_BYTES = 2_000_000
|
|
21
|
+
MARKETS = frozenset({"gb", "us", "de", "fr", "es", "it", "au", "ca"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class TransportResponse:
|
|
26
|
+
status: int
|
|
27
|
+
headers: Mapping[str, str]
|
|
28
|
+
body: bytes
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
Transport = Callable[[str, str, Mapping[str, str], bytes | None, float], TransportResponse]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _base_url(value: str) -> str:
|
|
35
|
+
parsed = urlsplit(value)
|
|
36
|
+
local = parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
|
|
37
|
+
if not parsed.hostname or parsed.scheme != "https" and not local:
|
|
38
|
+
raise SimlirError("configuration_error", "base_url must use HTTPS outside local development.")
|
|
39
|
+
if parsed.username or parsed.password or parsed.query or parsed.fragment:
|
|
40
|
+
raise SimlirError("configuration_error", "base_url cannot contain credentials, query, or fragment data.")
|
|
41
|
+
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _api_key(value: str) -> str:
|
|
45
|
+
key = value.strip()
|
|
46
|
+
if not key or len(key) > 512 or any(char.isspace() for char in key) or "your_key_here" in key.lower():
|
|
47
|
+
raise SimlirError("configuration_error", "api_key must be a non-empty secret value.")
|
|
48
|
+
return key
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _market(value: str) -> str:
|
|
52
|
+
market = value.strip().lower()
|
|
53
|
+
if market not in MARKETS:
|
|
54
|
+
raise SimlirError("invalid_params", f"market must be one of {', '.join(sorted(MARKETS))}.")
|
|
55
|
+
return market
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _string(value: str, field: str, maximum: int) -> str:
|
|
59
|
+
if not isinstance(value, str) or not value.strip():
|
|
60
|
+
raise SimlirError("invalid_params", f"{field} is required.")
|
|
61
|
+
result = value.strip()
|
|
62
|
+
if len(result) > maximum:
|
|
63
|
+
raise SimlirError("invalid_params", f"{field} must be {maximum} characters or fewer.")
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _number(value: float | None, field: str) -> float | None:
|
|
68
|
+
if value is None:
|
|
69
|
+
return None
|
|
70
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
|
|
71
|
+
raise SimlirError("invalid_params", f"{field} must be a non-negative number.")
|
|
72
|
+
return float(value)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _bounded_int(value: int | None, field: str, minimum: int, maximum: int) -> int | None:
|
|
76
|
+
if value is None:
|
|
77
|
+
return None
|
|
78
|
+
if not isinstance(value, int) or isinstance(value, bool) or not minimum <= value <= maximum:
|
|
79
|
+
raise SimlirError("invalid_params", f"{field} must be an integer between {minimum} and {maximum}.")
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _image_url(value: str) -> str:
|
|
84
|
+
raw = _string(value, "image_url", 2048)
|
|
85
|
+
parsed = urlsplit(raw)
|
|
86
|
+
host = parsed.hostname
|
|
87
|
+
if parsed.scheme != "https" or not host or parsed.username or parsed.password:
|
|
88
|
+
raise SimlirError("invalid_params", "image_url must be a hosted https URL.")
|
|
89
|
+
try:
|
|
90
|
+
address = ipaddress.ip_address(host)
|
|
91
|
+
if address.is_private or address.is_loopback or address.is_link_local or address.is_reserved:
|
|
92
|
+
raise SimlirError("invalid_params", "image_url must be a hosted https URL.")
|
|
93
|
+
except ValueError:
|
|
94
|
+
pass
|
|
95
|
+
return raw
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _default_transport(url: str, method: str, headers: Mapping[str, str], body: bytes | None, timeout: float) -> TransportResponse:
|
|
99
|
+
request = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
|
|
100
|
+
try:
|
|
101
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
102
|
+
return TransportResponse(response.status, dict(response.headers.items()), response.read(MAX_RESPONSE_BYTES + 1))
|
|
103
|
+
except urllib.error.HTTPError as error:
|
|
104
|
+
return TransportResponse(error.code, dict(error.headers.items()), error.read(MAX_RESPONSE_BYTES + 1))
|
|
105
|
+
except (urllib.error.URLError, TimeoutError, OSError) as error:
|
|
106
|
+
raise SimlirError("network_error", "The simlir API request failed.") from error
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Simlir:
|
|
110
|
+
def __init__(self, api_key: str, base_url: str | None = None, timeout: float = 15.0, max_retries: int = 2, transport: Transport | None = None) -> None:
|
|
111
|
+
self._api_key = _api_key(api_key)
|
|
112
|
+
self._base_url = _base_url(base_url or PUBLIC_API_BASE_URL)
|
|
113
|
+
self._timeout = min(max(float(timeout), 1.0), 60.0)
|
|
114
|
+
self._max_retries = min(max(int(max_retries), 0), 3)
|
|
115
|
+
self._transport = transport or _default_transport
|
|
116
|
+
|
|
117
|
+
def search(self, query: str, market: str, category: str | None = None, brand: str | None = None, min_price: float | None = None, max_price: float | None = None, limit: int | None = None, offset: int | None = None) -> SearchResponse:
|
|
118
|
+
values = self._search_values(query, market, category, brand, min_price, max_price, limit, offset)
|
|
119
|
+
return SearchResponse.from_dict(self._request("GET", "/v1/search", values))
|
|
120
|
+
|
|
121
|
+
def search_by_image(self, image_url: str, market: str, category: str | None = None, brand: str | None = None, min_price: float | None = None, max_price: float | None = None, limit: int | None = None, offset: int | None = None, query: str | None = None) -> ImageSearchResponse:
|
|
122
|
+
values = self._search_values(None, market, category, brand, min_price, max_price, limit, offset)
|
|
123
|
+
values["image_url"] = _image_url(image_url)
|
|
124
|
+
if query is not None: values["query"] = _string(query, "query", 1000)
|
|
125
|
+
return ImageSearchResponse.from_dict(self._request("POST", "/v1/search/image", values))
|
|
126
|
+
|
|
127
|
+
def lookup(self, identifier: str, market: str, type: str = "auto", brand: str | None = None, retailer: str | None = None, limit: int | None = None) -> LookupResponse:
|
|
128
|
+
identifier_value = _string(identifier, "identifier", 256)
|
|
129
|
+
market_value = _market(market)
|
|
130
|
+
if type not in {"auto", "gtin", "mpn", "sku"}:
|
|
131
|
+
raise SimlirError("invalid_params", "type must be one of auto, gtin, mpn, sku.")
|
|
132
|
+
values: dict[str, object] = {"identifier": identifier_value, "gl": market_value, "type": type}
|
|
133
|
+
if brand is not None: values["brand"] = _string(brand, "brand", 160)
|
|
134
|
+
if retailer is not None: values["retailer"] = _string(retailer, "retailer", 160)
|
|
135
|
+
bounded_limit = _bounded_int(limit, "limit", 1, 50)
|
|
136
|
+
if bounded_limit is not None: values["limit"] = bounded_limit
|
|
137
|
+
return LookupResponse.from_dict(self._request("GET", "/v1/lookup", values))
|
|
138
|
+
|
|
139
|
+
def get_product(self, id: str) -> ProductResponse:
|
|
140
|
+
product_id = _string(id, "id", 64)
|
|
141
|
+
try: UUID(product_id)
|
|
142
|
+
except ValueError as error: raise SimlirError("invalid_params", "id must be a valid product UUID.") from error
|
|
143
|
+
return ProductResponse.from_dict(self._request("GET", "/v1/product", {"id": product_id}))
|
|
144
|
+
|
|
145
|
+
def _search_values(self, query: str | None, market: str, category: str | None, brand: str | None, min_price: float | None, max_price: float | None, limit: int | None, offset: int | None) -> dict[str, object]:
|
|
146
|
+
values: dict[str, object] = {"gl": _market(market)}
|
|
147
|
+
if query is not None: values["q"] = _string(query, "query", 1000)
|
|
148
|
+
if category is not None: values["category"] = _string(category, "category", 160)
|
|
149
|
+
if brand is not None: values["brand"] = _string(brand, "brand", 160)
|
|
150
|
+
minimum = _number(min_price, "min_price"); maximum = _number(max_price, "max_price")
|
|
151
|
+
if minimum is not None: values["min_price"] = minimum
|
|
152
|
+
if maximum is not None: values["max_price"] = maximum
|
|
153
|
+
if minimum is not None and maximum is not None and minimum > maximum: raise SimlirError("invalid_params", "min_price cannot exceed max_price.")
|
|
154
|
+
bounded_limit = _bounded_int(limit, "limit", 1, 50); bounded_offset = _bounded_int(offset, "offset", 0, 500)
|
|
155
|
+
if bounded_limit is not None: values["limit"] = bounded_limit
|
|
156
|
+
if bounded_offset is not None: values["offset"] = bounded_offset
|
|
157
|
+
return values
|
|
158
|
+
|
|
159
|
+
def _request(self, method: str, endpoint: str, values: Mapping[str, object]) -> dict[str, object]:
|
|
160
|
+
body: bytes | None = None
|
|
161
|
+
if method == "GET":
|
|
162
|
+
url = f"{self._base_url}{endpoint}?{urlencode(values)}"
|
|
163
|
+
else:
|
|
164
|
+
url = f"{self._base_url}{endpoint}"
|
|
165
|
+
body = json.dumps(values).encode("utf-8")
|
|
166
|
+
headers = {"Accept": "application/json", "Authorization": f"Bearer {self._api_key}"}
|
|
167
|
+
if body is not None: headers["Content-Type"] = "application/json"
|
|
168
|
+
last_error: SimlirError | None = None
|
|
169
|
+
for attempt in range(self._max_retries + 1):
|
|
170
|
+
try:
|
|
171
|
+
response = self._transport(url, method, headers, body, self._timeout)
|
|
172
|
+
except SimlirError as error:
|
|
173
|
+
last_error = error
|
|
174
|
+
if attempt >= self._max_retries: raise
|
|
175
|
+
logger.warning("simlir request retry path=%s attempt=%s", endpoint, attempt + 1)
|
|
176
|
+
time.sleep(min(4.0, 0.1 * (2 ** attempt)))
|
|
177
|
+
continue
|
|
178
|
+
if len(response.body) > MAX_RESPONSE_BYTES:
|
|
179
|
+
raise SimlirError("malformed_response", "The simlir API response was too large.")
|
|
180
|
+
try: payload = json.loads(response.body.decode("utf-8"))
|
|
181
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
182
|
+
raise SimlirError("malformed_response", "The simlir API returned invalid JSON.") from error
|
|
183
|
+
if response.status < 200 or response.status >= 300:
|
|
184
|
+
retry_after = response.headers.get("retry-after")
|
|
185
|
+
retry_seconds = max(0, min(int(retry_after), 60)) if retry_after and retry_after.isdigit() else None
|
|
186
|
+
error = SimlirApiError(error_code_for_status(response.status), str(payload.get("message", f"The simlir API returned HTTP {response.status}.")) if isinstance(payload, dict) else f"The simlir API returned HTTP {response.status}.", response.status, retry_seconds, response.headers.get("x-request-id"))
|
|
187
|
+
if attempt < self._max_retries and response.status in RETRYABLE_STATUSES:
|
|
188
|
+
logger.warning("simlir request retry path=%s status=%s attempt=%s", endpoint, response.status, attempt + 1)
|
|
189
|
+
time.sleep(min(4.0, (retry_seconds or 0.1) * (2 ** attempt)))
|
|
190
|
+
continue
|
|
191
|
+
logger.error("simlir request failed path=%s code=%s status=%s", endpoint, error.code, response.status)
|
|
192
|
+
raise error
|
|
193
|
+
if not isinstance(payload, dict): raise SimlirError("malformed_response", "The simlir API returned an invalid response envelope.")
|
|
194
|
+
return payload
|
|
195
|
+
raise last_error or SimlirError("network_error", "The simlir API request failed.")
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class SimlirError(Exception):
|
|
8
|
+
code: str
|
|
9
|
+
message: str
|
|
10
|
+
status: int = 0
|
|
11
|
+
retry_after_seconds: int | None = None
|
|
12
|
+
request_id: str | None = None
|
|
13
|
+
|
|
14
|
+
def __post_init__(self) -> None:
|
|
15
|
+
super().__init__(self.message[:240])
|
|
16
|
+
self.message = self.message[:240]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SimlirApiError(SimlirError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def error_code_for_status(status: int) -> str:
|
|
24
|
+
if status in (400, 413):
|
|
25
|
+
return "invalid_params"
|
|
26
|
+
if status in (401, 403):
|
|
27
|
+
return "auth_required"
|
|
28
|
+
if status == 402:
|
|
29
|
+
return "insufficient_credits"
|
|
30
|
+
if status == 429:
|
|
31
|
+
return "rate_limit_exceeded"
|
|
32
|
+
return "provider_failure"
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Literal, Mapping
|
|
5
|
+
|
|
6
|
+
MarketCode = Literal["gb", "us", "de", "fr", "es", "it", "au", "ca"]
|
|
7
|
+
IdentifierLookupType = Literal["auto", "gtin", "mpn", "sku"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class VisualSummary:
|
|
12
|
+
summary: str
|
|
13
|
+
labels: list[str]
|
|
14
|
+
detected_text: list[str]
|
|
15
|
+
dominant_colours: list[str]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Dimensions:
|
|
20
|
+
value: dict[str, float]
|
|
21
|
+
unit: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Weight:
|
|
26
|
+
value: float
|
|
27
|
+
unit: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Colour:
|
|
32
|
+
primary: str | None
|
|
33
|
+
family: str | None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Price:
|
|
38
|
+
amount: float | None
|
|
39
|
+
currency: str | None
|
|
40
|
+
retailer: str | None
|
|
41
|
+
as_of: str | None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class ProductLinks:
|
|
46
|
+
buy: str | None
|
|
47
|
+
retailer: str | None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _visual(value: Mapping[str, Any] | None) -> VisualSummary | None:
|
|
51
|
+
if value is None:
|
|
52
|
+
return None
|
|
53
|
+
return VisualSummary(value["summary"], list(value["labels"]), list(value["detected_text"]), list(value["dominant_colours"]))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _dimensions(value: Mapping[str, Any] | None) -> Dimensions | None:
|
|
57
|
+
return None if value is None else Dimensions(dict(value["value"]), str(value["unit"]))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _weight(value: Mapping[str, Any] | None) -> Weight | None:
|
|
61
|
+
return None if value is None else Weight(float(value["value"]), str(value["unit"]))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _colour(value: Mapping[str, Any]) -> Colour:
|
|
65
|
+
return Colour(value.get("primary"), value.get("family"))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _price(value: Mapping[str, Any]) -> Price:
|
|
69
|
+
return Price(value.get("amount"), value.get("currency"), value.get("retailer"), value.get("as_of"))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _links(value: Mapping[str, Any]) -> ProductLinks:
|
|
73
|
+
return ProductLinks(value.get("buy"), value.get("retailer"))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class ApiProduct:
|
|
78
|
+
id: str
|
|
79
|
+
brand: str
|
|
80
|
+
category: str
|
|
81
|
+
gtin: str | None
|
|
82
|
+
title: str | None
|
|
83
|
+
description: str | None
|
|
84
|
+
product_description: str | None
|
|
85
|
+
spec: dict[str, Any] | None
|
|
86
|
+
cosmetic_features: dict[str, Any] | None
|
|
87
|
+
key_selling_points: list[str] | None
|
|
88
|
+
use_cases: list[str] | None
|
|
89
|
+
image_url: str | None
|
|
90
|
+
images: list[str]
|
|
91
|
+
visual: VisualSummary | None
|
|
92
|
+
certifications: list[str]
|
|
93
|
+
materials: list[str]
|
|
94
|
+
dimensions: Dimensions | None
|
|
95
|
+
weight: Weight | None
|
|
96
|
+
colour: Colour
|
|
97
|
+
release_year: int | None
|
|
98
|
+
country_of_origin: str | None
|
|
99
|
+
compatible_with: list[str]
|
|
100
|
+
included_in_box: list[str]
|
|
101
|
+
model_number: str | None
|
|
102
|
+
retailer_sku: str | None
|
|
103
|
+
product_identifiers: dict[str, Any]
|
|
104
|
+
review_score: float | None
|
|
105
|
+
review_count: int | None
|
|
106
|
+
pricing_model: str
|
|
107
|
+
product_condition: str
|
|
108
|
+
price: Price
|
|
109
|
+
links: ProductLinks
|
|
110
|
+
market: MarketCode
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def from_dict(cls, value: Mapping[str, Any]) -> ApiProduct:
|
|
114
|
+
return cls(
|
|
115
|
+
id=str(value["id"]), brand=str(value["brand"]), category=str(value["category"]),
|
|
116
|
+
gtin=value.get("gtin"), title=value.get("title"), description=value.get("description"),
|
|
117
|
+
product_description=value.get("product_description"), spec=value.get("spec"),
|
|
118
|
+
cosmetic_features=value.get("cosmetic_features"), key_selling_points=value.get("key_selling_points"),
|
|
119
|
+
use_cases=value.get("use_cases"), image_url=value.get("image_url"), images=list(value["images"]),
|
|
120
|
+
visual=_visual(value.get("visual")), certifications=list(value["certifications"]), materials=list(value["materials"]),
|
|
121
|
+
dimensions=_dimensions(value.get("dimensions")), weight=_weight(value.get("weight")), colour=_colour(value["colour"]),
|
|
122
|
+
release_year=value.get("release_year"), country_of_origin=value.get("country_of_origin"),
|
|
123
|
+
compatible_with=list(value["compatible_with"]), included_in_box=list(value["included_in_box"]),
|
|
124
|
+
model_number=value.get("model_number"), retailer_sku=value.get("retailer_sku"),
|
|
125
|
+
product_identifiers=dict(value["product_identifiers"]), review_score=value.get("review_score"),
|
|
126
|
+
review_count=value.get("review_count"), pricing_model=str(value["pricing_model"]),
|
|
127
|
+
product_condition=str(value["product_condition"]), price=_price(value["price"]), links=_links(value["links"]),
|
|
128
|
+
market=value["market"],
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class SearchResult(ApiProduct):
|
|
134
|
+
relevance_score: float | None
|
|
135
|
+
|
|
136
|
+
@classmethod
|
|
137
|
+
def from_dict(cls, value: Mapping[str, Any]) -> SearchResult:
|
|
138
|
+
product = ApiProduct.from_dict(value)
|
|
139
|
+
return cls(**product.__dict__, relevance_score=value.get("relevance_score"))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class SearchMeta:
|
|
144
|
+
query: str
|
|
145
|
+
mode: Literal["semantic"]
|
|
146
|
+
market: MarketCode
|
|
147
|
+
total_results: int
|
|
148
|
+
limit: int
|
|
149
|
+
offset: int
|
|
150
|
+
credits_used: Literal[2]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class SearchResponse:
|
|
155
|
+
results: list[SearchResult]
|
|
156
|
+
meta: SearchMeta
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def from_dict(cls, value: Mapping[str, Any]) -> SearchResponse:
|
|
160
|
+
meta = value["meta"]
|
|
161
|
+
return cls([SearchResult.from_dict(item) for item in value["results"]], SearchMeta(**meta))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@dataclass(frozen=True)
|
|
165
|
+
class ImageSearchMeta:
|
|
166
|
+
mode: Literal["visual"]
|
|
167
|
+
market: MarketCode
|
|
168
|
+
total_results: int
|
|
169
|
+
limit: int
|
|
170
|
+
offset: int
|
|
171
|
+
credits_used: Literal[3]
|
|
172
|
+
query: str | None = None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(frozen=True)
|
|
176
|
+
class ImageSearchResponse:
|
|
177
|
+
results: list[SearchResult]
|
|
178
|
+
meta: ImageSearchMeta
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def from_dict(cls, value: Mapping[str, Any]) -> ImageSearchResponse:
|
|
182
|
+
return cls([SearchResult.from_dict(item) for item in value["results"]], ImageSearchMeta(**value["meta"]))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@dataclass(frozen=True)
|
|
186
|
+
class ProductResponse:
|
|
187
|
+
product: ApiProduct
|
|
188
|
+
credits_used: Literal[1]
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def from_dict(cls, value: Mapping[str, Any]) -> ProductResponse:
|
|
192
|
+
return cls(ApiProduct.from_dict(value["product"]), value["credits_used"])
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True)
|
|
196
|
+
class LookupMeta:
|
|
197
|
+
identifier: str
|
|
198
|
+
requested_type: IdentifierLookupType
|
|
199
|
+
resolved_type: Literal["gtin", "mpn", "sku"] | None
|
|
200
|
+
matched_field: Literal["gtin", "model_number", "retailer_sku"] | None
|
|
201
|
+
market: MarketCode
|
|
202
|
+
brand: str | None
|
|
203
|
+
retailer: str | None
|
|
204
|
+
total_results: int
|
|
205
|
+
limit: int
|
|
206
|
+
credits_used: Literal[1]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@dataclass(frozen=True)
|
|
210
|
+
class LookupResponse:
|
|
211
|
+
results: list[ApiProduct]
|
|
212
|
+
meta: LookupMeta
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def from_dict(cls, value: Mapping[str, Any]) -> LookupResponse:
|
|
216
|
+
return cls([ApiProduct.from_dict(item) for item in value["results"]], LookupMeta(**value["meta"]))
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: simlir
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed Python client for the simlir public product API
|
|
5
|
+
Author: simlir engineering
|
|
6
|
+
License: Release candidate only. Not licensed for redistribution. Final public license requires legal approval.
|
|
7
|
+
|
|
8
|
+
Keywords: product data,product search,shopping api,gtin,sku,ai
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
|
|
16
|
+
# simlir
|
|
17
|
+
|
|
18
|
+
The typed Python client for the simlir public product API is intended for publication on PyPI as `simlir` version `0.1.0` under Apache-2.0. The SDK is open source; installing it does not provide free access to the Simlir service. API access still requires a Simlir account, API key, and any applicable credits or plan entitlement. See [`docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md`](../../docs/commercialisation/DEVELOPER-CHANNEL-LICENSING.md) for the public artefact scope and service boundary.
|
|
19
|
+
|
|
20
|
+
## Local verification
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python -m compileall -q src
|
|
24
|
+
python -m unittest discover -s tests -p 'test_*.py'
|
|
25
|
+
python -m pip wheel --no-deps --no-build-isolation --wheel-dir /tmp/simlir-python-sdk-wheel .
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Intended consumer API
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from simlir import Simlir
|
|
32
|
+
|
|
33
|
+
client = Simlir(api_key="sk_...")
|
|
34
|
+
result = client.search(query="wireless headphones", market="GB", limit=10)
|
|
35
|
+
for product in result.results:
|
|
36
|
+
print(product.title, product.price.amount, product.price.retailer)
|
|
37
|
+
|
|
38
|
+
exact = client.lookup(identifier="5051234567890", type="gtin", market="GB")
|
|
39
|
+
visual = client.search_by_image(
|
|
40
|
+
image_url="https://example.com/product.jpg",
|
|
41
|
+
market="GB",
|
|
42
|
+
query="a slim fridge freezer with a front water dispenser for a small flat",
|
|
43
|
+
)
|
|
44
|
+
product = client.get_product(id=result.results[0].id)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The dataclass response models are generated from the pinned public API shape and include the source contract hash in the package boundary. The SDK uses Python’s standard library HTTP client, validates markets, UUIDs, API keys, price ranges, hosted HTTPS image URLs, and optional context, bounds timeouts/retries/response size, and never logs credentials, query strings, request bodies, or response bodies. Image-only calls remain supported.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/simlir/__init__.py
|
|
5
|
+
src/simlir/client.py
|
|
6
|
+
src/simlir/contract.py
|
|
7
|
+
src/simlir/errors.py
|
|
8
|
+
src/simlir/models.py
|
|
9
|
+
src/simlir/py.typed
|
|
10
|
+
src/simlir.egg-info/PKG-INFO
|
|
11
|
+
src/simlir.egg-info/SOURCES.txt
|
|
12
|
+
src/simlir.egg-info/dependency_links.txt
|
|
13
|
+
src/simlir.egg-info/top_level.txt
|
|
14
|
+
tests/test_client.py
|
|
15
|
+
tests/test_pypi_metadata.spec.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
simlir
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import io
|
|
5
|
+
import logging
|
|
6
|
+
import pathlib
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
from simlir import Simlir
|
|
10
|
+
from simlir.client import TransportResponse
|
|
11
|
+
from simlir.errors import SimlirApiError, SimlirError
|
|
12
|
+
|
|
13
|
+
ROOT = pathlib.Path(__file__).resolve().parents[3]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def fixture(name: str) -> dict:
|
|
17
|
+
return json.loads((ROOT / "public/api/fixtures" / name).read_text())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PythonSdkTests(unittest.TestCase):
|
|
21
|
+
def test_maps_all_public_methods_to_contract(self) -> None:
|
|
22
|
+
calls: list[tuple[str, str, dict[str, str], bytes | None, float]] = []
|
|
23
|
+
|
|
24
|
+
def transport(url: str, method: str, headers: dict[str, str], body: bytes | None, timeout: float) -> TransportResponse:
|
|
25
|
+
calls.append((url, method, headers, body, timeout))
|
|
26
|
+
if "/search/image" in url:
|
|
27
|
+
payload = fixture("image-search-success.json")
|
|
28
|
+
elif "/lookup" in url:
|
|
29
|
+
payload = fixture("lookup-success.json")
|
|
30
|
+
elif "/product" in url:
|
|
31
|
+
payload = fixture("product-success.json")
|
|
32
|
+
else:
|
|
33
|
+
payload = fixture("search-success.json")
|
|
34
|
+
return TransportResponse(200, {"x-request-id": "req_py_test"}, json.dumps(payload).encode())
|
|
35
|
+
|
|
36
|
+
client = Simlir("sk_test_safe_key", transport=transport)
|
|
37
|
+
search = client.search("headphones", "GB", limit=10)
|
|
38
|
+
lookup = client.lookup("5051234567890", "GB", type="gtin")
|
|
39
|
+
visual = client.search_by_image("https://example.com/image.jpg", "GB", query="a slim fridge freezer for a small flat")
|
|
40
|
+
product = client.get_product(search.results[0].id)
|
|
41
|
+
self.assertEqual(search.meta.market, "gb")
|
|
42
|
+
self.assertEqual(lookup.meta.market, "gb")
|
|
43
|
+
self.assertEqual(visual.meta.mode, "visual")
|
|
44
|
+
self.assertTrue(product.product.id)
|
|
45
|
+
self.assertIn("q=headphones", calls[0][0])
|
|
46
|
+
self.assertEqual(calls[1][0].split("?")[1].split("&")[0], "identifier=5051234567890")
|
|
47
|
+
self.assertEqual(calls[2][1], "POST")
|
|
48
|
+
self.assertEqual(json.loads(calls[2][3].decode())["query"], "a slim fridge freezer for a small flat")
|
|
49
|
+
self.assertNotIn("sk_test_safe_key", calls[0][0])
|
|
50
|
+
|
|
51
|
+
def test_validates_inputs_and_retries_only_bounded_transient_failures(self) -> None:
|
|
52
|
+
self.assertRaises(SimlirError, lambda: Simlir("sk_test_safe_key").search("x", "nl"))
|
|
53
|
+
self.assertRaises(SimlirError, lambda: Simlir("sk_test_safe_key").search_by_image("http://localhost/image.jpg", "gb"))
|
|
54
|
+
self.assertRaises(SimlirError, lambda: Simlir("sk_test_safe_key").get_product("not-a-uuid"))
|
|
55
|
+
calls = 0
|
|
56
|
+
|
|
57
|
+
def transport(url: str, method: str, headers: dict[str, str], body: bytes | None, timeout: float) -> TransportResponse:
|
|
58
|
+
nonlocal calls
|
|
59
|
+
calls += 1
|
|
60
|
+
return TransportResponse(429 if calls == 1 else 401, {}, json.dumps({"message": "safe"}).encode())
|
|
61
|
+
|
|
62
|
+
client = Simlir("sk_test_safe_key", max_retries=1, transport=transport)
|
|
63
|
+
with self.assertRaises(SimlirApiError) as caught:
|
|
64
|
+
client.search("x", "gb")
|
|
65
|
+
self.assertEqual(caught.exception.code, "auth_required")
|
|
66
|
+
self.assertEqual(calls, 2)
|
|
67
|
+
|
|
68
|
+
def test_publication_metadata_is_explicitly_enabled(self) -> None:
|
|
69
|
+
pyproject = (ROOT / "developer-channels/python-sdk/pyproject.toml").read_text()
|
|
70
|
+
self.assertIn("publication_enabled = true", pyproject)
|
|
71
|
+
self.assertIn('setuptools>=68,<77', pyproject)
|
|
72
|
+
|
|
73
|
+
def test_error_diagnostics_do_not_include_api_key(self) -> None:
|
|
74
|
+
stream = io.StringIO()
|
|
75
|
+
handler = logging.StreamHandler(stream)
|
|
76
|
+
logger = logging.getLogger("simlir")
|
|
77
|
+
logger.addHandler(handler)
|
|
78
|
+
try:
|
|
79
|
+
client = Simlir("sk_test_secret_key", max_retries=0, transport=lambda *_: TransportResponse(401, {}, b'{"message":"invalid"}'))
|
|
80
|
+
with self.assertRaises(SimlirApiError):
|
|
81
|
+
client.search("headphones", "gb")
|
|
82
|
+
finally:
|
|
83
|
+
logger.removeHandler(handler)
|
|
84
|
+
self.assertNotIn("sk_test_secret_key", stream.getvalue())
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
unittest.main()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pathlib
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
ROOT = pathlib.Path(__file__).resolve().parents[3]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PythonSdkPyPiMetadataTests(unittest.TestCase):
|
|
11
|
+
def test_build_backend_is_pinned_to_a_pypi_supported_metadata_range(self) -> None:
|
|
12
|
+
pyproject = (ROOT / "developer-channels/python-sdk/pyproject.toml").read_text()
|
|
13
|
+
self.assertIn('requires = ["setuptools>=68,<77"]', pyproject)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__":
|
|
17
|
+
unittest.main()
|