-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
custom_x_ray.py
278 lines (243 loc) · 9.53 KB
/
custom_x_ray.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import json
from typing import TYPE_CHECKING, Any
from PyQt6.QtCore import QAbstractTableModel, QModelIndex, Qt, QVariant
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import (
QAbstractScrollArea,
QCheckBox,
QComboBox,
QDialog,
QDialogButtonBox,
QFormLayout,
QHBoxLayout,
QLineEdit,
QPlainTextEdit,
QPushButton,
QTableView,
QVBoxLayout,
)
from .custom_lemmas import ComboBoxDelegate
from .x_ray_share import get_custom_x_path
load_translations() # type: ignore
if TYPE_CHECKING:
_: Any
NER_LABEL_EXPLANATIONS = {
"EVENT": _("Named hurricanes, battles, wars, sports events, etc."),
"FAC": _("Buildings, airports, highways, bridges, etc."),
"GPE": _("Countries, cities, states"),
"LAW": _("Named documents made into laws"),
"LOC": _("Non-GPE locations, mountain ranges, bodies of water"),
"ORG": _("Companies, agencies, institutions, etc."),
"PERSON": _("People, including fictional"),
"PRODUCT": _("Objects, vehicles, foods, etc. (not services)"),
}
DESC_SOURCES = {
None: _("Book quote"),
1: _("Wikipedia"),
2: _("Other MediaWiki server"),
}
class CustomXRayDialog(QDialog):
def __init__(self, book_path: str, title: str, parent: Any = None) -> None:
super().__init__(parent)
self.setWindowTitle(_("Customize X-Ray for {}").format(title))
vl = QVBoxLayout()
self.setLayout(vl)
self.x_ray_table = QTableView(self)
self.x_ray_table.setAlternatingRowColors(True)
self.x_ray_model = XRayTableModel(book_path)
self.x_ray_table.setModel(self.x_ray_model)
self.x_ray_table.setItemDelegateForColumn(
1,
ComboBoxDelegate(
self.x_ray_table,
list(NER_LABEL_EXPLANATIONS.keys()),
{
i: exp
for i, exp in zip(
range(len(NER_LABEL_EXPLANATIONS)),
NER_LABEL_EXPLANATIONS.values(),
)
},
),
)
self.x_ray_table.setItemDelegateForColumn(
4, ComboBoxDelegate(self.x_ray_table, DESC_SOURCES)
)
self.x_ray_table.horizontalHeader().setMaximumSectionSize(400)
self.x_ray_table.setSizeAdjustPolicy(
QAbstractScrollArea.SizeAdjustPolicy.AdjustToContents
)
self.x_ray_table.resizeColumnsToContents()
vl.addWidget(self.x_ray_table)
search_line = QLineEdit()
search_line.setPlaceholderText(_("Search"))
search_line.textChanged.connect(lambda: self.search_x_ray(search_line.text()))
vl.addWidget(search_line)
edit_buttons = QHBoxLayout()
add_button = QPushButton(QIcon.ic("plus.png"), _("Add"))
add_button.clicked.connect(self.add_x_ray)
delete_button = QPushButton(QIcon.ic("minus.png"), _("Delete"))
delete_button.clicked.connect(self.delete_x_ray)
edit_buttons.addWidget(add_button)
edit_buttons.addWidget(delete_button)
vl.addLayout(edit_buttons)
save_button_box = QDialogButtonBox(
QDialogButtonBox.StandardButton.Save
| QDialogButtonBox.StandardButton.Cancel
)
save_button_box.accepted.connect(self.accept)
save_button_box.rejected.connect(self.reject)
vl.addWidget(save_button_box)
def search_x_ray(self, text: str) -> None:
if matches := self.x_ray_model.match(
self.x_ray_model.index(0, 0), Qt.ItemDataRole.DisplayRole, text
):
self.x_ray_table.setCurrentIndex(matches[0])
self.x_ray_table.scrollTo(matches[0])
def add_x_ray(self) -> None:
add_x_dlg = AddXRayDialog(self)
if add_x_dlg.exec() and (name := add_x_dlg.name_line.text()):
self.x_ray_model.insert_data(
[
name,
add_x_dlg.ner_label.currentData(),
add_x_dlg.aliases.text(),
add_x_dlg.description.toPlainText(),
add_x_dlg.source.currentData(),
add_x_dlg.omit.isChecked(),
]
)
self.x_ray_table.resizeColumnsToContents()
def delete_x_ray(self) -> None:
self.x_ray_model.delete_data(self.x_ray_table.selectedIndexes())
self.x_ray_table.resizeColumnsToContents()
class XRayTableModel(QAbstractTableModel):
def __init__(self, book_path: str) -> None:
super().__init__()
self.custom_path = get_custom_x_path(book_path)
if self.custom_path.exists():
with open(self.custom_path, encoding="utf-8") as f:
self.x_ray_data = json.load(f)
else:
self.x_ray_data = []
self.headers = [
_("Name"),
_("Named entity label"),
_("Aliases"),
_("Description"),
_("Description source"),
_("Omit"),
]
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return QVariant()
row = index.row()
column = index.column()
value = self.x_ray_data[row][column]
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
return value
elif role == Qt.ItemDataRole.ToolTipRole and column == 3:
return value
elif role == Qt.ItemDataRole.CheckStateRole and column == 5:
new_value = Qt.CheckState.Checked if value else Qt.CheckState.Unchecked
if isinstance(new_value, int): # PyQt5
return new_value
else: # PyQt6 Enum
return new_value.value
def rowCount(self, index):
return len(self.x_ray_data)
def columnCount(self, index):
return len(self.headers)
def headerData(self, section, orientation, role):
if (
role == Qt.ItemDataRole.DisplayRole
and orientation == Qt.Orientation.Horizontal
):
return self.headers[section]
def flags(self, index):
if not index.isValid():
return Qt.ItemFlag.ItemIsEnabled
flag = QAbstractTableModel.flags(self, index)
if index.column() == 5:
flag |= Qt.ItemFlag.ItemIsUserCheckable
else:
flag |= Qt.ItemFlag.ItemIsEditable
return flag
def setData(self, index, value, role):
if not index.isValid():
return False
row = index.row()
column = index.column()
if role == Qt.ItemDataRole.EditRole:
self.x_ray_data[row][column] = value
self.dataChanged.emit(index, index, [role])
return True
elif role == Qt.ItemDataRole.CheckStateRole and column == 5:
checked_value = (
Qt.CheckState.Checked
if isinstance(Qt.CheckState.Checked, int)
else Qt.CheckState.Checked.value
)
self.x_ray_data[row][column] = value == checked_value
self.dataChanged.emit(index, index, [role])
return True
return False
def insert_data(self, data):
index = QModelIndex()
self.beginInsertRows(index, self.rowCount(index), self.rowCount(index))
self.x_ray_data.append(data)
self.endInsertRows()
def delete_data(self, indexes):
for row in sorted(
[index.row() for index in indexes if index.row() >= 0], reverse=True
):
self.beginRemoveRows(QModelIndex(), row, row)
self.x_ray_data.pop(row)
self.endRemoveRows()
def save_data(self) -> None:
with open(self.custom_path, "w", encoding="utf-8") as f:
json.dump(self.x_ray_data, f, indent=2, ensure_ascii=False)
class AddXRayDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle(_("Add new X-Ray data"))
vl = QVBoxLayout()
self.setLayout(vl)
form_layout = QFormLayout()
form_layout.setFieldGrowthPolicy(
QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow
)
self.name_line = QLineEdit()
form_layout.addRow(_("Name"), self.name_line)
self.ner_label = QComboBox()
for index, (label, exp) in zip(
range(len(NER_LABEL_EXPLANATIONS)), NER_LABEL_EXPLANATIONS.items()
):
self.ner_label.addItem(label, label)
self.ner_label.setItemData(index, exp, Qt.ItemDataRole.ToolTipRole)
form_layout.addRow(_("NER label"), self.ner_label)
self.aliases = QLineEdit()
self.aliases.setPlaceholderText(_('Separate by ","'))
form_layout.addRow(_("Aliases"), self.aliases)
self.description = QPlainTextEdit()
form_layout.addRow(_("Description"), self.description)
self.description.setPlaceholderText(
_(
"Leave this empty to use description from Wikipedia or other "
"MediaWiki server"
)
)
self.source = QComboBox()
for value, text in DESC_SOURCES.items():
self.source.addItem(text, value)
form_layout.addRow(_("Description source"), self.source)
self.omit = QCheckBox()
form_layout.addRow(_("Omit"), self.omit)
confirm_button_box = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
confirm_button_box.accepted.connect(self.accept)
confirm_button_box.rejected.connect(self.reject)
vl.addLayout(form_layout)
vl.addWidget(confirm_button_box)
self.setLayout(vl)