Coverage for collectra/gui/data_display.py: 98.03%

254 statements  

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

1""" 

2Parses YAML structure, builds lineage relationships, and computes display values 

3for ImageCrop annotations based on the rules: 

4 

51. Container crop (has ImageCrop children) → display blank 

62. Leaf crop with Text child → traverse to deepest Text → display that text 

73. Leaf crop without Text child → display blank 

8 

9""" 

10 

11import copy 

12import uuid 

13from dataclasses import dataclass, field 

14 

15import networkx as nx 

16from pydantic import BaseModel, ConfigDict 

17 

18from collectra.commons.files import CollectraFile, CollectraResultsMetadata 

19from collectra.commons.results import pop_header, put_header 

20 

21from .utils import normalise_items 

22 

23 

24class CollectraNodeFactory: 

25 

26 @staticmethod 

27 def create_node(data: dict) -> "CollectraNode": 

28 """Factory method to create appropriate CollectraNode subclass.""" 

29 node_type = data.get("type", "") 

30 from collectra.utils import load_class_from_string 

31 from collectra.types.images import ImageCrop 

32 

33 try: 

34 is_crop = issubclass(load_class_from_string(node_type), ImageCrop) 

35 except (ImportError, AttributeError, ValueError): 

36 is_crop = "ImageCrop" in node_type 

37 if is_crop: 

38 crop_region = CollectraCropRegion( 

39 x_center=data["x_center"], 

40 y_center=data["y_center"], 

41 width_relative=data["width_relative"], 

42 height_relative=data["height_relative"], 

43 ) 

44 return CollectraAnnotationNode(**data, crop_region=crop_region) 

45 return CollectraNode(**data) 

46 

47 

48class CollectraNode(BaseModel): 

49 """Node in the annotation graph.""" 

50 

51 model_config = ConfigDict(extra="allow") 

52 

53 label: str 

54 type: str 

55 id: str 

56 parents: list[str] = [] 

57 data: object = "" 

58 embeddings: list[str] = [] 

59 orientation: str = "north" 

60 name: str = "" # user-set per-instance name, distinct from label (the category) 

61 

62 def model_dump(self, *args, **kwargs) -> dict[str, str | float]: 

63 data = super().model_dump(*args, **kwargs) 

64 label = data.pop("label", None) # Exclude label from dump 

65 if "path" in data and "data" not in self.model_fields_set: 

66 data.pop("data", None) 

67 if data["parents"]: 

68 data["parents"] = ( 

69 data["parents"][0] if len(data["parents"]) == 1 else data["parents"] 

70 ) 

71 else: 

72 data.pop("parents", None) 

73 if not data.get("name"): 

74 data.pop("name", None) # Don't clutter files that never set one 

75 if label is None: 

76 raise ValueError("Label is missing from node data.") 

77 return data 

78 

79 

80class CollectraCropRegion(BaseModel): 

81 """Crop region fields for annotation nodes.""" 

82 

83 x_center: float 

84 y_center: float 

85 width_relative: float 

86 height_relative: float 

87 

88 

89class CollectraAnnotationNode(CollectraNode): 

90 """Annotation node in the graph.""" 

91 

92 crop_region: CollectraCropRegion 

93 

94 @property 

95 def crop(self) -> dict[str, float]: 

96 """Return crop region as a dict.""" 

97 return self.crop_region.model_dump() 

98 

99 def model_dump(self, *args, **kwargs) -> dict[str, str | float]: 

100 data = super().model_dump(*args, **kwargs) 

101 data.pop("crop_region", None) # Remove crop_region field 

102 for key, value in self.crop.items(): 

103 data[key] = value 

104 return data 

105 

106 

107class NodeDisplayValue(BaseModel): 

108 """Display value for a node.""" 

109 

110 reason: str 

111 value: str | None = None 

112 source_id: str | None = None 

113 crop_region: dict[str, float] | None = None 

114 locked: bool = False 

115 

116 

117@dataclass 

118class CollectraGraph: 

119 """ 

120 Graph structure for annotation lineage relationships. 

121 

122 Provides clean interface for traversal without external dependencies. 

123 """ 

124 

125 _graph: nx.DiGraph = field(default_factory=nx.DiGraph) 

126 

127 metadata: CollectraResultsMetadata = field(default_factory=CollectraResultsMetadata) 

128 

129 # Cached indexes for O(1) lookups 

130 _children_index: dict[str, list[str]] = field(default_factory=dict, repr=False) 

131 _parents_index: dict[str, list[str]] = field(default_factory=dict, repr=False) 

132 

