recapi 0.4.12__tar.gz → 0.4.14__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.
- {recapi-0.4.12/recapi.egg-info → recapi-0.4.14}/PKG-INFO +3 -3
- {recapi-0.4.12 → recapi-0.4.14}/README.md +2 -2
- {recapi-0.4.12 → recapi-0.4.14}/pyproject.toml +1 -1
- {recapi-0.4.12 → recapi-0.4.14}/recapi/async_client.py +3 -3
- {recapi-0.4.12 → recapi-0.4.14}/recapi/client.py +29 -2
- {recapi-0.4.12 → recapi-0.4.14}/recapi/history.py +62 -21
- {recapi-0.4.12 → recapi-0.4.14/recapi.egg-info}/PKG-INFO +3 -3
- {recapi-0.4.12 → recapi-0.4.14}/tests/test_async_client.py +13 -0
- {recapi-0.4.12 → recapi-0.4.14}/tests/test_client.py +22 -7
- {recapi-0.4.12 → recapi-0.4.14}/tests/test_client_vectors.py +34 -0
- {recapi-0.4.12 → recapi-0.4.14}/tests/test_history.py +41 -5
- {recapi-0.4.12 → recapi-0.4.14}/LICENSE +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/recapi/__init__.py +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/recapi/py.typed +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/setup.cfg +0 -0
- {recapi-0.4.12 → recapi-0.4.14}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.14
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://recapi.io
|
|
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
49
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
50
50
|
|
|
51
51
|
```sh
|
|
52
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
237
237
|
|
|
238
238
|
| Method | What it does |
|
|
239
239
|
|---|---|
|
|
240
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
240
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
241
241
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
243
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -26,7 +26,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
26
26
|
(the dashboard's quick start shows the line with your API's address):
|
|
27
27
|
|
|
28
28
|
```sh
|
|
29
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
29
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -214,7 +214,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
214
214
|
|
|
215
215
|
| Method | What it does |
|
|
216
216
|
|---|---|
|
|
217
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
217
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
218
218
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
219
219
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
220
220
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.14"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -70,9 +70,9 @@ class AsyncClient:
|
|
|
70
70
|
# serve the fallback. Past its deadline, the call asks only for popular items.
|
|
71
71
|
return await asyncio.to_thread(fn, deadline, *args, **params)
|
|
72
72
|
|
|
73
|
-
async def track(self, item_id: str, level: int | str, **
|
|
74
|
-
"""Record an interaction: :meth:`Client.track`."""
|
|
75
|
-
await self._run(self._client.track, item_id, level, **
|
|
73
|
+
async def track(self, item_id: str, level: int | str, **fields: Any) -> None:
|
|
74
|
+
"""Record an interaction (ids, value, currency): :meth:`Client.track`."""
|
|
75
|
+
await self._run(self._client.track, item_id, level, **fields)
|
|
76
76
|
|
|
77
77
|
async def identify(self, anon_id: str, user_id: str) -> None:
|
|
78
78
|
"""At login, the visitor's history becomes the user's: :meth:`Client.identify`."""
|
|
@@ -14,6 +14,7 @@ import hashlib
|
|
|
14
14
|
import http.client
|
|
15
15
|
import json
|
|
16
16
|
import logging
|
|
17
|
+
import math
|
|
17
18
|
import os
|
|
18
19
|
import random
|
|
19
20
|
import threading
|
|
@@ -29,7 +30,7 @@ from typing import Any, Protocol
|
|
|
29
30
|
|
|
30
31
|
from .history import History, is_id
|
|
31
32
|
|
|
32
|
-
__version__ = "0.4.
|
|
33
|
+
__version__ = "0.4.14"
|
|
33
34
|
|
|
34
35
|
log = logging.getLogger("recapi")
|
|
35
36
|
Tags = Sequence[str] | None
|
|
@@ -478,19 +479,24 @@ class Client:
|
|
|
478
479
|
user_id: str | None = None,
|
|
479
480
|
anon_id: str | None = None,
|
|
480
481
|
recommendation_id: str | None = None,
|
|
482
|
+
value: float | None = None,
|
|
483
|
+
currency: str | None = None,
|
|
481
484
|
) -> None:
|
|
482
485
|
"""Record an interaction: the user's history changes at once, the event is queued.
|
|
483
486
|
|
|
484
487
|
``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
|
|
485
488
|
``purchase`` (10), ``reject`` (-10: never recommend the item to this
|
|
486
489
|
user again until a positive event on it). ``recommendation_id``
|
|
487
|
-
overrides the automatic attribution.
|
|
490
|
+
overrides the automatic attribution. ``value`` is what the buyer paid for
|
|
491
|
+
a purchase's line (0 for a free one), ``currency`` its ISO 4217 code; a
|
|
492
|
+
currency needs a value. Raises ``ValueError`` on a bad level, amount
|
|
488
493
|
or a bad user, visitor or recommendation id. An ``item_id`` the API would
|
|
489
494
|
refuse isn't one: a page often takes it from a visitor's URL, so the
|
|
490
495
|
event is dropped and logged instead.
|
|
491
496
|
"""
|
|
492
497
|
level = _level(level)
|
|
493
498
|
_check_ids(user_id=user_id, anon_id=anon_id, recommendation_id=recommendation_id)
|
|
499
|
+
_check_amount(value, currency)
|
|
494
500
|
# A crafted link must not fail the page. Nothing is kept: in the history
|
|
495
501
|
# it would make the API refuse every later list. The line never quotes
|
|
496
502
|
# the visitor's id.
|
|
@@ -521,6 +527,8 @@ class Client:
|
|
|
521
527
|
"user_id": user_id,
|
|
522
528
|
"anon_id": anon_id,
|
|
523
529
|
"recommendation_id": attributed,
|
|
530
|
+
"value": value,
|
|
531
|
+
"currency": currency,
|
|
524
532
|
"timestamp": _iso(t),
|
|
525
533
|
"event_id": str(uuid.uuid4()),
|
|
526
534
|
}
|
|
@@ -1328,6 +1336,25 @@ def _check_ids(**ids: str | None) -> None:
|
|
|
1328
1336
|
raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
|
|
1329
1337
|
|
|
1330
1338
|
|
|
1339
|
+
def _check_amount(value: object, currency: object) -> None:
|
|
1340
|
+
"""Refuse what the API would refuse in the event (spec/client_vectors.json "amounts")."""
|
|
1341
|
+
if value is not None and (
|
|
1342
|
+
isinstance(value, bool) or not isinstance(value, int | float) or not (0 <= value < math.inf)
|
|
1343
|
+
):
|
|
1344
|
+
raise ValueError("value must be a number of at least 0")
|
|
1345
|
+
if currency is None:
|
|
1346
|
+
return
|
|
1347
|
+
if value is None:
|
|
1348
|
+
raise ValueError("currency needs a value")
|
|
1349
|
+
if not (
|
|
1350
|
+
isinstance(currency, str)
|
|
1351
|
+
and len(currency) == 3
|
|
1352
|
+
and currency.isascii()
|
|
1353
|
+
and currency.isalpha()
|
|
1354
|
+
):
|
|
1355
|
+
raise ValueError("currency must be three letters (ISO 4217)")
|
|
1356
|
+
|
|
1357
|
+
|
|
1331
1358
|
def _usable_context(value: object) -> bool:
|
|
1332
1359
|
# An id, or nothing: an empty string reads as no context item.
|
|
1333
1360
|
return value is None or is_id(value) or (isinstance(value, str) and not value)
|
|
@@ -20,6 +20,7 @@ MAX_ID_BYTES = 256
|
|
|
20
20
|
# The API answers 400 above this, which fails the list: a damaged score is sent as this.
|
|
21
21
|
MAX_REQUEST_WEIGHT = 1e6
|
|
22
22
|
|
|
23
|
+
_LEVELS = range(1, 11)
|
|
23
24
|
_RATE = math.log(2) / HALF_LIFE_SECONDS
|
|
24
25
|
# Go's unicode.IsControl, which the API applies to every id: C0, DEL and C1.
|
|
25
26
|
_CONTROL = re.compile("[\x00-\x1f\x7f-\x9f]")
|
|
@@ -53,10 +54,28 @@ def _is_time(value: object) -> bool:
|
|
|
53
54
|
)
|
|
54
55
|
|
|
55
56
|
|
|
57
|
+
def _level(value: object) -> int:
|
|
58
|
+
"""Return a strongest level read from JSON: an integer 1-10, else 0 (unknown)."""
|
|
59
|
+
# 10.0 is 10; a float is compared, not converted (a NaN or 2.5 isn't in the range).
|
|
60
|
+
if isinstance(value, int | float) and not isinstance(value, bool) and value in _LEVELS:
|
|
61
|
+
return int(value)
|
|
62
|
+
return 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _strongest(a: int, b: int) -> int:
|
|
66
|
+
"""Return the max level of two sides of one entry.
|
|
67
|
+
|
|
68
|
+
Unknown (0) wins, since the unknown side may hold a purchase.
|
|
69
|
+
"""
|
|
70
|
+
return 0 if a == 0 or b == 0 else max(a, b)
|
|
71
|
+
|
|
72
|
+
|
|
56
73
|
class History:
|
|
57
74
|
"""One user's history: weighted top, recent list and rejection marks.
|
|
58
75
|
|
|
59
|
-
``top`` maps item -> (score, t),
|
|
76
|
+
``top`` maps item -> (score, t, m), where m is the strongest level applied
|
|
77
|
+
to the entry since it started (0 when unknown: an entry stored or sent
|
|
78
|
+
without it), ``recent`` is (item, t) oldest first,
|
|
60
79
|
``rejected`` maps item -> time of the newest rejection, ``last_t`` is the
|
|
61
80
|
newest event applied to the recent list (None when unknown).
|
|
62
81
|
"""
|
|
@@ -64,7 +83,7 @@ class History:
|
|
|
64
83
|
__slots__ = ("last_t", "recent", "rejected", "top")
|
|
65
84
|
|
|
66
85
|
def __init__(self) -> None:
|
|
67
|
-
self.top: dict[str, tuple[float, float]] = {}
|
|
86
|
+
self.top: dict[str, tuple[float, float, int]] = {}
|
|
68
87
|
self.recent: list[tuple[str, float]] = []
|
|
69
88
|
self.rejected: dict[str, float] = {}
|
|
70
89
|
self.last_t: float | None = None
|
|
@@ -91,11 +110,13 @@ class History:
|
|
|
91
110
|
del self.rejected[item]
|
|
92
111
|
current = self.top.get(item)
|
|
93
112
|
if current is None:
|
|
94
|
-
self.top[item] = (float(level), t)
|
|
113
|
+
self.top[item] = (float(level), t, level)
|
|
95
114
|
elif t >= current[1]:
|
|
96
|
-
|
|
115
|
+
m = _strongest(current[2], level)
|
|
116
|
+
self.top[item] = (current[0] * _decay(t - current[1]) + level, t, m)
|
|
97
117
|
else:
|
|
98
|
-
|
|
118
|
+
m = _strongest(current[2], level)
|
|
119
|
+
self.top[item] = (current[0] + level * _decay(current[1] - t), current[1], m)
|
|
99
120
|
if self.last_t is None or t >= self.last_t:
|
|
100
121
|
self.recent = [entry for entry in self.recent if entry[0] != item]
|
|
101
122
|
self.recent.append((item, t))
|
|
@@ -119,7 +140,7 @@ class History:
|
|
|
119
140
|
A time ahead of ``now`` reads as ``now``: a clock that ran ahead must not
|
|
120
141
|
grow the weight past what the API takes, or overflow.
|
|
121
142
|
"""
|
|
122
|
-
entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t) in self.top.items()]
|
|
143
|
+
entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t, _) in self.top.items()]
|
|
123
144
|
entries.sort(key=lambda e: (-e[1], e[0]))
|
|
124
145
|
return entries
|
|
125
146
|
|
|
@@ -131,7 +152,7 @@ class History:
|
|
|
131
152
|
if len(self.top) > TOP_K:
|
|
132
153
|
# Read at the newest entry when an event arrives out of order: at the old
|
|
133
154
|
# event's time ranked() would flatten the newer entries to their score.
|
|
134
|
-
at = max(now, *(
|
|
155
|
+
at = max(now, *(e[1] for e in self.top.values()))
|
|
135
156
|
self.top = {item: self.top[item] for item, _, _ in self.ranked(at)[:TOP_K]}
|
|
136
157
|
|
|
137
158
|
def _prune_rejected(self) -> None:
|
|
@@ -144,16 +165,19 @@ class History:
|
|
|
144
165
|
|
|
145
166
|
Weights are decayed to ``now``, at most what the API accepts, and rounded
|
|
146
167
|
half up to 4 decimals like JS ``Math.round`` (Python's ``round`` rounds half
|
|
147
|
-
to even); ages are whole seconds, never negative.
|
|
168
|
+
to even); ages are whole seconds, never negative. A fourth element is
|
|
169
|
+
the entry's strongest level, left out when unknown.
|
|
148
170
|
"""
|
|
149
|
-
history = [
|
|
150
|
-
|
|
171
|
+
history = []
|
|
172
|
+
for item, weight, t in self.ranked(now)[:TOP_K]:
|
|
173
|
+
entry: list[Any] = [
|
|
151
174
|
item,
|
|
152
175
|
math.floor(min(weight, MAX_REQUEST_WEIGHT) * 1e4 + 0.5) / 1e4,
|
|
153
176
|
max(0, math.floor((now - t) / 1000)),
|
|
154
177
|
]
|
|
155
|
-
|
|
156
|
-
|
|
178
|
+
if self.top[item][2] > 0:
|
|
179
|
+
entry.append(self.top[item][2])
|
|
180
|
+
history.append(entry)
|
|
157
181
|
recent = [item for item, _ in self.recent[-RECENT_SIZE:]]
|
|
158
182
|
return history, recent, self.rejected_order()
|
|
159
183
|
|
|
@@ -161,7 +185,8 @@ class History:
|
|
|
161
185
|
def from_snapshot(cls, snapshot: object) -> History:
|
|
162
186
|
"""Build a history from the server's snapshot, skipping invalid entries.
|
|
163
187
|
|
|
164
|
-
Each top entry is a score at ``as_of
|
|
188
|
+
Each top entry is a score at ``as_of`` with its strongest level (a third
|
|
189
|
+
element, unknown when absent or not 1-10), each rejected item a mark at
|
|
165
190
|
``as_of``. ``last_t`` stays unknown: ``as_of`` is the server clock, and a
|
|
166
191
|
local clock behind it would see every new event as out of order.
|
|
167
192
|
"""
|
|
@@ -171,7 +196,7 @@ class History:
|
|
|
171
196
|
as_of = snapshot["as_of"]
|
|
172
197
|
for e in _list(snapshot.get("top")):
|
|
173
198
|
if isinstance(e, list) and len(e) >= 2 and is_id(e[0]) and _is_weight(e[1]):
|
|
174
|
-
state.top[e[0]] = (float(e[1]), as_of)
|
|
199
|
+
state.top[e[0]] = (float(e[1]), as_of, _level(e[2]) if len(e) > 2 else 0)
|
|
175
200
|
seen: set[str] = set()
|
|
176
201
|
for item in _list(snapshot.get("recent")):
|
|
177
202
|
if is_id(item) and item not in seen:
|
|
@@ -188,20 +213,22 @@ class History:
|
|
|
188
213
|
def merge(self, other: History, now: float) -> History:
|
|
189
214
|
"""Return the union of two histories built from disjoint events.
|
|
190
215
|
|
|
191
|
-
Top scores add up, expressed at the later of the two times
|
|
216
|
+
Top scores add up, expressed at the later of the two times, and keep
|
|
217
|
+
the strongest level of the two (unknown if either is); the recent
|
|
192
218
|
lists are interleaved by time (``self`` first on ties); rejection marks
|
|
193
219
|
are united, and a mark older than the item's merged entry is dropped,
|
|
194
220
|
otherwise the item leaves the top and the recent list.
|
|
195
221
|
"""
|
|
196
222
|
out = History()
|
|
197
223
|
out.top = dict(self.top)
|
|
198
|
-
for item, (s, t) in other.top.items():
|
|
224
|
+
for item, (s, t, m) in other.top.items():
|
|
199
225
|
mine = out.top.get(item)
|
|
200
226
|
if mine is None:
|
|
201
|
-
out.top[item] = (s, t)
|
|
227
|
+
out.top[item] = (s, t, m)
|
|
202
228
|
continue
|
|
203
229
|
later = max(t, mine[1])
|
|
204
|
-
|
|
230
|
+
score = s * _decay(later - t) + mine[0] * _decay(later - mine[1])
|
|
231
|
+
out.top[item] = (score, later, _strongest(m, mine[2]))
|
|
205
232
|
|
|
206
233
|
out.rejected = dict(self.rejected)
|
|
207
234
|
for item, t in other.rejected.items():
|
|
@@ -242,12 +269,18 @@ class History:
|
|
|
242
269
|
return self.merge(trimmed, now)
|
|
243
270
|
|
|
244
271
|
def encode(self) -> dict[str, Any]:
|
|
245
|
-
"""Return the JSON-safe stored form (raw scores), shaped like JS ``encodeState``.
|
|
272
|
+
"""Return the JSON-safe stored form (raw scores), shaped like JS ``encodeState``.
|
|
273
|
+
|
|
274
|
+
``maxLevel`` is each top entry's strongest level, in top's order (0
|
|
275
|
+
unknown): a key of its own, not a fourth element, so a library from
|
|
276
|
+
before it still reads the state (it rejects a top entry of another length).
|
|
277
|
+
"""
|
|
246
278
|
return {
|
|
247
|
-
"top": [[item, s, t] for item, (s, t) in self.top.items()],
|
|
279
|
+
"top": [[item, s, t] for item, (s, t, _) in self.top.items()],
|
|
248
280
|
"recent": [[item, t] for item, t in self.recent],
|
|
249
281
|
"rejected": [[item, t] for item, t in self.rejected.items()],
|
|
250
282
|
"lastT": self.last_t,
|
|
283
|
+
"maxLevel": [m for _, _, m in self.top.values()],
|
|
251
284
|
}
|
|
252
285
|
|
|
253
286
|
@classmethod
|
|
@@ -255,12 +288,20 @@ class History:
|
|
|
255
288
|
"""Inverse of :meth:`encode`; None for any malformed field.
|
|
256
289
|
|
|
257
290
|
A state stored before rejections existed has no ``rejected``.
|
|
291
|
+
``maxLevel`` is read leniently: absent, not a list or not as long as
|
|
292
|
+
top, every level is unknown; a value that is not a level 1-10 is unknown.
|
|
258
293
|
"""
|
|
259
294
|
if not _valid_encoding(raw):
|
|
260
295
|
return None
|
|
261
296
|
assert isinstance(raw, dict)
|
|
262
297
|
state = cls()
|
|
263
|
-
|
|
298
|
+
levels = raw.get("maxLevel")
|
|
299
|
+
if not isinstance(levels, list) or len(levels) != len(raw["top"]):
|
|
300
|
+
levels = [0] * len(raw["top"])
|
|
301
|
+
state.top = {
|
|
302
|
+
item: (float(s), t, _level(m))
|
|
303
|
+
for (item, s, t), m in zip(raw["top"], levels, strict=True)
|
|
304
|
+
}
|
|
264
305
|
state.recent = [(item, t) for item, t in raw["recent"]]
|
|
265
306
|
state.rejected = {item: t for item, t in raw.get("rejected", [])}
|
|
266
307
|
state.last_t = raw["lastT"]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.14
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://recapi.io
|
|
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
49
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
50
50
|
|
|
51
51
|
```sh
|
|
52
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
To work on the library itself, install it from a checkout of recapi's repository
|
|
@@ -237,7 +237,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
237
237
|
|
|
238
238
|
| Method | What it does |
|
|
239
239
|
|---|---|
|
|
240
|
-
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
240
|
+
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None, value=None, currency=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. A purchase may carry `value` (what the buyer paid for the line) and `currency` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test. Raises `ValueError` for an invalid level or user, visitor or recommendation id, and for a negative or non-finite value or a currency without a value or not of three letters. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
241
241
|
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
242
|
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
243
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
@@ -115,6 +115,19 @@ class AsyncClient(APITest):
|
|
|
115
115
|
self.assertIn("invalid_request", logs.output[0])
|
|
116
116
|
self.assertNotIn("evil", logs.output[0])
|
|
117
117
|
|
|
118
|
+
def test_async_track_sends_an_amount(self) -> None:
|
|
119
|
+
client = self.async_client()
|
|
120
|
+
|
|
121
|
+
async def run() -> None:
|
|
122
|
+
await client.track("p1", "purchase", user_id="u", value=49.9, currency="EUR")
|
|
123
|
+
with self.assertRaises(ValueError):
|
|
124
|
+
await client.track("p1", "purchase", user_id="u", currency="EUR")
|
|
125
|
+
await client.flush()
|
|
126
|
+
|
|
127
|
+
asyncio.run(run())
|
|
128
|
+
sent = [e for batch in self.api.events() for e in batch]
|
|
129
|
+
self.assertEqual([(e["value"], e["currency"]) for e in sent], [(49.9, "EUR")])
|
|
130
|
+
|
|
118
131
|
def test_async_track_drops_an_unusable_item_id(self) -> None:
|
|
119
132
|
client = self.async_client()
|
|
120
133
|
|
|
@@ -256,7 +256,7 @@ class Recommend(APITest):
|
|
|
256
256
|
client.track("b", "cart", user_id="u")
|
|
257
257
|
result = client.recommend(user_id="u", count=4, placement="home", tags_any=["x"])
|
|
258
258
|
body = self.last_body("/v1/recommendations")
|
|
259
|
-
self.assertEqual(body["history"], [["b", 5.0, 0], ["a", 3.0, 1]])
|
|
259
|
+
self.assertEqual(body["history"], [["b", 5.0, 0, 5], ["a", 3.0, 1, 3]])
|
|
260
260
|
self.assertEqual(body["recent"], ["a", "b"])
|
|
261
261
|
self.assertEqual(
|
|
262
262
|
{k: body[k] for k in ("user_id", "count", "placement", "tags_any")},
|
|
@@ -574,6 +574,21 @@ class Store(APITest):
|
|
|
574
574
|
client.recommend(user_id="u")
|
|
575
575
|
self.assertEqual(self.last_body("/v1/recommendations")["history"], [])
|
|
576
576
|
|
|
577
|
+
def test_a_history_stored_by_the_previous_version_serves_the_same_lists(self) -> None:
|
|
578
|
+
# No maxLevel: its entries go out as before, an entry tracked since with its level.
|
|
579
|
+
store = recapi.MemoryStore()
|
|
580
|
+
client = self.client(store=store)
|
|
581
|
+
old = {"top": [["a", 3.0, T0]], "recent": [["a", T0]], "rejected": [], "lastT": T0}
|
|
582
|
+
key = client._key("u", None)
|
|
583
|
+
store.set(key, json.dumps({"history": old, "shown": [], "restored": True}))
|
|
584
|
+
client.track("s1", "view", user_id="u")
|
|
585
|
+
client.recommend(user_id="u")
|
|
586
|
+
body = self.last_body("/v1/recommendations")
|
|
587
|
+
self.assertEqual(body["history"], [["a", 3.0, 0], ["s1", 3.0, 0, 3]])
|
|
588
|
+
self.assertEqual(body["recent"], ["a", "s1"])
|
|
589
|
+
saved = json.loads(store.get(key))["history"]
|
|
590
|
+
self.assertEqual(([e[0] for e in saved["top"]], saved["maxLevel"]), (["a", "s1"], [0, 3]))
|
|
591
|
+
|
|
577
592
|
def test_a_stored_state_keeps_its_valid_and_newest_shown_entries(self) -> None:
|
|
578
593
|
# Written by another library version or by hand: bad entries are
|
|
579
594
|
# dropped one by one, and the next save keeps the newest 100.
|
|
@@ -947,7 +962,7 @@ class Snapshot(APITest):
|
|
|
947
962
|
client.recommend(user_id="u")
|
|
948
963
|
client.recommend(user_id="u")
|
|
949
964
|
body = self.last_body("/v1/recommendations")
|
|
950
|
-
self.assertEqual(body["history"], [["s", 4.0, 0], ["t", 3.0, 0]])
|
|
965
|
+
self.assertEqual(body["history"], [["s", 4.0, 0], ["t", 3.0, 0, 3]])
|
|
951
966
|
|
|
952
967
|
|
|
953
968
|
class Restore(APITest):
|
|
@@ -978,7 +993,7 @@ class Restore(APITest):
|
|
|
978
993
|
(fetch.method, fetch.headers["authorization"]), ("GET", f"Bearer {KEY}")
|
|
979
994
|
)
|
|
980
995
|
body = self.last_body("/v1/recommendations")
|
|
981
|
-
self.assertEqual(body["history"], [["s", 3.9997, 60], ["a", 3.0, 0]])
|
|
996
|
+
self.assertEqual(body["history"], [["s", 3.9997, 60], ["a", 3.0, 0, 3]])
|
|
982
997
|
self.assertEqual((body["recent"], body["exclude"]), (["s", "a"], ["bad"]))
|
|
983
998
|
self.assertTrue(self.restored(store, client))
|
|
984
999
|
client.recommend(user_id="u")
|
|
@@ -993,7 +1008,7 @@ class Restore(APITest):
|
|
|
993
1008
|
client.track("a", "view", user_id="u")
|
|
994
1009
|
client.recommend(user_id="u")
|
|
995
1010
|
body = self.last_body("/v1/recommendations")
|
|
996
|
-
self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0]], ["a"]))
|
|
1011
|
+
self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0, 3]], ["a"]))
|
|
997
1012
|
self.assertEqual(body["exclude"], ["s"])
|
|
998
1013
|
|
|
999
1014
|
def test_a_failed_fetch_keeps_the_local_history_and_is_tried_again(self) -> None:
|
|
@@ -1013,7 +1028,7 @@ class Restore(APITest):
|
|
|
1013
1028
|
result = client.recommend(user_id="u")
|
|
1014
1029
|
self.assertEqual(result.recommendation_id, "rec_1")
|
|
1015
1030
|
body = self.last_body("/v1/recommendations")
|
|
1016
|
-
self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0]], ["a"]))
|
|
1031
|
+
self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0, 3]], ["a"]))
|
|
1017
1032
|
self.assertFalse(self.restored(store, client))
|
|
1018
1033
|
self.api.on(self.HISTORY, Reply(200, self.STORED))
|
|
1019
1034
|
client.recommend(user_id="u")
|
|
@@ -1077,7 +1092,7 @@ class Restore(APITest):
|
|
|
1077
1092
|
self.api.on(self.HISTORY, reply)
|
|
1078
1093
|
client.track("a", "view", user_id="u")
|
|
1079
1094
|
client.recommend(user_id="u")
|
|
1080
|
-
want = ([["s", 3.9997, 60], ["a", 3.0, 0], ["b", 3.0, 0]], ["s", "a", "b"])
|
|
1095
|
+
want = ([["s", 3.9997, 60], ["a", 3.0, 0, 3], ["b", 3.0, 0, 3]], ["s", "a", "b"])
|
|
1081
1096
|
body = self.last_body("/v1/recommendations")
|
|
1082
1097
|
self.assertEqual((body["history"], body["recent"]), want)
|
|
1083
1098
|
client.recommend(user_id="u")
|
|
@@ -1178,7 +1193,7 @@ class Identify(APITest):
|
|
|
1178
1193
|
self.api.on("/v1/recommendations", Reply(200, recs(["z"], rec_id="rec_z")))
|
|
1179
1194
|
client.recommend(user_id="u")
|
|
1180
1195
|
body = self.last_body("/v1/recommendations")
|
|
1181
|
-
self.assertEqual(body["history"], [["a", 8.0, 0], ["b", 3.0, 0]])
|
|
1196
|
+
self.assertEqual(body["history"], [["a", 8.0, 0, 5], ["b", 3.0, 0, 3]])
|
|
1182
1197
|
self.assertEqual((body["recent"], body["exclude"]), (["a", "b"], ["x"]))
|
|
1183
1198
|
self.clock += MINUTE
|
|
1184
1199
|
client.track("r2", 3, user_id="u") # shown by both lists: the later one wins
|
|
@@ -480,3 +480,37 @@ class ClientVectors(APITest):
|
|
|
480
480
|
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
481
481
|
self.assertEqual(got, case["upserted"])
|
|
482
482
|
self.assertEqual(rejected, case["rejected"] or None)
|
|
483
|
+
|
|
484
|
+
def test_vector_amounts(self) -> None:
|
|
485
|
+
vectors = VECTORS["amounts"]
|
|
486
|
+
event = vectors["event"]
|
|
487
|
+
client = self.client()
|
|
488
|
+
bad = [*vectors["invalid"], {"value": float("nan")}, {"value": float("inf")}]
|
|
489
|
+
bad += [
|
|
490
|
+
{"value": float("-inf"), "currency": "EUR"},
|
|
491
|
+
{"value": True},
|
|
492
|
+
{"value": 1, "currency": ""},
|
|
493
|
+
{"value": 1, "currency": "ÉUR"}, # a letter, but not ASCII
|
|
494
|
+
{"value": 1, "currency": 978}, # the numeric code
|
|
495
|
+
]
|
|
496
|
+
for case in bad:
|
|
497
|
+
with self.subTest(case=case), self.assertRaises(ValueError):
|
|
498
|
+
client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
|
|
499
|
+
for case in vectors["valid"]:
|
|
500
|
+
client.track(event["item_id"], event["level"], user_id=event["user_id"], **case)
|
|
501
|
+
client.flush()
|
|
502
|
+
sent = [e for batch in self.api.events() for e in batch] # nothing of the invalid ones
|
|
503
|
+
self.assertEqual(len(sent), len(vectors["valid"]))
|
|
504
|
+
for want, got in zip(vectors["valid"], sent, strict=True):
|
|
505
|
+
for key in ("value", "currency"): # as given, absent when unset
|
|
506
|
+
self.assertEqual(got.get(key, "absent"), want.get(key, "absent"), want)
|
|
507
|
+
self.assertIs(type(got.get("value")), type(want.get("value")))
|
|
508
|
+
|
|
509
|
+
def test_every_vector_section_runs(self) -> None:
|
|
510
|
+
run = {"description", "max_events_per_request", "max_exclude", "recommend_timeout_ms",
|
|
511
|
+
"levels", "ids", "errors", "retry", "batches", "exclude", "context_ids", "fallback",
|
|
512
|
+
"restore", "identify", "stored_state", "metadata", "why", "lists", "upsert_items",
|
|
513
|
+
"amounts"} # fmt: skip
|
|
514
|
+
self.assertEqual(
|
|
515
|
+
set(VECTORS) - run, set(), "sections of spec/client_vectors.json not tested"
|
|
516
|
+
)
|
|
@@ -42,17 +42,53 @@ class SharedVectors(unittest.TestCase):
|
|
|
42
42
|
_, recent, rejected = state.wire(case["now"])
|
|
43
43
|
self.assertEqual(recent, case["expected_recent"])
|
|
44
44
|
self.assertEqual(rejected, case["expected_rejected"])
|
|
45
|
+
self.check_levels(state, case)
|
|
46
|
+
|
|
47
|
+
def check_levels(self, state: History, case: dict) -> None:
|
|
48
|
+
"""Compare each entry's strongest level with ``expected_max_level``, if the case has it."""
|
|
49
|
+
if "expected_max_level" in case:
|
|
50
|
+
got = {item: m for item, (_, _, m) in state.top.items()}
|
|
51
|
+
self.assertEqual(got, case["expected_max_level"])
|
|
52
|
+
|
|
53
|
+
def check_level_case(self, state: History, case: dict) -> None:
|
|
54
|
+
rel = VECTORS["tolerance"]["relative"]
|
|
55
|
+
ranked = state.ranked(case["now"])
|
|
56
|
+
self.assertEqual([e[0] for e in ranked], [e[0] for e in case["expected_top"]])
|
|
57
|
+
for (_, got, _), (_, want) in zip(ranked, case["expected_top"], strict=True):
|
|
58
|
+
self.assertLessEqual(abs(got - want), rel * max(1, abs(want)))
|
|
59
|
+
self.assertEqual(state.wire(case["now"])[1], case["expected_recent"])
|
|
60
|
+
self.check_levels(state, case)
|
|
61
|
+
|
|
62
|
+
def test_history_stored_level_vectors(self) -> None:
|
|
63
|
+
self.assertTrue(VECTORS["stored_cases"])
|
|
64
|
+
for case in VECTORS["stored_cases"]:
|
|
65
|
+
with self.subTest(case["name"]):
|
|
66
|
+
state = History.decode(case["stored"])
|
|
67
|
+
assert state is not None, "the stored state did not load"
|
|
68
|
+
for e in case["events"]:
|
|
69
|
+
state.apply(e["item"], e["level"], e["t"])
|
|
70
|
+
self.check_level_case(state, case)
|
|
71
|
+
again = History.decode(json.loads(json.dumps(state.encode())))
|
|
72
|
+
assert again is not None, "the encoded state did not load"
|
|
73
|
+
self.check_level_case(again, case)
|
|
74
|
+
|
|
75
|
+
def test_history_snapshot_level_vectors(self) -> None:
|
|
76
|
+
self.assertTrue(VECTORS["snapshot_cases"])
|
|
77
|
+
for case in VECTORS["snapshot_cases"]:
|
|
78
|
+
with self.subTest(case["name"]):
|
|
79
|
+
state = build([(e["item"], e["level"], e["t"]) for e in case["events"]])
|
|
80
|
+
snapshot = History.from_snapshot(case["snapshot"])
|
|
81
|
+
self.check_level_case(state.merge_snapshot(snapshot, case["now"]), case)
|
|
45
82
|
|
|
46
83
|
|
|
47
84
|
class Behaviour(unittest.TestCase):
|
|
48
85
|
def test_wire_rounds_half_up_and_never_sends_negative_ages(self) -> None:
|
|
49
86
|
state = History()
|
|
50
87
|
# JS Math.round(2.00025 * 1e4) / 1e4 is 2.0003; Python's round() says 2.0002.
|
|
51
|
-
state.top = {"a": (2.00025, T0), "b": (1.0, T0 + 5000), "c": (1.0, T0 - 61_500)}
|
|
88
|
+
state.top = {"a": (2.00025, T0, 3), "b": (1.0, T0 + 5000, 0), "c": (1.0, T0 - 61_500, 1)}
|
|
52
89
|
history, _, _ = state.wire(T0)
|
|
53
|
-
|
|
54
|
-
self.assertEqual(history
|
|
55
|
-
self.assertEqual((history[1][2], history[2][2]), (0, 61))
|
|
90
|
+
# The fourth element is the strongest level, left out when unknown.
|
|
91
|
+
self.assertEqual(history, [["a", 2.0003, 0, 3], ["b", 1.0, 0], ["c", 0.9999, 61, 1]])
|
|
56
92
|
|
|
57
93
|
def test_the_lists_are_bounded_and_rejections_alone_are_empty(self) -> None:
|
|
58
94
|
state = build([(f"i{i:02}", 1 + i % 3, T0 + i) for i in range(60)])
|
|
@@ -71,7 +107,7 @@ class Behaviour(unittest.TestCase):
|
|
|
71
107
|
"as_of": T0,
|
|
72
108
|
}
|
|
73
109
|
state = History.from_snapshot(snapshot)
|
|
74
|
-
self.assertEqual(state.top, {"a": (2.0, T0)})
|
|
110
|
+
self.assertEqual(state.top, {"a": (2.0, T0, 0)})
|
|
75
111
|
self.assertEqual(state.recent, [("a", T0), ("z", T0)])
|
|
76
112
|
self.assertEqual(state.rejected, {"x": T0})
|
|
77
113
|
self.assertIsNone(state.last_t)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|