kederi 0.1.0__py3-none-any.whl

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.
kederi/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Kederi: bank transaction enrichment. See https://kederi.com/docs."""
2
+
3
+ from .client import DEFAULT_BASE_URL, MAX_BATCH, Kederi
4
+ from .errors import KederiError
5
+
6
+ __all__ = ["Kederi", "KederiError", "DEFAULT_BASE_URL", "MAX_BATCH"]
7
+ __version__ = "0.1.0"
kederi/client.py ADDED
@@ -0,0 +1,245 @@
1
+ """The Kederi API client. Standard library only, so it adds no dependency.
2
+
3
+ Each method is one call to the API, and the method docstring names it. The
4
+ client stores nothing: like the API, it sends a request and returns the
5
+ answer.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import random
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence
18
+
19
+ from .errors import KederiError
20
+
21
+ __all__ = ["Kederi", "DEFAULT_BASE_URL", "MAX_BATCH"]
22
+
23
+ DEFAULT_BASE_URL = "https://kederi.com/v1"
24
+ # The API refuses a batch of more than this. enrich_all() splits for you.
25
+ MAX_BATCH = 1000
26
+ # Statuses worth a second try. 429 is a rate limit; the rest are transient.
27
+ _RETRY_STATUSES = {429, 500, 502, 503, 504}
28
+
29
+ Json = Dict[str, Any]
30
+
31
+
32
+ class Kederi:
33
+ """A client for the Kederi API.
34
+
35
+ ``api_key`` defaults to the ``KEDERI_API_KEY`` environment variable.
36
+ A rate-limited or transient failure is tried again up to ``max_retries``
37
+ times. A 429 waits for the ``Retry-After`` the API sends.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ api_key: Optional[str] = None,
43
+ *,
44
+ base_url: str = DEFAULT_BASE_URL,
45
+ timeout: float = 30.0,
46
+ max_retries: int = 2,
47
+ ) -> None:
48
+ self.api_key = api_key if api_key is not None else os.environ.get("KEDERI_API_KEY")
49
+ self.base_url = base_url.rstrip("/")
50
+ self.timeout = timeout
51
+ self.max_retries = max_retries
52
+ # The budget headers from the last answer (RateLimit-Remaining and
53
+ # the others), so a caller can slow down before a 429.
54
+ self.last_rate_limit: Dict[str, str] = {}
55
+
56
+ # ---- enrichment ----
57
+
58
+ def enrich(
59
+ self,
60
+ descriptor: str,
61
+ *,
62
+ direction: Optional[str] = None,
63
+ amount: Optional[float] = None,
64
+ date: Optional[str] = None,
65
+ account_id: Optional[str] = None,
66
+ category_map: Optional[Mapping[str, str]] = None,
67
+ ) -> Json:
68
+ """``POST /enrich``, single form. Returns ``{"input", "enrichment"}``."""
69
+ body: Json = {"descriptor": descriptor}
70
+ for key, value in (("direction", direction), ("amount", amount), ("date", date), ("account_id", account_id)):
71
+ if value is not None:
72
+ body[key] = value
73
+ if category_map is not None:
74
+ body["category_map"] = dict(category_map)
75
+ return self._request("POST", "/enrich", body)
76
+
77
+ def enrich_batch(
78
+ self,
79
+ transactions: Sequence[Mapping[str, Any]],
80
+ *,
81
+ category_map: Optional[Mapping[str, str]] = None,
82
+ ) -> List[Json]:
83
+ """``POST /enrich``, batch form, at most 1000 rows. Returns the ``results`` list.
84
+
85
+ Recurrence is found ACROSS the batch, so send a series in one call.
86
+ """
87
+ if len(transactions) > MAX_BATCH:
88
+ raise ValueError(f"at most {MAX_BATCH} transactions in one call; use enrich_all() to split")
89
+ body: Json = {"transactions": [dict(t) for t in transactions]}
90
+ if category_map is not None:
91
+ body["category_map"] = dict(category_map)
92
+ return self._request("POST", "/enrich", body)["results"]
93
+
94
+ def enrich_all(
95
+ self,
96
+ transactions: Iterable[Mapping[str, Any]],
97
+ *,
98
+ category_map: Optional[Mapping[str, str]] = None,
99
+ ) -> Iterator[Json]:
100
+ """``POST /enrich`` in batches of 1000, yielding each result in order.
101
+
102
+ A series that crosses a batch boundary is not detected as recurring.
103
+ For recurrence over a whole history, use ``reports()``.
104
+ """
105
+ chunk: List[Mapping[str, Any]] = []
106
+ for t in transactions:
107
+ chunk.append(t)
108
+ if len(chunk) == MAX_BATCH:
109
+ yield from self.enrich_batch(chunk, category_map=category_map)
110
+ chunk = []
111
+ if chunk:
112
+ yield from self.enrich_batch(chunk, category_map=category_map)
113
+
114
+ def statements(self, content: str, **fields: Any) -> Json:
115
+ """``POST /statements``: a statement file (CSV, OFX, QIF, JSON, or a PDF as base64).
116
+
117
+ Extra fields (``filename``, ``date_order``, ``mapping``, ``payload``,
118
+ ``profile``) go into the body as the API documents them.
119
+ """
120
+ return self._request("POST", "/statements", {"content": content, **fields})
121
+
122
+ def reports(
123
+ self,
124
+ transactions: Sequence[Mapping[str, Any]],
125
+ *,
126
+ reports: Optional[Sequence[str]] = None,
127
+ account_holder: Optional[str] = None,
128
+ **fields: Any,
129
+ ) -> Json:
130
+ """``POST /reports``: every analytic over the rows you send. Nothing is stored.
131
+
132
+ Each row needs ``amount`` and ``date``. Extra fields (``as_of``,
133
+ ``days``, ``balance``, ``category``, ``name``, ``q``) go into the body.
134
+ """
135
+ body: Json = {"transactions": [dict(t) for t in transactions], **fields}
136
+ if reports is not None:
137
+ body["reports"] = list(reports)
138
+ if account_holder is not None:
139
+ body["account_holder"] = account_holder
140
+ return self._request("POST", "/reports", body)
141
+
142
+ # ---- the directory ----
143
+
144
+ def merchant(self, merchant_id: str) -> Json:
145
+ """``GET /merchants/{id}``: the record for a ``merchant_id``."""
146
+ return self._request("GET", "/merchants/" + urllib.parse.quote(merchant_id, safe=""))
147
+
148
+ def taxonomy(self) -> Json:
149
+ """``GET /taxonomy``: the category names and intent labels, with a version."""
150
+ return self._request("GET", "/taxonomy")
151
+
152
+ def coverage(self) -> Json:
153
+ """``GET /coverage``: the countries and how many merchants each has."""
154
+ return self._request("GET", "/coverage")
155
+
156
+ # ---- corrections ----
157
+
158
+ def report_wrong(
159
+ self,
160
+ descriptor: str,
161
+ *,
162
+ name: Optional[str] = None,
163
+ category: Optional[str] = None,
164
+ intent: Optional[str] = None,
165
+ type: Optional[str] = None,
166
+ note: Optional[str] = None,
167
+ ) -> Json:
168
+ """``POST /feedback``: say what the right answer was. The narration is KEPT."""
169
+ expected = {k: v for k, v in (("name", name), ("category", category), ("intent", intent), ("type", type)) if v is not None}
170
+ body: Json = {"descriptor": descriptor}
171
+ if expected:
172
+ body["expected"] = expected
173
+ if note is not None:
174
+ body["note"] = note
175
+ return self._request("POST", "/feedback", body)
176
+
177
+ def feedback(self, status: Optional[str] = None) -> Json:
178
+ """``GET /feedback``: what became of the corrections you sent."""
179
+ return self._request("GET", "/feedback", query={"status": status})
180
+
181
+ # ---- the account ----
182
+
183
+ def me(self) -> Json:
184
+ """``GET /auth/me``: which account and key this client is."""
185
+ return self._request("GET", "/auth/me")
186
+
187
+ def usage(self, *, days: Optional[int] = None, from_: Optional[str] = None, to: Optional[str] = None) -> Json:
188
+ """``GET /usage``: billable enrichments. ``from_`` is the API's ``from``."""
189
+ return self._request("GET", "/usage", query={"days": days, "from": from_, "to": to})
190
+
191
+ # ---- transport ----
192
+
193
+ def _request(self, method: str, path: str, body: Optional[Json] = None, query: Optional[Mapping[str, Any]] = None) -> Json:
194
+ url = self.base_url + path
195
+ if query:
196
+ q = {k: v for k, v in query.items() if v is not None}
197
+ if q:
198
+ url += "?" + urllib.parse.urlencode(q)
199
+ data = json.dumps(body).encode("utf-8") if body is not None else None
200
+ headers = {"accept": "application/json", "user-agent": "kederi-python/0.1.0"}
201
+ if data is not None:
202
+ headers["content-type"] = "application/json"
203
+ if self.api_key:
204
+ headers["authorization"] = "Bearer " + self.api_key
205
+
206
+ attempt = 0
207
+ while True:
208
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
209
+ try:
210
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
211
+ self._note_budget(res.headers)
212
+ return json.loads(res.read().decode("utf-8") or "null")
213
+ except urllib.error.HTTPError as e:
214
+ self._note_budget(e.headers)
215
+ raw = e.read().decode("utf-8", "replace")
216
+ if e.code in _RETRY_STATUSES and attempt < self.max_retries:
217
+ time.sleep(self._wait(e.headers, attempt))
218
+ attempt += 1
219
+ continue
220
+ raise KederiError.from_response(e.code, raw, e.headers) from None
221
+ except urllib.error.URLError as e:
222
+ if attempt < self.max_retries:
223
+ time.sleep(self._wait(None, attempt))
224
+ attempt += 1
225
+ continue
226
+ raise KederiError(0, "network_error", str(e.reason)) from None
227
+
228
+ def _note_budget(self, headers: Any) -> None:
229
+ if headers is None:
230
+ return
231
+ self.last_rate_limit = {
232
+ k: v for k, v in headers.items() if k.lower().startswith("ratelimit-") or k.lower() == "retry-after"
233
+ }
234
+
235
+ @staticmethod
236
+ def _wait(headers: Any, attempt: int) -> float:
237
+ # The API says how long, on a 429. Otherwise back off with jitter.
238
+ if headers is not None:
239
+ ra = headers.get("Retry-After")
240
+ if ra:
241
+ try:
242
+ return min(float(ra), 60.0)
243
+ except ValueError:
244
+ pass
245
+ return min(0.5 * (2 ** attempt) + random.random() * 0.25, 8.0)
kederi/errors.py ADDED
@@ -0,0 +1,44 @@
1
+ """The one error type. The API answers an error as
2
+ ``{"error": {"code", "message", "details"?}}``, and this carries those fields.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ from typing import Any, Optional
9
+
10
+
11
+ class KederiError(Exception):
12
+ """An answer that was not a success.
13
+
14
+ ``status`` is the HTTP status (0 when the server was not reached).
15
+ ``code`` is the API's error code, for example ``invalid_request``,
16
+ ``rate_limited`` or ``quota_exceeded``. Branch on ``code``, not on the
17
+ message, which is written for a person.
18
+ """
19
+
20
+ def __init__(self, status: int, code: str, message: str, details: Any = None, retry_after: Optional[float] = None) -> None:
21
+ super().__init__(f"{status} {code}: {message}")
22
+ self.status = status
23
+ self.code = code
24
+ self.message = message
25
+ self.details = details
26
+ self.retry_after = retry_after
27
+
28
+ @classmethod
29
+ def from_response(cls, status: int, raw: str, headers: Any = None) -> "KederiError":
30
+ code, message, details = "http_error", raw[:500] or f"HTTP {status}", None
31
+ try:
32
+ err = json.loads(raw).get("error") or {}
33
+ code = err.get("code", code)
34
+ message = err.get("message", message)
35
+ details = err.get("details")
36
+ except (ValueError, AttributeError):
37
+ pass
38
+ retry_after = None
39
+ if headers is not None and headers.get("Retry-After"):
40
+ try:
41
+ retry_after = float(headers.get("Retry-After"))
42
+ except ValueError:
43
+ pass
44
+ return cls(status, code, message, details, retry_after)
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: kederi
3
+ Version: 0.1.0
4
+ Summary: Client for the Kederi transaction enrichment API
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://kederi.com/docs
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # kederi (Python)
13
+
14
+ A client for the [Kederi API](https://kederi.com/docs). It uses the Python
15
+ standard library only.
16
+
17
+ MIT licensed (see `LICENSE`). Not on PyPI yet: install it from this folder.
18
+
19
+ ```sh
20
+ pip install ./sdk/python
21
+ ```
22
+
23
+ ## Use
24
+
25
+ ```python
26
+ from kederi import Kederi, KederiError
27
+
28
+ k = Kederi() # reads KEDERI_API_KEY
29
+
30
+ r = k.enrich("NIP/GTB/ADEBAYO CHUKWU/rent for august", direction="debit")
31
+ print(r["enrichment"]["name"], r["enrichment"]["intent"])
32
+
33
+ # a batch, with your own categories
34
+ results = k.enrich_batch(
35
+ [{"descriptor": "SQ *BLUE BOTTLE 8005551234 CA"}, {"descriptor": "NETFLIX.COM"}],
36
+ category_map={"Coffee": "Eating out", "*": "Other"},
37
+ )
38
+
39
+ # any number of rows, in calls of 1000
40
+ for result in k.enrich_all(rows):
41
+ ...
42
+
43
+ # every report over rows you send; nothing is stored
44
+ reports = k.reports(rows, reports=["subscriptions", "counterparties"], account_holder="Ada Obi")
45
+
46
+ # the stable id of a merchant
47
+ m = k.merchant(results[0]["enrichment"]["merchant_id"])
48
+ ```
49
+
50
+ ## Errors and retries
51
+
52
+ A failure raises `KederiError` with `status`, `code`, `message` and
53
+ `details`. Branch on `code`. The client tries a 429 or a 5xx answer again,
54
+ twice by default (`max_retries`), and waits for the `Retry-After` the API
55
+ sends. `client.last_rate_limit` holds the budget headers from the last answer.
56
+
57
+ ## What it does not cover
58
+
59
+ Signing in and managing keys. An API key cannot manage API keys, so those
60
+ calls need a console session. Use the console at https://kederi.com/console.
61
+
62
+ ## Test
63
+
64
+ ```sh
65
+ python3 -m unittest discover -s sdk/python/tests
66
+ ```
@@ -0,0 +1,8 @@
1
+ kederi/__init__.py,sha256=i8AhJ7JRu_UXvxamMofQDv9ce0kST3eELKYuSI1wRIE,253
2
+ kederi/client.py,sha256=mnXnuv76yG4mGnwYONiqfCeYrlMX3Gnq44GxH9P0CTo,9628
3
+ kederi/errors.py,sha256=ibV21j7rB_6CkNgV32BIiX7V3S4xacvDBGf9u-p8q3s,1636
4
+ kederi-0.1.0.dist-info/licenses/LICENSE,sha256=-ffDXqTtQ2lvwZap5VrlH93FH_2qi4clZraPnW1A2xo,1067
5
+ kederi-0.1.0.dist-info/METADATA,sha256=1dOfMCM-Zc7gz7vbd4VInhEj8JfBHMZNwSdZ4VMXk7A,1851
6
+ kederi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ kederi-0.1.0.dist-info/top_level.txt,sha256=t9_IWDDcna8xBwTOvD6MFsDqMjtIRZq6QoARs3RxQf8,7
8
+ kederi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tolu Aina.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ kederi