Coverage for collectra/gui/backend.py: 89.73%

1558 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1""" 

2API backend for annotation display logic via pywebview's js_api interface. 

3 

4JavaScript usage: 

5 await pywebview.api.load_yaml("path/to/results.yaml") 

6 const result = await pywebview.api.get_display_value("node_id") 

7 const nodes = await pywebview.api.get_all_nodes() 

8""" 

9 

10import base64 

11import csv 

12import enum 

13import platform 

14import re 

15import threading 

16import time 

17import uuid 

18from collections.abc import Sequence 

19from contextlib import contextmanager, suppress 

20from dataclasses import dataclass 

21from pathlib import Path 

22from typing import TYPE_CHECKING 

23 

24import webview 

25 

26from collectra.commons.files import CollectraFile 

27 

28from . import run_log 

29from .data_display import CollectraAnnotationNode, CollectraGraph, NodeDisplayValue 

30from .scss_theme import compile_theme 

31 

32if TYPE_CHECKING: 

33 from collectra.pipelines.base import Pipeline 

34 

35 

36class ImageFormat(enum.Enum): 

37 PNG = "image/png" 

38 JPEG = "image/jpeg" 

39 JPG = "image/jpg" 

40 GIF = "image/gif" 

41 BMP = "image/bmp" 

42 WEBP = "image/webp" 

43 TIFF = "image/tiff" 

44 TIF = "image/tiff" 

45 

46 

47RUN_IN_PROGRESS = "A run is in progress on this page" 

48STALE_PAGE = "The run changed this page; open it again before editing" 

49NOTHING_TO_RUN = "Every page that can run already has its results" 

50NO_PAGE_CAN_RUN = "None of the pages can be run" 

51# How long closing the window waits for a stopping run to finish its task and 

52# put back any output it had moved aside. 

53RUN_STOP_TIMEOUT = 30 

54 

55 

56@dataclass 

57class _RunState: 

58 """What the run started from the Run button is doing, for get_run_status. 

59 

60 A single folder given as a Path is kept as a set of one. Folders are 

61 resolved, as the guard compares resolved folders. 

62 """ 

63 

64 folders: frozenset[Path] 

65 total: int 

66 running: bool = True 

67 started: int = 0 

68 done: int = 0 

69 stop: bool = False 

70 summary: str | None = None 

71 error: str | None = None 

72 unit: str = "tasks" 

73 

74 def __post_init__(self): 

75 if isinstance(self.folders, Path): 

76 self.folders = {self.folders} 

77 self.folders = frozenset(folder.resolve() for folder in self.folders) 

78 

79 @property 

80 def folder(self) -> Path | None: 

81 """The run's folder when it runs one page, else None.""" 

82 return next(iter(self.folders)) if len(self.folders) == 1 else None 

83 

84 

85def _crashed_report(plan, error: BaseException): 

86 """The report of a run that broke: planned skips kept, the rest failed.""" 

87 from collectra.pipelines.run_plan import RunReport, TaskOutcome 

88 

89 detail = f"{type(error).__name__}: {error}" 

90 return RunReport( 

91 [ 

92 ( 

93 TaskOutcome(task.name, "skipped", "kept existing output") 

94 if task.action == "skip" 

95 else TaskOutcome(task.name, "failed", detail) 

96 ) 

97 for task in plan.tasks 

98 ] 

99 ) 

100 

101 

102class GUIBackend: 

103 """ 

104 API class exposed to JavaScript via pywebview. 

105 

106 All public methods are accessible in JS as: 

107 window.pywebview.api.methodName(args) 

108 """ 

109 

110 def __init__(self, pipeline: "Pipeline", inputs=(), max_pixels: int = 4096): 

111 """ 

112 Initialize the API instance. 

113 

114 Sets up the annotation graph, YAML path, and window reference. 

115 All values are initially None until load_yaml() is called. 

116 """ 

117 if type(max_pixels) is not int or max_pixels < 1: 

118 raise ValueError("max_pixels must be a positive integer") 

119 self._max_pixels = max_pixels 

120 self._git_lock = threading.Lock() 

121 self._text_save_lock = threading.Lock() 

122 self._update_lock = threading.Lock() 

123 self._run_lock = threading.Lock() 

124 self._run_state: _RunState | None = None 

125 self._run_thread: threading.Thread | None = None 

126 # A page the run changed but that could not be reloaded afterwards. 

127 self._stale_folder: Path | None = None 

128 self._restart_requested = False 

129 self._restart_required = False 

130 self._pipeline = pipeline 

131 self._collectra_file: CollectraFile | None = None 

132 self._graph: CollectraGraph | None = None 

133 self._yaml_path: str | None = None 

134 self._window = None 

135 self._collectra_folders: list[dict] = [] 

136 self._parent_folder: str | None = None 

137 self._global_labels: set[str] = set() 

138 self._global_label_counts: dict[str, int] = {} # {label: total_count} 

139 self._global_link_names: set[str] = set() # names of Links on any page 

140 from .session_cache import FolderSessionCache 

141 

142 pipeline_path = getattr(pipeline, "path", None) 

143 self._session_cache = ( 

144 FolderSessionCache(pipeline_path) if pipeline_path else None 

145 ) 

146 from .arrangement import ArrangementStore 

147 

148 metadata = getattr(pipeline, "pipeline_metadata", {}) 

149 layouts = metadata.get("layouts") 

150 default_layout = None 

151 if pipeline_path and isinstance(layouts, list) and layouts: 

152 if isinstance(layouts[0], str) and layouts[0].strip(): 

153 default_layout = Path(pipeline_path) / layouts[0] 

154 self._arrangement = ( 

155 ArrangementStore( 

156 pipeline_path, 

157 pipeline_name=metadata.get("name") or getattr(pipeline, "name", None), 

158 default_layout=default_layout, 

159 ) 

160 if pipeline_path 

161 else None 

162 ) 

163 self._initial_items = ( 

164 self._load_input_paths(inputs) if inputs else self._restore_folder_session() 

165 ) 

166 

167 def _save_folder_session(self, folders=None) -> None: 

168 if self._session_cache is not None: 

169 paths = ( 

170 folders 

171 if folders is not None 

172 else [folder["path"] for folder in self._collectra_folders] 

173 ) 

174 self._session_cache.write([str(Path(path).resolve()) for path in paths]) 

175 

176 def _restore_folder_session(self): 

177 if self._session_cache is None: 

178 return None 

179 self._collectra_folders = [] 

180 seen = set() 

181 for value in self._session_cache.read(): 

182 try: 

183 path = Path(value).resolve() 

184 if path in seen or not path.is_dir(): 

185 continue 

186 scan = self._scan_collectra_folder(path) 

187 if scan is None: 

188 continue 

189 seen.add(path) 

190 self._collectra_folders.append( 

191 {"name": path.name, "path": str(path), **scan} 

192 ) 

193 except (OSError, ValueError): 

194 continue 

195 self._save_folder_session() 

196 if not self._collectra_folders: 

197 return None 

198 self._parent_folder = str(Path(self._collectra_folders[0]["path"]).parent) 

199 active = self._session_cache.read_active() 

200 active_index = next( 

201 ( 

202 index 

203 for index, folder in enumerate(self._collectra_folders) 

204 if folder["path"] == active 

205 ), 

206 0, 

207 ) 

208 return { 

209 **self._folder_list_result(), 

210 "provided": True, 

211 "mode": "parent", 

212 "active_index": active_index, 

213 } 

214 

215 def git_action(self, action: str, message: str = "", repository: str = "") -> dict: 

216 """Operate on the Git repository containing the active results file.""" 

217 from .source_control import run_git 

218 

219 if not self._yaml_path: 

220 return {"success": False, "error": "Open a results folder first"} 

221 if not self._git_lock.acquire(blocking=False): 

222 return {"success": False, "error": "A Git operation is already running"} 

223 try: 

224 # Git works on the whole repository, which may hold the running page. 

225 if action != "status" and self._run_lock.locked(): 

226 return {"success": False, "error": RUN_IN_PROGRESS} 

227 return run_git(Path(self._yaml_path).parent, action, message, repository) 

228 finally: 

229 self._git_lock.release() 

230 

231 def _run_guard(self, folder: Path | None = None) -> dict | None: 

232 """The error a write returns while a run is active on that folder. 

233 

234 Without a folder, the open page's folder is meant. Other pages stay 

235 editable during a run. 

236 """ 

237 state = self._run_state 

238 if folder is None: 

239 if self._yaml_path is None: 

240 return None 

241 folder = Path(self._yaml_path).parent 

242 folder = folder.resolve() 

243 if state is not None and state.running and folder in state.folders: 

244 return {"success": False, "error": RUN_IN_PROGRESS} 

245 if folder == self._stale_folder: 

246 return {"success": False, "error": STALE_PAGE} 

247 return None 

248 

249 @contextmanager 

250 def _editing(self, folder: Path | None = None): 

251 """Hold the shared edit lock for a write; yields the guard's error or None. 

252 

253 start_run takes the same lock, so a write that passed the guard has 

254 finished before a run begins. 

255 """ 

256 with self._text_save_lock: 

257 yield self._run_guard(folder) 

258 

259 def get_run_preview(self, overwrite: bool = False) -> dict: 

260 """Which tasks a run of the open page would run, re-run or skip. 

261 

262 Planning loads the page into the pipeline as a run does, so it holds 

263 the run lock: no run starts while a preview is being made. 

264 

265 Args: 

266 overwrite: Re-run every task that has output, replacing it. 

267 

268 Returns: 

269 Whether the page can run, its planned tasks and a message. 

270 """ 

271 try: 

272 folder = self._run_folder() 

273 if not self._run_lock.acquire(blocking=False): 

274 raise RuntimeError("A run is already in progress") 

275 try: 

276 plan = self._plan(folder, overwrite) 

277 finally: 

278 self._run_lock.release() 

279 except Exception as error: 

280 return { 

281 "success": True, 

282 "can_run": False, 

283 "tasks": [], 

284 "message": str(error), 

285 } 

286 return { 

287 "success": True, 

288 "can_run": True, 

289 "tasks": [ 

290 {"name": task.name, "action": task.action, "reason": task.reason} 

291 for task in plan.tasks 

292 ], 

293 "message": ( 

294 f"Warning: {'; '.join(plan.warnings)}." if plan.warnings else "" 

295 ), 

296 } 

297 

298 def _run_folder(self) -> Path: 

299 """The open page's folder, if a pipeline can run on it.""" 

300 if self._yaml_path is None: 

301 raise RuntimeError("Open a page first") 

302 if self._pipeline is None: 

303 raise RuntimeError("No pipeline is loaded") 

304 return Path(self._yaml_path).parent.resolve() 

305 

306 def _plan(self, folder: Path, overwrite: bool): 

307 """The page's plan; overwrite is passed only when it is asked for.""" 

308 if overwrite: 

309 return self._pipeline.plan_page_run(folder, overwrite=True) 

310 return self._pipeline.plan_page_run(folder) 

311 

312 def start_run(self, note: str = "", overwrite: bool = False) -> dict: 

313 """Run the pipeline on the open page in the background. 

314 

315 The log's "started" entry is written first; if it cannot be, nothing 

316 runs. The run keeps the folder open now, even if another page is 

317 opened while it runs. 

318 

319 Args: 

320 note: A note for the run log. 

321 overwrite: Re-run every task that has output, replacing it. 

322 

323 Returns: 

324 Whether the run started, with the error if it did not. 

325 """ 

326 

327 def prepare(): 

328 folder = self._run_folder() 

329 with self._text_save_lock: 

330 # Taken once no edit is half-way through; later edits are refused. 

331 plan = self._plan(folder, overwrite) 

332 self._run_state = _RunState(folder, total=len(plan.to_run)) 

333 run_log.begin_entry( 

334 folder, 

335 pipeline=self._pipeline.name, 

336 version=self._pipeline.version, 

337 note=note, 

338 plan=plan, 

339 ) 

340 return self._run_in_background, (self._run_state, plan) 

341 

342 return self._start(prepare) 

343 

344 def _start(self, prepare) -> dict: 

345 """Start a run on a background thread, unless a run or Git is busy. 

346 

347 Args: 

348 prepare: Sets the run's state and writes its "started" entries; 

349 returns the thread's target and arguments. 

350 

351 Returns: 

352 Whether the run started, with the error if it did not. 

353 """ 

354 if not self._run_lock.acquire(blocking=False): 

355 return {"success": False, "error": "A run is already in progress"} 

356 previous = self._run_state 

357 try: 

358 if self._git_lock.locked(): 

359 raise RuntimeError( 

360 "A Git operation is running; try again when it finishes" 

361 ) 

362 target, args = prepare() 

363 except Exception as error: 

364 self._run_state = previous 

365 self._run_lock.release() 

366 return {"success": False, "error": str(error)} 

367 self._run_thread = threading.Thread(target=target, args=args, daemon=True) 

368 self._run_thread.start() 

369 return {"success": True} 

370 

371 def _collection_plans(self, overwrite: bool) -> tuple[dict, list[dict]]: 

372 """Plan every page in the list the way a run of the collection runs it. 

373 

374 Without overwrite the run re-runs nothing, so a task the page's own 

375 plan would re-run is skipped and keeps its output. 

376 

377 Args: 

378 overwrite: Re-run every task that has output, replacing it. 

379 

380 Returns: 

381 The plan of each page that can run, by resolved folder, and the 

382 name of each page that cannot, with the reason. 

383 """ 

384 from collectra.pipelines.run_plan import RunPlan, TaskPlan 

385 

386 if self._pipeline is None: 

387 raise RuntimeError("No pipeline is loaded") 

388 if not self._collectra_folders: 

389 raise RuntimeError("Open a page first") 

390 plans, unplannable = {}, [] 

391 for page in self._collectra_folders: 

392 folder = Path(page["path"]).resolve() 

393 try: 

394 plan = self._plan(folder, overwrite) 

