Coverage for geoparser/gazetteer/build/progress.py: 100%

206 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1""" 

2Console output helpers for the gazetteer build pipeline. 

3 

4Build activity is grouped by pipeline stage (preparing sources, compiling 

5features, building the artifact; see :mod:`builder`), mirroring how the old 

6installer grouped progress by source: each stage owns a persistent bar that 

7reads "<verb>ing ..." while it runs and "<verb>ed ..." once every item in it 

8has completed, turning from cyan to green. Individual items within a stage (a 

9download, a staged source, a query run against a feature block, ...) render 

10as dimmed, indented bars nested under their stage and disappear as soon as 

11they finish, so only the stage bars and the currently active item remain on 

12screen. There are no checkmarks and no byte counts for downloads; progress 

13within an item is shown as a percentage (or, for indeterminate work, an 

14animated bar with no percentage). A determinate item that finishes 

15successfully is snapped to 100% and held there briefly (see 

16:data:`_COMPLETION_PAUSE_SECONDS`) before it disappears, so it visibly 

17completes rather than seeming to vanish mid-step, whether it was polling 

18normally or sitting at some percentage right up to the end. A failed item 

19disappears immediately instead, since there is no completed state to show. 

20 

21Every item that appears leaves a mark on its stage: the stage advances by one 

22the moment its item disappears, so the stage's own percentage always 

23reflects real, finished work rather than jumping only once several items 

24have quietly come and gone. A stage's ``total_items`` is a best 

25estimate (the exact number of items some units of work will show, e.g. an 

26acquisition's download-then-extract, is only known once it runs); the count 

27grows on the fly if advances outrun it, so the displayed total never falls 

28behind reality, and is snapped to match whatever actually completed once the 

29stage exits. 

30 

31Database operations (a single DuckDB query, or a batch of SQLite statements) 

32report a percentage too, using :func:`track`, which runs the operation on a 

33background thread while polling a caller-supplied progress function (for 

34DuckDB, ``connection.query_progress()``; for known-size batches, the fraction 

35of rows or statements completed so far). These are estimates: DuckDB does not 

36track progress for every query shape, and statement-count progress does not 

37account for statements taking unequal time, but they give a useful sense of 

38motion for otherwise silent, long-running steps. Their items are always 

39created determinate (``total=100``) so they read "0%" immediately rather than 

40ever showing an animated, indeterminate bar, even briefly. Each individual 

41query gets its own item, shown and disposed of in turn, rather than several 

42queries sharing one bar (which would either not reflect their real, separate 

43progress or require guessing at how to divide the bar between them). 

44""" 

45 

46import threading 

47import time 

48import typing as t 

49from contextlib import contextmanager 

50from contextvars import ContextVar 

51 

52from rich.console import Console 

53from rich.progress import BarColumn, Progress, ProgressColumn, Task, TimeElapsedColumn 

54from rich.rule import Rule 

55from rich.spinner import Spinner 

56from rich.table import Column, Table 

57from rich.text import Text 

58 

59# Connector that visually nests an item (child) bar under its stage. 

60_CHILD_CONNECTOR = " └─ " 

61_CHILD_SPINNER_NAME = "dots" 

62 

63# How long a completed item lingers at 100% before disappearing. Without 

64# this, an item that jumps straight from 0% (or wherever it was polling) to 

65# done in the same instant it finishes never actually renders its completed 

66# state, making the step look like it vanished rather than finished. 

67_COMPLETION_PAUSE_SECONDS = 0.15 

68 

69# Status colors. A stage is "in progress" (cyan) until all of its items 

70# complete, then "done" (green); item bars always use the in-progress color 

71# since they disappear on completion. 

72_RUNNING_STYLE = "cyan" 

73_DONE_STYLE = "green" 

74 

75_console = Console(stderr=True) 

76 

77# The Progress shared by every stage and item of the current build. 

78_active_progress: ContextVar[t.Optional[Progress]] = ContextVar( 

79 "active_build_progress", default=None 

80) 

81# The stage currently accepting items, so item() can attach without callers 

82# threading a stage object through unrelated modules (e.g. acquire.py). 

