Silly98 commited on
Commit
1c2db23
·
verified ·
1 Parent(s): 4d0e061

Delete visualize_seg.py

Browse files
Files changed (1) hide show
  1. visualize_seg.py +0 -536
visualize_seg.py DELETED
@@ -1,536 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- Visualize .seg face labels on a STEP model.
5
-
6
- Face order follows the TopExp_Explorer (topological walk), matching the
7
- ordering used in face_labeler.py and BRepNet feature extraction.
8
- """
9
- from __future__ import annotations
10
-
11
- import sys
12
- import os
13
- import argparse
14
- from dataclasses import dataclass
15
- from typing import List, Optional, Tuple
16
-
17
- # Qt binding selection + pythonocc backend init
18
- try:
19
- from PyQt5 import QtCore, QtWidgets
20
- _qt_backend = "qt-pyqt5"
21
- except ImportError: # pragma: no cover
22
- from PySide2 import QtCore, QtWidgets
23
- _qt_backend = "qt-pyside2"
24
-
25
- from OCC.Display.backend import load_backend
26
-
27
- load_backend(_qt_backend)
28
-
29
- from OCC.Core.STEPControl import STEPControl_Reader
30
- from OCC.Core.IFSelect import IFSelect_RetDone
31
- from OCC.Core.TopExp import TopExp_Explorer
32
- from OCC.Core.TopAbs import TopAbs_FACE
33
- from OCC.Core.TopoDS import topods
34
- from OCC.Core.Quantity import Quantity_Color, Quantity_TOC_RGB
35
- from OCC.Display.qtDisplay import qtViewer3d
36
- try:
37
- from OCC.Core.Aspect import Aspect_TOL_SOLID
38
- from OCC.Core.Prs3d import Prs3d_LineAspect
39
- except Exception: # pragma: no cover - optional OCC build
40
- Aspect_TOL_SOLID = None
41
- Prs3d_LineAspect = None
42
- try:
43
- from OCC.Core.Graphic3d import Graphic3d_NOM_MATTE, Graphic3d_NOM_NEON
44
- except Exception: # pragma: no cover - optional OCC build
45
- Graphic3d_NOM_MATTE = None
46
- Graphic3d_NOM_NEON = None
47
- try:
48
- from OCC.Core.Graphic3d import Graphic3d_TOSM_UNLIT
49
- except Exception: # pragma: no cover - optional OCC build
50
- Graphic3d_TOSM_UNLIT = None
51
-
52
- CLASS_NAMES = [
53
- "SOL",
54
- "Through hole",
55
- "blind hole",
56
- "chamfer",
57
- "Fillet",
58
- "Through cut",
59
- "Blind cut",
60
- ]
61
-
62
- CLASS_COLORS_HEX = [
63
- "#1f77b4", # blue
64
- "#2ca02c", # green
65
- "#d62728", # red
66
- "#9467bd", # purple
67
- "#8c564b", # brown
68
- "#e377c2", # pink
69
- "#ff7f0e", # orange
70
- ]
71
-
72
- UNLABELED_COLOR_HEX = "#d0d0d0"
73
- HIGHLIGHT_COLOR_HEX = "#FFD400"
74
- EDGE_COLOR_HEX = "#2b2b2b"
75
-
76
-
77
- def hex_to_rgb01(color_hex: str) -> Tuple[float, float, float]:
78
- color_hex = color_hex.lstrip("#")
79
- r = int(color_hex[0:2], 16) / 255.0
80
- g = int(color_hex[2:4], 16) / 255.0
81
- b = int(color_hex[4:6], 16) / 255.0
82
- return r, g, b
83
-
84
-
85
- def rgb01_to_quantity(rgb: Tuple[float, float, float]) -> Quantity_Color:
86
- return Quantity_Color(rgb[0], rgb[1], rgb[2], Quantity_TOC_RGB)
87
-
88
-
89
- def text_color_for_bg(color_hex: str) -> str:
90
- r, g, b = hex_to_rgb01(color_hex)
91
- luminance = (0.299 * r + 0.587 * g + 0.114 * b)
92
- return "#000000" if luminance > 0.6 else "#ffffff"
93
-
94
-
95
- def load_seg_labels(seg_path: str) -> List[int]:
96
- labels: List[int] = []
97
- with open(seg_path, "r", encoding="utf-8") as handle:
98
- for line in handle:
99
- line = line.strip()
100
- if line == "":
101
- continue
102
- labels.append(int(line))
103
- return labels
104
-
105
-
106
- @dataclass
107
- class FaceItem:
108
- face: object
109
- ais: object
110
-
111
-
112
- class SegViewer(QtWidgets.QMainWindow):
113
- def __init__(self, step_path: Optional[str] = None, seg_path: Optional[str] = None):
114
- super().__init__()
115
- self.setWindowTitle("BRepMFR Seg Viewer")
116
- self.resize(1600, 1000)
117
- self.setMinimumSize(1200, 800)
118
-
119
- self.class_names = CLASS_NAMES
120
- self.class_colors_rgb = [hex_to_rgb01(c) for c in CLASS_COLORS_HEX]
121
- self.class_colors = [rgb01_to_quantity(c) for c in self.class_colors_rgb]
122
- self.unlabeled_color = rgb01_to_quantity(hex_to_rgb01(UNLABELED_COLOR_HEX))
123
- self.highlight_color = rgb01_to_quantity(hex_to_rgb01(HIGHLIGHT_COLOR_HEX))
124
-
125
- self.face_items: List[FaceItem] = []
126
- self.labels: List[Optional[int]] = []
127
- self.seg_labels: Optional[List[int]] = None
128
- self.current_index: Optional[int] = None
129
- self.highlight_enabled = True
130
- self.step_path: Optional[str] = None
131
- self.seg_path: Optional[str] = None
132
-
133
- self._build_ui()
134
- self.update_step_label()
135
- self.update_seg_label()
136
- self.update_info()
137
-
138
- if step_path:
139
- self.load_step(step_path)
140
- if seg_path:
141
- self.load_seg(seg_path)
142
-
143
- def _build_ui(self) -> None:
144
- central = QtWidgets.QWidget(self)
145
- root_layout = QtWidgets.QHBoxLayout(central)
146
- root_layout.setContentsMargins(8, 8, 8, 8)
147
- root_layout.setSpacing(8)
148
-
149
- self.viewer = qtViewer3d(central)
150
- self.viewer.InitDriver()
151
- self.display = self.viewer._display
152
- try:
153
- self.display.Context.SetAutomaticHilight(False)
154
- except Exception:
155
- pass
156
- self._configure_viewer_visuals()
157
- root_layout.addWidget(self.viewer, 1)
158
-
159
- panel = QtWidgets.QWidget(central)
160
- panel_layout = QtWidgets.QVBoxLayout(panel)
161
- panel_layout.setContentsMargins(0, 0, 0, 0)
162
- panel_layout.setSpacing(6)
163
- root_layout.addWidget(panel, 0)
164
-
165
- self.btn_import_step = QtWidgets.QPushButton("Import STEP")
166
- self.btn_import_step.clicked.connect(self.on_import_step)
167
- panel_layout.addWidget(self.btn_import_step)
168
-
169
- self.btn_import_seg = QtWidgets.QPushButton("Import .seg")
170
- self.btn_import_seg.clicked.connect(self.on_import_seg)
171
- panel_layout.addWidget(self.btn_import_seg)
172
-
173
- self.btn_clear_all = QtWidgets.QPushButton("Clear All")
174
- self.btn_clear_all.clicked.connect(self.on_clear_all)
175
- panel_layout.addWidget(self.btn_clear_all)
176
-
177
- self.chk_highlight = QtWidgets.QCheckBox("Highlight current")
178
- self.chk_highlight.setChecked(True)
179
- self.chk_highlight.toggled.connect(self.on_toggle_highlight)
180
- panel_layout.addWidget(self.chk_highlight)
181
-
182
- self.btn_review = QtWidgets.QPushButton("Summary")
183
- self.btn_review.clicked.connect(self.on_review)
184
- panel_layout.addWidget(self.btn_review)
185
-
186
- panel_layout.addSpacing(8)
187
-
188
- nav_layout = QtWidgets.QHBoxLayout()
189
- self.btn_prev = QtWidgets.QPushButton("<< Prev")
190
- self.btn_prev.clicked.connect(self.on_prev)
191
- self.btn_next = QtWidgets.QPushButton("Next >>")
192
- self.btn_next.clicked.connect(self.on_next)
193
- nav_layout.addWidget(self.btn_prev)
194
- nav_layout.addWidget(self.btn_next)
195
- panel_layout.addLayout(nav_layout)
196
-
197
- self.step_label = QtWidgets.QLabel("STEP: (none)")
198
- self.step_label.setWordWrap(True)
199
- panel_layout.addWidget(self.step_label)
200
-
201
- self.seg_label = QtWidgets.QLabel("SEG: (none)")
202
- self.seg_label.setWordWrap(True)
203
- panel_layout.addWidget(self.seg_label)
204
-
205
- self.info_label = QtWidgets.QLabel("No STEP loaded")
206
- self.info_label.setWordWrap(True)
207
- panel_layout.addWidget(self.info_label)
208
-
209
- panel_layout.addSpacing(8)
210
-
211
- legend_label = QtWidgets.QLabel("Label Colors")
212
- legend_label.setStyleSheet("font-weight: bold;")
213
- panel_layout.addWidget(legend_label)
214
-
215
- grid = QtWidgets.QGridLayout()
216
- grid.setSpacing(6)
217
- for idx, name in enumerate(self.class_names):
218
- item = QtWidgets.QLabel(f"{idx}: {name}")
219
- bg = CLASS_COLORS_HEX[idx]
220
- fg = text_color_for_bg(bg)
221
- item.setStyleSheet(
222
- f"background-color: {bg}; color: {fg}; padding: 3px 6px; border-radius: 2px;"
223
- )
224
- grid.addWidget(item, idx, 0)
225
- panel_layout.addLayout(grid)
226
-
227
- panel_layout.addStretch(1)
228
- self.setCentralWidget(central)
229
-
230
- def update_step_label(self) -> None:
231
- if self.step_path:
232
- name = os.path.basename(self.step_path)
233
- self.step_label.setText(f"STEP: {name}")
234
- self.setWindowTitle(f"BRepMFR Seg Viewer - {name}")
235
- else:
236
- self.step_label.setText("STEP: (none)")
237
- self.setWindowTitle("BRepMFR Seg Viewer")
238
-
239
- def update_seg_label(self) -> None:
240
- if self.seg_path:
241
- name = os.path.basename(self.seg_path)
242
- self.seg_label.setText(f"SEG: {name}")
243
- else:
244
- self.seg_label.setText("SEG: (none)")
245
-
246
- def keyPressEvent(self, event) -> None: # pragma: no cover - UI only
247
- if event.key() in (QtCore.Qt.Key_Right, QtCore.Qt.Key_D):
248
- self.on_next()
249
- return
250
- if event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_A):
251
- self.on_prev()
252
- return
253
- super().keyPressEvent(event)
254
-
255
- def on_import_step(self) -> None:
256
- path, _ = QtWidgets.QFileDialog.getOpenFileName(
257
- self, "Open STEP", "", "STEP Files (*.stp *.step)"
258
- )
259
- if path:
260
- self.load_step(path)
261
-
262
- def on_import_seg(self) -> None:
263
- path, _ = QtWidgets.QFileDialog.getOpenFileName(
264
- self, "Open SEG", "", "SEG Files (*.seg)"
265
- )
266
- if path:
267
- self.load_seg(path)
268
-
269
- def on_clear_all(self) -> None:
270
- if not self.step_path and not self.seg_path and not self.face_items and self.seg_labels is None:
271
- return
272
- try:
273
- self.display.EraseAll()
274
- self.display.Repaint()
275
- except Exception:
276
- pass
277
- self.face_items.clear()
278
- self.labels.clear()
279
- self.seg_labels = None
280
- self.current_index = None
281
- self.step_path = None
282
- self.seg_path = None
283
- self.update_step_label()
284
- self.update_seg_label()
285
- self.update_info()
286
-
287
- def on_toggle_highlight(self, checked: bool) -> None:
288
- self.highlight_enabled = checked
289
- if self.current_index is None:
290
- return
291
- color = self.get_highlight_color(self.current_index) if checked else self.get_base_color(self.current_index)
292
- self.set_face_color(self.current_index, color)
293
-
294
- def on_review(self) -> None:
295
- if not self.face_items:
296
- QtWidgets.QMessageBox.information(self, "Summary", "No STEP loaded.")
297
- return
298
- counts = [0 for _ in self.class_names]
299
- unlabeled = 0
300
- for label in self.labels:
301
- if label is None:
302
- unlabeled += 1
303
- else:
304
- counts[label] += 1
305
- lines = [
306
- f"Total faces: {len(self.labels)}",
307
- f"Unlabeled: {unlabeled}",
308
- "",
309
- ]
310
- for idx, name in enumerate(self.class_names):
311
- lines.append(f"{idx} {name}: {counts[idx]}")
312
- QtWidgets.QMessageBox.information(self, "Summary", "\n".join(lines))
313
-
314
- def on_prev(self) -> None:
315
- if self.current_index is None:
316
- return
317
- if self.current_index <= 0:
318
- return
319
- self.set_current_index(self.current_index - 1)
320
-
321
- def on_next(self) -> None:
322
- if self.current_index is None:
323
- return
324
- if self.current_index >= len(self.face_items) - 1:
325
- return
326
- self.set_current_index(self.current_index + 1)
327
-
328
- def load_step(self, path: str) -> None:
329
- reader = STEPControl_Reader()
330
- status = reader.ReadFile(path)
331
- if status != IFSelect_RetDone:
332
- QtWidgets.QMessageBox.warning(
333
- self, "Load STEP", f"Failed to read STEP file: {path}"
334
- )
335
- return
336
- reader.TransferRoots()
337
- shape = reader.OneShape()
338
- self.step_path = path
339
- self.update_step_label()
340
-
341
- self.display.EraseAll()
342
- self.face_items.clear()
343
- self.labels.clear()
344
- self.current_index = None
345
-
346
- explorer = TopExp_Explorer(shape, TopAbs_FACE)
347
- while explorer.More():
348
- face = topods.Face(explorer.Current())
349
- ais = self.display.DisplayShape(face, update=False, color=self.unlabeled_color)
350
- if isinstance(ais, list):
351
- ais = ais[0]
352
- self._apply_face_material(ais)
353
- try:
354
- self.display.Context.SetDisplayMode(ais, 1, False)
355
- except Exception:
356
- pass
357
- try:
358
- self.display.Context.Redisplay(ais, False)
359
- except Exception:
360
- pass
361
- self.face_items.append(FaceItem(face=face, ais=ais))
362
- self.labels.append(None)
363
- explorer.Next()
364
-
365
- if not self.face_items:
366
- QtWidgets.QMessageBox.warning(
367
- self, "Load STEP", "No faces found in STEP file."
368
- )
369
- self.display.Repaint()
370
- return
371
-
372
- if self.seg_labels is not None:
373
- self.apply_seg_labels()
374
-
375
- self.display.FitAll()
376
- self.set_current_index(0)
377
- self.display.Repaint()
378
-
379
- def load_seg(self, path: str) -> None:
380
- try:
381
- labels = load_seg_labels(path)
382
- except Exception as exc:
383
- QtWidgets.QMessageBox.warning(self, "Load SEG", f"Failed to read .seg: {exc}")
384
- return
385
- self.seg_path = path
386
- self.seg_labels = labels
387
- self.update_seg_label()
388
- if self.face_items:
389
- self.apply_seg_labels()
390
-
391
- def apply_seg_labels(self) -> None:
392
- if not self.face_items:
393
- return
394
- num_faces = len(self.face_items)
395
- labels: List[Optional[int]] = [None for _ in range(num_faces)]
396
- invalid = 0
397
- for idx in range(num_faces):
398
- if self.seg_labels is None or idx >= len(self.seg_labels):
399
- continue
400
- label = self.seg_labels[idx]
401
- if 0 <= label < len(self.class_names):
402
- labels[idx] = label
403
- else:
404
- invalid += 1
405
- extra = 0 if self.seg_labels is None else max(0, len(self.seg_labels) - num_faces)
406
- missing = 0 if self.seg_labels is None else max(0, num_faces - len(self.seg_labels))
407
- self.labels = labels
408
- self.recolor_all_faces()
409
- if invalid or extra or missing:
410
- QtWidgets.QMessageBox.warning(
411
- self,
412
- "SEG Mismatch",
413
- "Loaded labels with mismatches:\n"
414
- f"- Missing labels: {missing}\n"
415
- f"- Extra labels: {extra}\n"
416
- f"- Invalid labels: {invalid}\n\n"
417
- "Missing/invalid labels are shown as unlabeled (gray).",
418
- )
419
-
420
- def update_info(self) -> None:
421
- if self.current_index is None:
422
- self.info_label.setText("No STEP loaded")
423
- return
424
- label = self.labels[self.current_index]
425
- label_text = "Unlabeled" if label is None else f"{label}: {self.class_names[label]}"
426
- self.info_label.setText(
427
- f"Face {self.current_index + 1}/{len(self.face_items)}\n"
428
- f"Label: {label_text}"
429
- )
430
-
431
- def get_base_color(self, index: int) -> Quantity_Color:
432
- label = self.labels[index]
433
- return self.unlabeled_color if label is None else self.class_colors[label]
434
-
435
- def get_highlight_color(self, index: int) -> Quantity_Color:
436
- return self.highlight_color
437
-
438
- def set_current_index(self, index: int) -> None:
439
- if not self.face_items:
440
- return
441
- index = max(0, min(index, len(self.face_items) - 1))
442
- if self.current_index is not None:
443
- self.set_face_color(self.current_index, self.get_base_color(self.current_index))
444
- self.current_index = index
445
- self.apply_current_highlight(self.current_index)
446
- self.update_info()
447
-
448
- def apply_current_highlight(self, index: int) -> None:
449
- if self.highlight_enabled:
450
- self.set_face_color(index, self.get_highlight_color(index))
451
- else:
452
- self.set_face_color(index, self.get_base_color(index))
453
-
454
- def recolor_all_faces(self) -> None:
455
- for idx in range(len(self.face_items)):
456
- self.set_face_color(idx, self.get_base_color(idx), repaint=False)
457
- if self.current_index is not None and self.highlight_enabled:
458
- self.set_face_color(
459
- self.current_index, self.get_highlight_color(self.current_index), repaint=False
460
- )
461
- self.display.Repaint()
462
-
463
- def set_face_color(self, index: int, color: Quantity_Color, repaint: bool = True) -> None:
464
- ais = self.face_items[index].ais
465
- if isinstance(ais, list):
466
- for item in ais:
467
- self._set_ais_color(item, color)
468
- else:
469
- self._set_ais_color(ais, color)
470
- if repaint:
471
- self.display.Repaint()
472
-
473
- def _set_ais_color(self, ais, color: Quantity_Color) -> None:
474
- try:
475
- ais.SetColor(color)
476
- except Exception:
477
- self.display.Context.SetColor(ais, color, False)
478
- self._apply_face_material(ais)
479
- self.display.Context.Redisplay(ais, False)
480
-
481
- def _apply_face_material(self, ais) -> None:
482
- applied = False
483
- if Graphic3d_NOM_NEON is not None:
484
- try:
485
- ais.SetMaterial(Graphic3d_NOM_NEON)
486
- applied = True
487
- except Exception:
488
- pass
489
- if not applied and Graphic3d_NOM_MATTE is not None:
490
- try:
491
- ais.SetMaterial(Graphic3d_NOM_MATTE)
492
- except Exception:
493
- pass
494
- self._apply_face_edges(ais)
495
-
496
- def _configure_viewer_visuals(self) -> None:
497
- if Graphic3d_TOSM_UNLIT is None:
498
- return
499
- try:
500
- self.display.View.SetShadingModel(Graphic3d_TOSM_UNLIT)
501
- except Exception:
502
- pass
503
-
504
- def _apply_face_edges(self, ais) -> None:
505
- if Prs3d_LineAspect is None or Aspect_TOL_SOLID is None:
506
- return
507
- try:
508
- drawer = ais.Attributes()
509
- drawer.SetFaceBoundaryDraw(True)
510
- line_aspect = Prs3d_LineAspect(
511
- rgb01_to_quantity(hex_to_rgb01(EDGE_COLOR_HEX)),
512
- Aspect_TOL_SOLID,
513
- 1.0,
514
- )
515
- drawer.SetFaceBoundaryAspect(line_aspect)
516
- except Exception:
517
- pass
518
-
519
-
520
- def main() -> int:
521
- parser = argparse.ArgumentParser(description="Visualize .seg labels on STEP models.")
522
- parser.add_argument("--step", type=str, default=None, help="Path to STEP file")
523
- parser.add_argument("--seg", type=str, default=None, help="Path to .seg label file")
524
- args = parser.parse_args()
525
-
526
- step_path = args.step if args.step and os.path.exists(args.step) else None
527
- seg_path = args.seg if args.seg and os.path.exists(args.seg) else None
528
-
529
- app = QtWidgets.QApplication(sys.argv)
530
- window = SegViewer(step_path=step_path, seg_path=seg_path)
531
- window.show()
532
- return app.exec_()
533
-
534
-
535
- if __name__ == "__main__":
536
- raise SystemExit(main())