395 except Exception as error: 

396 reason = str(error).partition("\n")[0] 

397 unplannable.append({"name": folder.name, "reason": reason}) 

398 continue 

399 if not overwrite: 

400 tasks = [] 

401 for task in plan.tasks: 

402 if task.action == "rerun": 

403 task = TaskPlan(task.name, "skip", "already has output") 

404 tasks.append(task) 

405 plan = RunPlan(tasks, plan.warnings) 

406 plans[folder] = plan 

407 return plans, unplannable 

408 

409 @staticmethod 

410 def _nothing_to_run(plans: dict) -> str: 

411 """Why a run of the collection would run nothing, or "" if it would.""" 

412 if not plans: 

413 return NO_PAGE_CAN_RUN 

414 if not any(plan.to_run for plan in plans.values()): 

415 return NOTHING_TO_RUN 

416 return "" 

417 

418 def get_collection_preview(self, overwrite: bool = False) -> dict: 

419 """What a run of every page in the list would run and replace. 

420 

421 Planning holds the run lock, as get_run_preview does. 

422 

423 Args: 

424 overwrite: Re-run every task that has output, replacing it. 

425 

426 Returns: 

427 Whether the collection can run; how many pages are listed, have 

428 results, have none and have tasks to run; each task that would 

429 run, with the number of pages it runs on and replaces output on; 

430 the pages that cannot run, with the reason; and a message. 

431 """ 

432 preview = { 

433 "success": True, 

434 "can_run": False, 

435 "pages": len(self._collectra_folders), 

436 "to_replace": 0, 

437 "first_time": 0, 

438 "to_run": 0, 

439 "tasks": [], 

440 "unplannable": [], 

441 "message": "", 

442 } 

443 try: 

444 if not self._run_lock.acquire(blocking=False): 

445 raise RuntimeError("A run is already in progress") 

446 try: 

447 plans, preview["unplannable"] = self._collection_plans(overwrite) 

448 finally: 

449 self._run_lock.release() 

450 except Exception as error: 

451 return {**preview, "message": str(error)} 

452 tasks, to_replace = {}, 0 

453 for plan in plans.values(): 

454 for task in plan.tasks: 

455 entry = tasks.setdefault( 

456 task.name, {"name": task.name, "pages": 0, "replace": 0} 

457 ) 

458 if task.action != "skip": 

459 entry["pages"] += 1 

460 if task.action == "rerun": 

461 entry["replace"] += 1 

462 if any(task.action != "run" for task in plan.tasks): 

463 to_replace += 1 

464 message = self._nothing_to_run(plans) 

465 return { 

466 **preview, 

467 "can_run": not message, 

468 "to_replace": to_replace, 

469 "first_time": len(plans) - to_replace, 

470 "to_run": sum(bool(plan.to_run) for plan in plans.values()), 

471 "tasks": [entry for entry in tasks.values() if entry["pages"]], 

472 "message": message, 

473 } 

474 

475 def start_collection_run(self, note: str = "", overwrite: bool = False) -> dict: 

476 """Run the pipeline on every page in the list in the background. 

477 

478 Pages that cannot be planned are left out. Each page's "started" entry 

479 is written first; if one cannot be, nothing runs. 

480 

481 Args: 

482 note: A note for each page's run log. 

483 overwrite: Re-run every task, replacing its output. 

484 

485 Returns: 

486 Whether the run started, with the error if it did not. 

487 """ 

488 from collectra.pipelines.run_plan import RunReport, TaskOutcome 

489 

490 def prepare(): 

491 with self._text_save_lock: 

492 # Wait for any edit in progress, then refuse later ones 

493 plans, _ = self._collection_plans(overwrite) 

494 if message := self._nothing_to_run(plans): 

495 raise RuntimeError(message) 

496 state = _RunState(frozenset(plans), total=len(plans), unit="pages") 

497 self._run_state = state 

498 started = [] 

499 for folder, plan in plans.items(): 

500 try: 

501 run_log.begin_entry( 

502 folder, 

503 pipeline=self._pipeline.name, 

504 version=self._pipeline.version, 

505 note=note, 

506 plan=plan, 

507 ) 

508 except OSError as error: 

509 # Log the pages already started as not run 

510 for begun in started: 

511 cancelled = [ 

512 TaskOutcome(task.name, "cancelled", "the run did not start") 

513 for task in plans[begun].tasks 

514 ] 

515 with suppress(OSError): 

516 run_log.finish_entry(begun, RunReport(cancelled), 0) 

517 raise RuntimeError( 

518 f"The run log of {folder.name} could not be written: {error}" 

519 ) from error 

520 started.append(folder) 

521 rerun = set() 

522 if overwrite: 

523 # Every plan lists all the pipeline's tasks 

524 rerun = {task.name for task in next(iter(plans.values())).tasks} 

525 

526 def run(): 

527 def page_done(folder: Path) -> None: 

528 state.done += 1 

529 

530 return self._pipeline.run_pages( 

531 plans, rerun, lambda: state.stop, page_done 

532 ) 

533 

534 return self._record_run, (state, plans, run) 

535 

536 return self._start(prepare) 

537 

538 def _run_in_background(self, state: _RunState, plan) -> None: 

539 from collectra.pipelines.run_plan import RunReport 

540 

541 def should_stop() -> bool: 

542 # Called before each planned task starts. 

543 state.done = state.started 

544 state.started += 1 

545 return state.stop 

546 

547 def run() -> dict: 

548 report = self._pipeline.run_page(state.folder, plan, should_stop) 

549 if not isinstance(report, RunReport): 

550 raise TypeError( 

551 f"run_page returned {type(report).__name__}, not a RunReport" 

552 ) 

553 return {state.folder: report} 

554 

555 self._record_run(state, {state.folder: plan}, run) 

556 

557 def _record_run(self, state: _RunState, plans: dict, run) -> None: 

558 """Run, log each page's report, reload the open page and end the run. 

559 

560 A run that breaks is recorded as failed on every page. 

561 

562 Args: 

563 state: The run's state. 

564 plans: The plan of each page in the run. 

565 run: Runs the pages and returns the report of each. 

566 """ 

567 from collectra.pipelines.run_plan import RunReport 

568 

569 began = time.monotonic() 

570 crash = None 

571 try: 

572 try: 

573 reports = run() 

574 except BaseException as error: 

575 crash = error 

576 state.error = str(error) 

577 reports = { 

578 folder: _crashed_report(plan, error) 

579 for folder, plan in plans.items() 

580 } 

581 outcomes = [ 

582 outcome for report in reports.values() for outcome in report.outcomes 

583 ] 

584 state.summary = run_log.summarize(RunReport(outcomes)) 

585 if state.unit == "pages": 

586 state.summary = f"{len(plans)} pages: {state.summary}" 

587 else: 

588 state.done = sum( 

589 outcome.status in ("ran", "re-ran", "failed") 

590 for outcome in outcomes 

591 ) 

592 seconds = time.monotonic() - began 

593 for folder, report in reports.items(): 

594 try: 

595 run_log.finish_entry(folder, report, seconds) 

596 except Exception as error: 

597 page = f" of {folder.name}" if state.unit == "pages" else "" 

598 state.error = ( 

599 f"The results were kept, but the run log{page}: {error}" 

600 ) 

601 self._reload_after_run(state) 

602 except Exception as error: 

603 state.error = f"The run could not be recorded: {error}" 

604 finally: 

605 with self._text_save_lock: 

606 state.running = False 

607 self._run_lock.release() 

608 if crash is not None and not isinstance(crash, Exception): 

609 raise crash 

610 

611 def _reload_after_run(self, state: _RunState) -> None: 

612 """Reload the open page if it is the run's, so no edit saves the old one.""" 

613 with self._text_save_lock: 

614 folder = self._yaml_path and Path(self._yaml_path).parent.resolve() 

615 if folder in state.folders: 

616 result = self._load_yaml(self._yaml_path) 

617 if not result["success"]: 

618 self._stale_folder = folder 

619 state.error = ( 

620 "The page could not be reloaded after the run: " 

621 f"{result['error']}" 

622 ) 

623 

624 def get_run_status(self) -> dict: 

625 """Progress of the latest run, for the frontend to poll.""" 

626 state = self._run_state 

627 if state is None: 

628 return { 

629 "running": False, 

630 "finished": False, 

631 "folder": "", 

632 "current": None, 

633 "done": 0, 

634 "total": 0, 

635 "summary": None, 

636 "error": None, 

637 } 

638 status = { 

639 "running": state.running, 

640 "finished": not state.running, 

641 "folder": str(state.folder), 

642 "current": None, 

643 "done": state.done, 

644 "total": state.total, 

645 "summary": state.summary, 

646 "error": state.error, 

647 } 

648 if state.unit == "pages": 

649 status.update( 

650 folder="", folders=sorted(map(str, state.folders)), unit="pages" 

651 ) 

652 return status 

653 

654 def stop_run(self) -> dict: 

655 """Ask the run to start no further task.""" 

656 state = self._run_state 

657 if state is None or not state.running: 

658 return {"success": False} 

659 state.stop = True 

660 return {"success": True} 

661 

662 def get_arrangement(self) -> dict: 

663 """The saved panel/tab arrangement for this pipeline, or None.""" 

664 if self._arrangement is None: 

665 return {"success": True, "arrangement": None} 

666 return {"success": True, "arrangement": self._arrangement.read()} 

667 

668 def save_arrangement(self, arrangement: dict) -> dict: 

669 """Remember the panel/tab arrangement (per user, per pipeline).""" 

670 from .arrangement import sanitize_arrangement 

671 

672 clean = sanitize_arrangement(arrangement) 

673 if clean is None: 

674 return {"success": False, "error": "Not a valid arrangement"} 

675 if self._arrangement is not None: 

676 self._arrangement.write(clean) 

677 return {"success": True} 

678 

679 def _available_layouts(self): 

680 metadata = getattr(self._pipeline, "pipeline_metadata", {}) 

681 entries = [] 

682 layouts = metadata.get("layouts", []) 

683 for index, filename in enumerate(layouts if isinstance(layouts, list) else []): 

684 if isinstance(filename, str) and filename.strip(): 

685 entries.append( 

686 ( 

687 f"pipeline:{index}", 

688 "pipeline", 

689 Path(filename).stem, 

690 Path(self._pipeline.path) / filename, 

691 ) 

692 ) 

693 if self._arrangement: 

694 for path in self._arrangement.custom_layouts(): 

695 entries.append((f"custom:{path.name}", "custom", path.stem, path)) 

696 return entries 

697 

698 def restart_gui(self) -> dict: 

699 """Close the GUI so start() can replace the process with fresh code.""" 

700 if self._window is None: 

701 return {"success": False, "error": "No GUI window is open."} 

702 if self._run_lock.locked(): 

703 # Replacing the process would end the run without putting back the 

704 # output its re-run tasks had moved aside. 

705 return { 

706 "success": False, 

707 "error": "Stop the run, or wait for it to finish, before restarting.", 

708 } 

709 if not self._update_lock.acquire(blocking=False): 

710 return { 

711 "success": False, 

712 "error": "Wait for the update to finish before restarting.", 

713 } 

714 try: 

715 if self._collectra_folders: 

716 self._save_folder_session() 

717 elif self._yaml_path: 

718 self._save_folder_session([Path(self._yaml_path).parent]) 

719 self._restart_requested = True 

720 self._window.destroy() 

721 return {"success": True} 

722 except Exception as error: 

723 self._restart_requested = False 

724 return {"success": False, "error": str(error)} 

725 finally: 

726 self._update_lock.release() 

727 

728 def get_layouts(self) -> dict: 

729 """List workflow and named user layouts without exposing arbitrary file access.""" 

730 metadata = getattr(self._pipeline, "pipeline_metadata", {}) 

731 return { 

732 "success": True, 

733 "pipeline_name": metadata.get("name") 

734 or getattr(self._pipeline, "name", "Pipeline"), 

735 "layouts": [ 

736 {"id": key, "source": source, "name": name} 

737 for key, source, name, _ in self._available_layouts() 

738 ], 

739 } 

740 

741 # Settings: the environment variables stored for this pipeline. Each call 

742 # returns the whole list, so the dialog only has to draw it again. 

743 

744 def _env_listing(self, change=None) -> dict: 

745 from ..pipelines.env import EnvError 

746 

747 env = getattr(self._pipeline, "env", None) 

748 if env is None: 

749 return { 

750 "success": False, 

751 "error": "This pipeline has no settings.", 

752 "variables": [], 

753 } 

754 error = None 

755 try: 

756 if change is not None: 

757 change(env) 

758 except EnvError as problem: 

759 error = str(problem) 

760 try: 

761 entries = env.entries() 

762 except EnvError as problem: 

763 error, entries = error or str(problem), [] 

764 listing = { 

765 "success": error is None, 

766 "pipeline": env.name, 

767 "path": str(env.path), 

768 "keyring_available": env.keyring_available(), 

769 "variables": [ 

770 { 

771 "name": entry.name, 

772 "value": entry.display(), 

773 "private": entry.private, 

774 "overridden": entry.overridden, 

775 "override": entry.override, 

776 "replaces_shell": entry.replaces_shell, 

777 "missing": entry.value is None, 

778 } 

779 for entry in entries 

780 ], 

781 } 

782 if error is not None: 

783 listing["error"] = error 

784 return listing 

785 

786 def get_env_variables(self) -> dict: 

787 """The stored variables, with private values masked.""" 

788 return self._env_listing() 

789 

790 def set_env_variable( 

791 self, name: str, value: str, private: bool = False, override: bool = False 

792 ) -> dict: 

793 """Store a variable; it applies to runs started from this window too.""" 

794 return self._env_listing( 

795 lambda env: env.store(name, value, private=private, override=override) 

796 ) 

797 

798 def set_env_override(self, name: str, override: bool) -> dict: 

799 """Choose whether a stored variable replaces a value set in the shell.""" 