83_active_stage: ContextVar[t.Optional["Stage"]] = ContextVar( 

84 "active_build_stage", default=None 

85) 

86 

87 

88class _DescriptionColumn(ProgressColumn): 

89 """ 

90 Render stage and item descriptions so the two are easy to tell apart. 

91 

92 A stage task is shown as its running label in bold cyan while any of its 

93 items are outstanding, then its done label in bold green once complete. 

94 An item task is dimmed and nested under its stage with a tree connector 

95 and an animated spinner while it runs. 

96 """ 

97 

98 def __init__(self, width: int) -> None: 

99 super().__init__( 

100 table_column=Column(width=width, no_wrap=True, overflow="ellipsis") 

101 ) 

102 self._child_spinner = Spinner(_CHILD_SPINNER_NAME, style="dim") 

103 

104 def render(self, task: Task) -> Text: 

105 if task.fields.get("is_stage"): 

106 if task.finished: 

107 return Text(str(task.fields["done_label"]), style=f"bold {_DONE_STYLE}") 

108 return Text(str(task.description), style=f"bold {_RUNNING_STYLE}") 

109 line = Text(_CHILD_CONNECTOR, style="dim") 

110 line.append_text(self._child_spinner.render(task.get_time())) 

111 line.append(" ") 

112 line.append(str(task.description), style="dim") 

113 return line 

114 

115 

116class _ProgressReadoutColumn(ProgressColumn): 

117 """ 

118 Render the progress readout for a task. 

119 

120 Both a stage and an item read as a plain percentage when their progress 

121 is known, or left blank for indeterminate work (its bar animates 

122 instead); showing the same "NN%" form for both keeps the display 

123 consistent rather than mixing a raw item count into an otherwise 

124 percentage-based display. The column has a fixed, narrow width so this 

125 text changing length (e.g. "9%" to "100%", or one row disappearing while 

126 another remains) never shifts every other column alongside it. The width 

127 is sized to the widest reading ("100%"), so right-aligned text fills it 

128 at that width with no slack, giving the same one-space gap on both sides 

129 (to the bar on the left, to the elapsed time on the right); narrower 

130 readings still lean right and open up a larger gap on the left only. 

131 """ 

132 

133 def __init__(self) -> None: 

134 super().__init__( 

135 table_column=Column(width=4, justify="right", no_wrap=True) 

136 ) 

137 

138 def render(self, task: Task) -> Text: 

139 if task.total: 

140 return Text(f"{int(task.percentage)}%", style="progress.percentage") 

141 return Text("") 

142 

143 

144class _StyledBarColumn(BarColumn): 

145 """ 

146 Bar column colored by status: a stage bar turns from in-progress to done 

147 when all of its items complete, while item bars always use the 

148 in-progress color (they disappear on completion, before it would matter). 

149 """ 

150 

151 def render(self, task: Task): 

152 if task.fields.get("is_stage") and task.finished: 

153 style = _DONE_STYLE 

154 else: 

155 style = _RUNNING_STYLE 

156 self.complete_style = style 

157 self.finished_style = style 

158 return super().render(task) 

159 

160 

161def _layout_width() -> int: 

162 """Return the current terminal width.""" 

163 return max(_console.size.width, 1) 

164 

165 

166def _description_width() -> int: 

167 """Return the description column width (half of the layout width).""" 

