-
Notifications
You must be signed in to change notification settings - Fork 0
/
__main__.py
181 lines (154 loc) · 5.83 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2024 Sascha Brawer <sascha@brawer.ch>
# SPDX-License-Identifier: MIT
import os
import sys
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QColor, QKeyEvent, QPainter, QPen, QPixmap
from PyQt6.QtWidgets import QFileDialog
from .vision import find_symbols
from PyQt6.QtWidgets import (
QApplication,
QCheckBox,
QDialog,
QHBoxLayout,
QLabel,
QPushButton,
QRadioButton,
QVBoxLayout,
QWidget,
)
app = None
class ClassifyDialog(QDialog):
def __init__(self, parent):
super(ClassifyDialog, self).__init__(parent)
self.candidate = None
self.candidates = []
self.candidate_ids = {} # id -> index in self.candidates
vbox = QVBoxLayout()
self.image = image = QLabel()
self.symbol_buttons = {}
self.symbol_classes = {}
class_box = QWidget()
clay = QVBoxLayout()
class_box.setLayout(clay)
for key, folder, label in [
("X", "other", "Other"),
("A", "white_circle", "White Circle \u25CB"),
("B", "double_white_circle", "Double White Circle \u29BE"),
("P", "black_dot", "Black Dot ·"),
("Q", "double_black_circle", "Double Black Circle \u29BF"),
("T", "small_cross", "Small Cross ×"),
("U", "large_cross", "Large Cross ✛"),
("V", "triangle", "Triangle ⟁"),
]:
button = QRadioButton(f"{key} {label}")
button.folder = os.path.join("corpus", folder)
os.makedirs(button.folder, exist_ok=True)
clay.addWidget(button)
button.toggled.connect(self._on_radio_toggle)
self.symbol_buttons[key] = button
content_box = QWidget()
content_layout = QHBoxLayout()
content_box.setLayout(content_layout)
content_layout.addWidget(image)
content_layout.addWidget(class_box, alignment=Qt.AlignmentFlag.AlignTop)
navrow = QWidget()
self.prev_button = prev = QPushButton("Previous", parent=navrow)
self.prev_button.setEnabled(False)
self.next_button = next = QPushButton("Next", parent=navrow)
self.next_button.setEnabled(False)
self.next_button.clicked.connect(self._on_next)
self.prev_button.clicked.connect(self._on_prev)
lay = QHBoxLayout()
lay.addWidget(prev)
lay.addWidget(next)
navrow.setLayout(lay)
vbox.addWidget(content_box)
vbox.addWidget(navrow, alignment=Qt.AlignmentFlag.AlignRight)
self.setLayout(vbox)
def _on_next(self):
self.save_to_corpus()
id = self.candidate_ids[self.candidate]
if id + 1 < len(self.candidates):
self.set_candidate(self.candidates[id + 1][0])
def _on_prev(self):
self.save_to_corpus()
idx = self._candidate_index()
if idx - 1 >= 0:
self.set_candidate(self.candidates[idx - 1][0])
def _candidate_index(self):
return self.candidate_ids[self.candidate]
def _on_radio_toggle(self):
any_checked = any(b.isChecked() for b in self.symbol_buttons.values())
if any_checked:
self.save_to_corpus()
def save_to_corpus(self):
if self.candidate is None:
return
candidate_index = self.candidate_ids[self.candidate]
_, png = self.candidates[candidate_index]
for key, button in self.symbol_buttons.items():
filepath = os.path.join(button.folder, self.candidate + ".png")
if button.isChecked():
with open(filepath, "wb") as png_file:
png_file.write(png)
else:
try:
os.remove(filepath)
except FileNotFoundError:
pass
def keyPressEvent(self, event):
if type(event) != QKeyEvent:
return super().keyPressEvent(event)
key = event.text().upper()
if key not in self.symbol_buttons:
return super().keyPressEvent(event)
for bkey, b in self.symbol_buttons.items():
b.setChecked(key == bkey)
def add_candidate(self, id, image):
self.candidate_ids[id] = len(self.candidates)
self.candidates.append((id, image))
def set_candidate(self, id):
assert type(id) == str, id
if self.candidate == id:
return
self.candidate = id
pixmap = QPixmap(256, 256)
if id is not None:
_, png = self.candidates[self.candidate_ids[id]]
pixmap.loadFromData(png, format="png")
else:
pixmap.fill(QColor(255, 255, 255))
p = QPainter(pixmap)
p.setPen(QPen(QColor(0x44, 0x44, 0xFF, 0xCC), 3))
w = 32
width, height = pixmap.width(), pixmap.height()
cx, cy = int(width / 2), int(height / 2)
p.drawLine(cx, cy - w, cx, cy + w)
p.drawLine(cx - w, cy, cx + w, cy)
p.end()
pixmap.setDevicePixelRatio(2.0)
self.image.setPixmap(pixmap)
for button in self.symbol_buttons.values():
button.setChecked(False)
idx = self._candidate_index()
self.next_button.setEnabled(idx + 1 < len(self.candidates))
self.next_button.setDefault(idx + 1 < len(self.candidates))
self.prev_button.setEnabled(idx > 0)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
dialog.setNameFilter("PDFs (*.pdf)")
if not dialog.exec():
sys.exit(0)
classify_dialog = ClassifyDialog(parent=None)
for f in dialog.selectedFiles():
for id, img in find_symbols(f):
classify_dialog.add_candidate(id, img)
classify_dialog.set_candidate(classify_dialog.candidates[0][0])
classify_dialog.show()
sys.exit(app.exec())