800 return self._env_listing(lambda env: env.set_override(name, override)) 

801 

802 def delete_env_variable(self, name: str) -> dict: 

803 return self._env_listing(lambda env: env.remove(name)) 

804 

805 def clear_env_variables(self) -> dict: 

806 return self._env_listing(lambda env: env.remove_all()) 

807 

808 def check_updates(self) -> dict: 

809 from .updates import collectra_repository, inspect_repository 

810 

811 if not self._update_lock.acquire(blocking=False): 

812 return { 

813 "success": False, 

814 "error": "An update operation is already running.", 

815 } 

816 try: 

817 targets = [ 

818 ("pipeline", getattr(self._pipeline, "path", None), "Pipeline"), 

819 ("collectra", collectra_repository(), "Collectra"), 

820 ] 

821 return { 

822 "success": True, 

823 "restart_required": self._restart_required, 

824 "repositories": [ 

825 {"id": key, **inspect_repository(root, label)} 

826 for key, root, label in targets 

827 ], 

828 } 

829 finally: 

830 self._update_lock.release() 

831 

832 def install_update(self, target: str) -> dict: 

833 from .updates import collectra_repository, update_repository 

834 

835 if target not in {"pipeline", "collectra"}: 

836 return {"success": False, "error": "Unknown update target."} 

837 if self._run_lock.locked(): 

838 # The run is using the code an update would replace. 

839 return { 

840 "success": False, 

841 "error": "Stop the run, or wait for it to finish, before updating.", 

842 } 

843 if not self._update_lock.acquire(blocking=False): 

844 return { 

845 "success": False, 

846 "error": "An update operation is already running.", 

847 } 

848 try: 

849 root, label = ( 

850 (getattr(self._pipeline, "path", None), "Pipeline") 

851 if target == "pipeline" 

852 else (collectra_repository(), "Collectra") 

853 ) 

854 repository = {"id": target, **update_repository(root, label)} 

855 if repository["status"] == "updated": 

856 self._restart_required = True 

857 return {"success": True, "repository": repository} 

858 finally: 

859 self._update_lock.release() 

860 

861 def load_layout(self, layout_id: str) -> dict: 

862 from .arrangement import ArrangementStore 

863 

864 for key, _, _, path in self._available_layouts(): 

865 if key == layout_id: 

866 arrangement = ArrangementStore._read_file(path) 

867 if arrangement is not None: 

868 return {"success": True, "arrangement": arrangement} 

869 return {"success": False, "error": "This layout is missing or invalid."} 

870 return {"success": False, "error": "Layout not found."} 

871 

872 def reveal_layout(self, layout_id: str) -> dict: 

873 """Reveal a workflow or custom layout in the system file manager.""" 

874 for key, _, _, path in self._available_layouts(): 

875 if key == layout_id: 

876 return self.reveal_in_folder(str(path.resolve())) 

877 return {"success": False, "error": "Layout not found."} 

878 

879 def save_named_layout(self, name: str, arrangement: dict) -> dict: 

880 from .arrangement import sanitize_arrangement 

881 

882 clean = sanitize_arrangement(arrangement) 

883 if clean is None or self._arrangement is None: 

884 return {"success": False, "error": "No valid layout to save."} 

885 try: 

886 self._arrangement.save_named(name, clean) 

887 except (ValueError, OSError) as error: 

888 return {"success": False, "error": str(error)} 

889 return {"success": True} 

890 

891 def activate_layout(self, layout_id: str) -> dict: 

892 """Persist a chosen layout without touching the loaded results.""" 

893 result = self.load_layout(layout_id) 

894 if not result["success"] or self._arrangement is None: 

895 return ( 

896 result 

897 if not result["success"] 

898 else {"success": False, "error": "No pipeline open."} 

899 ) 

900 try: 

901 self._arrangement._write_file( 

902 self._arrangement.path, result["arrangement"], raise_errors=True 

903 ) 

904 except OSError as error: 

905 return {"success": False, "error": str(error)} 

906 return {"success": True} 

907 

908 def get_initial_items(self) -> dict: 

909 """Return startup items once the JavaScript bridge is ready.""" 

910 return self._initial_items or {"success": True, "provided": False} 

911 

912 def _load_input_paths(self, inputs) -> dict: 

913 """Open the startup inputs, importing those that are not results yet. 

914 

915 An input in a folder holding results.yaml opens that folder without 

916 writing anything. 

917 

918 Args: 

919 inputs: The files and folders given on the command line. 

920 

921 Returns: 

922 dict with the folder list, and the import notice when there is one. 

923 """ 

924 paths = [Path(value).expanduser().resolve() for value in inputs] 

925 pending = [] 

926 for path in paths: 

927 if not path.exists(): 

928 raise FileNotFoundError(f"GUI input does not exist: {path}") 

929 directory = path.parent if path.is_file() else path 

930 if not (directory / "results.yaml").is_file(): 

931 pending.append(path) 

932 report = self._import_report(pending) 

933 imported = self._notice(report) 

934 pages = {} # Pages created or opened above, by folder 

935 for page in report.pages if report else []: 

936 pages.setdefault(page.parent, []).append(page) 

937 seen = set() 

938 for path in paths: 

939 directory = path.parent if path.is_file() else path 

940 if (directory / "results.yaml").is_file(): 

941 candidates = [directory] 

942 elif path.is_dir(): 

943 candidates = [ 

944 child 

945 for child in sorted(path.iterdir()) 

946 if child.is_dir() and child.suffix == f".{self._extension}" 

947 ] 

948 else: 

949 # Imported above; a folder's pages go to its first file 

950 candidates = pages.pop(path.parent, []) 

951 for candidate in candidates: 

952 scan = self._scan_collectra_folder(candidate) 

953 if scan is None: 

954 continue 

955 candidate = candidate.resolve() 

956 if candidate in seen: 

957 continue 

958 seen.add(candidate) 

959 self._collectra_folders.append( 

960 { 

961 "name": candidate.name, 

962 "path": str(candidate), 

963 **scan, 

964 } 

965 ) 

966 if not self._collectra_folders: 

967 raise ValueError( 

968 f"No GUI results found in: {', '.join(str(path) for path in paths)}" 

969 ) 

970 self._parent_folder = str(Path(self._collectra_folders[0]["path"]).parent) 

971 self._save_folder_session() 

972 result = {**self._folder_list_result(), "provided": True, "mode": "parent"} 

973 if imported: 

974 print(imported["summary"]) 

975 result["import"] = imported 

976 return result 

977 

978 def _import_paths(self, paths: Sequence[Path]) -> dict: 

979 """Import the raw inputs among the paths a user opens. 

980 

981 Args: 

982 paths: The files and folders being opened. 

983 

984 Returns: 

985 dict with the summary notice and the failed names, or an empty dict 

986 when only existing results were opened. 

987 """ 

988 return self._notice(self._import_report(paths)) 

989 

990 def _import_report(self, paths: Sequence[Path]): 

991 """Import the raw inputs among the paths, if the pipeline imports. 

992 

993 Args: 

994 paths: The files and folders being opened. 

995 

996 Returns: 

997 The pipeline's ImportReport, or None when nothing was imported. 

998 """ 

999 import_inputs = getattr(self._pipeline, "import_inputs", None) 

1000 return import_inputs(paths) if import_inputs and paths else None 

1001 

1002 def _notice(self, report) -> dict: 

1003 """What the page shows of an import: see _import_paths.""" 

1004 summary = report.summary(self._pipeline.name) if report else "" 

1005 return {"summary": summary, "failed": report.failed} if summary else {} 

1006 

1007 @property 

1008 def _extension(self) -> str: 

1009 """Use the extension owned by the live pipeline.""" 

1010 return self._pipeline.ext 

1011 

1012 def set_window(self, window): 

1013 """Store the window reference for use in dialogs, and watch it close.""" 

1014 self._window = window 

1015 window.events.closing += self._on_closing 

1016 

1017 def _on_closing(self) -> None: 

1018 """Stop a run when the window closes, and give it a while to end. 

1019 

1020 The run stops between tasks; waiting lets a re-run task finish and put 

1021 back the output it moved aside. The wait is bounded so that a task 

1022 that never ends cannot keep the window from closing. 

1023 """ 

1024 thread = self._run_thread 

1025 if thread is None or not thread.is_alive(): 

1026 return 

1027 if self._run_state is not None: 

1028 self._run_state.stop = True 

1029 thread.join(RUN_STOP_TIMEOUT) 

1030 

1031 def reveal_in_folder(self, path: str) -> dict: 

1032 """Reveal a file in the OS file manager, selected within its folder. 

1033 

1034 Args: 

1035 path: Absolute path to reveal (e.g. a specimen's results.yaml 

1036 file, selected within its .grapto folder). 

1037 

1038 Returns: 

1039 dict with 'success' or 'error' 

1040 """ 

1041 import subprocess 

1042 

1043 target = Path(path) 

1044 if not target.exists(): 

1045 return {"success": False, "error": f"Path not found: {path}"} 

1046 

1047 system = platform.system() 

1048 if system == "Darwin": 

1049 # -R reveals + selects the item in its *parent's* Finder window — 

1050 # actual "Reveal in Finder" behavior — not the folder's own contents. 

1051 command = ["open", "-R", str(target)] 

1052 elif system == "Windows": 

1053 # Explorer's reveal+select is one combined `/select,<path>` argument. 

1054 command = ["explorer", f"/select,{target}"] 

1055 else: 

1056 # No universal reveal+select convention across Linux desktop 

1057 # environments — opening the parent folder is the closest 

1058 # approximation available via a single xdg-open call. 

1059 command = ["xdg-open", str(target.parent)] 

1060 

1061 try: 

1062 subprocess.run(command) 

1063 return {"success": True} 

1064 except Exception as e: 

1065 return {"success": False, "error": str(e)} 

1066 

1067 def copy_to_clipboard(self, text: str) -> dict: 

1068 """Copy text to the system clipboard (used by the 'Copy Path' menu item). 

1069 

1070 The webview's own clipboard API is unavailable outside secure contexts, 

1071 so use the operating system's clipboard tool instead. 

1072 

1073 Returns: 

1074 dict with 'success' or 'error' 

1075 """ 

1076 import subprocess 

1077 

1078 system = platform.system() 

1079 if system == "Darwin": 

1080 commands = [["pbcopy"]] 

1081 elif system == "Windows": 

1082 commands = [["clip"]] 

1083 else: 

1084 commands = [["xclip", "-selection", "clipboard"], ["wl-copy"]] 

1085 

1086 for command in commands: 

1087 try: 

1088 subprocess.run(command, input=text, text=True, check=True) 

1089 return {"success": True} 

1090 except FileNotFoundError: 

1091 continue 

1092 except Exception as e: 

1093 return {"success": False, "error": str(e)} 

1094 return { 

1095 "success": False, 

1096 "error": f"No clipboard tool found ({' or '.join(c[0] for c in commands)})", 

1097 } 

1098 

1099 def _scan_collectra_folder(self, folder_path: Path) -> dict | None: 

1100 """ 

1101 Scan a folder for YAML and image files. 

1102 

1103 Args: 

1104 folder_path: Path to the folder to scan 

1105 

1106 Returns: 

1107 dict with yaml_path and optional image_path, or None without results 

1108 """ 

1109 results_path = folder_path / "results.yaml" 

1110 image_path = None 

1111 image_extensions = [f".{ext.lower()}" for ext in ImageFormat.__members__.keys()] 

1112 

1113 for filename in sorted(folder_path.iterdir(), reverse=True): 

1114 if not filename.is_file(): 

1115 continue 

1116 

1117 if filename.suffix.lower() in image_extensions and image_path is None: 

1118 image_path = filename 

1119 

1120 if image_path: 

1121 break 

1122 

1123 if not results_path.is_file(): 

1124 return None 

1125 

1126 return { 

1127 "yaml_path": str(results_path), 

1128 "image_path": str(image_path) if image_path else "", 

1129 } 

1130 

1131 def select_folder(self) -> dict: 

1132 """ 

1133 Open native folder dialog and scan for YAML/image files. 

1134 

1135 Returns: 

1136 dict with folder_path, yaml_path, image_path (all absolute paths) 

1137 """ 

1138 

1139 if self._window is None: 

1140 return {"success": False, "error": "Window not initialized"} 

1141 

1142 try: 

1143 result = self._window.create_file_dialog( 

1144 dialog_type=webview.FileDialog.FOLDER 

1145 ) 

1146 

1147 if not result or len(result) == 0: 

1148 return {"success": False, "error": "No folder selected"} 

1149 

1150 folder_path = Path(result[0]) 

1151 imported = ( 

1152 self._import_paths([folder_path]) 

1153 if folder_path.suffix == f".{self._extension}" 

1154 else {} 

1155 ) 

1156 

1157 scan_result = self._scan_collectra_folder(folder_path) 

1158 if scan_result is None: 

1159 return { 

1160 "success": False, 

1161 "error": "No results.yaml found in folder", 

1162 } 

1163 

1164 folder_result = { 

1165 "success": True, 

1166 "folder_path": str(folder_path), 

1167 **scan_result, 

1168 } 

1169 if imported: 

1170 folder_result["import"] = imported 

1171 return folder_result 

1172 

1173 except Exception as e: 

1174 return {"success": False, "error": str(e)} 

1175 

1176 def select_parent_folder(self) -> dict: 

1177 """ 

1178 Open native folder dialog and scan for subdirectories with the specified extension. 

1179 

1180 Returns: 

1181 dict with parent_path and list of folder names/indices 

1182 """ 

1183 if self._window is None: 

1184 return {"success": False, "error": "Window not initialized"} 

1185 

1186 try: 

1187 result = self._window.create_file_dialog( 

1188 dialog_type=webview.FileDialog.FOLDER 

1189 ) 

1190 

1191 if not result or len(result) == 0: 

1192 return {"success": False, "error": "No folder selected"} 

