kedai 0.2.1__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.

Potentially problematic release.


This version of kedai might be problematic. Click here for more details.

kedai-0.2.1/PKG-INFO ADDED
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: kedai
3
+ Version: 0.2.1
4
+ Summary: Read a published Kedai dashboard or call a published Kedai endpoint from Python.
5
+ Author: Kedai
6
+ License: MIT
7
+ Project-URL: Homepage, https://kedai.io
8
+ Project-URL: Documentation, https://app.kedai.io/python/
9
+ Keywords: kedai,dashboard,workflow,api
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # kedai
17
+
18
+ Kedai turns a data need into a maintained workflow with a stable endpoint, a schedule and a
19
+ shareable dashboard; this package reads what Kedai publishes, from Python. Learn more at
20
+ https://kedai.io.
21
+
22
+ Read a published Kedai dashboard, or call a published Kedai endpoint, from Python. Standard
23
+ library only; `pandas` is optional.
24
+
25
+ ```python
26
+ import kedai
27
+
28
+ board = kedai.dashboard.get("https://app.kedai.io/v/form4-monitor")
29
+ board.widgets["filings"].to_df() # the table card, as the page shows it
30
+ board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
31
+ board.widgets["total"].value(range=7) # the metric over the last seven days
32
+ board.widgets["total"].recipe() # the calls that read this card, as data
33
+
34
+ answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
35
+ answer["result"]
36
+ ```
37
+
38
+ A widget's methods: `value()` and `formatted()` read a metric, `points()` a line, area, bar
39
+ or donut, `table()` a table, and `to_df()` any of them as a pandas DataFrame; `rows()` is the
40
+ card's stored rows in the date window. `recipe()` lists the ones that read the widget's
41
+ card, each with the one-line comment a published page's "Use this data" snippet prints
42
+ beside it, and `kedai.dashboard.recipes()` lists them for every card kind.
43
+
44
+ A private dashboard takes an account key (`api_key=` or `KEDAI_API_KEY`). Card values are
45
+ computed from the dashboard's data document with the same rules the page uses: a date
46
+ window over the cards' date fields (`"all"`, `7`, `30`, or `("2026-11-01", "2026-11-28")`),
47
+ sums per label, trend points sorted by label, breakdowns sorted by value with a donut's
48
+ long tail folded into `Other`, tables newest first.
49
+
50
+ Every Kedai deployment also serves this package from its own release, at `/python/`:
51
+ `pip install https://app.kedai.io/python/kedai-0.2.1-py3-none-any.whl`.
52
+
53
+ The package is `kedai` on PyPI; the server's own code is also a Python package named `kedai`
54
+ but is never published there. A developer environment holding both should keep the server
55
+ on its path and read this package through its own virtual environment.
kedai-0.2.1/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # kedai
2
+
3
+ Kedai turns a data need into a maintained workflow with a stable endpoint, a schedule and a
4
+ shareable dashboard; this package reads what Kedai publishes, from Python. Learn more at
5
+ https://kedai.io.
6
+
7
+ Read a published Kedai dashboard, or call a published Kedai endpoint, from Python. Standard
8
+ library only; `pandas` is optional.
9
+
10
+ ```python
11
+ import kedai
12
+
13
+ board = kedai.dashboard.get("https://app.kedai.io/v/form4-monitor")
14
+ board.widgets["filings"].to_df() # the table card, as the page shows it
15
+ board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
16
+ board.widgets["total"].value(range=7) # the metric over the last seven days
17
+ board.widgets["total"].recipe() # the calls that read this card, as data
18
+
19
+ answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
20
+ answer["result"]
21
+ ```
22
+
23
+ A widget's methods: `value()` and `formatted()` read a metric, `points()` a line, area, bar
24
+ or donut, `table()` a table, and `to_df()` any of them as a pandas DataFrame; `rows()` is the
25
+ card's stored rows in the date window. `recipe()` lists the ones that read the widget's
26
+ card, each with the one-line comment a published page's "Use this data" snippet prints
27
+ beside it, and `kedai.dashboard.recipes()` lists them for every card kind.
28
+
29
+ A private dashboard takes an account key (`api_key=` or `KEDAI_API_KEY`). Card values are
30
+ computed from the dashboard's data document with the same rules the page uses: a date
31
+ window over the cards' date fields (`"all"`, `7`, `30`, or `("2026-11-01", "2026-11-28")`),
32
+ sums per label, trend points sorted by label, breakdowns sorted by value with a donut's
33
+ long tail folded into `Other`, tables newest first.
34
+
35
+ Every Kedai deployment also serves this package from its own release, at `/python/`:
36
+ `pip install https://app.kedai.io/python/kedai-0.2.1-py3-none-any.whl`.
37
+
38
+ The package is `kedai` on PyPI; the server's own code is also a Python package named `kedai`
39
+ but is never published there. A developer environment holding both should keep the server
40
+ on its path and read this package through its own virtual environment.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kedai"
7
+ version = "0.2.1"
8
+ description = "Read a published Kedai dashboard or call a published Kedai endpoint from Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Kedai" }]
13
+ keywords = ["kedai", "dashboard", "workflow", "api"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = []
20
+
21
+ [project.urls]
22
+ Homepage = "https://kedai.io"
23
+ Documentation = "https://app.kedai.io/python/"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
kedai-0.2.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """Kedai from Python: a published dashboard's widgets and a published endpoint's calls."""
2
+
3
+ from . import dashboard
4
+ from .endpoint import EndpointError, invoke, schema
5
+
6
+ __all__ = ["dashboard", "invoke", "schema", "EndpointError"]
7
+ __version__ = "0.2.1"
@@ -0,0 +1,341 @@
1
+ """Read a published Kedai dashboard: the same numbers the page shows, as Python values.
2
+
3
+ board = kedai.dashboard.get("https://app.kedai.io/v/form4-monitor")
4
+ board.widgets["filings"].table() # the rows, newest first
5
+ board.widgets["new_per_day"].points() # the chart's points: [{"label": ..., "value": ...}]
6
+ board.widgets["total"].value() # the number on the metric card
7
+ board.widgets["filings"].to_df() # any of the above as a pandas DataFrame (requires pandas)
8
+ board.widgets["total"].recipe() # which of those calls read this card, as data
9
+
10
+ A dashboard's data document is one consistent snapshot: the layout (its cards) and the
11
+ dataset the cards read. Every card's aggregation happens here, by the rules the page uses
12
+ (plugins/dashboard/kedai_dashboard/dashboard.js): the date window over the cards' date
13
+ fields, sums per label, trend points sorted by label, breakdowns sorted by value with a
14
+ donut's long tail folded into "Other", tables newest first. A private dashboard takes an
15
+ account key (`api_key=` or KEDAI_API_KEY).
16
+
17
+ Every method a published page's "Use this data" snippet shows declares itself with
18
+ @reads: the card kinds it serves and the card keys whose values name the fields it reads.
19
+ The first line of its docstring is the comment the snippet prints. recipes() is that
20
+ table, to_df() dispatches through it, and the server that serves this package publishes
21
+ it as /python/manifest.json, which the page composes every snippet from. A new method or
22
+ card kind is therefore a change to this file and a new release, never to the page.
23
+ """
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import urllib.error
29
+ import urllib.request
30
+ from datetime import date, timedelta
31
+
32
+ __all__ = ["get", "Dashboard", "Widget", "DashboardError", "format_value", "money", "recipes"]
33
+
34
+ DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
35
+ MAX_RESPONSE_BYTES = 16 * 1024 * 1024
36
+ # The release in __init__.py and pyproject.toml; tests/clients keeps the three in step.
37
+ USER_AGENT = "kedai-python/0.2.1 (+https://kedai.io)"
38
+ MAX_SAFE_INTEGER = 2**53 - 1
39
+ MAX_CATEGORIES = 366
40
+ DONUT_SLICES = 7
41
+ BAR_ROWS = 12
42
+
43
+
44
+ class DashboardError(RuntimeError):
45
+ """The dashboard could not be read or a card could not be computed; .status, .detail."""
46
+
47
+ def __init__(self, status, detail):
48
+ super().__init__(f"HTTP {status}: {detail}" if status else detail)
49
+ self.status, self.detail = status, detail
50
+
51
+
52
+ def get(url, api_key=None, timeout=30):
53
+ """Fetch a published dashboard's data document and wrap it. `url` is the page's address
54
+ (https://host/v/<view>) or its data address; a private view needs an account key."""
55
+ data_url = url.rstrip("/")
56
+ if not data_url.endswith("/data"):
57
+ data_url += "/data"
58
+ document, etag = _fetch(data_url, api_key, timeout)
59
+ return Dashboard(document, url=data_url, api_key=api_key, timeout=timeout, etag=etag)
60
+
61
+
62
+ def _fetch(url, api_key, timeout, etag=None):
63
+ headers = {"accept": "application/json", "user-agent": USER_AGENT}
64
+ key = api_key or os.environ.get("KEDAI_API_KEY")
65
+ if key:
66
+ headers["authorization"] = "Bearer " + key
67
+ if etag:
68
+ headers["if-none-match"] = etag
69
+ request = urllib.request.Request(url, headers=headers, method="GET")
70
+ try:
71
+ with urllib.request.urlopen(request, timeout=timeout) as response:
72
+ if response.status == 304:
73
+ return None, etag
74
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
75
+ answer = response.headers.get("etag")
76
+ except urllib.error.HTTPError as refused:
77
+ if refused.code == 304:
78
+ return None, etag
79
+ body = refused.read(65536).decode("utf-8", "replace")
80
+ try:
81
+ detail = json.loads(body).get("detail") or body
82
+ except ValueError:
83
+ detail = body or "the view sent no sentence"
84
+ raise DashboardError(refused.code, detail) from None
85
+ if len(raw) > MAX_RESPONSE_BYTES:
86
+ raise DashboardError(None, f"the data document exceeded {MAX_RESPONSE_BYTES} bytes")
87
+ try:
88
+ document = json.loads(raw.decode("utf-8"))
89
+ except ValueError as error:
90
+ raise DashboardError(None, f"the data document is not JSON: {error}") from None
91
+ if not isinstance(document, dict) or not isinstance(document.get("layout"), dict):
92
+ raise DashboardError(None, "the answer is not a dashboard data document")
93
+ return document, answer
94
+
95
+
96
+ class Dashboard:
97
+ """One snapshot of a published dashboard: its layout, its dataset and its widgets by card id."""
98
+
99
+ def __init__(self, document, *, url=None, api_key=None, timeout=30, etag=None):
100
+ self.document, self.url, self.api_key, self.timeout, self.etag = document, url, api_key, timeout, etag
101
+ self.version = document.get("version")
102
+ self.revision = document.get("revision")
103
+ self.data_version = document.get("data_version")
104
+ self.layout = document["layout"]
105
+ self.type = document.get("type")
106
+ self.value = document.get("value")
107
+ self.freshness = document.get("freshness")
108
+ self.widgets = {card["id"]: Widget(self, card) for card in self.layout.get("cards", [])}
109
+
110
+ @property
111
+ def title(self):
112
+ return self.layout.get("title")
113
+
114
+ @property
115
+ def cards(self):
116
+ return list(self.layout.get("cards", []))
117
+
118
+ def refresh(self):
119
+ """The current snapshot: this one when the server says nothing changed, else a new one."""
120
+ if not self.url:
121
+ return self
122
+ document, etag = _fetch(self.url, self.api_key, self.timeout, self.etag)
123
+ if document is None:
124
+ return self
125
+ return Dashboard(document, url=self.url, api_key=self.api_key, timeout=self.timeout, etag=etag)
126
+
127
+ def dates(self):
128
+ """The first and last date any dated card sees, as the page computes its windows."""
129
+ found = []
130
+ for card in self.cards:
131
+ rows = self.value.get(card["source"]) if card.get("source") else self.value
132
+ if card.get("date") and isinstance(rows, list):
133
+ found.extend(str(row.get(card["date"])) for row in rows
134
+ if isinstance(row, dict) and isinstance(row.get(card["date"]), str) and DATE.match(row[card["date"]]))
135
+ found.sort()
136
+ return (found[0], found[-1]) if found else (None, None)
137
+
138
+ def window(self, range="all"):
139
+ """(from, to) for a range: "all", 7 or 30 days back from the latest date, or (from, to)."""
140
+ first, last = self.dates()
141
+ if isinstance(range, (tuple, list)) and len(range) == 2:
142
+ return (range[0] or first, range[1] or last)
143
+ if isinstance(range, dict):
144
+ return (range.get("from") or first, range.get("to") or last)
145
+ if range in ("all", None) or not last:
146
+ return (first, last)
147
+ days = int(range)
148
+ start = date.fromisoformat(last) - timedelta(days=days - 1)
149
+ return (start.isoformat(), last)
150
+
151
+
152
+ # The kinds a recipe names when it serves every card kind another recipe names.
153
+ EVERY_KIND = "*"
154
+ # How a script that reads a published dashboard begins, for the snippets a published page
155
+ # composes from this module; recipes() gives each card kind's calls. URL and ID stand for
156
+ # the page's address and a card's id, which the page writes in as quoted strings.
157
+ SCRIPT = {
158
+ "get": {"call": "kedai.dashboard.get(URL)",
159
+ "keyed_call": 'kedai.dashboard.get(URL, api_key=os.environ["KEDAI_API_KEY"])',
160
+ "keyed_import": "import os",
161
+ "comment": "",
162
+ "keyed_comment": "a private dashboard needs your account key"},
163
+ "widgets": "board.widgets[ID]",
164
+ "range": 'Add range=7, range=30 or range=("2026-01-01", "2026-01-31") to any call to limit the dates.',
165
+ }
166
+
167
+
168
+ def reads(*kinds, fields=(), aggregate=None, requires=None):
169
+ """Declare a Widget method one of the calls a published page's snippet shows.
170
+
171
+ `kinds` are the card kinds it serves, or EVERY_KIND; `fields` the card keys whose
172
+ values name the fields it reads (label, value, date, columns); `aggregate` how it
173
+ combines the first of those over the rows ("sum"), when it does; `requires` the extra
174
+ it needs ("pandas"), when it needs one. The first line of the method's docstring is
175
+ the comment the snippet prints beside the call, so it reads as one line."""
176
+ def declare(method):
177
+ method.reads = {"kinds": tuple(kinds), "fields": tuple(fields), "aggregate": aggregate, "requires": requires}
178
+ return method
179
+ return declare
180
+
181
+
182
+ class Widget:
183
+ """One card of a dashboard, computed as the page computes it."""
184
+
185
+ def __init__(self, dashboard, card):
186
+ self.dashboard, self.card = dashboard, card
187
+ self.id, self.kind, self.title = card["id"], card.get("kind"), card.get("title")
188
+
189
+ def __repr__(self):
190
+ return f"Widget({self.id!r}, kind={self.kind!r})"
191
+
192
+ def rows(self, range="all"):
193
+ """The card's source within the date window: a list of rows, or a scalar for a
194
+ metric card over a scalar source."""
195
+ card = self.card
196
+ source = self.dashboard.value.get(card["source"]) if card.get("source") else self.dashboard.value
197
+ if not isinstance(source, list):
198
+ return source
199
+ if not card.get("date"):
200
+ return list(source)
201
+ start, end = self.dashboard.window(range)
202
+ if start and end and start > end:
203
+ return []
204
+ key = card["date"]
205
+ return [row for row in source
206
+ if (not start or str(row.get(key)) >= start) and (not end or str(row.get(key)) <= end)]
207
+
208
+ @reads("metric", fields=("value", "date"), aggregate="sum")
209
+ def value(self, range="all"):
210
+ """The number on the card.
211
+
212
+ Its value field summed over the date window, or the stored number when the card
213
+ reads a single number, which no date window narrows."""
214
+ rows = self.rows(range)
215
+ if isinstance(rows, list):
216
+ return sum_values(row.get(self.card.get("value")) for row in rows)
217
+ return rows
218
+
219
+ @reads("metric", fields=("value", "date"))
220
+ def formatted(self, range="all"):
221
+ """The same number, formatted as the card shows it."""
222
+ return format_value(self.value(range), self.card.get("format", "integer"))
223
+
224
+ @reads("line", "area", "bar", "donut", fields=("label", "value", "date"))
225
+ def points(self, range="all"):
226
+ """The chart's points, as a list of {"label": ..., "value": ...}.
227
+
228
+ Grouped by label and summed over the date window, as the page draws them: a line or
229
+ area by label; bars and donuts by value, largest first, a donut's tail past seven
230
+ slices folded into Other."""
231
+ rows = self.rows(range)
232
+ if not isinstance(rows, list):
233
+ raise DashboardError(None, "Select a table source for this chart.")
234
+ groups = {}
235
+ label_key, value_key = self.card.get("label"), self.card.get("value")
236
+ for row in rows:
237
+ label = row.get(label_key)
238
+ label = "Unlabelled" if label is None else str(label)
239
+ groups[label] = sum_values([groups.get(label, 0), row.get(value_key)])
240
+ points = [{"label": label, "value": value} for label, value in groups.items()]
241
+ if len(points) > MAX_CATEGORIES:
242
+ raise DashboardError(None, f"This chart exceeds {MAX_CATEGORIES} categories. Narrow or aggregate its source.")
243
+ if self.kind in ("line", "area"):
244
+ points.sort(key=lambda p: p["label"])
245
+ else:
246
+ points.sort(key=lambda p: (-p["value"], p["label"]))
247
+ if self.kind == "donut" and len(points) > DONUT_SLICES + 1:
248
+ rest = points[DONUT_SLICES:]
249
+ points = points[:DONUT_SLICES] + [{"label": f"Other ({len(rest)})", "value": sum_values(p["value"] for p in rest)}]
250
+ return points
251
+
252
+ @reads("table", fields=("columns", "date"))
253
+ def table(self, range="all"):
254
+ """The rows, newest first.
255
+
256
+ In the page's order: newest first by the date field, then latest first; whole rows
257
+ when the card names no columns."""
258
+ rows = self.rows(range)
259
+ if not isinstance(rows, list):
260
+ raise DashboardError(None, "Select a table source for this card.")
261
+ key = self.card.get("date")
262
+ indexed = list(enumerate(rows))
263
+ indexed.sort(key=lambda pair: ((str(pair[1].get(key)) if key else ""), pair[0]), reverse=True)
264
+ columns = self.card.get("columns")
265
+ return [{k: row.get(k) for k in columns} if columns else dict(row) for _, row in indexed]
266
+
267
+ @reads(EVERY_KIND, requires="pandas")
268
+ def to_df(self, range="all"):
269
+ """The same data as a pandas DataFrame.
270
+
271
+ It frames the card's first recipe other than formatted(), so recipes() is the one
272
+ table of which call reads which kind: a table's rows, a chart's points, a metric's
273
+ number as one row named after its method."""
274
+ framed = next((entry["method"] for entry in self.recipe() if entry["method"] not in {"formatted", "to_df"}), None)
275
+ if framed is None:
276
+ raise DashboardError(None, (
277
+ f"Card {self.id!r} is a {self.kind!r} card, a kind this kedai package declares no call for; "
278
+ f"it reads {', '.join(recipes())} cards. A newer kedai may read it: install the one the "
279
+ "dashboard's server serves at /python/."))
280
+ try:
281
+ import pandas
282
+ except ImportError: # pragma: no cover
283
+ raise DashboardError(None, "to_df needs pandas installed.") from None
284
+ result = getattr(self, framed)(range)
285
+ return pandas.DataFrame(result if isinstance(result, list) else [{framed: result}])
286
+
287
+ def recipe(self):
288
+ """The calls a published page's snippet shows for this card, in method order: one
289
+ {"method", "call", "comment", "fields", "aggregate", "requires"} each (recipes())."""
290
+ return recipes().get(self.kind, [])
291
+
292
+
293
+ def recipes():
294
+ """{kind: [recipe]} for every card kind a Widget method declares with @reads, each list
295
+ in method definition order. A recipe is {"method", "call", "comment", "fields",
296
+ "aggregate", "requires"}: the call a snippet writes, its docstring's first line, and the
297
+ declaration. A new list each time, so a caller may keep or change it."""
298
+ declared = [(name, member) for name, member in vars(Widget).items() if hasattr(member, "reads")]
299
+ kinds = dict.fromkeys(kind for _, member in declared for kind in member.reads["kinds"] if kind != EVERY_KIND)
300
+ return {kind: [_recipe(name, member) for name, member in declared
301
+ if kind in member.reads["kinds"] or EVERY_KIND in member.reads["kinds"]]
302
+ for kind in kinds}
303
+
304
+
305
+ def _recipe(name, method):
306
+ said = method.reads
307
+ lines = (method.__doc__ or "").strip().splitlines()
308
+ return {"method": name, "call": name + "()", "comment": lines[0].strip() if lines else "",
309
+ "fields": list(said["fields"]), "aggregate": said["aggregate"], "requires": said["requires"]}
310
+
311
+
312
+ def sum_values(values):
313
+ total = 0
314
+ for value in values:
315
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value or value in (float("inf"), float("-inf")):
316
+ raise DashboardError(None, "This card received a non-numeric value.")
317
+ total += value
318
+ if abs(total) > MAX_SAFE_INTEGER:
319
+ raise DashboardError(None, "This chart exceeds its numeric bounds; aggregate or narrow the source upstream.")
320
+ return total
321
+
322
+
323
+ def money(n, places=2):
324
+ """Whole USD micro-units as the page prints them: half-up, grouped, `places` decimals."""
325
+ if not isinstance(n, int) or isinstance(n, bool) or abs(n) > MAX_SAFE_INTEGER:
326
+ raise DashboardError(None, "Currency requires safe integer USD micro-units.")
327
+ sign, n = ("−", -n) if n < 0 else ("", n)
328
+ div = 10 ** (6 - places)
329
+ n = (n + div // 2) // div
330
+ scale = 10 ** places
331
+ whole, fraction = divmod(n, scale)
332
+ return sign + "$" + f"{whole:,}" + (f".{fraction:0{places}d}" if places else "")
333
+
334
+
335
+ def format_value(n, kind="integer", detail=False):
336
+ """A card's number as the page prints it: currency from micro-units, else grouped."""
337
+ if kind == "usd_micro":
338
+ return money(n, 4 if detail or abs(n) < 10000 else 2)
339
+ if kind == "decimal":
340
+ return f"{round(n, 2):,.2f}".rstrip("0").rstrip(".") if isinstance(n, float) else f"{n:,}"
341
+ return f"{round(n):,}"
@@ -0,0 +1,101 @@
1
+ """Call a published Kedai endpoint: one file, standard library only. Experimental.
2
+
3
+ import kedai
4
+ answer = kedai.invoke("https://host/api/v1/endpoints/<token>",
5
+ api_key="kedai_ek_...", query="widget", limit=5)
6
+ print(answer["result"]) # the result record, keyed by Output name
7
+ print(answer["revision"]) # the immutable revision that answered
8
+ print(kedai.schema("https://host/api/v1/endpoints/<token>", api_key="kedai_ek_..."))
9
+
10
+ The body is the request record: each keyword is one of the endpoint's Inputs, and a value
11
+ is whatever its type takes -- a string, a number, a boolean, a list, a table (a list of
12
+ row dicts), a record (a dict), or None for a nullable field; `schema()` reads the types.
13
+ The key is sent as a bearer header and never placed in the URL; leave it out (or set
14
+ KEDAI_API_KEY) on a draft that has minted none. Each call carries a fresh Idempotency-Key;
15
+ pass idempotency_key=answer["idempotency_key"] to re-send the same request and get the same
16
+ answer back. Refusals raise EndpointError with .status, .error, .detail, .retry_after and,
17
+ for a request the interface refused, .path/.expected/.arrived; a "delivery_unknown" error
18
+ means the work may have run and must not be retried blindly.
19
+ """
20
+
21
+ import json
22
+ import os
23
+ import time
24
+ import urllib.error
25
+ import urllib.request
26
+ import uuid
27
+
28
+ __all__ = ["invoke", "schema", "EndpointError"]
29
+ MAX_RESPONSE_BYTES = 2 * 1024 * 1024
30
+
31
+
32
+ class EndpointError(RuntimeError):
33
+ """The endpoint refused or failed; .status, .error (a code or None), .detail, .retry_after,
34
+ and for a refused request record .path, .expected and .arrived (else None)."""
35
+
36
+ def __init__(self, status, error, detail, retry_after=None, path=None, expected=None, arrived=None):
37
+ super().__init__(f"HTTP {status} {error or 'refused'}: {detail}")
38
+ self.status, self.error, self.detail, self.retry_after = status, error, detail, retry_after
39
+ self.path, self.expected, self.arrived = path, expected, arrived
40
+
41
+
42
+ def invoke(url, api_key=None, idempotency_key=None, timeout=180, **fields):
43
+ """POST the request record to a published endpoint or channel URL; returns the envelope.
44
+
45
+ The envelope is the server's (revision, canonical_path, result, determinism, charge,
46
+ completeness, and channel/channel_path through a channel) plus idempotency_key and
47
+ cache (None, "miss" or "hit; age=<s>"). Each keyword is one Input of the record, sent
48
+ as JSON exactly as given.
49
+ """
50
+ try:
51
+ body = json.dumps(fields, allow_nan=False).encode("utf-8")
52
+ except (TypeError, ValueError) as error:
53
+ raise TypeError(f"every input must be a JSON value: {error}") from None
54
+ key = idempotency_key or f"v1:{int(time.time() * 1000):013d}:{uuid.uuid4()}"
55
+ headers = {"content-type": "application/json", "accept": "application/json", "idempotency-key": key}
56
+ answer = _exchange(url, "POST", body, headers, api_key, timeout)
57
+ return {**answer["body"], "idempotency_key": key, "cache": answer["headers"].get("x-kedai-cache")}
58
+
59
+
60
+ def schema(url, api_key=None, timeout=30):
61
+ """GET <endpoint url>/schema: {revision, canonical_path, input_schema, output_schema, interface}."""
62
+ answer = _exchange(url.rstrip("/") + "/schema", "GET", None, {"accept": "application/json"}, api_key, timeout)
63
+ return answer["body"]
64
+
65
+
66
+ def _exchange(url, method, data, headers, api_key, timeout):
67
+ headers.setdefault("user-agent", "kedai-python/0.1.0 (+https://kedai.io)")
68
+ api_key = api_key or os.environ.get("KEDAI_API_KEY")
69
+ if api_key:
70
+ headers["authorization"] = "Bearer " + api_key
71
+ request = urllib.request.Request(url, data=data, headers=headers, method=method)
72
+ try:
73
+ with urllib.request.urlopen(request, timeout=timeout) as response:
74
+ status, answer, body = response.status, response.headers, _read(response, response.status)
75
+ except urllib.error.HTTPError as refused:
76
+ status, answer, body = refused.code, refused.headers, _read(refused, refused.code)
77
+ if status != 200:
78
+ detail = body.get("detail") or body.get("message") or "the endpoint sent no sentence"
79
+ raise EndpointError(
80
+ status, body.get("error"), detail, _seconds(answer.get("retry-after")),
81
+ body.get("path"), body.get("expected"), body.get("arrived"),
82
+ )
83
+ return {"body": body, "headers": answer}
84
+
85
+
86
+ def _seconds(retry_after):
87
+ try:
88
+ return float(retry_after) if retry_after else None
89
+ except ValueError: # an HTTP-date; the contract sends whole seconds
90
+ return None
91
+
92
+
93
+ def _read(response, status):
94
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
95
+ if len(raw) > MAX_RESPONSE_BYTES:
96
+ raise EndpointError(status, "response_too_large", f"the response exceeded {MAX_RESPONSE_BYTES} bytes")
97
+ try:
98
+ body = json.loads(raw.decode("utf-8") or "{}")
99
+ except ValueError:
100
+ body = {}
101
+ return body if isinstance(body, dict) else {}
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: kedai
3
+ Version: 0.2.1
4
+ Summary: Read a published Kedai dashboard or call a published Kedai endpoint from Python.
5
+ Author: Kedai
6
+ License: MIT
7
+ Project-URL: Homepage, https://kedai.io
8
+ Project-URL: Documentation, https://app.kedai.io/python/
9
+ Keywords: kedai,dashboard,workflow,api
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # kedai
17
+
18
+ Kedai turns a data need into a maintained workflow with a stable endpoint, a schedule and a
19
+ shareable dashboard; this package reads what Kedai publishes, from Python. Learn more at
20
+ https://kedai.io.
21
+
22
+ Read a published Kedai dashboard, or call a published Kedai endpoint, from Python. Standard
23
+ library only; `pandas` is optional.
24
+
25
+ ```python
26
+ import kedai
27
+
28
+ board = kedai.dashboard.get("https://app.kedai.io/v/form4-monitor")
29
+ board.widgets["filings"].to_df() # the table card, as the page shows it
30
+ board.widgets["new_per_day"].points() # [{"label": "2026-11-20", "value": 3}, ...]
31
+ board.widgets["total"].value(range=7) # the metric over the last seven days
32
+ board.widgets["total"].recipe() # the calls that read this card, as data
33
+
34
+ answer = kedai.invoke("https://app.kedai.io/api/v1/endpoints/<token>", api_key="kedai_ek_...", cik="0000320193")
35
+ answer["result"]
36
+ ```
37
+
38
+ A widget's methods: `value()` and `formatted()` read a metric, `points()` a line, area, bar
39
+ or donut, `table()` a table, and `to_df()` any of them as a pandas DataFrame; `rows()` is the
40
+ card's stored rows in the date window. `recipe()` lists the ones that read the widget's
41
+ card, each with the one-line comment a published page's "Use this data" snippet prints
42
+ beside it, and `kedai.dashboard.recipes()` lists them for every card kind.
43
+
44
+ A private dashboard takes an account key (`api_key=` or `KEDAI_API_KEY`). Card values are
45
+ computed from the dashboard's data document with the same rules the page uses: a date
46
+ window over the cards' date fields (`"all"`, `7`, `30`, or `("2026-11-01", "2026-11-28")`),
47
+ sums per label, trend points sorted by label, breakdowns sorted by value with a donut's
48
+ long tail folded into `Other`, tables newest first.
49
+
50
+ Every Kedai deployment also serves this package from its own release, at `/python/`:
51
+ `pip install https://app.kedai.io/python/kedai-0.2.1-py3-none-any.whl`.
52
+
53
+ The package is `kedai` on PyPI; the server's own code is also a Python package named `kedai`
54
+ but is never published there. A developer environment holding both should keep the server
55
+ on its path and read this package through its own virtual environment.
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/kedai/__init__.py
4
+ src/kedai/dashboard.py
5
+ src/kedai/endpoint.py
6
+ src/kedai.egg-info/PKG-INFO
7
+ src/kedai.egg-info/SOURCES.txt
8
+ src/kedai.egg-info/dependency_links.txt
9
+ src/kedai.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ kedai