-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.py
511 lines (403 loc) · 17.8 KB
/
ui.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt, QTimer, QObject, Signal, QThread
from qtpy.QtWidgets import *
import collections
import requests
import core
import traceback
import webbrowser
import time
class ConfigToggleAction(QAction):
def __init__(self, text, config_key, default, parent):
super().__init__(parent, text=text)
self._config_key = config_key
self._default = default
self.setCheckable(True)
self.setChecked(self._get_value_from_config())
self.triggered.connect(self._action_triggered)
def _get_value_from_config(self):
try:
return core.config[self._config_key]
except KeyError:
core.config.set(self._config_key, self._default)
return self._default
def _action_triggered(self):
core.config.set(self._config_key, not self._get_value_from_config())
class CanvasWidget(QWidget):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self._off_x = 0
self._off_y = 0
self._scale = 1
self._pixmap = None
def _recalc_im(self):
if self._pixmap is None:
return
w, h = self._pixmap.width(), self._pixmap.height()
cw, ch = self.width(), self.height()
self._scale = max(0, min(cw / w, ch / h))
self._off_x, self._off_y = cw/2 - w*self._scale/2, ch/2 - h*self._scale/2
def set_image(self, qim):
try:
self._pixmap = QtGui.QPixmap.fromImage(qim.copy())
self._recalc_im()
except ZeroDivisionError:
raise
except:
traceback.print_exc()
raise
self.repaint()
def clear_image(self):
self._pixmap = None
self.repaint()
def resizeEvent(self, event):
self._recalc_im()
super().resizeEvent(event)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
# paint background
if core.config.get("background", False):
brush = QtGui.QBrush(Qt.black, Qt.Dense4Pattern)
painter.fillRect(0, 0, self.width(), self.height(), brush)
try:
# paint pixmap
if self._pixmap is not None:
painter.drawPixmap(
self._off_x,
self._off_y,
self._pixmap.width() * self._scale,
self._pixmap.height() * self._scale,
self._pixmap
)
except:
traceback.print_exc()
def mousePressEvent(self, event):
# https://doc.qt.io/qt-5/dnd.html#dragging
if event.button() == Qt.LeftButton:
drag = QtGui.QDrag(self)
mime_data = QtCore.QMimeData()
mime_data.setImageData(self._pixmap)
drag.setMimeData(mime_data)
drag.exec_()
class PostList:
def __init__(self, gen=None, prefetch=5):
self._prev = collections.deque(maxlen=50)
self._next = collections.deque()
self._cur = None
self._gen = gen
self.prefetch = prefetch
self._no = 0
def append(self, obj):
self._next.append(obj)
def next_count(self):
return len(self._next)
def next(self):
if self._gen is not None:
while self.next_count() < self.prefetch:
self.append(next(self._gen))
# raises IndexError if len(self._next) <= 0
self._prev.append(self._cur)
self._cur = self._next.popleft()
self._no += 1
return self._cur
def prev_count(self):
return len(self._prev)
def prev(self):
# raises IndexError if len(self._prev) <= 0
self._next.appendleft(self._cur)
self._cur = self._prev.pop()
self._no -= 1
return self._cur
def cur(self):
return self._cur
def get_no(self) -> int:
return self._no
def clear(self):
self._cur = None
self._prev.clear()
self._next.clear()
self._no = 0
def set_generator(self, gen):
self.clear()
self._gen = gen
class SubmissionLoader(QObject):
"""
Worker class for lazily loading submission images
"""
loaded = Signal(QtGui.QImage)
done = Signal()
def __init__(self, submission, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.submission = submission
self.im = None
self._title = None
self.shown = False
self.quit_flag = False
@property
def title(self):
if self._title is not None:
return self._title
else:
return self.submission.title
def _load_url(self, url):
data = requests.get(url, stream=True).content
try:
image = QtGui.QImage()
image.loadFromData(data)
self.im = image
print(f"{self.submission.id}: Loaded: {url}")
self.loaded.emit(self.im)
except:
print(f"ERROR loading: {self.submission.id}: Loaded: {url}")
traceback.print_exc()
def load(self):
try:
self._title = self.submission.title
except:
pass
no_preview_flag = True
try:
for resolution in self.submission.preview["images"][0]["resolutions"][:1]:
try:
self._load_url(resolution["url"])
no_preview_flag = False
except:
pass
except:
pass # continue to below
if not no_preview_flag:
while not self.shown and not self.quit_flag:
time.sleep(0.1)
try:
self._load_url(self.submission.url)
except:
print("Could not load image from submission url: {}".format(self.submission.url))
traceback.print_exc()
self.done.emit()
class MainWindow(QMainWindow):
def __init__(self, parent=None, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.api = core.Api()
self.post_list = PostList(prefetch=core.config.get("prefetch", 5))
# region widgets
self.menu_bar = QMenuBar(self)
self.menu_options = QMenu(self.menu_bar)
self.menu_options.setTitle("&Options")
self.menu_bar.addAction(self.menu_options.menuAction())
self.setMenuBar(self.menu_bar)
self.central_widget = QWidget(self)
self.central_layout = QVBoxLayout(self.central_widget)
self.panel_top = QWidget(self.central_widget)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.panel_top.sizePolicy().hasHeightForWidth())
self.panel_top.setSizePolicy(sizePolicy)
self.layout_top = QHBoxLayout(self.panel_top)
self.label_subreddit = QLabel(self.panel_top, text="Subreddit(s): ")
self.layout_top.addWidget(self.label_subreddit)
self.edit_subreddit = QLineEdit(self.panel_top)
self.layout_top.addWidget(self.edit_subreddit)
self.label_flair = QLabel(self.panel_top, text="Flair: ")
self.layout_top.addWidget(self.label_flair)
self.edit_flair = QLineEdit(self.panel_top)
self.layout_top.addWidget(self.edit_flair)
self.label_score = QLabel(self.panel_top, text="Min Score: ")
self.layout_top.addWidget(self.label_score)
self.spin_score = QSpinBox(self.panel_top)
self.spin_score.setMinimum(0)
self.spin_score.setMaximum(999999999)
self.spin_score.setSingleStep(1)
spin_size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
spin_size_policy.setHorizontalStretch(0)
spin_size_policy.setVerticalStretch(0)
spin_size_policy.setHeightForWidth(self.spin_score.sizePolicy().hasHeightForWidth())
self.spin_score.setSizePolicy(spin_size_policy)
self.layout_top.addWidget(self.spin_score)
self.btn_go = QPushButton(self.panel_top, text="Go")
self.layout_top.addWidget(self.btn_go)
self.central_layout.addWidget(self.panel_top)
self.panel_centre = QWidget(self.central_widget)
self.layout_centre = QVBoxLayout(self.panel_centre)
self.panel_centre_top = QWidget(self.panel_centre)
self.layout_centre_top = QHBoxLayout(self.panel_centre_top)
self.layout_centre_top.setContentsMargins(0, 0, 0, 0)
self.label_title = QLabel(self.panel_centre, text="TITLE HERE")
self.layout_centre_top.addWidget(self.label_title)
self.label_score = QLabel(self.panel_centre, text="5.3k")
score_size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
score_size_policy.setHorizontalStretch(0)
score_size_policy.setVerticalStretch(0)
score_size_policy.setHeightForWidth(self.label_score.sizePolicy().hasHeightForWidth())
self.label_score.setSizePolicy(score_size_policy)
self.layout_centre_top.addWidget(self.label_score)
sizePolicy.setHeightForWidth(self.panel_centre_top.sizePolicy().hasHeightForWidth())
self.panel_centre_top.setSizePolicy(sizePolicy)
self.layout_centre.addWidget(self.panel_centre_top)
self.canvas = CanvasWidget(self.panel_centre)
self.layout_centre.addWidget(self.canvas)
self.central_layout.addWidget(self.panel_centre)
self.panel_bottom = QWidget(self.central_widget)
sizePolicy.setHeightForWidth(self.panel_bottom.sizePolicy().hasHeightForWidth())
self.panel_bottom.setSizePolicy(sizePolicy)
self.layout_bottom = QHBoxLayout(self.panel_bottom)
self.btn_prev = QPushButton(self.panel_bottom, text="Prev (A)")
self.layout_bottom.addWidget(self.btn_prev)
self.btn_next = QPushButton(self.panel_bottom, text="Next (D)")
self.layout_bottom.addWidget(self.btn_next)
self.btn_external = QPushButton(self.panel_bottom, text="Open Externally (X)")
self.layout_bottom.addWidget(self.btn_external)
horizontal_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.layout_bottom.addItem(horizontal_spacer)
self.label_no_display = QLabel(self.panel_bottom, text="#0000")
self.layout_bottom.addWidget(self.label_no_display)
self.central_layout.addWidget(self.panel_bottom)
self.setCentralWidget(self.central_widget)
# endregion
# actions
self.menu_options.addAction(ConfigToggleAction("Background", "background", False, self))
self.menu_options.addAction(ConfigToggleAction("Hide Seen", "hide_seen", False, self))
# signal connecting + shortcuts
self._skip_callback = self._btn_next_clicked
self.btn_go.clicked.connect(self._btn_go_clicked)
self.btn_next.clicked.connect(self._btn_next_clicked)
self.btn_prev.clicked.connect(self._btn_prev_clicked)
self.btn_external.clicked.connect(self._btn_external_clicked)
QShortcut(QtGui.QKeySequence("D"), self, lambda: self._btn_next_clicked())
QShortcut(QtGui.QKeySequence("A"), self, lambda: self._btn_prev_clicked())
QShortcut(QtGui.QKeySequence("X"), self, lambda: self._btn_external_clicked())
self.btn_next.setFocus()
# need to keep reference to threads otherwise will get GC'd
self._threads = []
# load config
try:
self.spin_score.setValue(core.config.get("prev_score", 1))
self.edit_subreddit.setText(core.config["prev_subreddit"])
self.edit_flair.setText(core.config["prev_flair"])
self.btn_go.click()
except:
pass
def _get_generator(self):
def _handle_thread_termination(thread, submission_loader):
try:
submission_loader.quit_flag = True
thread.quit()
thread.wait()
thread.deleteLater()
except RuntimeError:
pass
subreddit = self.edit_subreddit.text()
flair = self.edit_flair.text()
score = self.spin_score.value()
core.config["prev_subreddit"] = subreddit
core.config["prev_flair"] = flair
core.config["prev_score"] = score
def _raw_generator():
if core.config.get("server_side_filtering", False) and core.config.get("hide_seen", False) and score > 0:
# fancier and faster score querying by querying the pushshift API for score directly
# however, when filtering by score, the API only gives results >2months ago*
# therefore, score filter client-side for the first 2 months, then use server-side filtering
# and combine the two generators
# however since I can't be sure about the precise value of *, I should provide some overlap
# this is fine though if hide_seen, since duplicates will be filtered out anyway, otherwise
# there will be duplicates.
# Therefore, the fancier score querying is only available if hide_seen
cur_timestamp = time.time()
three_months = 60 * 60 * 24 * 30 * 3 # approx 3 months in seconds
# Assuming posts are received from the pushshift API in chronological order, and
# list order is retained when saving config,
# can cut out this first (slow) section if the last seen_ids value is from longer than a month ago
skip_local_filtering_step = False
seen_ids = core.config.get("seen_ids", [])
if len(seen_ids) > 0:
last_seen_submission = self.api.praw.submission(id=seen_ids[-1])
if cur_timestamp - last_seen_submission.created >= three_months:
skip_local_filtering_step = True
print("Skipped local filtering step!")
if not skip_local_filtering_step:
for submission in self.api.search(subreddit, flair):
if cur_timestamp - submission.created < three_months:
yield submission
else:
break
print("Switching to server-side score filtering! Post loading speeds should now increase!")
for submission in self.api.search(subreddit, flair, score=f">{score}"):
yield submission
else:
for submission in self.api.search(subreddit, flair):
yield submission
for submission in _raw_generator():
# filter out non-image posts
if submission.is_self or submission.media is not None:
continue
# filter out by score
if submission.score < score:
continue
# filter out seen if hide_seen option is checked
if core.config["hide_seen"]:
if submission.id in core.config.get("seen_ids", []):
continue
# instantiate and start SubmissionLoader thread
submission_loader = SubmissionLoader(submission, None)
thread = QThread()
submission_loader.moveToThread(thread)
thread.started.connect(submission_loader.load)
submission_loader.done.connect(lambda: _handle_thread_termination(thread, submission_loader))
thread.start()
self._threads.append(thread)
yield submission_loader
def _btn_go_clicked(self):
self.post_list.set_generator(self._get_generator())
self.canvas.clear_image()
print("updated generator!")
self._btn_next_clicked()
def _update_im(self, im):
if im is not None:
try:
self.canvas.set_image(im)
print("updated canvas im!")
except:
try:
self._skip_callback()
print("skipped due to error!")
except:
traceback.print_exc()
def _load_from_submission_loader(self, get_submission_loader_func):
self.canvas.clear_image()
try:
cur_submission_loader = self.post_list.cur()
if cur_submission_loader is not None:
cur_submission_loader.shown = False
cur_submission_loader.disconnect()
except TypeError:
pass
except:
traceback.print_exc()
submission_loader = get_submission_loader_func()
if submission_loader is not None:
submission_loader.shown = True
try:
# update seen_ids
seen_ids = core.config.get("seen_ids", [])
if submission_loader.submission.id not in seen_ids:
seen_ids.append(submission_loader.submission.id)
core.config.set("seen_ids", seen_ids)
self._update_im(submission_loader.im)
submission_loader.loaded.connect(self._update_im)
self.label_title.setText(submission_loader.title)
self.label_score.setText(core.human_number(submission_loader.submission.score))
self.label_no_display.setText(f"#{self.post_list.get_no():05d}")
except:
print("Submission loader fatal exception! Skipping!")
traceback.print_exc()
self._skip_callback()
def _btn_next_clicked(self):
self._skip_callback = self._btn_next_clicked
self._load_from_submission_loader(self.post_list.next)
def _btn_prev_clicked(self):
self._skip_callback = self._btn_prev_clicked
if self.post_list.prev_count() > 0:
self._load_from_submission_loader(self.post_list.prev)
def _btn_external_clicked(self):
submission_loader = self.post_list.cur()
webbrowser.open(submission_loader.submission.shortlink)