1193 

1194 parent_path = Path(result[0]) 

1195 return self._scan_parent_folder(parent_path) 

1196 

1197 except Exception as e: 

1198 return {"success": False, "error": str(e)} 

1199 

1200 def select_collectra_path(self) -> dict: 

1201 """ 

1202 Open native folder dialog and load either a single collectra folder 

1203 (if it matches the extension) or a parent folder of collectra subfolders. 

1204 

1205 Returns: 

1206 dict with mode "single" or "parent" and the relevant data. 

1207 """ 

1208 if self._window is None: 

1209 return {"success": False, "error": "Window not initialized"} 

1210 

1211 try: 

1212 result = self._window.create_file_dialog( 

1213 dialog_type=webview.FileDialog.FOLDER 

1214 ) 

1215 

1216 if not result or len(result) == 0: 

1217 return {"success": False, "error": "No folder selected"} 

1218 

1219 selected_path = Path(result[0]) 

1220 

1221 # A previously-viewed page's yaml path is otherwise never cleared, 

1222 # and _collectra_dirs() searches near it — so without this, asset 

1223 # lookups (get_logo, get_theme_css) can silently keep matching a 

1224 # file from whatever project was open before this new selection. 

1225 self._yaml_path = None 

1226 self._collectra_file = None 

1227 self._graph = None 

1228 

1229 if selected_path.suffix == f".{self._extension}": 

1230 imported = self._import_paths([selected_path]) 

1231 scan_result = self._scan_collectra_folder(selected_path) 

1232 if scan_result is None: 

1233 return { 

1234 "success": False, 

1235 "error": "No YAML or image file found in folder", 

1236 } 

1237 self._collectra_folders = [] 

1238 self._parent_folder = str(selected_path.parent) 

1239 self._save_folder_session([selected_path]) 

1240 single_result = { 

1241 "success": True, 

1242 "mode": "single", 

1243 "folder_path": str(selected_path), 

1244 "yaml_path": scan_result["yaml_path"], 

1245 "image_path": scan_result["image_path"], 

1246 } 

1247 if imported: 

1248 single_result["import"] = imported 

1249 return single_result 

1250 

1251 parent_result = self._scan_parent_folder(selected_path) 

1252 if parent_result.get("success"): 

1253 parent_result["mode"] = "parent" 

1254 return parent_result 

1255 

1256 except Exception as e: 

1257 return {"success": False, "error": str(e)} 

1258 

1259 def _scan_parent_folder(self, parent_path: Path) -> dict: 

1260 # Never import into a folder with results 

1261 imported = ( 

1262 {} 

1263 if (parent_path / "results.yaml").is_file() 

1264 else self._import_paths([parent_path]) 

1265 ) 

1266 self._parent_folder = str(parent_path) 

1267 self._collectra_folders = [] 

1268 

1269 for entry in sorted(parent_path.iterdir()): 

1270 if not entry.is_dir(): 

1271 continue 

1272 if not entry.suffix == f".{self._extension}": 

1273 continue 

1274 

1275 scan_result = self._scan_collectra_folder(entry) 

1276 if scan_result is not None: 

1277 self._collectra_folders.append( 

1278 { 

1279 "name": entry.name, 

1280 "path": str(entry), 

1281 "yaml_path": scan_result["yaml_path"], 

1282 "image_path": scan_result["image_path"], 

1283 } 

1284 ) 

1285 

1286 self._save_folder_session() 

1287 result = self._folder_list_result() 

1288 if imported: 

1289 result["import"] = imported 

1290 return result 

1291 

1292 def _folder_list_result(self) -> dict: 

1293 folders = [ 

1294 { 

1295 "name": f["name"], 

1296 "path": f["path"], 

1297 "yaml_path": f["yaml_path"], 

1298 "index": i, 

1299 } 

1300 for i, f in enumerate(self._collectra_folders) 

1301 ] 

1302 

1303 # Compute aggregate label statistics across all folders 

1304 self._global_label_counts = {} 

1305 self._global_link_names = set() 

1306 for folder in self._collectra_folders: 

1307 try: 

1308 collectra_file = CollectraFile.from_data(Path(folder["path"])) 

1309 temp_graph = CollectraGraph.from_collectra_file(collectra_file) 

1310 label_counts = temp_graph.count_nodes_by_label( 

1311 type_filter="collectra.ImageCrop" 

1312 ) 

1313 # Accumulate unique labels 

1314 self._global_labels.update(temp_graph.get_unique_labels()) 

1315 self._global_link_names.update(temp_graph.link_names()) 

1316 # Accumulate counts 

1317 for label, count in label_counts.items(): 

1318 self._global_label_counts[label] = ( 

1319 self._global_label_counts.get(label, 0) + count 

1320 ) 

1321 except Exception: 

1322 # Skip folders that can't be loaded 

1323 pass 

1324 

1325 return { 

1326 "success": True, 

1327 "parent_path": self._parent_folder, 

1328 "folders": folders, 

1329 "global_label_counts": self._global_label_counts, 

1330 "global_total": sum(self._global_label_counts.values()), 

1331 "ext": self._extension, 

1332 } 

1333 

1334 def load_collectra_folder(self, index: int) -> dict: 

1335 """ 

1336 Load a folder by its index from the previously scanned parent folder. 

1337 

1338 Args: 

1339 index: Index of the folder in the _collectra_folders list 

1340 

1341 Returns: 

1342 dict with folder_name, yaml_path, image_path 

1343 """ 

1344 if not self._collectra_folders: 

1345 return { 

1346 "success": False, 

1347 "error": "No folders loaded. Call select_parent_folder first.", 

1348 } 

1349 

1350 if index < 0 or index >= len(self._collectra_folders): 

1351 return {"success": False, "error": f"Invalid folder index: {index}"} 

1352 

1353 folder = self._collectra_folders[index] 

1354 return { 

1355 "success": True, 

1356 "folder_name": folder["name"], 

1357 "folder_path": folder["path"], 

1358 "yaml_path": folder["yaml_path"], 

1359 "image_path": folder["image_path"], 

1360 } 

1361 

1362 def get_active_node_ids(self, page_index: int) -> dict: 

1363 """Return the labels, real types, and real result ids that belong to a page. 

1364 

1365 `results.yaml` indexes each node by an internal id (a label plus a 

1366 generated suffix for anything not an original source node), but the 

1367 The pipeline DAG uses the plain label as its node id. 

1368 Correlating against the DAG must go through `label`, not `id`. 

1369 

1370 The frontend greys out and disables every DAG node whose id is NOT in 

1371 active_ids, can use node_types[label] to show the node's real type, 

1372 and node_ids[label] to show the real results.yaml id(s) — a list, 

1373 not a single value, since a detector-type node (e.g. 

1374 collectra.ObjectDetectorYOLO) declares one output label in the 

1375 pipeline but can produce any number of real instances per page 

1376 (one per detected object), all sharing that same label. 

1377 node_parents supplies each instance's actual direct parent ids so 

1378 lineage lists do not include unrelated instances of the same label. 

1379 """ 

1380 if not self._collectra_folders: 

1381 return {"success": False, "error": "No folders loaded."} 

1382 if page_index < 0 or page_index >= len(self._collectra_folders): 

1383 return {"success": False, "error": f"Invalid page index: {page_index}"} 

1384 

1385 folder = self._collectra_folders[page_index] 

1386 try: 

1387 if ( 

1388 self._graph is not None 

1389 and self._yaml_path is not None 

1390 and Path(self._yaml_path).resolve() 

1391 == Path(folder["yaml_path"]).resolve() 

1392 ): 

1393 graph = self._graph 

1394 else: 

1395 collectra_file = CollectraFile.from_data(Path(folder["path"])) 

1396 graph = CollectraGraph.from_collectra_file(collectra_file) 

1397 node_types: dict[str, str] = {} 

1398 node_ids: dict[str, list[str]] = {} 

1399 crop_labels = set() 

1400 for node_id in graph.nodes: 

1401 node = graph.get_node(node_id) 

1402 if node and node.label: 

1403 node_types[node.label] = node.type 

1404 node_ids.setdefault(node.label, []).append(node_id) 

1405 if isinstance(node, CollectraAnnotationNode): 

1406 crop_labels.add(node.label) 

1407 return { 

1408 "success": True, 

1409 "active_ids": list(node_types.keys()), 

1410 "node_types": node_types, 

1411 "node_ids": node_ids, 

1412 "node_parents": { 

1413 node_id: graph.parents(node_id) 

1414 for node_id in graph.nodes 

1415 if graph.get_node(node_id) 

1416 }, 

1417 "crop_labels": sorted(crop_labels), 

1418 } 

1419 except Exception as e: 

1420 return {"success": False, "error": str(e)} 

1421 

1422 def get_image_base64(self, image_path: str) -> dict: 

1423 """ 

1424 Read an image file and return its base64 data. 

1425 

1426 Args: 

1427 image_path: Absolute path to the image file 

1428 

1429 Returns: 

1430 dict with base64-encoded data URI 

1431 """ 

1432 try: 

1433 extension = Path(image_path).suffix.lower() 

1434 mime_type = ImageFormat[extension[1:].upper()].value 

1435 

1436 with open(image_path, "rb") as f: 

1437 image_data = f.read() 

1438 

1439 base64_data = base64.b64encode(image_data).decode("utf-8") 

1440 

1441 return {"success": True, "data": f"data:{mime_type};base64,{base64_data}"} 

1442 

1443 except Exception as e: 

1444 return {"success": False, "error": str(e)} 

1445 

1446 def _display_context(self, rgb_view: int = 0): 

1447 from collectra.display import DisplayContext 

1448 

1449 if self._graph is None or self._yaml_path is None: 

1450 raise ValueError("No page loaded") 

1451 records = { 

1452 node_id: { 

1453 **self._graph.get_node(node_id).model_dump(), 

1454 "label": self._graph.get_node(node_id).label, 

1455 } 

1456 for node_id in self._graph.nodes 

1457 if self._graph.get_node(node_id) 

1458 } 

1459 return DisplayContext( 

1460 records, 

1461 Path(self._yaml_path).parent, 

1462 rgb_view=rgb_view, 

1463 max_pixels=self._max_pixels, 

1464 ) 

1465 

1466 def get_artefact_display(self, node_id: str = "", rgb_view: int = 0) -> dict: 

1467 """Ask the actual artefact class how it should be presented.""" 

1468 try: 

1469 context = self._display_context(rgb_view=rgb_view) 

1470 if not node_id: 

1471 from collectra.types.images import Image, ImageCrop 

1472 from collectra.utils import load_class_from_string 

1473 

1474 for candidate in context.records: 

1475 try: 

1476 cls = load_class_from_string(context.records[candidate]["type"]) 

1477 except (ImportError, AttributeError): 

1478 continue 

1479 if issubclass(cls, Image) and not issubclass(cls, ImageCrop): 

1480 node_id = candidate 

1481 break 

1482 node_id = self._graph.resolve_id(node_id) 

1483 item = context.artefact(node_id) 

1484 view = item.display(context) 

1485 if "links" in view: 

1486 self._add_classifier_slots( 

1487 view["links"], context.records[view["target_id"]]["label"] 

1488 ) 

1489 return { 

1490 "success": True, 

1491 "view": view, 

1492 "id": node_id, 

1493 "type": context.records[node_id]["type"], 

1494 } 

1495 except Exception as e: 

1496 return {"success": False, "error": str(e)} 

1497 

1498 def _classifier_slots(self, label: str) -> list[dict]: 

1499 """The tasks that take images of ``label`` and output Links, with their classes. 

1500 

1501 A task whose outputs are Links sets a Link by choosing one of them. 

1502 """ 

1503 try: 

1504 nodes = self._pipeline.gui_graph()["nodes"] 

1505 except Exception: 

1506 # A pipeline that cannot be read only costs the extra choices. 

1507 return [] 

1508 link_nodes = { 

1509 node["id"] for node in nodes if "collectra.Link" in node.get("types", []) 

1510 } 

1511 return [ 

1512 {"task": node["id"], "options": node["outputs"]} 

1513 for node in nodes 

1514 if node["nodeType"] == "Task" 

1515 and label in node["inputs"] 

1516 and node["outputs"] 

1517 and set(node["outputs"]) <= link_nodes 

1518 ] 

1519 

1520 def _add_classifier_slots(self, links: list[dict], label: str) -> None: 

1521 """Mark the Link a classifier sets, or add an empty slot where it set none. 

1522 

1523 The link is the one named after one of the task's classes; a link with 

1524 any other name is left as it is. 

1525 """ 

1526 for slot in self._classifier_slots(label): 

1527 match = next( 

1528 ( 

1529 link 

1530 for link in links 

1531 if link["name"] in slot["options"] and "task" not in link 

1532 ), 

1533 None, 

1534 ) 

1535 if match is None: 

1536 links.append({"id": None, "name": None, **slot}) 

1537 else: 

1538 match.update(slot) 

1539 

1540 def rotate_image_clockwise(self, node_id: str) -> dict: 

1541 """Persist a clockwise quarter-turn for an image and descendant images.""" 

1542 with self._editing() as refused: 

1543 if refused: 

1544 return refused 

1545 from collectra.types.images import Image, Orientation 

1546 from collectra.types.links import Link 

1547 from collectra.utils import load_class_from_string 

1548 

1549 changes = [] 

1550 try: 

1551 context = self._display_context() 

1552 item = context.artefact(self._graph.resolve_id(node_id)) 

1553 if isinstance(item, Link): 

1554 item = item.resolve() 

1555 if not isinstance(item, Image): 

1556 raise ValueError("Only image artefacts can be rotated") 

1557 pending, seen = [item.id], set() 

1558 while pending: 

1559 current = pending.pop() 

1560 if current in seen: 

1561 continue 

1562 seen.add(current) 

1563 pending.extend(self._graph.children(current)) 

1564 node = self._graph.get_node(current) 