133 # Labels seen in the source YAML, in original order — including ones whose 

134 # value was `[]` (a pipeline task ran and found nothing). Those never 

135 # become graph nodes, so nothing else remembers they exist; without this, 

136 # to_data() silently drops them on every save. 

137 _known_labels: list[str] = field(default_factory=list, repr=False) 

138 

139 @property 

140 def nodes(self) -> list[str]: 

141 """List of node IDs in the graph.""" 

142 if self._graph is None: 

143 return [] 

144 return list(self._graph.nodes) 

145 

146 @classmethod 

147 def from_yaml_data(cls, data: dict) -> "CollectraGraph": 

148 """Build graph from parsed YAML data.""" 

149 data = copy.deepcopy(data) 

150 metadata = pop_header(data) 

151 return cls._from_data(data, metadata) 

152 

153 @classmethod 

154 def from_collectra_file(cls, collectra_file: CollectraFile) -> "CollectraGraph": 

155 """Build a display graph backed by a loaded Collectra file.""" 

156 return cls._from_data( 

157 copy.deepcopy(collectra_file.data), 

158 collectra_file.collectra_results_metadata, 

159 ) 

160 

161 @classmethod 

162 def _from_data( 

163 cls, data: dict, metadata: CollectraResultsMetadata 

164 ) -> "CollectraGraph": 

165 graph = cls(metadata=metadata) 

166 

167 for label, value in data.items(): 

168 graph._known_labels.append(label) 

169 items = normalise_items(value) 

170 for item in items: 

171 if isinstance(item, dict) and "id" in item: 

172 item["label"] = label # Store label for reverse lookup 

173 graph.add_node(item) 

174 

175 return graph 

176 

177 def add_node(self, data: dict) -> None: 

178 """Add a node and its parent edges.""" 

179 data["parents"] = normalise_items(data.get("parents", [])) 

180 node = CollectraNodeFactory.create_node(data) 

181 self._graph.add_node( 

182 node.id, 

183 node=node, 

184 ) 

185 

186 for parent in data["parents"]: 

187 self._graph.add_edge(parent, node.id) 

188 

189 def children(self, node_id: str) -> list[str]: 

190 """Get immediate children of a node.""" 

191 return list(self._graph.successors(node_id)) 

192 

193 def parents(self, node_id: str) -> list[str]: 

194 """Get immediate parents of a node.""" 

195 return list(self._graph.predecessors(node_id)) 

196 

197 def get_node(self, node_id: str) -> CollectraNode | None: 

198 """Get the AnnotationNode object for a given node ID.""" 

199 node = self._graph.nodes.get(node_id, {}).get("node", None) 

200 return node 

201 

202 def resolve_id(self, node_id: str) -> str: 

203 """Translate a DAG label (e.g. "formation") to its real internal node id 

204 (e.g. "formation-<uuid>"). The DAG only ever knows the label; nodes are 

205 keyed internally by id. Returns node_id unchanged if it's already a real 

206 id, or if no node with that label exists. 

207 """ 

208 if node_id in self._graph.nodes: 

209 return node_id 

210 for candidate_id in self._graph.nodes: 

211 node = self.get_node(candidate_id) 

212 if node and node.label == node_id: 

213 return candidate_id 

214 return node_id 

215 

216 def get_type(self, node_id: str) -> str: 

217 """Get type of a node.""" 

218 node = self.get_node(node_id) 

219 return node.type if node else "" 

220 

221 def get_label(self, node_id: str) -> str: 

222 """Get label of a node.""" 

223 node = self.get_node(node_id) 

224 return node.label if node else "" 

225 

226 def get_data(self, node_id: str) -> str: 

227 """Get data field of a node.""" 

228 node = self.get_node(node_id) 

229 return node.data if node else "" 

230 

231 def get_name(self, node_id: str) -> str: 

232 """Get name field of a node.""" 

233 node = self.get_node(node_id) 

234 return node.name if node else "" 

235 

236 def get_crop_region(self, node_id: str) -> dict[str, float]: 

237 """ 

238 Get the crop region coordinates of a node. 

239 

240 Args: 

241 node_id: The node ID to get crop region from 

242 

243 Returns: 

244 dict with x_center, y_center, width_relative, height_relative 

245 

246 Raises: 

247 ValueError: If node is missing crop region fields 

248 """ 

249 node = self.get_node(node_id) 

250 if not isinstance(node, CollectraAnnotationNode): 

251 raise ValueError(f"Node {node_id} is not an annotation node.") 

252 

253 return node.crop 

254 

255 def get_unique_labels(self) -> list[str]: 

