inference-tracker 0.9.4__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.
@@ -0,0 +1,262 @@
1
+ """Tracks calls to eachlabs' API (https://api.eachlabs.ai), made over plain HTTP.
2
+
3
+ import inference_tracker
4
+
5
+ http = inference_tracker.eachlabs.track_http(httpx.AsyncClient()) # or httpx.Client, requests.Session
6
+
7
+ How eachlabs' API works (docs.eachlabs.ai, read 2026-11-18): a prediction is created with POST /v1/prediction,
8
+ {"model": slug, "version": "1.0.0", "input": {...}}, and eachlabs answers {"status": "success", "predictionID": id}
9
+ ("success" means it was created, not that it ran). The app then polls GET /v1/prediction/<id> until its status is
10
+ success, error or cancelled, or eachlabs posts the same answer to the app's webhook_url.
11
+
12
+ What is recorded:
13
+ - a created prediction: a "start" record with the prediction id as request id, and the poll answer that says the
14
+ prediction ended: the "finish", ok, or "error" / "cancelled" (status "error"). The status may be polled with
15
+ another watched session than the one that created it.
16
+ - a create eachlabs refused (an error answer): one "call" record with "http_<status>" (eachlabs answers with a
17
+ sentence, which isn't copied).
18
+ - a create that got no answer (a timeout, a broken connection): one "call" record with the exception's class name
19
+ ("cancelled" when the app cancelled it). A poll without an answer, or with an error answer, changes nothing: the
20
+ prediction may still be running.
21
+ Predictions answered to a webhook aren't seen finishing here. Other paths and hosts pass through unseen. The call
22
+ itself is never changed, and tracking never raises: a problem in it is logged and the call goes on.
23
+
24
+ Usage and cost: the ended prediction's metrics carry its cost, in dollars at list price with any credit rebate taken
25
+ off (metrics.cost), and on metered models the billed seconds and output size. They're kept in the finish record's
26
+ units as cost_usd, billed_seconds, predict_seconds and output_gb. The settings that change the price are copied from
27
+ the input by name (duration, resolution...), with the model's version; reference media are counted, never copied.
28
+ Never the prompt, nor any media URL.
29
+
30
+ The model is eachlabs' slug ("p-video-upscale"). The parent is taken from the context, as for every record.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import logging
36
+ import re
37
+ import threading
38
+ import time
39
+ from collections import OrderedDict
40
+ from collections.abc import Iterable, Mapping
41
+ from typing import Any
42
+
43
+ from . import _attach, _client, _http
44
+ from ._record import Record, cancelled
45
+
46
+ logger = logging.getLogger("inference_tracker")
47
+
48
+ PROVIDER = "eachlabs"
49
+ HOSTS = frozenset({"api.eachlabs.ai"})
50
+ # Input fields copied onto the record because they change the price (or say how long the video is).
51
+ SETTINGS = (
52
+ "duration",
53
+ "resolution",
54
+ "target_resolution",
55
+ "upscale_factor",
56
+ "mode",
57
+ "draft",
58
+ "fps",
59
+ "target_fps",
60
+ "aspect_ratio",
61
+ "num_frames",
62
+ "num_outputs",
63
+ "num_images",
64
+ "width",
65
+ "height",
66
+ "size",
67
+ "image_size",
68
+ "quality",
69
+ "go_fast",
70
+ "turbo",
71
+ )
72
+ # Input fields holding media URLs, counted (never copied): reference images, videos and audio change the price.
73
+ MEDIA = {
74
+ "input_images": ("image", "images", "image_url", "image_urls", "first_frame_image", "last_frame_image"),
75
+ "input_videos": ("video", "videos", "video_url"),
76
+ "input_audios": ("audio", "audio_url"),
77
+ }
78
+ # The ended prediction's metrics, as units.
79
+ METRICS = {"cost": "cost_usd", "billed_seconds": "billed_seconds", "predict_time": "predict_seconds", "output_gb": "output_gb"}
80
+ # Predictions created and not seen ended yet, by id, shared by every watched session. Beyond this many, the oldest
81
+ # is forgotten.
82
+ MAX_OPEN = 1000
83
+ _ENDED = {"success": None, "succeeded": None, "completed": None, "error": "error", "failed": "error", "cancelled": "cancelled", "canceled": "cancelled"}
84
+
85
+ _CREATE = re.compile(r"^/v\d+/prediction/?$")
86
+ _STATUS = re.compile(r"^/v\d+/prediction/(?P<id>[^/]+)/?$")
87
+
88
+ _open: OrderedDict[str, _Call] = OrderedDict()
89
+ _open_lock = threading.Lock()
90
+
91
+
92
+ def track_http(client: Any, *, settings: Iterable[str] = SETTINGS) -> Any:
93
+ """Watches an httpx.Client, httpx.AsyncClient or requests.Session for calls to eachlabs' API, and returns the
94
+ same client. See the module docstring."""
95
+ try:
96
+ watcher = _HttpWatcher(settings)
97
+ _attach.learn(watcher)
98
+ if not _http.watch(client, watcher):
99
+ logger.warning("inference_tracker: can't watch a %s for eachlabs calls", type(client).__name__)
100
+ except Exception:
101
+ logger.exception("inference_tracker: could not watch a client for eachlabs calls")
102
+ return client
103
+
104
+
105
+ # --- one call ----------------------------------------------------------------------------------
106
+
107
+
108
+ class _Call:
109
+ """The record of one prediction while this process follows it."""
110
+
111
+ def __init__(self, model: str | None, settings: dict[str, Any], units: dict[str, float], started: tuple):
112
+ started_at, self._clock = started
113
+ self.record = Record.new(PROVIDER, model, phase="start", started_at=started_at, settings=settings)
114
+ self.units = units
115
+ self.done = False
116
+
117
+ def created(self, request_id: str) -> None:
118
+ self.record.request_id = request_id
119
+ _client.record(self.record)
120
+ with _open_lock:
121
+ _open[request_id] = self
122
+ while len(_open) > MAX_OPEN:
123
+ _open.popitem(last=False)
124
+
125
+ def finish(self, error_type: str | None, metrics: dict[str, float]) -> None:
126
+ if self.done:
127
+ return
128
+ self.done = True
129
+ start = self.record
130
+ with _open_lock:
131
+ _open.pop(start.request_id, None)
132
+ _client.record(
133
+ Record.new(
134
+ PROVIDER,
135
+ start.model,
136
+ phase="finish",
137
+ request_id=start.request_id,
138
+ status="error" if error_type else "ok",
139
+ error_type=error_type,
140
+ duration_s=self._elapsed(),
141
+ units={**self.units, **metrics},
142
+ user_id=start.user_id,
143
+ task_id=start.task_id,
144
+ parent_provider=start.parent_provider,
145
+ parent_request_id=start.parent_request_id,
146
+ call_name=start.call_name,
147
+ )
148
+ )
149
+
150
+ def completed(self, error_type: str | None, stopped: bool = False) -> None:
151
+ """A create that was refused or got no answer: one "call" record, without a request id."""
152
+ if self.done:
153
+ return
154
+ self.done = True
155
+ r = self.record
156
+ r.phase = "call"
157
+ r.status, r.error_type = ("cancelled" if stopped else "error" if error_type else "ok"), error_type
158
+ r.duration_s, r.units = self._elapsed(), dict(self.units)
159
+ _client.record(r)
160
+
161
+ def _elapsed(self) -> float:
162
+ return round(time.monotonic() - self._clock, 3)
163
+
164
+
165
+ # --- over HTTP ---------------------------------------------------------------------------------------
166
+
167
+
168
+ class _HttpWatcher:
169
+ name = "eachlabs"
170
+
171
+ def __init__(self, settings: Iterable[str]):
172
+ self.settings = tuple(settings)
173
+
174
+ def accepts(self, host: str) -> bool:
175
+ return host in HOSTS
176
+
177
+ def wants_body(self, ex: _http.Exchange) -> bool:
178
+ kind, request_id = _route(ex)
179
+ if kind == "create":
180
+ return True # the prediction's id is in it
181
+ return kind == "status" and ex.ok and _peek(request_id) is not None
182
+
183
+ def seen(self, ex: _http.Exchange) -> None:
184
+ kind, request_id = _route(ex)
185
+ if kind == "create":
186
+ self._created(ex)
187
+ elif kind == "status" and ex.ok and isinstance(ex.body, Mapping):
188
+ call = _peek(request_id)
189
+ status = ex.body.get("status")
190
+ status = status.lower() if isinstance(status, str) else status
191
+ if call is not None and status in _ENDED:
192
+ call.finish(_ENDED[status], _metrics(ex.body.get("metrics")))
193
+
194
+ def failed(self, ex: _http.Exchange) -> None:
195
+ kind, _ = _route(ex)
196
+ if kind == "create" and (call := self._start(ex)) is not None:
197
+ call.completed(_http.error_type(ex), cancelled(ex.error))
198
+
199
+ def _start(self, ex: _http.Exchange) -> _Call | None:
200
+ try:
201
+ body = ex.request_json()
202
+ body = body if isinstance(body, Mapping) else {}
203
+ data = body.get("input")
204
+ data = data if isinstance(data, Mapping) else {}
205
+ settings = {k: data[k] for k in self.settings if data.get(k) is not None}
206
+ version = body.get("version")
207
+ if isinstance(version, str) and version:
208
+ settings["version"] = version
209
+ units = {name: n for name, keys in MEDIA.items() if (n := sum(_count(data.get(k)) for k in keys))}
210
+ model = body.get("model")
211
+ model = model if isinstance(model, str) and model else None
212
+ return _Call(model, settings, units, (ex.started_at, ex.clock))
213
+ except Exception:
214
+ logger.exception("inference_tracker: could not start tracking an eachlabs call")
215
+ return None
216
+
217
+ def _created(self, ex: _http.Exchange) -> None:
218
+ call = self._start(ex)
219
+ if call is None:
220
+ return
221
+ body = ex.body if isinstance(ex.body, Mapping) else {}
222
+ request_id = body.get("predictionID") or body.get("id")
223
+ if not ex.ok or not isinstance(request_id, str) or not request_id:
224
+ call.completed(f"http_{ex.status}" if not ex.ok else "no_prediction_id")
225
+ return
226
+ call.created(request_id)
227
+
228
+
229
+ def _route(ex: _http.Exchange) -> tuple[str | None, str | None]:
230
+ """What a request to eachlabs was: ("create" | "status" | None, the prediction id in the URL)."""
231
+ if ex.method == "POST" and _CREATE.match(ex.path):
232
+ return "create", None
233
+ match = _STATUS.match(ex.path)
234
+ if ex.method == "GET" and match is not None:
235
+ return "status", match["id"]
236
+ return None, None
237
+
238
+
239
+ def _peek(request_id: Any) -> _Call | None:
240
+ with _open_lock:
241
+ return _open.get(request_id)
242
+
243
+
244
+ def _metrics(m: Any) -> dict[str, float]:
245
+ """The ended prediction's cost and metered usage, numbers only."""
246
+ if not isinstance(m, Mapping):
247
+ return {}
248
+ out = {}
249
+ for key, unit in METRICS.items():
250
+ v = m.get(key)
251
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
252
+ out[unit] = float(v)
253
+ return out
254
+
255
+
256
+ def _count(value: Any) -> int:
257
+ """How many media a field holds: one URL, or a list of them."""
258
+ if isinstance(value, str):
259
+ return 1 if value else 0
260
+ if isinstance(value, (list, tuple)):
261
+ return sum(1 for v in value if v)
262
+ return 0