1565 if node and issubclass(load_class_from_string(node.type), Image): 

1566 orientation = Orientation.from_string(node.orientation) 

1567 next_orientation = Orientation( 

1568 (orientation.value + 1) % 4 

1569 ).to_string() 

1570 changes.append((node, node.orientation, next_orientation)) 

1571 for node, previous, updated in changes: 

1572 node.orientation = updated 

1573 self._save_collectra_file() 

1574 return { 

1575 "success": True, 

1576 "updated_ids": [node.id for node, _, _ in changes], 

1577 } 

1578 except Exception as error: 

1579 for node, previous, updated in changes: 

1580 node.orientation = previous 

1581 return {"success": False, "error": str(error)} 

1582 

1583 def update_segmentation_mask( 

1584 self, node_id: str, strokes: list, results_path: str, orientation: str 

1585 ) -> dict: 

1586 """Save strokes to their original results page, even after navigation.""" 

1587 from collectra.display import DisplayContext 

1588 from collectra.displays.image_segmentation import segmentation 

1589 from collectra.gui.segmentation import paint_mask 

1590 from collectra.types.links import Link 

1591 

1592 try: 

1593 with self._text_save_lock: 

1594 target = Path(results_path).resolve() 

1595 if guard := self._run_guard(target.parent): 

1596 return guard 

1597 if target.name != "results.yaml" or not target.is_file(): 

1598 raise ValueError("Mask edits must target a results.yaml file") 

1599 collectra_file = CollectraFile.from_data(target.parent) 

1600 graph = CollectraGraph.from_collectra_file(collectra_file) 

1601 records = { 

1602 key: { 

1603 **graph.get_node(key).model_dump(), 

1604 "label": graph.get_node(key).label, 

1605 } 

1606 for key in graph.nodes 

1607 if graph.get_node(key) 

1608 } 

1609 context = DisplayContext( 

1610 records, target.parent, max_pixels=self._max_pixels 

1611 ) 

1612 item = context.artefact(graph.resolve_id(node_id)) 

1613 if isinstance(item, Link): 

1614 item = item.resolve() 

1615 changed = paint_mask(item, strokes, orientation) 

1616 return { 

1617 "success": True, 

1618 "changed": changed, 

1619 "segmentation": segmentation(context, item), 

1620 } 

1621 except Exception as error: 

1622 return {"success": False, "error": str(error)} 

1623 

1624 def get_display_annotations(self, node_id: str) -> dict: 

1625 try: 

1626 context = self._display_context() 

1627 image = context.artefact(self._graph.resolve_id(node_id)) 

1628 from collectra.types.links import Link 

1629 

1630 if type(image) is Link: 

1631 image = image.resolve() 

1632 return {"success": True, "rows": context.annotations(image)} 

1633 except Exception as e: 

1634 return {"success": False, "error": str(e)} 

1635 

1636 def update_display_text( 

1637 self, node_id: str, content: str, results_path: str | None = None 

1638 ) -> dict: 

1639 """Save changed text to its captured page, even after navigation.""" 

1640 try: 

1641 from collectra.display import DisplayContext 

1642 

1643 with self._text_save_lock: 

1644 target = Path(results_path or self._yaml_path).resolve() 

1645 if guard := self._run_guard(target.parent): 

1646 return guard 

1647 if target.name != "results.yaml": 

1648 raise ValueError("Text edits must target a results.yaml file") 

1649 if self._yaml_path and target == Path(self._yaml_path).resolve(): 

1650 graph, collectra_file = self._graph, self._collectra_file 

1651 else: 

1652 collectra_file = CollectraFile.from_data(target.parent) 

1653 graph = CollectraGraph.from_collectra_file(collectra_file) 

1654 records = { 

1655 key: { 

1656 **graph.get_node(key).model_dump(), 

1657 "label": graph.get_node(key).label, 

1658 } 

1659 for key in graph.nodes 

1660 if graph.get_node(key) 

1661 } 

1662 context = DisplayContext( 

1663 records, target.parent, max_pixels=self._max_pixels 

1664 ) 

1665 item = context.artefact(graph.resolve_id(node_id)) 

1666 view = item.display(context) 

1667 if view.get("kind") != "text" or not view.get("editable"): 

1668 raise ValueError("This artefact does not expose editable text") 

1669 target_id = view["target_id"] 

1670 path = context.text_path(target_id) 

1671 if path: 

1672 if path.read_text(encoding="utf-8") == content: 

1673 return {"success": True, "changed": False} 

1674 path.write_text(content, encoding="utf-8") 

1675 else: 

1676 if graph.get_data(target_id) == content: 

1677 return {"success": True, "changed": False} 

1678 previous = graph.get_data(target_id) 

1679 graph.set_data(target_id, content) 

1680 try: 

1681 collectra_file.data = graph.to_data() 

1682 collectra_file.save() 

1683 except Exception: 

1684 graph.set_data(target_id, previous) 

1685 collectra_file.data = graph.to_data() 

1686 raise 

1687 return {"success": True, "changed": True} 

1688 except Exception as e: 

1689 return {"success": False, "error": str(e)} 

1690 

1691 def load_yaml(self, path: str) -> dict: 

1692 with self._text_save_lock: 

1693 return self._load_yaml(path) 

1694 

1695 def _load_yaml(self, path: str) -> dict: 

1696 """ 

1697 Load a YAML file and build the annotation graph. 

1698 

1699 Args: 

1700 path: Path to the YAML file 

1701 

1702 Returns: 

1703 dict with 'success', 'node_count', 'edge_count', or 'error' 

1704 """ 

1705 try: 

1706 collectra_path = Path(path) 

1707 directory = ( 

1708 collectra_path if collectra_path.is_dir() else collectra_path.parent 

1709 ) 

1710 collectra_file = CollectraFile.from_data(directory) 

1711 graph = CollectraGraph.from_collectra_file(collectra_file) 

1712 self._collectra_file = collectra_file 

1713 self._graph = graph 

1714 self._stale_folder = None 

1715 previous_path = self._yaml_path 

1716 self._yaml_path = str(self._collectra_file.results_path) 

1717 if self._session_cache is not None and previous_path != self._yaml_path: 

1718 self._session_cache.write_active( 

1719 str(self._collectra_file.results_path.parent.resolve()) 

1720 ) 

1721 if not self._collectra_folders: 

1722 self._save_folder_session([self._collectra_file.results_path.parent]) 

1723 

1724 # Accumulate labels from this graph 

1725 self._global_labels.update(self._graph.get_unique_labels()) 

1726 

1727 return {"success": True, "path": self._yaml_path} 

1728 except Exception as e: 

1729 return {"success": False, "error": str(e)} 

1730 

1731 def get_display_value(self, node_id: str) -> dict: 

1732 """ 

1733 Compute display value for an annotation. 

1734 

1735 Args: 

1736 node_id: The annotation ID 

1737 

1738 Returns: 

1739 dict with 'value', 'source_id', 'reason', or 'error' 

1740 """ 

1741 if self._graph is None: 

1742 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

1743 

1744 try: 

1745 result = self._graph.compute_display_value(self._graph.resolve_id(node_id)) 

1746 return { 

1747 "success": True, 

1748 "value": result.value, 

1749 "source_id": result.source_id, 

1750 "crop_region": result.crop_region, 

1751 "reason": result.reason, 

1752 } 

1753 except Exception as e: 

1754 return {"success": False, "error": str(e)} 

1755 

1756 def get_page_texts(self) -> dict: 

1757 """Return markdown and TEI content for the current page folder.""" 

1758 if self._yaml_path is None: 

1759 return {"success": False, "error": "No page loaded."} 

1760 page_dir = Path(self._yaml_path).parent 

1761 result: dict = {"success": True} 

1762 for key, filename in (("markdown", "markdown.md"), ("tei", "tei.xml")): 

1763 p = page_dir / filename 

1764 if p.exists(): 

1765 result[key] = p.read_text(encoding="utf-8") 

1766 result[f"{key}_found"] = True 

1767 else: 

1768 result[key] = None 

1769 result[f"{key}_found"] = False 

1770 return result 

1771 

1772 def update_page_text(self, kind: str, content: str) -> dict: 

1773 """Write markdown or TEI content back to the current page's folder. 

1774 

1775 Args: 

1776 kind: "markdown" or "tei" 

1777 content: the full text to write 

1778 

1779 Returns: 

1780 dict with 'success' or 'error' 

1781 """ 

1782 with self._editing() as refused: 

1783 if refused: 

1784 return refused 

1785 if self._yaml_path is None: 

1786 return {"success": False, "error": "No page loaded."} 

1787 

1788 filenames = {"markdown": "markdown.md", "tei": "tei.xml"} 

1789 filename = filenames.get(kind) 

1790 if filename is None: 

1791 return {"success": False, "error": f"Unknown kind: {kind}"} 

1792 

1793 try: 

1794 page_dir = Path(self._yaml_path).parent 

1795 (page_dir / filename).write_text(content, encoding="utf-8") 

1796 return {"success": True} 

1797 except Exception as e: 

1798 return {"success": False, "error": str(e)} 

1799 

1800 def get_all_nodes(self) -> dict: 

1801 """ 

1802 Get all node IDs in the graph. 

1803 

1804 Returns: 

1805 dict with 'nodes' list or 'error' 

1806 """ 

1807 if self._graph is None: 

1808 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

1809 

1810 return {"success": True, "nodes": self._graph.nodes} 

1811 

1812 def get_node_info(self, node_id: str) -> dict: 

1813 """ 

1814 Get detailed information about a node. 

1815 

1816 Args: 

1817 node_id: The annotation ID 

1818 

1819 Returns: 

1820 dict with node type, data, children, parents, or 'error' 

1821 """ 

1822 if self._graph is None: 

1823 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

1824 

1825 node_id = self._graph.resolve_id(node_id) 

1826 if node_id not in self._graph.nodes: 

1827 return {"success": False, "error": f"Node '{node_id}' not found"} 

1828 

1829 return { 

1830 "success": True, 

1831 "id": node_id, 

1832 "type": self._graph.get_type(node_id), 

1833 "data": self._graph.get_data(node_id), 

1834 "children": self._graph.children(node_id), 

1835 "parents": self._graph.parents(node_id), 

1836 } 

1837 

1838 def get_nodes_by_type(self, type_filter: str) -> dict: 

1839 """ 

1840 Get all nodes containing a type substring. 

1841 

1842 Args: 

1843 type_filter: Substring to match in node types (e.g., "ImageCrop", "Text") 

1844 

1845 Returns: 

1846 dict with 'nodes' list of matching node IDs 

1847 """ 

1848 if self._graph is None: 

1849 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

1850 

1851 matching = [ 

1852 node_id 

1853 for node_id in self._graph.nodes 

1854 if type_filter in self._graph.get_type(node_id) 

1855 ] 

1856 

1857 return {"success": True, "nodes": matching, "count": len(matching)} 

1858 

1859 def get_available_labels(self) -> dict: 

1860 """ 

1861 Get all unique labels accumulated across all loaded files. 

1862 

1863 Returns: 

1864 dict with 'success' and 'labels' list (sorted) 

1865 """ 

1866 try: 

1867 labels = sorted(self._global_labels) 

1868 return {"success": True, "labels": labels} 

1869 except Exception as e: 

1870 return {"success": False, "error": str(e)} 

1871 

1872 def get_label_statistics(self) -> dict: 

1873 """ 

1874 Return counts of nodes per label in current graph. 

1875 

1876 Returns: 

1877 dict with 'success', 'label_counts', and 'total' 

1878 """ 

1879 if self._graph is None: 

1880 return {"success": False, "error": "No graph loaded"} 

1881 

1882 # Count only ImageCrop types (annotations visible in grid) 

1883 label_counts = self._graph.count_nodes_by_label( 

1884 type_filter="collectra.ImageCrop" 

1885 ) 

1886 

1887 return { 

1888 "success": True, 

1889 "label_counts": label_counts, 

1890 "total": sum(label_counts.values()), 

1891 } 

1892 

1893 def get_global_label_statistics(self) -> dict: 

1894 """ 

1895 Return aggregated label counts across all files in parent folder. 

1896 

1897 Returns: 

1898 dict with 'success', 'label_counts', and 'total' 

1899 """ 

1900 return { 

1901 "success": True, 

1902 "label_counts": self._global_label_counts, 

1903 "total": sum(self._global_label_counts.values()), 

1904 } 

1905 

1906 def get_all_nodes_for_grid(self) -> dict: 

1907 """ 

1908 Return all nodes formatted for AG Grid rows. 

1909 

1910 Returns: 

1911 dict with 'rows' list containing node data for grid display 

1912 """ 

1913 if self._graph is None: 

1914 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

1915 

1916 rows = [] 

1917 for node_id in self._graph.nodes: 

1918 node_display_value: NodeDisplayValue = self._graph.compute_display_value( 

1919 node_id 

1920 ) 

1921 rows.append( 

1922 { 

1923 "id": node_id, 

1924 "type": self._graph.get_type(node_id), 

1925 "data": str(self._graph.get_data(node_id)), 

1926 "name": self._graph.get_name(node_id), 

1927 "label": self._graph.get_label(node_id), 

1928 "displayValue": node_display_value.value, 

1929 "crop_region": node_display_value.crop_region, 

1930 "displaySourceId": node_display_value.source_id, 

1931 "reason": node_display_value.reason, 

1932 "parents": ", ".join(self._graph.parents(node_id)), 

1933 "children": ", ".join(self._graph.children(node_id)), 

1934 "locked": node_display_value.locked, 

1935 } 

1936 ) 

1937 

1938 return {"success": True, "rows": rows} 

1939 

1940 def update_node_data( 

1941 self, node_id: str, new_data: str, crop_id: str | None = None 

1942 ) -> dict: 

1943 """ 

1944 Update the data of a specific node. 

1945 

1946 Args: 

1947 node_id: The annotation ID 

1948 new_data: New data to set for the node 

1949 

1950 Returns: 

1951 dict with 'success' or 'error' 

1952 """ 