168 return max(_layout_width() // 2, 1) 

169 

170 

171def _make_progress() -> Progress: 

172 """Build a progress display with the shared column layout.""" 

173 return Progress( 

174 _DescriptionColumn(_description_width()), 

175 _StyledBarColumn(), 

176 _ProgressReadoutColumn(), 

177 TimeElapsedColumn(), 

178 console=_console, 

179 expand=True, 

180 ) 

181 

182 

183def print_build_header(gazetteer_name: str) -> None: 

184 """ 

185 Print a heading before a gazetteer build begins. 

186 

187 Args: 

188 gazetteer_name: Name of the gazetteer being built 

189 """ 

190 _console.print() 

191 _console.print(Rule(gazetteer_name, style="bold")) 

192 _console.print() 

193 

194 

195def print_build_summary(feature_count: int, name_count: int) -> None: 

196 """ 

197 Print a short summary after a gazetteer build completes. 

198 

199 Args: 

200 feature_count: Number of features in the artifact 

201 name_count: Number of names in the artifact 

202 """ 

203 table = Table(show_header=False, box=None, pad_edge=False) 

204 table.add_column(style="dim") 

205 table.add_column(justify="right") 

206 table.add_row("Features", f"{feature_count:,}") 

207 table.add_row("Names", f"{name_count:,}") 

208 

209 _console.print() 

210 _console.print("Summary", style="bold") 

211 _console.print() 

212 _console.print(table) 

213 _console.print() 

214 

215 

216@contextmanager 

217def build_display() -> t.Iterator[None]: 

218 """ 

219 Open the shared live display for a build. 

220 

221 Stages and items created within the ``with`` block attach to this 

222 display. Nesting is supported: an inner call reuses the already-active 

223 display. 

224 

225 Yields: 

226 None 

227 """ 

228 if _active_progress.get() is not None: 

229 yield 

230 return 

231 progress = _make_progress() 

232 token = _active_progress.set(progress) 

233 try: 

234 with progress: 

235 yield 

236 finally: 

237 _active_progress.reset(token) 

238 

239 

240class Stage: 

241 """ 

242 A pipeline stage's progress: a persistent bar tracking completed items. 

243 

244 Items are transient nested bars created with :func:`item`; they attach to 

245 whichever stage is currently active and disappear once finished. Callers 

246 advance the stage's own item count explicitly with :meth:`advance`, once 

247 for every item bar that appeared and finished, so nothing disappears 

248 without leaving a mark on the stage it belongs to. ``total_items`` is 

249 only an initial estimate: it grows automatically if advances outrun it, 

250 so the displayed total is never less than what has actually completed. 

251 """ 

252 

253 def __init__(self, running_label: str, done_label: str, total_items: int): 

254 self.running_label = running_label 

255 self.done_label = done_label 

256 self.total_items = total_items 

257 self._completed = 0 

258 self._progress: t.Optional[Progress] = None 

259 self._owns_display = False 

260 self._task_id: t.Optional[int] = None 

261 self._stage_token = None 

262 

263 def __enter__(self) -> "Stage": 

264 progress = _active_progress.get() 

265 if progress is None: 

266 progress = _make_progress() 

267 progress.start() 

268 self._owns_display = True 

269 self._progress = progress 

270 self._task_id = progress.add_task( 

271 self.running_label, 

272 total=self.total_items, 

273 is_stage=True, 

274 done_label=self.done_label, 

275 ) 

276 self._stage_token = _active_stage.set(self) 

277 return self 

278 

279 def __exit__(self, exc_type, exc_val, exc_tb) -> None: 

280 _active_stage.reset(self._stage_token) 

281 if exc_type is None: 

282 # Snap to completion so the bar turns green and the label flips 

283 # to its done form even if a caller under-counted advances. 

284 self._progress.update(self._task_id, completed=self.total_items) 

285 if self._owns_display: 

286 self._progress.stop() 

287 

288 def advance(self, count: int = 1) -> None: 

289 """ 

290 Mark ``count`` more items of this stage as completed. 

291 

292 Grows ``total_items`` first if this would otherwise complete more 

293 items than the stage's estimate accounted for, so the bar never 

294 shows more completed than total and never has to jump backwards. 

295 """ 

296 self._completed += count 

297 if self._completed > self.total_items: 

298 self.total_items = self._completed 

299 self._progress.update(self._task_id, total=self.total_items) 

300 self._progress.advance(self._task_id, count) 

301 

302 def item( 

303 self, description: str, total: t.Optional[float] = None 

304 ) -> "_Item": 

305 """Create an item bar nested under this stage.""" 

306 task_id = self._progress.add_task(description, total=total, is_child=True) 

307 return _Item(self._progress, task_id, total=total) 

308 

309 

310@contextmanager 

311def stage(running_label: str, done_label: str, total_items: int) -> t.Iterator[Stage]: 

312 """ 

313 Open a stage's progress group. 

314 

315 Args: 

316 running_label: Label shown while the stage has outstanding items 

317 done_label: Label shown once every item has completed 

318 total_items: Estimated number of items the stage represents; grows 

319 automatically (see :meth:`Stage.advance`) if more complete 

320 

321 Yields: 

322 The active :class:`Stage` 

323 """ 

324 group = Stage(running_label, done_label, total_items) 

325 with group: 

326 yield group 

327 

328 

329class _Item: 

330 """A transient, nested progress bar for one unit of work within a stage.""" 

331 

332 def __init__( 

333 self, 

334 progress: Progress, 

335 task_id: int, 

336 total: t.Optional[float] = None, 

337 ): 

338 self._progress = progress 

339 self._task_id = task_id 

340 self._determinate = total is not None 

341 self._total = total 

342 

343 def update(self, advance: float) -> None: 

344 """Advance this item's progress by ``advance`` units.""" 

345 self._progress.update(self._task_id, advance=advance) 

346 

347 def set_progress(self, percent: float) -> None: 

348 """ 

349 Set this item's progress to an absolute percentage (0-100). 

350 

351 Callers that intend to report a percentage should create the item 

352 with ``total=100`` up front, so it reads "0%" immediately rather than 

353 flashing an animated, indeterminate bar before the first call. If it 

354 wasn't, this switches it from indeterminate to determinate on first 

355 use, as a fallback. 

356 """ 

357 if not self._determinate: 

358 self._progress.update(self._task_id, total=100) 

359 self._determinate = True 

360 self._total = 100 

361 self._progress.update(self._task_id, completed=percent) 

362 

363 def close(self, success: bool = True) -> None: 

364 """ 

365 Finish this item and remove its bar. 

366 

367 On success, a determinate item is first snapped to its full total 

368 (in case the caller under-reported the very last step) and briefly 

369 held on screen so its completed state is actually visible, rather 

370 than disappearing in the same instant it reaches 100% (see 

371 :data:`_COMPLETION_PAUSE_SECONDS`). A failed item disappears at once; 

372 there is nothing meaningful to show. 

373 

374 Args: 

375 success: Whether the work this item tracked finished without error 

376 """ 

377 if success and self._determinate and self._total: 

378 self._progress.update(self._task_id, completed=self._total) 

379 self._progress.refresh() 

380 time.sleep(_COMPLETION_PAUSE_SECONDS) 

381 self._progress.remove_task(self._task_id) 

382 

383 

384@contextmanager 

385def item(description: str, total: t.Optional[float] = None) -> t.Iterator[_Item]: 

386 """ 

387 Display a nested, transient progress item. 

388 

389 Attaches under the currently active stage (see :func:`stage`) so it nests 

390 and disappears the way the stage's own items do. Outside of an active 

391 stage it manages a standalone display, indeterminate by default. 

392 

393 Args: 

394 description: Human-readable description of the item 

395 total: Known quantity of work, if any (renders a percentage); ``None`` 

396 renders an animated, indeterminate bar 

397 

398 Yields: 

399 The active item bar 

400 """ 

401 active_stage = _active_stage.get() 

402 if active_stage is not None: 

403 bar = active_stage.item(description, total) 

404 success = False 

405 try: 

406 yield bar 

407 success = True 

408 finally: 

409 bar.close(success=success) 

410 return 

411 

412 progress = _active_progress.get() 

413 owns_display = progress is None 

414 if owns_display: 

415 progress = _make_progress() 

416 progress.start() 

417 task_id = progress.add_task(description, total=total, is_child=True) 

418 bar = _Item(progress, task_id, total=total) 

419 success = False 

420 try: 

421 yield bar 

422 success = True 

423 finally: 

424 bar.close(success=success) 

425 if owns_display: 

426 progress.stop() 

427 

428 

429def track( 

430 bar: _Item, 

431 poll: t.Callable[[], t.Optional[float]], 

432 run: t.Callable[[], None], 

433 poll_interval: float = 0.1, 

434) -> None: 

435 """ 

436 Run ``run()`` on a background thread while reporting live progress on ``bar``. 

437 

438 ``poll()`` is called periodically (from this thread, so it must be safe to 

439 call concurrently with ``run()``) and should return a percentage in 

440 ``[0, 100]`` once known. Until the first such reading, ``poll()`` may 

441 return a negative number or ``None``; used for querying DuckDB's own query 

442 progress (``connection.query_progress()``), which reports -1 for queries it 

443 cannot track. ``bar`` should already be determinate (created with 

444 ``total=100``) so it reads "0%" rather than flashing an animated, 

445 indeterminate bar for the (possibly long) stretch before the first 

446 reading arrives, or at all if ``poll()`` never returns one. Once ``run()`` 

447 finishes successfully, ``bar`` is snapped to 100% regardless of the last 

448 polled value, since DuckDB's estimate can undershoot right up to the end. 

449 

450 A caller with several queries to run should give each its own item and 

451 ``track()`` call in turn, rather than share one bar between them: that 

452 way every bar's progress is real, and the display simply shows one 

453 finishing before the next appears. 

454 

455 Args: 

456 bar: The item bar to update; should be created with ``total=100`` 

457 poll: Returns the current progress percentage, or a negative 

458 number/``None`` while not yet known 

459 run: The work to perform; exceptions are re-raised on the calling 

460 thread once it returns 

461 poll_interval: Seconds between polls 

462 

463 Raises: 

464 Whatever exception ``run()`` raised, re-raised on the calling thread 

465 """ 

466 error: t.List[BaseException] = [] 

467 

468 def _run() -> None: 

469 try: 

470 run() 

471 except BaseException as exc: # noqa: BLE001 - re-raised below 

472 error.append(exc) 

473 

474 thread = threading.Thread(target=_run, daemon=True) 

475 thread.start() 

476 while thread.is_alive(): 

477 _sample(bar, poll) 

478 thread.join(timeout=poll_interval) 

479 thread.join() 

480 if error: 

481 raise error[0] 

482 bar.set_progress(100) 

483 

484 

485def _sample(bar: _Item, poll: t.Callable[[], t.Optional[float]]) -> None: 

486 """Read one progress value and apply it to ``bar``, ignoring poll errors.""" 

487 try: 

488 value = poll() 

489 except Exception: 

490 return 

491 if value is not None and value >= 0: 

492 bar.set_progress(value) 

493 

494 

495def advance(count: int = 1) -> None: 

496 """ 

497 Advance the currently active stage's item count, if any. 

498 

499 Lets modules record completed work (see :mod:`acquire`) without holding a 

500 reference to the stage object. 

501 

502 Args: 

503 count: Number of items to mark as completed 

504 """ 

505 active_stage = _active_stage.get() 

506 if active_stage is not None: 

507 active_stage.advance(count) 

508 

509 

510def label_suffixes(labels: t.Sequence[str]) -> t.List[str]: 

511 """ 

512 Number labels that repeat, so identical-looking items are told apart. 

513 

514 Several items in a row can legitimately share a base description (e.g. 

515 one "Collecting names from X" per configured name, or one "Assembling 

516 features from X" per feature block that happens to share a source). Left 

517 unnumbered, a repeat looks like the previous item's bar restarted rather 

518 than a new, distinct one appearing; this returns a same-length list of 

519 suffixes to append to each label; ``""`` for labels that occur only once, 

520 or ``" (i/N)"`` (1-based, in order of appearance) for each occurrence of 

521 one that repeats. 

522 

523 Args: 

524 labels: Base descriptions, in the order their items will be shown 

525 

526 Returns: 

527 Suffix to append to each label at the same position 

528 

529 Example: 

530 >>> label_suffixes(["Loading A", "Collecting names from A", "Collecting names from A"]) 

531 ['', ' (1/2)', ' (2/2)'] 

532 """ 

533 totals: t.Dict[str, int] = {} 

534 for label in labels: 

535 totals[label] = totals.get(label, 0) + 1 

536 seen: t.Dict[str, int] = {} 

537 suffixes = [] 

538 for label in labels: 

539 total = totals[label] 

540 if total <= 1: 

541 suffixes.append("") 

542 continue 

543 seen[label] = seen.get(label, 0) + 1 

544 suffixes.append(f" ({seen[label]}/{total})") 

545 return suffixes