256 """Get all unique labels from nodes in the graph.""" 

257 labels = set() 

258 for node_id in self._graph.nodes: 

259 node = self.get_node(node_id) 

260 if node and node.label: 

261 labels.add(node.label) 

262 return sorted(labels) 

263 

264 def link_names(self) -> set[str]: 

265 """The labels of the Link nodes: the names Links have been given.""" 

266 from collectra.types.links import is_link_type 

267 

268 return { 

269 node.label 

270 for node_id in self._graph.nodes 

271 if (node := self.get_node(node_id)) and is_link_type(node.type) 

272 } 

273 

274 def count_nodes_by_label(self, type_filter: str = None) -> dict[str, int]: 

275 """Count nodes grouped by label, optionally filtered by type.""" 

276 counts = {} 

277 for node_id in self._graph.nodes: 

278 node = self.get_node(node_id) 

279 if node and node.label: 

280 if type_filter is None or node.type == type_filter: 

281 counts[node.label] = counts.get(node.label, 0) + 1 

282 return counts 

283 

284 def set_label(self, node_id: str, label: str) -> None: 

285 """Set label field of a node.""" 

286 node = self.get_node(node_id) 

287 if node is None: 

288 raise ValueError(f"Node {node_id} not found in graph.") 

289 node.label = label 

290 

291 def forget_label_if_unused(self, label: str) -> None: 

292 """Stop remembering ``label`` as an empty result once no node has it. 

293 

294 Used when nodes were moved to another label on purpose, so the old one 

295 is not written back as ``[]``. 

296 """ 

297 if label not in self.get_unique_labels() and label in self._known_labels: 

298 self._known_labels.remove(label) 

299 

300 def set_name(self, node_id: str, name: str) -> None: 

301 """Set name field of a node.""" 

302 node = self.get_node(node_id) 

303 if node is None: 

304 raise ValueError(f"Node {node_id} not found in graph.") 

305 node.name = name 

306 

307 def set_data(self, node_id: str, data: str, crop_id: str | None = None) -> None: 

308 """Set data field of a node.""" 

309 if node_id: 

310 node = self.get_node(node_id) 

311 if node is None: 

312 raise ValueError(f"Node {node_id} not found in graph.") 

313 node.data = data 

314 return 

315 if not crop_id: 

316 raise ValueError(f"Node {node_id} not found and crop_id not provided.") 

317 text_data = { 

318 "label": "user_annotation_text", 

319 "type": "collectra.Text", 

320 "id": f"user_text_{uuid.uuid4().hex[:8]}", 

321 "parents": crop_id, 

322 "data": data, 

323 } 

324 self.add_node(text_data) 

325 

326 def set_crop_region(self, node_id: str, crop_region: dict[str, float]) -> None: 

327 """Set crop region fields of a node (x_center, y_center, width_relative, height_relative).""" 

328 node = self.get_node(node_id) 

329 crop: CollectraCropRegion = CollectraCropRegion(**crop_region) 

330 if not isinstance(node, CollectraAnnotationNode): 

331 raise ValueError(f"Node {node_id} is not an annotation node.") 

332 node.crop_region = crop 

333 

334 def remove_node(self, node_id: str) -> None: 

335 """Remove a node and all edges connected to it.""" 

336 self._graph.remove_node(node_id) 

337 

338 def rename_id(self, old_id: str, new_id: str) -> None: 

339 """Changes a node's id, re-pointing every parent/child edge to match (nx.relabel_nodes).""" 

340 if old_id not in self._graph.nodes: 

341 raise ValueError(f"Node {old_id} not found in graph.") 

342 if new_id in self._graph.nodes: 

343 raise ValueError(f"Node {new_id} already exists in graph.") 

344 nx.relabel_nodes(self._graph, {old_id: new_id}, copy=False) 

345 node = self.get_node(new_id) 

346 if node: 

347 node.id = new_id 

348 

349 def children_of_type(self, node_id: str, type_substr: str) -> list[str]: 

350 """Get immediate children containing type_substr in their type.""" 

351 return [ 

352 child_id 

353 for child_id in self.children(node_id) 

354 if type_substr in self.get_type(child_id) 

355 ] 

356 

357 def dfs_leaves(self, start: str, type_filter: str) -> list[str]: 

358 """ 

359 DFS traversal following only edges to nodes matching type_filter. 

360 Returns leaf nodes (nodes with no children of the filtered type). 

361 """ 

362 leaves = [] 

363 visited = set() 

364 stack = [start] 

365 

366 while stack: 

367 node_id = stack.pop() 