1953 with self._editing() as refused: 

1954 if refused: 

1955 return refused 

1956 try: 

1957 if self._graph is None: 

1958 raise ValueError("No graph loaded. Call load_yaml first.") 

1959 # node_id may be "" when creating a new Text node via crop_id — only 

1960 # resolve a real, non-empty id (an empty label would never match). 

1961 resolved_id = self._graph.resolve_id(node_id) if node_id else node_id 

1962 self._graph.set_data(resolved_id, new_data, crop_id) 

1963 self._save_collectra_file() 

1964 return self.get_all_nodes_for_grid() 

1965 except Exception as e: 

1966 return {"success": False, "error": str(e)} 

1967 

1968 def update_node_coordinates( 

1969 self, node_id: str, crop_region: dict, view_id: str = "" 

1970 ) -> dict: 

1971 """ 

1972 Update the crop region coordinates of a specific node. 

1973 

1974 Args: 

1975 node_id: The annotation ID 

1976 crop_region: dict with x_center, y_center, width_relative, height_relative 

1977 

1978 Returns: 

1979 dict with 'success' and updated rows, or 'error' 

1980 """ 

1981 with self._editing() as refused: 

1982 if refused: 

1983 return refused 

1984 try: 

1985 if self._graph is None: 

1986 raise ValueError("No graph loaded. Call load_yaml first.") 

1987 if view_id: 

1988 context = self._display_context() 

1989 crop_region = context.region( 

1990 context.artefact(view_id), crop_region, inverse=True 

1991 ) 

1992 self._graph.set_crop_region( 

1993 self._graph.resolve_id(node_id), crop_region 

1994 ) 

1995 self._save_collectra_file() 

1996 return self.get_all_nodes_for_grid() 

1997 except Exception as e: 

1998 return {"success": False, "error": str(e)} 

1999 

2000 def _next_annotation_id(self, label: str) -> str: 

2001 """Matches the pipeline's scheme (label+N) — reuses the smallest 

2002 suffix a deletion freed up, rather than always growing past the 

2003 highest one ever used. Shared with preview_annotation_id.""" 

2004 existing_numbers = set() 

2005 for node_id in self._graph.nodes: 

2006 node = self._graph.get_node(node_id) 

2007 if node and node.label == label: 

2008 suffix = node_id[len(label) :] 

2009 if suffix.isdigit(): 

2010 existing_numbers.add(int(suffix)) 

2011 n = 1 

2012 while n in existing_numbers: 

2013 n += 1 

2014 return f"{label}{n}" 

2015 

2016 def preview_annotation_id(self, label: str) -> dict: 

2017 """What create_annotation would name the next box with this label, without creating anything.""" 

2018 if self._graph is None: 

2019 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

2020 return {"success": True, "id": self._next_annotation_id(label)} 

2021 

2022 def create_annotation( 

2023 self, 

2024 crop_region: dict, 

2025 label: str, 

2026 parent_id: str, 

2027 image_path: str = "", 

2028 name: str = "", 

2029 crop_id: str = "", 

2030 view_id: str = "", 

2031 ) -> dict: 

2032 """ 

2033 Create a new ImageCrop annotation with a Text child. 

2034 

2035 Args: 

2036 crop_region: dict with x_center, y_center, width_relative, height_relative 

2037 name: optional per-instance display name, distinct from label 

2038 crop_id: explicit node id; auto-numbered (label + N) when blank 

2039 

2040 Returns: 

2041 dict with updated grid data or 'error' 

2042 """ 

2043 with self._editing() as refused: 

2044 if refused: 

2045 return refused 

2046 if self._graph is None: 

2047 return { 

2048 "success": False, 

2049 "error": "No graph loaded. Call load_yaml first.", 

2050 } 

2051 

2052 if not image_path: 

2053 return { 

2054 "success": False, 

2055 "error": "Image path is required to create annotation.", 

2056 } 

2057 

2058 try: 

2059 if view_id: 

2060 context = self._display_context() 

2061 image = context.artefact(view_id) 

2062 crop_region = context.region(image, crop_region, inverse=True) 

2063 image_path = str(image.get_path()) 

2064 parent_id = parent_id or image.id 

2065 # Find root Image node 

2066 root_image_id = parent_id if view_id else None 

2067 for node_id in self._graph.nodes: 

2068 node_type = self._graph.get_type(node_id) 

2069 if "Image" in node_type and "ImageCrop" not in node_type: 

2070 root_image_id = node_id 

2071 break 

2072 

2073 if root_image_id is None: 

2074 return { 

2075 "success": False, 

2076 "error": "No root Image node found in graph.", 

2077 } 

2078 

2079 orientation = "north" 

2080 

2081 if parent_id: 

2082 parent_node = self._graph.get_node(parent_id) 

2083 if parent_node: 

2084 orientation = parent_node.orientation 

2085 

2086 crop_id = crop_id.strip() or self._next_annotation_id(label) 

2087 if crop_id in self._graph.nodes: 

2088 return { 

2089 "success": False, 

2090 "error": f"Id '{crop_id}' already exists.", 

2091 } 

2092 

2093 if self._yaml_path is None: 

2094 raise ValueError("YAML path is not set.") 

2095 

2096 asset_path = Path(image_path) 

2097 if view_id: 

2098 try: 

2099 asset_path = asset_path.relative_to(context.directory) 

2100 except ValueError: 

2101 pass 

2102 else: 

2103 asset_path = Path(asset_path.name) 

2104 # Create ImageCrop node 

2105 crop_data = { 

2106 "label": label, 

2107 "type": "collectra.ImageCrop", 

2108 "id": crop_id, 

2109 "parents": parent_id if parent_id else root_image_id, 

2110 "orientation": orientation, 

2111 "data": str(asset_path), 

2112 "name": name, 

2113 **crop_region, 

2114 } 

2115 self._graph.add_node(crop_data) 

2116 self._global_labels.add(label) 

2117 # Update global label counts if in parent folder mode 

2118 if self._collectra_folders: 

2119 self._global_label_counts[label] = ( 

2120 self._global_label_counts.get(label, 0) + 1 

2121 ) 

2122 # Save and return updated grid 

2123 self._save_collectra_file() 

2124 result = self.get_all_nodes_for_grid() 

2125 # Include updated global stats in response 

2126 if self._collectra_folders: 

2127 result["global_label_counts"] = self._global_label_counts 

2128 result["global_total"] = sum(self._global_label_counts.values()) 

2129 return result 

2130 

2131 except Exception as e: 

2132 return {"success": False, "error": str(e)} 

2133 

2134 def _node_and_descendants(self, node_id: str) -> list[str]: 

2135 """The node followed by every descendant (any type, any depth), 

2136 breadth first, each id once.""" 

2137 ids = [] 

2138 queue = [node_id] 

2139 seen = {node_id} 

2140 while queue: 

2141 current = queue.pop(0) 

2142 ids.append(current) 

2143 for child_id in self._graph.children(current): 

2144 if child_id not in seen: 

2145 seen.add(child_id) 

2146 queue.append(child_id) 

2147 return ids 

2148 

2149 def search_artefacts(self, query: str) -> dict: 

2150 """ 

2151 Find the artefacts on the open page that contain ``query`` 

2152 (case-insensitive) in their content: the text of a Text artefact or 

2153 a custom name. DAG labels and ids are not searched. 

2154 

2155 Returns: 

2156 dict with 'matches': one entry per artefact, in page order, each 

2157 with id, DAG label (to place it in the tabs), type, the first 

2158 field that matched (text, name) and a snippet around the match 

2159 """ 

2160 if self._graph is None: 

2161 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

2162 

2163 needle = (query or "").strip().lower() 

2164 if not needle: 

2165 return {"success": True, "matches": []} 

2166 

2167 from collectra.types.texts import Text 

2168 from collectra.utils import load_class_from_string 

2169 

2170 context = self._display_context() 

2171 matches = [] 

2172 for node_id in self._nodes_top_down(): 

2173 node = self._graph.get_node(node_id) 

2174 if node is None: 

2175 continue 

2176 fields = [] 

2177 try: 

2178 if issubclass(load_class_from_string(node.type), Text): 

2179 path = context.text_path(node_id) 

2180 if path: 

2181 text = path.read_text(encoding="utf-8") 

2182 elif context.records.get(node_id, {}).get("path"): 

2183 text = ( 

2184 "" # its file is missing: nothing to search, not its path 

2185 ) 

2186 else: 

2187 text = node.data 

2188 fields.append(("text", str(text or ""))) 

2189 except Exception: 

2190 # One artefact that cannot be read (unknown type, a type that is not 

2191 # a class, a file that is not text) must not stop the whole search. 

2192 pass 

2193 fields.append(("name", node.name or "")) 

2194 for field, value in fields: 

2195 found = re.search(re.escape(needle), value, re.IGNORECASE) 

2196 position = found.start() if found else -1 

2197 if position != -1: 

2198 matches.append( 

2199 { 

2200 "id": node_id, 

2201 "label": node.label, 

2202 "type": node.type, 

2203 "field": field, 

2204 "snippet": self._snippet( 

2205 value, position, len(found.group()) 

2206 ), 

2207 } 

2208 ) 

2209 break 

2210 # Walk the matches the way the pipeline reads; labels it does not know 

2211 # (made by hand) come last. The sort is stable, so within one label the 

2212 # order of the page is kept. 

2213 ranks = self._pipeline_label_ranks() 

2214 matches.sort(key=lambda match: ranks.get(match["label"], len(ranks))) 

2215 return {"success": True, "matches": matches} 

2216 

2217 def _text_artefact_labels(self) -> list[str]: 

2218 """The pipeline's text artefact labels, in the order the pipeline reads.""" 

2219 from collectra.types.base import ArtefactNode 

2220 from collectra.types.texts import Text 

2221 

2222 try: 

2223 self._pipeline._ensure_workflow_connected() # builds the nodes 

2224 manager = self._pipeline.node_manager 

2225 labels = [] 

2226 for name in manager.get_node_names(): 

2227 node = manager.resolve_node(name) 

2228 if isinstance(node, ArtefactNode) and any( 

2229 isinstance(type_, type) and issubclass(type_, Text) 

2230 for type_ in node.types 

2231 ): 

2232 labels.append(name) 

2233 except Exception: 

2234 return [] 

2235 ranks = self._pipeline_label_ranks() 

2236 return sorted(labels, key=lambda label: ranks.get(label, len(ranks))) 

2237 

2238 def _page_text_nodes(self, graph) -> dict[str, list[str]]: 

2239 """The ids of a page's text artefacts, by DAG label.""" 

2240 from collectra.types.texts import Text 

2241 from collectra.utils import load_class_from_string 

2242 

2243 nodes: dict[str, list[str]] = {} 

2244 for node_id in graph.nodes: 

2245 node = graph.get_node(node_id) 

2246 if node is None: 

2247 continue 

2248 try: 

2249 if issubclass(load_class_from_string(node.type), Text): 

2250 nodes.setdefault(node.label, []).append(node_id) 

2251 except Exception: 

2252 continue # an unknown type is not a text 

2253 return nodes 

2254 

2255 def _page_text_cells( 

2256 self, graph, directory: Path, limit: int 

2257 ) -> tuple[dict[str, str], list[str]]: 

2258 """The text of each text artefact on a page, by DAG label, and the 

2259 labels that can be edited from the table: those with exactly one 

2260 artefact, shown in full. A label with several artefacts has them 

2261 joined with " | "; each is cut at ``limit``.""" 

2262 from collectra.display import DisplayContext 

2263 

2264 records = { 

2265 node_id: { 

2266 **graph.get_node(node_id).model_dump(), 

2267 "label": graph.get_node(node_id).label, 

2268 } 

2269 for node_id in graph.nodes 

2270 if graph.get_node(node_id) 

2271 } 

2272 context = DisplayContext(records, directory, max_pixels=self._max_pixels) 

2273 cells: dict[str, str] = {} 

2274 editable = [] 

2275 for label, node_ids in self._page_text_nodes(graph).items(): 

2276 values, whole = [], True 

2277 for node_id in node_ids: 

2278 record = records[node_id] 

2279 try: 

2280 path = context.text_path(node_id) 

2281 if path: 

2282 text = path.read_text(encoding="utf-8") 

2283 elif record.get("path"): 

2284 text = "" # its file is missing: show nothing, not its path 

2285 else: 

2286 text = record.get("data") or "" 

2287 except Exception: 

2288 whole = False # one unreadable artefact must not blank the table 

2289 continue 

2290 text = str(text) 

2291 if len(text) > limit: 

2292 text = text[:limit] + "\u2026" 

2293 whole = False 

2294 values.append(text) 

2295 if not values: 

2296 continue 

2297 cells[label] = " | ".join(values) 

2298 if whole and len(node_ids) == 1: 

2299 editable.append(label) 

2300 return cells, editable 

2301 

2302 def get_table_data(self, max_chars: int = 2000) -> dict: 

2303 """ 

2304 Return the text artefacts of every loaded page for the table view. 

2305 

2306 Returns: 

2307 dict with 'columns' (the text artefact labels, in pipeline order) 

2308 and 'rows': one per loaded folder, in sidebar order, each with 

2309 'index', 'name', the text of each label that page has, and 

2310 '__editable': the labels whose text set_table_cells can change. 

2311 """ 

2312 if not self._collectra_folders: 

2313 return {"success": True, "columns": [], "rows": []} 

2314 columns = self._text_artefact_labels() 

2315 rows = [] 

2316 for index, folder in enumerate(self._collectra_folders): 

2317 row = {"index": index, "name": folder["name"]} 

2318 try: 

2319 if ( 

2320 self._graph is not None 

2321 and self._yaml_path is not None 

2322 and Path(self._yaml_path).resolve() 

2323 == Path(folder["yaml_path"]).resolve() 

2324 ): 

