dmlops 0.2.10__py3-none-win_amd64.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.
dmlops/_spool.py ADDED
@@ -0,0 +1,367 @@
1
+ """Background spool + uploader thread, and the heartbeat thread.
2
+
3
+ Three background threads per process (plus short-lived helpers):
4
+
5
+ - ``Uploader``: drains the in-memory spool — batched ``events`` POSTs
6
+ (metrics lines + terminal logLines) and ``save`` tasks (presign → PUT →
7
+ confirm). Failures requeue with exponential backoff (offline spool; a
8
+ mid-run PAT expiry therefore never loses telemetry).
9
+ - ``Heartbeat``: empty ``events`` call every 15s — refreshes the server-side
10
+ heartbeat and doubles as the cancel-signal poll.
11
+ - ``ResourceSampler`` (see ``_resource.py``): samples machine/GPU usage and
12
+ enqueues ``resourceSamples`` events.
13
+
14
+ A 409 with code ``CANCELLED`` flips the run's cancel flag: no exception is
15
+ raised inside threads (``Run.log_metric()`` raises ``MlopsCancelled`` on the caller
16
+ thread instead).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import threading
22
+ import time
23
+ import warnings
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ from ._transport import Transport
27
+ from ._uploader import upload_file, warn_upload_failed
28
+ from .exceptions import MlopsConflict, MlopsError
29
+
30
+ if TYPE_CHECKING:
31
+ from ._status import UploadStatusLine
32
+
33
+ MAX_LINES_PER_POST = 1000
34
+ MAX_LOGLINES_PER_POST = 500
35
+ MAX_SAMPLES_PER_POST = 720
36
+ FLUSH_INTERVAL = 0.5
37
+ BACKOFF_STEPS = (1.0, 2.0, 5.0, 10.0, 30.0)
38
+ MAX_SAVE_ATTEMPTS = 5
39
+ FLUSH_HARD_CAP_SECS = 30.0
40
+
41
+
42
+ def _split_event_payload(payload: dict[str, Any]) -> list[dict[str, Any]]:
43
+ """Split even a single oversized event item into server-sized POSTs."""
44
+ lines = list(payload.get("lines") or [])
45
+ log_lines = list(payload.get("logLines") or [])
46
+ samples = list(payload.get("resourceSamples") or [])
47
+ chunks: list[dict[str, Any]] = []
48
+ line_pos = 0
49
+ log_pos = 0
50
+ sample_pos = 0
51
+ while line_pos < len(lines) or log_pos < len(log_lines) or sample_pos < len(samples):
52
+ chunk: dict[str, Any] = {}
53
+ if line_pos < len(lines):
54
+ chunk["lines"] = lines[line_pos : line_pos + MAX_LINES_PER_POST]
55
+ line_pos += len(chunk["lines"])
56
+ if log_pos < len(log_lines):
57
+ chunk["logLines"] = log_lines[log_pos : log_pos + MAX_LOGLINES_PER_POST]
58
+ log_pos += len(chunk["logLines"])
59
+ if sample_pos < len(samples):
60
+ chunk["resourceSamples"] = samples[sample_pos : sample_pos + MAX_SAMPLES_PER_POST]
61
+ sample_pos += len(chunk["resourceSamples"])
62
+ chunks.append(chunk)
63
+ return chunks
64
+
65
+
66
+ class Uploader(threading.Thread):
67
+ def __init__(
68
+ self,
69
+ transport: Transport,
70
+ experiment_id: str,
71
+ run: Any,
72
+ status: "UploadStatusLine | None" = None,
73
+ ) -> None:
74
+ super().__init__(name=f"mlops-uploader-{experiment_id[:8]}", daemon=True)
75
+ self._transport = transport
76
+ self._experiment_id = experiment_id
77
+ self._run = run
78
+ self._status = status
79
+ self._cond = threading.Condition()
80
+ self._queue: list[dict[str, Any]] = []
81
+ self._pending_saves = 0
82
+ self._stopping = False
83
+ self._flush_deadline: float | None = None
84
+ self._warned_event_drop = False
85
+
86
+ def submit(self, item: dict[str, Any]) -> None:
87
+ is_save = item.get("type") == "save"
88
+ with self._cond:
89
+ if self._stopping:
90
+ return
91
+ self._queue.append(item)
92
+ if is_save:
93
+ self._pending_saves += 1
94
+ self._cond.notify()
95
+ if is_save:
96
+ self._emit_status()
97
+
98
+ def _save_done(self) -> None:
99
+ """One save finished (uploaded or given up after max attempts)."""
100
+ with self._cond:
101
+ if self._pending_saves > 0:
102
+ self._pending_saves -= 1
103
+ self._emit_status()
104
+
105
+ def _emit_status(self) -> None:
106
+ """Push the pending-save count to the terminal status line. Called
107
+ outside the condition lock (the status line has its own lock and
108
+ never acquires ours)."""
109
+ status = self._status
110
+ if status is None:
111
+ return
112
+ with self._cond:
113
+ count = self._pending_saves
114
+ try:
115
+ status.set_pending(count)
116
+ except Exception:
117
+ pass
118
+
119
+ def pending(self) -> int:
120
+ with self._cond:
121
+ return len(self._queue)
122
+
123
+ def pending_saves(self) -> int:
124
+ """Save tasks not yet finished (queued, in-flight, or retrying)."""
125
+ with self._cond:
126
+ return self._pending_saves
127
+
128
+ def flush_and_stop(self, timeout: float = 5.0) -> None:
129
+ """Stop accepting new items and wait up to `timeout`s for the queue
130
+ to drain (in-flight retries included)."""
131
+ with self._cond:
132
+ self._stopping = True
133
+ self._flush_deadline = time.monotonic() + timeout
134
+ self._cond.notify_all()
135
+ self.join(timeout + 2.0)
136
+
137
+ def run(self) -> None: # noqa: D102 - thread entry
138
+ backoff = 0
139
+ while True:
140
+ with self._cond:
141
+ while (
142
+ not self._queue
143
+ and not self._stopping
144
+ and not self._flush_expired()
145
+ ):
146
+ self._cond.wait(timeout=FLUSH_INTERVAL)
147
+ finishing = self._flush_expired() or (
148
+ self._stopping and not self._queue
149
+ )
150
+ abandoned: list[str] = []
151
+ if finishing:
152
+ # Normal drain or flush hard-timeout: any leftover saves
153
+ # are abandoned, so the status line resets to zero.
154
+ abandoned = [
155
+ i["path"] for i in self._queue if i.get("type") == "save"
156
+ ]
157
+ self._pending_saves = 0
158
+ else:
159
+ batch = self._drain_locked()
160
+ if finishing:
161
+ if abandoned:
162
+ shown = ", ".join(abandoned[:3]) + (
163
+ " …" if len(abandoned) > 3 else ""
164
+ )
165
+ warnings.warn(
166
+ f"[mlops] {len(abandoned)} artifact(s) abandoned at flush deadline: {shown}",
167
+ stacklevel=2,
168
+ )
169
+ self._emit_status()
170
+ return
171
+ try:
172
+ retry = self._process(batch)
173
+ except MlopsConflict as exc:
174
+ if getattr(exc, "code", "") == "CANCELLED":
175
+ self._run._set_cancelled()
176
+ with self._cond:
177
+ self._stopping = True # the thread exits below: submit() must reject new work
178
+ self._queue.clear()
179
+ self._pending_saves = 0
180
+ self._emit_status()
181
+ return
182
+ # A terminal run rejects everything else too; drop this batch.
183
+ backoff = 0
184
+ continue
185
+ except Exception as exc:
186
+ # Safety net: an unexpected bug must never kill the uploader
187
+ # thread (telemetry would silently stop and the run would be
188
+ # reaped as interrupted). Drop the batch and release its save
189
+ # slots so finish() does not wait on them forever.
190
+ warnings.warn(
191
+ f"[mlops] uploader dropped a batch after unexpected error: {exc!r}",
192
+ stacklevel=2,
193
+ )
194
+ for item in batch:
195
+ if item.get("type") == "save":
196
+ self._run._saved_paths.discard(item["path"])
197
+ self._save_done()
198
+ backoff = 0
199
+ continue
200
+ if not retry:
201
+ backoff = 0
202
+ continue
203
+ # Reinsert directly: submit() intentionally rejects new work once
204
+ # stopping, but in-flight retries must still drain during flush.
205
+ with self._cond:
206
+ self._queue = retry + self._queue
207
+ delay = BACKOFF_STEPS[min(backoff, len(BACKOFF_STEPS) - 1)]
208
+ backoff += 1
209
+ time.sleep(delay)
210
+
211
+ def _flush_expired(self) -> bool:
212
+ if self._flush_deadline is None:
213
+ return False
214
+ now = time.monotonic()
215
+ if not self._queue:
216
+ return now >= self._flush_deadline
217
+ # Hard cap: give up on stuck items past the flush deadline.
218
+ return now >= self._flush_deadline + FLUSH_HARD_CAP_SECS
219
+
220
+ def _drain_locked(self) -> list[dict[str, Any]]:
221
+ batch = self._queue
222
+ self._queue = []
223
+ return batch
224
+
225
+ def _process(self, batch: list[dict[str, Any]]) -> list[dict[str, Any]]:
226
+ expanded: list[dict[str, Any]] = []
227
+ for item in batch:
228
+ if item["type"] == "events":
229
+ expanded.extend(
230
+ {"type": "events", "payload": payload}
231
+ for payload in _split_event_payload(item["payload"])
232
+ )
233
+ else:
234
+ expanded.append(item)
235
+
236
+ events: dict[str, Any] = {}
237
+
238
+ def flush_events(remaining: list[dict[str, Any]]) -> list[dict[str, Any]] | None:
239
+ nonlocal events
240
+ if not events:
241
+ return None
242
+ payload = events
243
+ try:
244
+ self._post_events(payload)
245
+ except MlopsConflict:
246
+ raise
247
+ except MlopsError as exc:
248
+ if getattr(exc, "status", None) in (400, 403, 404, 413):
249
+ # Permanent rejection: re-sending the same bytes can
250
+ # never succeed (validation failure, non-owner, run
251
+ # deleted, oversized). Drop the batch — warned once —
252
+ # and keep processing later items. 401/5xx/network
253
+ # errors (status None) still requeue below.
254
+ if not self._warned_event_drop:
255
+ self._warned_event_drop = True
256
+ warnings.warn(
257
+ f"[mlops] events rejected by server (HTTP {exc.status}) — "
258
+ f"dropping batch and all future rejected batches: {exc}",
259
+ stacklevel=2,
260
+ )
261
+ events = {}
262
+ return None
263
+ return [{"type": "events", "payload": payload}] + remaining
264
+ events = {}
265
+ return None
266
+
267
+ for index, item in enumerate(expanded):
268
+ if item["type"] == "save":
269
+ retry = flush_events(expanded[index:])
270
+ if retry is not None:
271
+ return retry
272
+ save = dict(item)
273
+ try:
274
+ # Path sources stay paths: every attempt re-reads and
275
+ # re-hashes the file, so a mid-retry modification
276
+ # uploads its newer bytes on the next attempt.
277
+ upload_file(
278
+ self._transport,
279
+ self._experiment_id,
280
+ save["source"],
281
+ save["path"],
282
+ )
283
+ except MlopsConflict:
284
+ raise
285
+ except Exception as exc:
286
+ attempts = int(save.get("attempts", 0)) + 1
287
+ if attempts >= MAX_SAVE_ATTEMPTS:
288
+ warn_upload_failed(save["path"], exc)
289
+ self._run._saved_paths.discard(save["path"])
290
+ self._save_done()
291
+ continue
292
+ save["attempts"] = attempts
293
+ return [save] + expanded[index + 1 :]
294
+ self._save_done()
295
+ continue
296
+
297
+ payload = item["payload"]
298
+ lines = payload.get("lines") or []
299
+ log_lines = payload.get("logLines") or []
300
+ samples = payload.get("resourceSamples") or []
301
+ bucket_lines = events.setdefault("lines", [])
302
+ bucket_logs = events.setdefault("logLines", [])
303
+ bucket_samples = events.setdefault("resourceSamples", [])
304
+ if (
305
+ (bucket_lines and len(bucket_lines) + len(lines) > MAX_LINES_PER_POST)
306
+ or (bucket_logs and len(bucket_logs) + len(log_lines) > MAX_LOGLINES_PER_POST)
307
+ or (bucket_samples and len(bucket_samples) + len(samples) > MAX_SAMPLES_PER_POST)
308
+ ):
309
+ retry = flush_events(expanded[index:])
310
+ if retry is not None:
311
+ return retry
312
+ bucket_lines = events.setdefault("lines", [])
313
+ bucket_logs = events.setdefault("logLines", [])
314
+ bucket_samples = events.setdefault("resourceSamples", [])
315
+ bucket_lines.extend(lines)
316
+ bucket_logs.extend(log_lines)
317
+ bucket_samples.extend(samples)
318
+
319
+ retry = flush_events([])
320
+ return retry or []
321
+
322
+ def _post_events(self, payload: dict[str, Any]) -> None:
323
+ if (
324
+ not payload.get("lines")
325
+ and not payload.get("logLines")
326
+ and not payload.get("resourceSamples")
327
+ ):
328
+ return
329
+ self._transport.request(
330
+ "POST",
331
+ f"/api/experiments/{self._experiment_id}/events",
332
+ payload,
333
+ )
334
+
335
+
336
+ class Heartbeat(threading.Thread):
337
+ """15s empty events call: heartbeat refresh + cancel-signal poll."""
338
+
339
+ INTERVAL = 15.0
340
+
341
+ def __init__(self, transport: Transport, experiment_id: str, run: Any) -> None:
342
+ super().__init__(name=f"mlops-heartbeat-{experiment_id[:8]}", daemon=True)
343
+ self._transport = transport
344
+ self._experiment_id = experiment_id
345
+ self._run = run
346
+ self._stop = threading.Event()
347
+
348
+ def stop(self) -> None:
349
+ self._stop.set()
350
+
351
+ def run(self) -> None: # noqa: D102 - thread entry
352
+ while not self._stop.wait(self.INTERVAL):
353
+ if self._run._finished:
354
+ return
355
+ try:
356
+ self._transport.request(
357
+ "POST",
358
+ f"/api/experiments/{self._experiment_id}/events",
359
+ {"heartbeat": True},
360
+ )
361
+ except MlopsConflict as exc:
362
+ if getattr(exc, "code", "") == "CANCELLED":
363
+ self._run._set_cancelled()
364
+ except MlopsError:
365
+ pass # offline: the uploader's spool covers the gap
366
+ except Exception:
367
+ pass # the heartbeat thread must never die
dmlops/_status.py ADDED
@@ -0,0 +1,90 @@
1
+ """Terminal upload status line for background artifact saves.
2
+
3
+ While background ``save`` tasks are in flight, a single line at the
4
+ terminal bottom shows ``[mlops] ↑ N artifact(s) uploading…``; it is erased
5
+ once everything is uploaded. The line is written to the ORIGINAL stderr
6
+ (before the tee is installed), so it never reaches the Web Logs and never
7
+ interleaves with captured training output — ``Tee.write`` erases the line
8
+ before forwarding user output and redraws it afterwards.
9
+
10
+ Requires a TTY and ``capture_output=True`` (the tee provides the
11
+ erase/redraw coordination). Set ``MLOPS_SDK_STATUS_LINE=0`` (or
12
+ ``false``/``no``) to disable. Every write is best-effort: the status line
13
+ must never break the training script.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ import threading
21
+ from typing import Any
22
+
23
+ _DISABLED_VALUES = {"0", "false", "no"}
24
+
25
+
26
+ def status_line_enabled(stream: Any) -> bool:
27
+ """True when the status line may be drawn on ``stream``: a real TTY and
28
+ ``MLOPS_SDK_STATUS_LINE`` not opted out."""
29
+ try:
30
+ if not stream.isatty():
31
+ return False
32
+ except Exception:
33
+ return False
34
+ return (
35
+ os.environ.get("MLOPS_SDK_STATUS_LINE") or ""
36
+ ).strip().lower() not in _DISABLED_VALUES
37
+
38
+
39
+ class UploadStatusLine:
40
+ """One-line upload progress indicator drawn on the original stderr."""
41
+
42
+ def __init__(self, stream: Any) -> None:
43
+ self._stream = stream
44
+ self._lock = threading.Lock()
45
+ self._drawn = False
46
+ self._pending = 0
47
+ if sys.platform == "win32":
48
+ try:
49
+ from ._tui import _enable_windows_vt
50
+
51
+ _enable_windows_vt()
52
+ except Exception:
53
+ pass
54
+
55
+ def set_pending(self, n: int) -> None:
56
+ """Update the in-flight save count; draws or erases as needed."""
57
+ with self._lock:
58
+ self._pending = n
59
+ if n > 0:
60
+ self._write(f"\r\x1b[2K[mlops] ↑ {n} artifact(s) uploading…")
61
+ self._drawn = True
62
+ elif self._drawn:
63
+ self._write("\r\x1b[2K")
64
+ self._drawn = False
65
+
66
+ def erase(self) -> None:
67
+ """Clear the line (called by Tee before forwarding user output)."""
68
+ with self._lock:
69
+ if self._drawn:
70
+ self._write("\r\x1b[2K")
71
+ self._drawn = False
72
+
73
+ def redraw(self) -> None:
74
+ """Repaint the line (called by Tee after forwarding user output)."""
75
+ with self._lock:
76
+ if self._pending > 0:
77
+ self._write(
78
+ f"\r\x1b[2K[mlops] ↑ {self._pending} artifact(s) uploading…"
79
+ )
80
+ self._drawn = True
81
+
82
+ def _write(self, text: str) -> None:
83
+ try:
84
+ self._stream.write(text)
85
+ self._stream.flush()
86
+ except Exception:
87
+ pass # the status line must never break the training script
88
+
89
+
90
+ __all__ = ["UploadStatusLine", "status_line_enabled"]
dmlops/_tee.py ADDED
@@ -0,0 +1,192 @@
1
+ """stdout/stderr tee for terminal capture.
2
+
3
+ Swaps ``sys.stdout`` / ``sys.stderr`` after ``mlops.create_experiment()``: writes go to
4
+ the original stream AND into the spool as ``logLines`` batches, so the Web
5
+ experiment Logs page renders the training terminal live (incremental polling
6
+ of ``GET /api/experiments/:id/logs``).
7
+
8
+ Line semantics: data is split on ``\\n``; a ``\\r`` progress-bar fragment is
9
+ held until a ``\\n`` arrives or a 2s timer flushes it (server-side the text
10
+ goes through the same carriage-return collapse as tqdm bars from workers).
11
+
12
+ Boundaries (documented): only this process's own stdout/stderr is captured —
13
+ subprocess output and the user's real tty are not. Under Jupyter the swap
14
+ works the same (references are swapped; no fileno is required).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import sys
20
+ import threading
21
+ import time
22
+ from typing import TYPE_CHECKING, Any, Callable
23
+
24
+ if TYPE_CHECKING:
25
+ from ._status import UploadStatusLine
26
+
27
+ _CARRIAGE_FLUSH_SECS = 2.0
28
+
29
+
30
+ def _collapse_cr(line: str) -> str:
31
+ """Terminal scrollback equivalent of an in-place tqdm bar line: keep the
32
+ last non-empty segment (`text\\r` redraws overwrite earlier segments)."""
33
+ parts = line.split("\r")
34
+ for part in reversed(parts):
35
+ if part:
36
+ return part
37
+ return ""
38
+
39
+
40
+ class Tee:
41
+ def __init__(
42
+ self,
43
+ original: Any,
44
+ emit: "Callable[[list[str]], None]",
45
+ status: "UploadStatusLine | None" = None,
46
+ ) -> None:
47
+ self._original = original
48
+ self._emit = emit
49
+ self._status = status
50
+ self._buffer = ""
51
+ self._lock = threading.Lock()
52
+ self._timer: threading.Timer | None = None
53
+
54
+ # -- stream protocol -------------------------------------------------
55
+ def __getattr__(self, name: str) -> Any:
56
+ # Proxy the rest of the stream protocol (isatty, encoding, fileno…)
57
+ # so libraries inspecting sys.stdout keep working under capture.
58
+ return getattr(self._original, name)
59
+
60
+ def write(self, data: str) -> int:
61
+ if self._status is not None:
62
+ try:
63
+ self._status.erase()
64
+ except Exception:
65
+ pass
66
+ try:
67
+ self._original.write(data)
68
+ self._original.flush()
69
+ except Exception:
70
+ pass
71
+ if self._status is not None:
72
+ try:
73
+ self._status.redraw()
74
+ except Exception:
75
+ pass
76
+ with self._lock:
77
+ self._buffer += data
78
+ self._drain_locked(newline_only=True)
79
+ pending = self._buffer
80
+ if pending and (self._timer is None or not self._timer.is_alive()):
81
+ self._timer = threading.Timer(_CARRIAGE_FLUSH_SECS, self._flush_pending)
82
+ self._timer.daemon = True
83
+ self._timer.start()
84
+ return len(data)
85
+
86
+ def flush(self) -> None:
87
+ try:
88
+ self._original.flush()
89
+ except Exception:
90
+ pass
91
+ self._flush_pending()
92
+
93
+ def _flush_pending(self) -> None:
94
+ with self._lock:
95
+ self._drain_locked(newline_only=False)
96
+
97
+ def _drain_locked(self, *, newline_only: bool) -> None:
98
+ lines: list[str] = []
99
+ while "\n" in self._buffer:
100
+ line, _, rest = self._buffer.partition("\n")
101
+ lines.append(line)
102
+ self._buffer = rest
103
+ if not newline_only and self._buffer:
104
+ lines.append(self._buffer)
105
+ self._buffer = ""
106
+ # tqdm-style progress bars: keep the last non-empty segment so a
107
+ # trailing `\r` (cursor return after the bar text) does not collapse
108
+ # the whole line to empty on the server.
109
+ lines = [_collapse_cr(line) for line in lines]
110
+ lines = [line for line in lines if line.strip()]
111
+ if lines:
112
+ try:
113
+ self._emit(lines)
114
+ except Exception:
115
+ pass # capture must never break the training script
116
+
117
+ def restore(self) -> None:
118
+ with self._lock:
119
+ if self._timer is not None:
120
+ self._timer.cancel()
121
+ self._drain_locked(newline_only=False)
122
+
123
+
124
+ class TerminalCapture:
125
+ """Installs/restores the sys.stdout/sys.stderr tees."""
126
+
127
+ def __init__(
128
+ self,
129
+ emit: "Callable[[list[str]], None]",
130
+ status: "UploadStatusLine | None" = None,
131
+ ) -> None:
132
+ self._emit = emit
133
+ self._status = status
134
+ self._installed: list[tuple[Any, Tee]] = []
135
+ self._active = False
136
+
137
+ def install(self) -> None:
138
+ if self._active:
139
+ return
140
+ self._active = True
141
+ tees: dict[int, "Tee"] = {}
142
+ for attr in ("stdout", "stderr"):
143
+ original = getattr(sys, attr)
144
+ tee = Tee(original, self._emit, status=self._status)
145
+ self._installed.append((attr, original, tee))
146
+ tees[id(original)] = tee
147
+ # Libraries imported before mlops.create_experiment() (e.g. ultralytics) hold the
148
+ # ORIGINAL sys.stdout/sys.stderr object inside logging handlers /
149
+ # tqdm defaults created at import time. Re-point those at the tee so
150
+ # their output reaches the remote terminal too; anything created
151
+ # after the swap picks the tee up from sys.stderr automatically.
152
+ self._adopt_logging_handlers(tees)
153
+ for attr, _original, tee in self._installed:
154
+ setattr(sys, attr, tee)
155
+
156
+ @staticmethod
157
+ def _adopt_logging_handlers(tees: "dict[int, Tee]") -> None:
158
+ try:
159
+ import logging
160
+ except Exception:
161
+ return
162
+ loggers = [logging.root, *logging.Logger.manager.loggerDict.values()]
163
+ seen: set[int] = set()
164
+ for logger in loggers:
165
+ if not isinstance(logger, logging.Logger):
166
+ continue
167
+ for handler in logger.handlers:
168
+ if id(handler) in seen:
169
+ continue
170
+ seen.add(id(handler))
171
+ stream = getattr(handler, "stream", None)
172
+ if stream is None:
173
+ continue
174
+ replacement = tees.get(id(stream))
175
+ if replacement is not None and replacement is not stream:
176
+ try:
177
+ handler.setStream(replacement)
178
+ except Exception:
179
+ pass
180
+
181
+ def restore(self) -> None:
182
+ if not self._active:
183
+ return
184
+ for attr, original, tee in self._installed:
185
+ tee.restore()
186
+ setattr(sys, attr, original)
187
+ self._installed = []
188
+ self._active = False
189
+
190
+ @property
191
+ def active(self) -> bool:
192
+ return self._active