|
| 1 | +"""Jupyter-compatible progress display helpers for PySR.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import re |
| 6 | +import sys |
| 7 | +from contextlib import contextmanager |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import Callable, Iterator, Protocol |
| 10 | + |
| 11 | + |
| 12 | +_PROGRESS_PATTERN = re.compile(r"Progress:\s*(\d+)\s*/\s*(\d+)\s*total iterations") |
| 13 | + |
| 14 | + |
| 15 | +class _ProgressDisplay(Protocol): |
| 16 | + def update(self, current: int, total: int) -> None: ... |
| 17 | + |
| 18 | + def close(self) -> None: ... |
| 19 | + |
| 20 | + |
| 21 | +class _NullProgressDisplay: |
| 22 | + def update(self, current: int, total: int) -> None: |
| 23 | + return None |
| 24 | + |
| 25 | + def close(self) -> None: |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +class _TqdmProgressDisplay: |
| 30 | + def __init__(self, total: int): |
| 31 | + from tqdm.notebook import tqdm |
| 32 | + |
| 33 | + self._bar = tqdm(total=total, desc="PySR fit", leave=True) |
| 34 | + self._current = 0 |
| 35 | + |
| 36 | + def update(self, current: int, total: int) -> None: |
| 37 | + if total != self._bar.total: |
| 38 | + self._bar.total = total |
| 39 | + delta = max(0, current - self._current) |
| 40 | + if delta > 0: |
| 41 | + self._bar.update(delta) |
| 42 | + self._current = current |
| 43 | + |
| 44 | + def close(self) -> None: |
| 45 | + self._bar.close() |
| 46 | + |
| 47 | + |
| 48 | +class _IpywidgetsProgressDisplay: |
| 49 | + def __init__(self, total: int): |
| 50 | + from IPython.display import display |
| 51 | + from ipywidgets import HTML, IntProgress, VBox |
| 52 | + |
| 53 | + self._bar = IntProgress(value=0, min=0, max=max(total, 1), description="PySR fit") |
| 54 | + self._label = HTML(value=f"0 / {total} iterations") |
| 55 | + self._widget = VBox([self._bar, self._label]) |
| 56 | + display(self._widget) |
| 57 | + |
| 58 | + def update(self, current: int, total: int) -> None: |
| 59 | + self._bar.max = max(total, 1) |
| 60 | + self._bar.value = min(max(current, 0), self._bar.max) |
| 61 | + self._label.value = f"{current} / {total} iterations" |
| 62 | + |
| 63 | + def close(self) -> None: |
| 64 | + return None |
| 65 | + |
| 66 | + |
| 67 | +def _is_notebook_session() -> bool: |
| 68 | + try: |
| 69 | + from IPython import get_ipython |
| 70 | + except Exception: |
| 71 | + return False |
| 72 | + |
| 73 | + ipython = get_ipython() |
| 74 | + if ipython is None: |
| 75 | + return False |
| 76 | + return ipython.__class__.__name__ == "ZMQInteractiveShell" |
| 77 | + |
| 78 | + |
| 79 | +def _create_display(total: int) -> _ProgressDisplay: |
| 80 | + try: |
| 81 | + return _TqdmProgressDisplay(total=total) |
| 82 | + except Exception: |
| 83 | + pass |
| 84 | + |
| 85 | + try: |
| 86 | + return _IpywidgetsProgressDisplay(total=total) |
| 87 | + except Exception: |
| 88 | + return _NullProgressDisplay() |
| 89 | + |
| 90 | + |
| 91 | +@dataclass |
| 92 | +class _ProgressLineParser: |
| 93 | + on_progress: Callable[[int, int], None] |
| 94 | + |
| 95 | + def parse_line(self, line: str) -> None: |
| 96 | + match = _PROGRESS_PATTERN.search(line) |
| 97 | + if match is None: |
| 98 | + return |
| 99 | + current = int(match.group(1)) |
| 100 | + total = int(match.group(2)) |
| 101 | + self.on_progress(current, total) |
| 102 | + |
| 103 | + |
| 104 | +class _ProgressCaptureStream: |
| 105 | + def __init__(self, target_stream, parser: _ProgressLineParser): |
| 106 | + self._target = target_stream |
| 107 | + self._parser = parser |
| 108 | + self._buffer = "" |
| 109 | + |
| 110 | + def write(self, text: str) -> int: |
| 111 | + if not isinstance(text, str): |
| 112 | + text = str(text) |
| 113 | + written = self._target.write(text) |
| 114 | + self._buffer += text |
| 115 | + while "\n" in self._buffer: |
| 116 | + line, self._buffer = self._buffer.split("\n", 1) |
| 117 | + self._parser.parse_line(line) |
| 118 | + return written if isinstance(written, int) else len(text) |
| 119 | + |
| 120 | + def flush(self) -> None: |
| 121 | + if self._buffer: |
| 122 | + self._parser.parse_line(self._buffer) |
| 123 | + self._buffer = "" |
| 124 | + if hasattr(self._target, "flush"): |
| 125 | + self._target.flush() |
| 126 | + |
| 127 | + def __getattr__(self, name: str): |
| 128 | + return getattr(self._target, name) |
| 129 | + |
| 130 | + |
| 131 | +class JupyterProgressContext: |
| 132 | + """Capture text progress lines and render a notebook progress widget.""" |
| 133 | + |
| 134 | + def __init__(self, total_iterations: int): |
| 135 | + self.total_iterations = max(int(total_iterations), 1) |
| 136 | + self.display: _ProgressDisplay = _NullProgressDisplay() |
| 137 | + self._parser = _ProgressLineParser(self._on_progress) |
| 138 | + self._current = 0 |
| 139 | + |
| 140 | + def _on_progress(self, current: int, total: int) -> None: |
| 141 | + self._current = current |
| 142 | + self.display.update(current, total) |
| 143 | + |
| 144 | + @contextmanager |
| 145 | + def capture(self) -> Iterator[None]: |
| 146 | + self.display = _create_display(self.total_iterations) |
| 147 | + self.display.update(0, self.total_iterations) |
| 148 | + stdout_capture = _ProgressCaptureStream(sys.stdout, self._parser) |
| 149 | + stderr_capture = _ProgressCaptureStream(sys.stderr, self._parser) |
| 150 | + old_stdout, old_stderr = sys.stdout, sys.stderr |
| 151 | + try: |
| 152 | + sys.stdout = stdout_capture |
| 153 | + sys.stderr = stderr_capture |
| 154 | + yield |
| 155 | + finally: |
| 156 | + stdout_capture.flush() |
| 157 | + stderr_capture.flush() |
| 158 | + sys.stdout, sys.stderr = old_stdout, old_stderr |
| 159 | + self.display.update(self.total_iterations, self.total_iterations) |
| 160 | + self.display.close() |
| 161 | + |
| 162 | + |
| 163 | +def should_use_jupyter_progress(*, progress: bool, verbosity: int, is_single_output: bool) -> bool: |
| 164 | + """Whether PySR should use Python-side notebook progress handling.""" |
| 165 | + if not progress or verbosity <= 0 or not is_single_output: |
| 166 | + return False |
| 167 | + return _is_notebook_session() |
0 commit comments