2325 graph = self._graph 

2326 else: 

2327 graph = CollectraGraph.from_collectra_file( 

2328 CollectraFile.from_data(Path(folder["path"])) 

2329 ) 

2330 cells, editable = self._page_text_cells( 

2331 graph, Path(folder["path"]), max_chars 

2332 ) 

2333 except Exception: 

2334 cells, editable = ( 

2335 {}, 

2336 [], 

2337 ) # a folder that cannot be loaded is still a row 

2338 for label, text in cells.items(): 

2339 if label not in columns: 

2340 columns.append(label) # made by hand, not in the pipeline 

2341 row[label] = text 

2342 row["__editable"] = editable 

2343 rows.append(row) 

2344 return {"success": True, "columns": columns, "rows": rows} 

2345 

2346 def export_table_csv(self, headers: dict | None = None) -> dict: 

2347 """ 

2348 Ask where to save, then write the table as a CSV: a "File" column and 

2349 one column per text artefact, one row per loaded page, with every text 

2350 in full. 

2351 

2352 Args: 

2353 headers: optional column titles by text artefact label, as the 

2354 table shows them 

2355 

2356 Returns: 

2357 dict with 'success' and 'path', or 'cancelled' when no file was 

2358 chosen 

2359 """ 

2360 if self._window is None: 

2361 return {"success": False, "error": "Window not initialized"} 

2362 try: 

2363 table = self.get_table_data(max_chars=10**12) 

2364 if not table.get("columns") and not table.get("rows"): 

2365 return {"success": False, "error": "No files are loaded"} 

2366 result = self._window.create_file_dialog( 

2367 dialog_type=webview.FileDialog.SAVE, 

2368 save_filename="table.csv", 

2369 file_types=("CSV files (*.csv)",), 

2370 ) 

2371 if not result: 

2372 return {"success": False, "cancelled": True} 

2373 path = Path(result if isinstance(result, (str, Path)) else result[0]) 

2374 if not path.suffix: 

2375 path = path.with_suffix(".csv") 

2376 columns = table["columns"] 

2377 headers = headers or {} 

2378 # utf-8-sig so that Excel reads non-ASCII text correctly 

2379 with open(path, "w", encoding="utf-8-sig", newline="") as handle: 

2380 writer = csv.writer(handle) 

2381 writer.writerow(["File"] + [headers.get(c) or c for c in columns]) 

2382 for row in table["rows"]: 

2383 writer.writerow([row["name"]] + [row.get(c, "") for c in columns]) 

2384 return {"success": True, "path": str(path)} 

2385 except Exception as e: 

2386 return {"success": False, "error": str(e)} 

2387 

2388 def set_table_cells(self, edits: list[dict]) -> dict: 

2389 """ 

2390 Save text pasted or typed into the table. 

2391 

2392 Args: 

2393 edits: each {'index': the page's index in the sidebar, 'label': the 

2394 text artefact's DAG label, 'text': the new text} 

2395 

2396 Only a label with exactly one text artefact on its page can be set; 

2397 the rest are skipped, not created. Every other edit is still saved 

2398 when one fails. 

2399 

2400 Returns: 

2401 dict with 'saved' (the edits that were written, or already held 

2402 that text) and 'skipped' (each edit that was not, with a 'reason') 

2403 """ 

2404 saved, skipped = [], [] 

2405 by_page: dict[int, list[dict]] = {} 

2406 for edit in edits or []: 

2407 by_page.setdefault(edit.get("index"), []).append(edit) 

2408 for index, page_edits in by_page.items(): 

2409 

2410 def skip(edit, reason): 

2411 skipped.append( 

2412 {"index": index, "label": edit.get("label"), "reason": reason} 

2413 ) 

2414 

2415 if not isinstance(index, int) or not 0 <= index < len( 

2416 self._collectra_folders 

2417 ): 

2418 for edit in page_edits: 

2419 skip(edit, "No such page") 

2420 continue 

2421 folder = self._collectra_folders[index] 

2422 try: 

2423 if ( 

2424 self._graph is not None 

2425 and self._yaml_path is not None 

2426 and Path(self._yaml_path).resolve() 

2427 == Path(folder["yaml_path"]).resolve() 

2428 ): 

2429 graph = self._graph 

2430 else: 

2431 graph = CollectraGraph.from_collectra_file( 

2432 CollectraFile.from_data(Path(folder["path"])) 

2433 ) 

2434 nodes = self._page_text_nodes(graph) 

2435 except Exception as e: 

2436 for edit in page_edits: 

2437 skip(edit, str(e)) 

2438 continue 

2439 for edit in page_edits: 

2440 node_ids = nodes.get(edit.get("label"), []) 

2441 if len(node_ids) != 1: 

2442 skip(edit, "Needs exactly one text artefact on the page") 

2443 continue 

2444 result = self.update_display_text( 

2445 node_ids[0], str(edit.get("text", "")), folder["yaml_path"] 

2446 ) 

2447 if result.get("success"): 

2448 saved.append({"index": index, "label": edit["label"]}) 

2449 else: 

2450 skip(edit, result.get("error", "Could not save")) 

2451 return {"success": True, "saved": saved, "skipped": skipped} 

2452 

2453 def _pipeline_label_ranks(self) -> dict[str, int]: 

2454 from .pipeline_order import pipeline_label_ranks 

2455 

2456 try: 

2457 return pipeline_label_ranks(self._pipeline.gui_graph()) 

2458 except Exception: 

2459 return {} 

2460 

2461 def _nodes_top_down(self) -> list[str]: 

2462 """Every node, each followed by its descendants (the image, then its 

2463 crops, then their texts), so results read in the order of the page.""" 

2464 ordered, seen = [], set() 

2465 

2466 def visit(node_id: str) -> None: 

2467 if node_id in seen: 

2468 return 

2469 seen.add(node_id) 

2470 ordered.append(node_id) 

2471 for child_id in self._graph.children(node_id): 

2472 visit(child_id) 

2473 

2474 for node_id in self._graph.nodes: 

2475 if not self._graph.parents(node_id): 

2476 visit(node_id) 

2477 for node_id in self._graph.nodes: # anything only reachable around a cycle 

2478 visit(node_id) 

2479 return ordered 

2480 

2481 @staticmethod 

2482 def _snippet(value: str, position: int, length: int, context: int = 40) -> str: 

2483 """The match with a little text either side, trimmed with ellipses.""" 

2484 start = max(0, position - context) 

2485 end = min(len(value), position + length + context) 

2486 snippet = " ".join(value[start:end].split()) 

2487 return ("…" if start > 0 else "") + snippet + ("…" if end < len(value) else "") 

2488 

2489 def get_delete_preview(self, node_id: str) -> dict: 

2490 """ 

2491 List what delete_annotation would remove along with a node, without 

2492 changing anything. 

2493 

2494 Args: 

2495 node_id: The annotation ID (or DAG label) about to be deleted 

2496 

2497 Returns: 

2498 dict with the resolved 'id' and 'children' (each with id, label 

2499 and type, nearest first), or 'error' on failure 

2500 """ 

2501 if self._graph is None: 

2502 return {"success": False, "error": "No graph loaded. Call load_yaml first."} 

2503 

2504 node_id = self._graph.resolve_id(node_id) 

2505 if node_id not in self._graph.nodes: 

2506 return {"success": False, "error": f"Node '{node_id}' not found"} 

2507 

2508 children = [] 

2509 seen = {node_id} 

2510 

2511 def walk(current: str, depth: int) -> None: 

2512 for child_id in self._graph.children(current): 

2513 if child_id in seen: 

2514 continue 

2515 seen.add(child_id) 

2516 node = self._graph.get_node(child_id) 

2517 children.append( 

2518 { 

2519 "id": child_id, 

2520 "label": node.label if node else "", 

2521 "type": node.type if node else "", 

2522 "depth": depth, 

2523 } 

2524 ) 

2525 walk(child_id, depth + 1) 

2526 

2527 walk(node_id, 1) 

2528 return { 

2529 "success": True, 

2530 "id": node_id, 

2531 "children": children, 

2532 "keeps_self": not self._graph.parents(node_id), 

2533 } 

2534 

2535 def _remove_nodes(self, to_delete: list[str]) -> dict: 

2536 """Remove the given nodes, update label counts, save and return the 

2537 refreshed grid plus the removed ids.""" 

2538 deleted_labels = [ 

2539 node.label 

2540 for node_id in to_delete 

2541 if (node := self._graph.get_node(node_id)) 

2542 ] 

2543 

2544 # Deepest-reached first, so a node's own children are already gone 

2545 # before it is. 

2546 for node_id in reversed(to_delete): 

2547 self._graph.remove_node(node_id) 

2548 

2549 # Update global label counts if in parent folder mode 

2550 if self._collectra_folders: 

2551 for label in deleted_labels: 

2552 if label in self._global_label_counts: 

2553 self._global_label_counts[label] -= 1 

2554 if self._global_label_counts[label] <= 0: 

2555 del self._global_label_counts[label] 

2556 

2557 self._save_collectra_file() 

2558 result = self.get_all_nodes_for_grid() 

2559 # Every id actually removed — the frontend needs this to close any 

2560 # tab left open on a cascaded descendant. 

2561 result["deleted_ids"] = to_delete 

2562 if self._collectra_folders: 

2563 result["global_label_counts"] = self._global_label_counts 

2564 result["global_total"] = sum(self._global_label_counts.values()) 

2565 return result 

2566 

2567 def delete_nested(self, node_id: str) -> dict: 

2568 """ 

2569 Delete everything nested under a node but keep the node itself (used 

2570 for the page image, which cannot be removed). 

2571 

2572 Returns: 

2573 dict with updated grid data and 'deleted_ids', or 'error' 

2574 """ 

2575 with self._editing() as refused: 

2576 if refused: 

2577 return refused 

2578 if self._graph is None: 

2579 return { 

2580 "success": False, 

2581 "error": "No graph loaded. Call load_yaml first.", 

2582 } 

2583 

2584 try: 

2585 node_id = self._graph.resolve_id(node_id) 

2586 if node_id not in self._graph.nodes: 

2587 return {"success": False, "error": f"Node '{node_id}' not found"} 

2588 return self._remove_nodes(self._node_and_descendants(node_id)[1:]) 

2589 except Exception as e: 

2590 return {"success": False, "error": str(e)} 

2591 

2592 def delete_annotation(self, node_id: str) -> dict: 

2593 """ 

2594 Delete an ImageCrop annotation and everything nested under it — 

2595 cascades to its Text children, any child ImageCrops (sub-crops), and 

2596 so on at any depth. Deleting a crop that still has children used to 

2597 leave them behind pointing at a now-nonexistent parent id (a dangling 

2598 reference the graph library then treats as a bare placeholder node, 

2599 breaking id-uniqueness checks for that id ever after) — cascading is 

2600 the only way to guarantee no orphans. 

2601 

2602 Args: 

2603 node_id: The ImageCrop annotation ID to delete 

2604 

2605 Returns: 

2606 dict with updated grid data on success, or 'error' on failure 

2607 """ 

2608 with self._editing() as refused: 

2609 if refused: 

2610 return refused 

2611 if self._graph is None: 

2612 return { 

2613 "success": False, 

2614 "error": "No graph loaded. Call load_yaml first.", 

2615 } 

2616 

2617 try: 

2618 node_id = self._graph.resolve_id(node_id) 

2619 

2620 # Collect every descendant before deleting anything — walking the 

2621 # graph while removing nodes from it would skip some. 

2622 return self._remove_nodes(self._node_and_descendants(node_id)) 

2623 

2624 except Exception as e: 

2625 return {"success": False, "error": str(e)} 

2626 

2627 def rename_annotation( 

2628 self, 

2629 node_id: str, 

2630 name: str, 

2631 label: str | None = None, 

2632 new_id: str | None = None, 

2633 ) -> dict: 

2634 """ 

2635 Sets an ImageCrop annotation's display name. label and new_id are 

2636 optional; omitted, that field is left as-is. 

2637 

2638 Args: 

2639 node_id: The ImageCrop annotation ID to rename 

2640 name: The new name 

2641 label: optional new label 

2642 new_id: optional new id — re-points every parent reference to match 

2643 

2644 Returns: 

2645 dict with updated grid data on success, or 'error' on failure 

2646 """ 

2647 with self._editing() as refused: 

2648 if refused: 

2649 return refused 

2650 if self._graph is None: 

2651 return { 

2652 "success": False, 

2653 "error": "No graph loaded. Call load_yaml first.", 

2654 } 

2655 

2656 try: 

2657 node_id = self._graph.resolve_id(node_id) 

2658 if new_id and new_id != node_id: 

2659 self._graph.rename_id(node_id, new_id) 

2660 node_id = new_id 

2661 if label is not None: 

2662 self._graph.set_label(node_id, label) 

2663 self._graph.set_name(node_id, name) 

2664 self._save_collectra_file() 

2665 return self.get_all_nodes_for_grid() 

2666 

2667 except Exception as e: 

2668 return {"success": False, "error": str(e)} 

2669 

2670 def get_link_names(self) -> dict: 

2671 """The names a Link can be given: those used on this page and, when a 

2672 folder of pages is open, on any of its pages.""" 

2673 names = set(self._global_link_names) 

2674 if self._graph is not None: 

2675 names.update(self._graph.link_names()) 

2676 return {"success": True, "names": sorted(names)} 

2677 

2678 def set_link_name(self, link_id: str, name: str) -> dict: 

2679 """ 

2680 Give a Link another name (its label, the key it has in results.yaml). 

2681 

2682 A Link whose id is its old name, as ``handwritten`` usually is, takes the 

2683 new name as its id too, so the two keep matching; if that id is already 

2684 in use it gets a short suffix instead. Any other id is left alone. 

2685 

2686 Returns: 

2687 dict with updated grid data and the Link's (possibly new) 'id', or 'error' 

2688 """ 