368 if node_id in visited: 

369 continue 

370 visited.add(node_id) 

371 

372 # Get children matching the type filter 

373 typed_children = self.children_of_type(node_id, type_filter) 

374 

375 if not typed_children: 

376 # This is a leaf in the filtered subgraph 

377 leaves.append(node_id) 

378 else: 

379 stack.extend(typed_children) 

380 

381 return leaves 

382 

383 def find_deepest(self, start: str, type_filter: str) -> str: 

384 """ 

385 Find the deepest node reachable from start following only type_filter edges. 

386 Returns the first leaf found (DFS order). 

387 """ 

388 leaves = self.dfs_leaves(start, type_filter) 

389 return leaves[0] if leaves else "" 

390 

391 def to_yaml_data(self) -> dict: 

392 """Convert graph back to YAML data structure.""" 

393 return put_header(self.metadata, self.to_data()) 

394 

395 def to_data(self) -> dict: 

396 """Convert graph nodes to the data held by a CollectraFile.""" 

397 yaml_data: dict = {} 

398 

399 for node_id in self._graph.nodes: 

400 node = self.get_node(node_id) 

401 if node is None: 

402 continue 

403 node_data = node.model_dump() 

404 yaml_data.setdefault(node.label, []).append({**node_data}) 

405 

406 def _collapse(value: list[dict]) -> list[dict] | dict: 

407 return value[0] if len(value) == 1 else value 

408 

409 final_data: dict[str, list[dict] | dict] = {} 

410 

411 # Known labels first, in original order, so a label with no current 

412 # nodes (never had any, or had all of them deleted) round-trips as 

413 # `[]` instead of disappearing. 

414 for label in self._known_labels: 

415 final_data[label] = _collapse(yaml_data.pop(label, [])) 

416 

417 # Anything left is a label created fresh this session (e.g. a new 

418 # user-added Text node) that wasn't in the original data. 

419 for key, value in yaml_data.items(): 

420 final_data[key] = _collapse(value) 

421 

422 return final_data 

423 

424 def compute_display_value(self, node_id: str) -> NodeDisplayValue: 

425 """ 

426 Compute display value for an annotation. 

427 

428 Args: 

429 node_id: The node ID to compute display value for 

430 

431 Returns: 

432 NodeDisplayValue with value, source_id, crop_region, reason 

433 """ 

434 if self.get_node(node_id) is None: 

435 return NodeDisplayValue(reason=f"{node_id} Element not found") 

436 

437 node_type = self.get_type(node_id) 

438 

439 # Rule: Image type displays empty 

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

441 return NodeDisplayValue( 

442 reason=f"{node_id} is of collectra.Image type: display blank", 

443 locked=True, 

444 ) 

445 

446 # Rules for ImageCrop 

447 if "ImageCrop" in node_type: 

448 crop_data = self.get_crop_region(node_id) 

449 

450 # Rule 1: Container crop (has ImageCrop children) 

451 if self.children_of_type(node_id, "ImageCrop"): 

452 return NodeDisplayValue( 

453 crop_region=crop_data, 

454 reason=f"{node_id} is a container crop: display blank", 

455 locked=True, 

456 ) 

457 

458 # Rule 2: Leaf crop with Text child 

459 text_children = self.children_of_type(node_id, "Text") 

460 text_children = text_children[0] if text_children else "" 

461 if text_children: 

462 deepest_id = self.find_deepest(text_children, "Text") 

463 if deepest_id == "": 

464 raise ValueError( 

465 f"Expected to find deepest Text child for node {node_id}, but none found." 

466 ) 

467 deepest_data = self.get_data(deepest_id) if deepest_id else "" 

468 return NodeDisplayValue( 

469 value=deepest_data, 

470 source_id=deepest_id, 

471 crop_region=crop_data, 

472 reason=f"Leaf crop {node_id} with Text child: deepest Text is {deepest_id}", 

473 ) 

474 

475 # Rule 3: Leaf crop without Text child 

476 return NodeDisplayValue( 

477 value="", 

478 source_id="", 

479 crop_region=crop_data, 

480 reason=f"Leaf crop {node_id} without Text child", 

481 ) 

482 

483 # Text elements (for completeness) 

484 if "Text" in node_type: 

485 return NodeDisplayValue( 

486 value=self.get_data(node_id), 

487 source_id=node_id, 

488 crop_region=None, 

489 reason="Text element: display data", 

490 ) 

491 

492 return NodeDisplayValue( 

493 value="", 

494 source_id="", 

495 crop_region=None, 

496 reason="Unknown type", 

497 )