2689 with self._editing() as refused: 

2690 if refused: 

2691 return refused 

2692 from collectra.types.links import is_link_type 

2693 

2694 if self._graph is None: 

2695 return { 

2696 "success": False, 

2697 "error": "No graph loaded. Call load_yaml first.", 

2698 } 

2699 

2700 try: 

2701 link_id = self._graph.resolve_id(link_id) 

2702 node = self._graph.get_node(link_id) 

2703 if node is None: 

2704 return {"success": False, "error": f"Node '{link_id}' not found"} 

2705 if not is_link_type(node.type): 

2706 return {"success": False, "error": f"'{link_id}' is not a Link"} 

2707 name = (name or "").strip() 

2708 if not name: 

2709 return {"success": False, "error": "A Link needs a name"} 

2710 old_name = node.label 

2711 new_id = link_id 

2712 if name != old_name: 

2713 if link_id == old_name: 

2714 new_id = name 

2715 if new_id in self._graph.nodes: 

2716 new_id = f"{name}-{uuid.uuid4().hex[:8]}" 

2717 self._graph.rename_id(link_id, new_id) 

2718 self._graph.set_label(new_id, name) 

2719 self._graph.forget_label_if_unused(old_name) 

2720 self._global_link_names.add(name) 

2721 self._save_collectra_file() 

2722 return {**self.get_all_nodes_for_grid(), "id": new_id} 

2723 except Exception as e: 

2724 return {"success": False, "error": str(e)} 

2725 

2726 def create_link(self, parent_id: str, name: str) -> dict: 

2727 """ 

2728 Add a Link named ``name`` (its label) under an image. 

2729 

2730 Its id is the name, or the name with a short suffix when that id is 

2731 already in use. 

2732 

2733 Returns: 

2734 dict with updated grid data and the Link's 'id', or 'error' 

2735 """ 

2736 with self._editing() as refused: 

2737 if refused: 

2738 return refused 

2739 if self._graph is None: 

2740 return { 

2741 "success": False, 

2742 "error": "No graph loaded. Call load_yaml first.", 

2743 } 

2744 

2745 try: 

2746 parent_id = self._graph.resolve_id(parent_id) 

2747 if self._graph.get_node(parent_id) is None: 

2748 return {"success": False, "error": f"Node '{parent_id}' not found"} 

2749 name = (name or "").strip() 

2750 if not name: 

2751 return {"success": False, "error": "A Link needs a name"} 

2752 link_id = name 

2753 if link_id in self._graph.nodes: 

2754 link_id = f"{name}-{uuid.uuid4().hex[:8]}" 

2755 self._graph.add_node( 

2756 { 

2757 "label": name, 

2758 "type": "collectra.Link", 

2759 "id": link_id, 

2760 "parents": parent_id, 

2761 } 

2762 ) 

2763 self._global_link_names.add(name) 

2764 self._save_collectra_file() 

2765 return {**self.get_all_nodes_for_grid(), "id": link_id} 

2766 except Exception as e: 

2767 return {"success": False, "error": str(e)} 

2768 

2769 def _save_collectra_file(self) -> None: 

2770 """Persist GUI edits through the shared Collectra file writer.""" 

2771 if self._collectra_file is None or self._graph is None: 

2772 raise ValueError("No Collectra file loaded to save to.") 

2773 self._collectra_file.data = self._graph.to_data() 

2774 self._collectra_file.save() 

2775 

2776 def _collectra_dirs(self) -> list[Path]: 

2777 """Return all .collectra directories to search, in priority order. 

2778 

2779 Search order: pipeline path → root itself → root's children → root's parent's children. 

2780 The parent search lets the user open a book sub-folder (e.g. Livy-Books21-25/) 

2781 while the .collectra lives as a sibling inside the project root (LivyProject/). 

2782 """ 

2783 dirs: list[Path] = [] 

2784 pipeline_path = self._pipeline.path 

2785 if pipeline_path.is_dir(): 

2786 dirs.append(pipeline_path) 

2787 roots: list[Path] = [] 

2788 if self._parent_folder: 

2789 roots.append(Path(self._parent_folder)) 

2790 if self._yaml_path: 

2791 roots.append(Path(self._yaml_path).parent.parent) 

2792 seen = set() 

2793 

2794 def _scan(directory: Path) -> None: 

2795 """Add any .collectra dirs found directly inside `directory`.""" 

2796 if not directory.is_dir(): 

2797 return 

2798 if directory.suffix == ".collectra" and directory not in seen: 

2799 dirs.append(directory) 

2800 seen.add(directory) 

2801 return 

2802 try: 

2803 for entry in directory.iterdir(): 

2804 if ( 

2805 entry.is_dir() 

2806 and entry.suffix == ".collectra" 

2807 and entry not in seen 

2808 ): 

2809 dirs.append(entry) 

2810 seen.add(entry) 

2811 except (PermissionError, OSError): 

2812 pass 

2813 

2814 for root in roots: 

2815 _scan(root) # look inside the selected folder 

2816 _scan(root.parent) # look inside the parent (sibling .collectra case) 

2817 

2818 return dirs 

2819 

2820 def _pipeline_metadata(self) -> dict: 

2821 """Return metadata retained by the live pipeline object.""" 

2822 return self._pipeline.pipeline_metadata.copy() 

2823 

2824 def get_pipeline_graph(self) -> dict: 

2825 """Return the graph already constructed by the live pipeline.""" 

2826 return {"success": True, **self._pipeline.gui_graph()} 

2827 

2828 def get_theme_css(self) -> dict: 

2829 """Load the CSS theme named in pipeline metadata, anywhere in the .collectra tree. 

2830 

2831 Falls back to a file literally named theme.css, then any CSS file, when no 

2832 named file is found. 

2833 """ 

2834 named = self._pipeline_metadata().get("theme", "") 

2835 for directory in self._collectra_dirs(): 

2836 # 1. Exact name from metadata 

2837 if named: 

2838 try: 

2839 hits = list(directory.rglob(named)) 

2840 except (PermissionError, OSError): 

2841 hits = [] 

2842 if hits and hits[0].suffix.lower() == ".scss": 

2843 try: 

2844 return { 

2845 "success": True, 

2846 "css": compile_theme(hits[0]), 

2847 "path": str(hits[0]), 

2848 } 

2849 except Exception as e: 

2850 # A broken theme must not leave the app unstyled 

2851 return {**self._default_theme_css(), "warning": str(e)} 

2852 if hits: 

2853 try: 

2854 with open(hits[0], "r") as f: 

2855 return { 

2856 "success": True, 

2857 "css": f.read(), 

2858 "path": str(hits[0]), 

2859 } 

2860 except Exception as e: 

2861 return {"success": False, "error": str(e)} 

2862 

2863 # 2. Fallback: prefer a file named theme.css, else any CSS file 

2864 try: 

2865 css_files = [ 

2866 f for f in directory.iterdir() if f.suffix == ".css" and f.is_file() 

2867 ] 

2868 except (PermissionError, OSError): 

2869 continue 

2870 preferred = next((f for f in css_files if f.stem == "theme"), None) 

2871 target = preferred or (css_files[0] if css_files else None) 

2872 if target: 

2873 try: 

2874 with open(target, "r") as f: 

2875 return {"success": True, "css": f.read(), "path": str(target)} 

2876 except Exception as e: 

2877 return {"success": False, "error": str(e)} 

2878 

2879 return self._default_theme_css() 

2880 

2881 def _default_theme_css(self) -> dict: 

2882 """The CSS of the bundled default theme.""" 

2883 asset_path = Path(get_resource_path("assets/theme.css")) 

2884 if asset_path.is_file(): 

2885 try: 

2886 with open(asset_path, "r") as f: 

2887 return {"success": True, "css": f.read(), "path": str(asset_path)} 

2888 except Exception as e: 

2889 return {"success": False, "error": str(e)} 

2890 

2891 return {"success": False, "error": "No CSS theme file found"} 

2892 

2893 def _encode_logo(self, path: Path) -> dict: 

2894 """Encode a logo file (PNG/SVG/etc.) as a base64 data URI with the right MIME type.""" 

2895 try: 

2896 ext = path.suffix.lower() 

2897 if ext == ".svg": 

2898 mime = "image/svg+xml" 

2899 else: 

2900 mime = ImageFormat[ext[1:].upper()].value 

2901 with open(path, "rb") as f: 

2902 data = base64.b64encode(f.read()).decode("utf-8") 

2903 return {"success": True, "data": f"data:{mime};base64,{data}"} 

2904 except Exception as e: 

2905 return {"success": False, "error": str(e)} 

2906 

2907 def get_logo(self) -> dict: 

2908 """Find the logo named in pipeline metadata (PNG or SVG), anywhere in the .collectra tree. 

2909 

2910 Falls back to globbing for a logo-ish image when no named file is found, 

2911 then to Collectra's own bundled logo when the project has none at all — 

2912 callers rely on this always succeeding so a project with no logo doesn't 

2913 keep showing whichever project's logo loaded previously. 

2914 """ 

2915 named = self._pipeline_metadata().get("logo", "") 

2916 image_exts = {f".{e.lower()}" for e in ImageFormat.__members__} | {".svg"} 

2917 for directory in self._collectra_dirs(): 

2918 # 1. Exact name from metadata 

2919 if named: 

2920 try: 

2921 hits = list(directory.rglob(named)) 

2922 except (PermissionError, OSError): 

2923 hits = [] 

2924 if hits: 

2925 return self._encode_logo(hits[0]) 

2926 # 2. Glob fallback: prefer a "logo"-named image, else any image/SVG 

2927 try: 

2928 candidates = [ 

2929 f for f in directory.rglob("*") if f.suffix.lower() in image_exts 

2930 ] 

2931 except (PermissionError, OSError): 

2932 continue 

2933 logos = [f for f in candidates if "logo" in f.stem.lower()] 

2934 target = logos[0] if logos else (candidates[0] if candidates else None) 

2935 if target: 

2936 return self._encode_logo(target) 

2937 

2938 # Fall back to bundled default asset 

2939 asset_path = Path(get_resource_path("assets/CollectraLogoAndTitle.svg")) 

2940 if asset_path.is_file(): 

2941 return self._encode_logo(asset_path) 

2942 

2943 return {"success": False, "error": "No logo file found"} 

2944 

2945 

2946def _set_macos_app_name(name: str) -> None: 

2947 """Set the app identity before Cocoa creates its native application menu.""" 

2948 if platform.system() != "Darwin": 

2949 return 

2950 try: 

2951 from Foundation import NSBundle, NSProcessInfo 

2952 

2953 info = NSBundle.mainBundle().infoDictionary() 

2954 info["CFBundleName"] = name 

2955 info["CFBundleDisplayName"] = name 

2956 NSProcessInfo.processInfo().setProcessName_(name) 

2957 except Exception: 

2958 # A packaged launcher also supplies these names in its Info.plist. 

2959 import logging 

2960 

2961 logging.getLogger(__name__).warning( 

2962 "Could not set macOS application name", exc_info=True 

2963 ) 

2964 

2965 

2966def _disable_macos_tabbing() -> None: 

2967 """Disable macOS Window Tab Bar for the pywebview window.""" 

2968 import platform 

2969 

2970 if platform.system() != "Darwin": 

2971 return 

2972 try: 

2973 from AppKit import NSApplication 

2974 

2975 for win in NSApplication.sharedApplication().windows(): 

2976 win.setTabbingMode_(2) # NSWindowTabbingModeDisallowed = 2 

2977 except Exception: 

2978 pass 

2979 

2980 

2981def get_resource_path(relative_path: str) -> str: 

2982 """Get the path to a bundled resource, works for dev and PyInstaller.""" 

2983 import sys 

2984 

2985 if getattr(sys, "frozen", False): 

2986 # Running as PyInstaller bundle 

2987 base_path = Path(getattr(sys, "_MEIPASS", "")) 

2988 else: 

2989 # Running in development 

2990 base_path = Path(__file__).parent 

2991 return str(base_path / relative_path) 

2992 

2993 

2994def start( 

2995 pipeline: "Pipeline", 

2996 debug: bool = False, 

2997 inputs=(), 

2998 max_pixels: int = 4096, 

2999): 

3000 """ 

3001 Create and start the pywebview window with the API. 

3002 

3003 Args: 

3004 pipeline: The live pipeline whose graph the GUI displays. 

3005 debug: Enable developer tools 

3006 inputs: Optional result files/folders to populate the sidebar at startup. 

3007 max_pixels: Maximum image/mask preview dimension in pixels. 

3008 """ 

3009 _set_macos_app_name(pipeline.name) 

3010 api = GUIBackend(pipeline, inputs=inputs, max_pixels=max_pixels) 

3011 html_path = get_resource_path("index.html") 

3012 window = webview.create_window( 

3013 title=pipeline.name, 

3014 url=html_path, 

3015 js_api=api, 

3016 width=1200, 

3017 height=800, 

3018 min_size=(800, 600), 

3019 ) 

3020 

3021 def on_started(): 

3022 api.set_window(window) 

3023 _disable_macos_tabbing() 

3024 arrange_native_menu() 

3025 

3026 from .native_menu import arrange_native_menu, build_native_menu 

3027 

3028 webview.start(func=on_started, debug=debug, menu=build_native_menu(window)) 

3029 if api._restart_requested: 

3030 import os 

3031 import sys 

3032 

3033 arguments = [ 

3034 sys.executable, 

3035 "-m", 

3036 "collectra.main", 

3037 "--pipeline", 

3038 str(Path(pipeline.path).resolve() / "pipeline.yaml"), 

3039 "gui", 

3040 ] 

3041 if debug: 

3042 arguments.append("--debug") 

3043 arguments.extend(["--max-pixels", str(max_pixels)]) 

3044 # Reuse the environment and process. Startup restores saved results, 

3045 # the selected page, and layout rather than the original launch inputs. 

3046 os.execv(sys.executable, arguments) 

3047 return window