-
Notifications
You must be signed in to change notification settings - Fork 4
/
mainwindow.py
1596 lines (1434 loc) · 64.2 KB
/
mainwindow.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from functools import partial
import os
import platform
import datetime
from PySide6.QtWidgets import (
QApplication,
QDialog,
QFileDialog,
QInputDialog,
QLabel,
QMainWindow,
QMenu,
QMessageBox,
QTableWidgetItem,
)
from PySide6.QtGui import QIcon, QStandardItemModel, QStandardItem, QDesktopServices
from PySide6.QtCore import (
Qt,
Signal,
Slot,
QTranslator,
QObject,
QCoreApplication,
QEvent,
QMetaMethod,
QUrl,
)
from dotenv import load_dotenv
from os import path
from platformdirs import user_data_dir
from api_output import update_out_api
from camera_info import CameraInfo
from get_camera_info import get_camera_info
from http_server import start_http_server, update_http_server
from ocr_training_data import OCRTrainingDataDialog
from screen_capture_source import ScreenCapture
from source_view import ImageViewer
from defaults import (
default_boxes,
default_info_for_box_name,
normalize_settings_dict,
format_prefixes,
)
from storage import (
TextDetectionTargetMemoryStorage,
fetch_data,
remove_data,
store_data,
store_custom_box_name,
rename_custom_box_name_in_storage,
remove_custom_box_name_in_storage,
fetch_custom_box_names,
)
from obs_websocket import (
create_obs_scene_from_export,
open_obs_websocket,
update_text_source,
)
from template_fields import evaluate_template_field
from text_detection_target import TextDetectionTarget, TextDetectionTargetWithResult
from sc_logging import logger
from update_check import check_for_updates
from log_view import LogViewerDialog
import file_output
from video_settings import VideoSettingsDialog
from vmix_output import VMixAPI
from ui_mainwindow import Ui_MainWindow
from ui_about import Ui_Dialog as Ui_About
from ui_connect_obs import Ui_Dialog as Ui_ConnectObs
from ui_url_source import Ui_Dialog as Ui_UrlSource
from ui_screen_capture import Ui_Dialog as Ui_ScreenCapture
def clear_layout(layout):
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
widget = None
else:
clear_layout(item.layout())
class MainWindow(QMainWindow):
# add a signal to update sources
update_sources = Signal(list)
get_sources = Signal()
def __init__(self, translator: QTranslator, parent: QObject):
super(MainWindow, self).__init__()
self.parent_object = parent
self.ui = Ui_MainWindow()
logger.info("Starting ScoreSight")
self.ui.setupUi(self)
self.translator = translator
# load env variables
load_dotenv()
self.setWindowTitle(f"ScoreSight - v{os.getenv('LOCAL_RELEASE_TAG')}")
if platform.system() == "Windows":
# set the icon
self.setWindowIcon(
QIcon(
path.abspath(
path.join(path.dirname(__file__), "icons/Windows-icon-open.ico")
)
)
)
self.menubar = self.menuBar()
file_menu = self.menubar.addMenu("File")
# check for updates
check_for_updates(False)
file_menu.addAction("Check for Updates", lambda: check_for_updates(True))
file_menu.addAction("About", self.openAboutDialog)
file_menu.addAction("View Current Log", self.openLogsDialog)
file_menu.addAction("Import Configuration", self.importConfiguration)
file_menu.addAction("Export Configuration", self.exportConfiguration)
file_menu.addAction("Open Configuration Folder", self.openConfigurationFolder)
file_menu.addAction("OCR Training Data Setup", self.openOCRTrainingDataDialog)
# Add "Language" menu
languageMenu = file_menu.addMenu("Language")
# Add language options
self.addLanguageOption(languageMenu, "English (US)", "en_US")
self.addLanguageOption(languageMenu, "French (France)", "fr_FR")
self.addLanguageOption(languageMenu, "Spanish (Spain)", "es_ES")
self.addLanguageOption(languageMenu, "German", "de_DE")
self.addLanguageOption(languageMenu, "Italian", "it_IT")
self.addLanguageOption(languageMenu, "Japanese", "ja_JP")
self.addLanguageOption(languageMenu, "Korean", "ko_KR")
self.addLanguageOption(languageMenu, "Dutch", "nl_NL")
self.addLanguageOption(languageMenu, "Polish", "pl_PL")
self.addLanguageOption(languageMenu, "Portuguese (Brazil)", "pt_BR")
self.addLanguageOption(languageMenu, "Portuguese (Portugal)", "pt_PT")
self.addLanguageOption(languageMenu, "Russian", "ru_RU")
self.addLanguageOption(languageMenu, "Chinese (Simplified)", "zh_CN")
# Hide the menu bar by default
self.menubar.setVisible(False)
# Show the menu bar when the Alt key is pressed
self.installEventFilter(self)
self.ui.pushButton_connectObs.clicked.connect(self.openOBSConnectModal)
self.vmixUiSetup()
start_http_server()
self.ui.pushButton_stabilize.setEnabled(True)
self.ui.pushButton_stabilize.clicked.connect(self.toggleStabilize)
self.ui.toolButton_topCrop.clicked.connect(self.cropMode)
# check configuation if crop is enabled
self.ui.toolButton_topCrop.setChecked(
fetch_data("scoresight.json", "crop_mode", False)
)
self.ui.widget_cropPanel.setVisible(self.ui.toolButton_topCrop.isChecked())
self.ui.widget_cropPanel.setEnabled(self.ui.toolButton_topCrop.isChecked())
self.ui.spinBox_leftCrop.valueChanged.connect(
partial(self.globalSettingsChanged, "left_crop")
)
self.ui.spinBox_leftCrop.setValue(fetch_data("scoresight.json", "left_crop", 0))
self.ui.spinBox_rightCrop.valueChanged.connect(
partial(self.globalSettingsChanged, "right_crop")
)
self.ui.spinBox_rightCrop.setValue(
fetch_data("scoresight.json", "right_crop", 0)
)
self.ui.spinBox_topCrop.valueChanged.connect(
partial(self.globalSettingsChanged, "top_crop")
)
self.ui.spinBox_topCrop.setValue(fetch_data("scoresight.json", "top_crop", 0))
self.ui.spinBox_bottomCrop.valueChanged.connect(
partial(self.globalSettingsChanged, "bottom_crop")
)
self.ui.spinBox_bottomCrop.setValue(
fetch_data("scoresight.json", "bottom_crop", 0)
)
self.ui.checkBox_enableOutAPI.toggled.connect(
partial(self.globalSettingsChanged, "enable_out_api")
)
self.ui.checkBox_enableOutAPI.setChecked(
fetch_data("scoresight.json", "enable_out_api", False)
)
# connect toolButton_rotate
self.ui.toolButton_rotate.clicked.connect(self.rotateImage)
self.ui.widget_detectionCadence.setVisible(True)
self.ui.horizontalSlider_detectionCadence.setValue(
fetch_data("scoresight.json", "detection_cadence", 5)
)
self.ui.horizontalSlider_detectionCadence.valueChanged.connect(
self.detectionCadenceChanged
)
self.ui.toolButton_addBox.clicked.connect(self.addBox)
self.ui.toolButton_removeBox.clicked.connect(self.removeCustomBox)
self.video_settings_dialog = None
self.ui.toolButton_videoSettings.clicked.connect(self.openVideoSettings)
self.ui.lineEdit_api_url.textChanged.connect(
partial(self.globalSettingsChanged, "out_api_url")
)
self.ui.lineEdit_api_url.setText(
fetch_data("scoresight.json", "out_api_url", "")
)
self.ui.checkBox_enableOutAPI.toggled.connect(
partial(self.globalSettingsChanged, "enable_out_api")
)
self.ui.checkBox_enableOutAPI.setChecked(
fetch_data("scoresight.json", "enable_out_api", False)
)
self.ui.comboBox_api_encode.currentTextChanged.connect(
partial(self.globalSettingsChanged, "out_api_encoding")
)
self.ui.comboBox_api_encode.setCurrentIndex(
self.ui.comboBox_api_encode.findText(
fetch_data("scoresight.json", "out_api_encoding", "JSON")
)
)
self.obs_websocket_client = None
ocr_models = [
"Daktronics",
"General Scoreboard",
"General Fonts (English)",
"General Scoreboard Large",
]
self.ui.comboBox_ocrModel.addItems(ocr_models)
self.ui.comboBox_ocrModel.setCurrentIndex(
fetch_data("scoresight.json", "ocr_model", 1)
) # default to General Scoreboard
self.ui.frame_source_view.setEnabled(False)
self.ui.groupBox_target_settings.setEnabled(False)
self.ui.pushButton_makeBox.clicked.connect(self.makeBox)
self.ui.pushButton_removeBox.clicked.connect(self.removeBox)
self.ui.tableWidget_boxes.itemClicked.connect(self.listItemClicked)
# connect the edit triggers
self.ui.tableWidget_boxes.itemDoubleClicked.connect(self.editBoxName)
self.ui.pushButton_refresh_sources.clicked.connect(
lambda: self.get_sources.emit()
)
self.detectionTargetsStorage = TextDetectionTargetMemoryStorage()
self.detectionTargetsStorage.data_changed.connect(self.detectionTargetsChanged)
self.ui.pushButton_createOBSScene.clicked.connect(self.createOBSScene)
self.ui.pushButton_selectFolder.clicked.connect(self.selectOutputFolder)
self.ui.toolButton_trashFolder.clicked.connect(self.clearOutputFolder)
self.ui.pushButton_stopUpdates.toggled.connect(self.toggleStopUpdates)
self.ui.comboBox_ocrModel.currentIndexChanged.connect(self.ocrModelChanged)
self.ui.pushButton_restoreDefaults.clicked.connect(self.restoreDefaults)
self.ui.toolButton_zoomReset.clicked.connect(self.resetZoom)
self.ui.toolButton_osd.toggled.connect(self.toggleOSD)
self.ui.toolButton_showOCRrects.toggled.connect(self.toggleOCRRects)
self.ui.checkBox_smoothing.toggled.connect(
partial(self.genericSettingsChanged, "smoothing")
)
self.ui.checkBox_skip_empty.toggled.connect(
partial(self.genericSettingsChanged, "skip_empty")
)
self.ui.horizontalSlider_conf_thresh.valueChanged.connect(
self.confThreshChanged
)
self.ui.lineEdit_format.textChanged.connect(
partial(self.genericSettingsChanged, "format_regex")
)
self.ui.comboBox_fieldType.currentIndexChanged.connect(
partial(self.genericSettingsChanged, "type")
)
self.ui.checkBox_skip_similar_image.toggled.connect(
partial(self.genericSettingsChanged, "skip_similar_image")
)
self.ui.checkBox_autocrop.toggled.connect(
partial(self.genericSettingsChanged, "autocrop")
)
self.ui.horizontalSlider_cleanup.valueChanged.connect(self.cleanupThreshChanged)
self.ui.horizontalSlider_dilate.valueChanged.connect(
partial(self.genericSettingsChanged, "dilate")
)
self.ui.horizontalSlider_skew.valueChanged.connect(
partial(self.genericSettingsChanged, "skew")
)
self.ui.horizontalSlider_vscale.valueChanged.connect(
partial(self.genericSettingsChanged, "vscale")
)
self.ui.checkBox_removeLeadingZeros.toggled.connect(
partial(self.genericSettingsChanged, "remove_leading_zeros")
)
self.ui.checkBox_rescalePatch.toggled.connect(
partial(self.genericSettingsChanged, "rescale_patch")
)
self.ui.checkBox_normWHRatio.toggled.connect(
partial(self.genericSettingsChanged, "normalize_wh_ratio")
)
self.ui.checkBox_invertPatch.toggled.connect(
partial(self.genericSettingsChanged, "invert_patch")
)
self.ui.checkBox_dotDetector.toggled.connect(
partial(self.genericSettingsChanged, "dot_detector")
)
self.ui.checkBox_ordinalIndicator.toggled.connect(
partial(self.genericSettingsChanged, "ordinal_indicator")
)
self.ui.comboBox_binarizationMethod.currentIndexChanged.connect(
partial(self.genericSettingsChanged, "binarization_method")
)
self.ui.checkBox_templatefield.toggled.connect(self.makeTemplateField)
self.ui.lineEdit_templatefield.textChanged.connect(
partial(self.genericSettingsChanged, "templatefield_text")
)
self.ui.comboBox_formatPrefix.currentIndexChanged.connect(
self.formatPrefixChanged
)
self.ui.checkBox_updateOnchange.toggled.connect(self.toggleUpdateOnChange)
# populate the tableWidget_boxes with the default and custom boxes
custom_boxes_names = fetch_custom_box_names()
for box_name in [box["name"] for box in default_boxes] + custom_boxes_names:
item = QTableWidgetItem(
QIcon(
path.abspath(
path.join(path.dirname(__file__), "icons/circle-x.svg")
)
),
box_name,
)
item.setData(Qt.ItemDataRole.UserRole, "unchecked")
self.ui.tableWidget_boxes.insertRow(self.ui.tableWidget_boxes.rowCount())
self.ui.tableWidget_boxes.setItem(
self.ui.tableWidget_boxes.rowCount() - 1, 0, item
)
disabledItem = QTableWidgetItem()
disabledItem.setFlags(Qt.ItemFlag.NoItemFlags)
self.ui.tableWidget_boxes.setItem(
self.ui.tableWidget_boxes.rowCount() - 1, 1, disabledItem
)
self.image_viewer = None
self.obs_connect_modal = None
self.source_name = None
self.updateOCRResults = True
self.log_dialog = None
if fetch_data("scoresight.json", "open_on_startup", False):
logger.info("Opening log dialog on startup")
self.openLogsDialog()
if fetch_data("scoresight.json", "obs"):
self.connectObs()
self.out_folder = fetch_data("scoresight.json", "output_folder")
if self.out_folder:
if not path.exists(self.out_folder):
self.out_folder = None
remove_data("scoresight.json", "output_folder")
else:
self.ui.lineEdit_folder.setText(self.out_folder)
self.first_csv_append = True
self.last_aggregate_save = datetime.datetime.now()
self.ui.checkBox_saveCsv.toggled.connect(
partial(self.globalSettingsChanged, "save_csv")
)
self.ui.checkBox_saveCsv.setChecked(
fetch_data("scoresight.json", "save_csv", False)
)
self.ui.checkBox_saveXML.toggled.connect(
partial(self.globalSettingsChanged, "save_xml")
)
self.ui.checkBox_saveXML.setChecked(
fetch_data("scoresight.json", "save_xml", False)
)
self.ui.comboBox_appendMethod.currentIndexChanged.connect(
partial(self.globalSettingsChanged, "append_method")
)
self.ui.horizontalSlider_aggsPerSecond.valueChanged.connect(
partial(self.globalSettingsChanged, "aggs_per_second")
)
self.ui.comboBox_appendMethod.setCurrentIndex(
fetch_data("scoresight.json", "append_method", 3)
)
self.ui.horizontalSlider_aggsPerSecond.setValue(
fetch_data("scoresight.json", "aggs_per_second", 5)
)
self.ui.checkBox_updateOnchange.setChecked(
fetch_data("scoresight.json", "update_on_change", True)
)
self.ui.checkBox_vmix_send_same.setChecked(
fetch_data("scoresight.json", "vmix_send_same", False)
)
self.ui.checkBox_vmix_send_same.toggled.connect(
partial(self.globalSettingsChanged, "vmix_send_same")
)
self.ui.pushButton_saveOCRTrainingData.clicked.connect(self.saveOCRTrainingData)
self.ui.pushButton_saveOCRTrainingData.setChecked(
fetch_data("scoresight.json", "save_ocr_training_data", False)
)
self.update_sources.connect(self.updateSources)
self.get_sources.connect(self.getSources)
self.get_sources.emit()
def saveOCRTrainingData(self):
self.globalSettingsChanged(
"save_ocr_training_data", self.ui.pushButton_saveOCRTrainingData.isChecked()
)
def openVideoSettings(self):
# only allow opening the video settings for an OpenCV type source
if not self.image_viewer or self.image_viewer is None:
return
if self.image_viewer.getCameraInfo().type != CameraInfo.CameraType.OPENCV:
return
if self.video_settings_dialog is None:
# open the logs dialog
self.video_settings_dialog = VideoSettingsDialog()
self.video_settings_dialog.setWindowTitle("Video Settings")
self.video_settings_dialog.init_ui(self.image_viewer.getCameraCapture())
# show the dialog, non modal
self.video_settings_dialog.show()
def rotateImage(self):
# store the rotation in the scoresight.json
rotation = fetch_data("scoresight.json", "rotation", 0)
rotation += 90
if rotation >= 360:
rotation = 0
self.globalSettingsChanged("rotation", rotation)
def cropMode(self):
# if the toolButton_topCrop is unchecked, go to crop mode
if self.ui.toolButton_topCrop.isChecked():
self.ui.widget_cropPanel.setVisible(True)
self.ui.widget_cropPanel.setEnabled(True)
self.globalSettingsChanged("crop_mode", True)
else:
self.ui.widget_cropPanel.setVisible(False)
self.ui.widget_cropPanel.setEnabled(False)
self.globalSettingsChanged("crop_mode", False)
def globalSettingsChanged(self, settingName, value):
store_data("scoresight.json", settingName, value)
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Alt:
self.menubar.setVisible(True)
elif event.type() == QEvent.FocusOut and self.menubar.isVisible():
self.menubar.setVisible(False)
elif event.type() == QEvent.WindowDeactivate and self.menubar.isVisible():
self.menubar.setVisible(False)
return super().eventFilter(obj, event)
def focusOutEvent(self, event):
if self.menubar.isVisible():
self.menubar.setVisible(False)
super().focusOutEvent(event)
def changeEvent(self, event):
if event.type() == QEvent.WindowDeactivate and self.menubar.isVisible():
self.menubar.setVisible(False)
super().changeEvent(event)
def changeLanguage(self, locale):
locale_file = path.abspath(
path.join(path.dirname(__file__), "translations", f"scoresight_{locale}.qm")
)
logger.info(f"Changing language to {locale_file}")
if not self.translator.load(locale_file):
logger.error(f"Could not load translation for {locale_file}")
return
appInstance = QApplication.instance()
if appInstance:
logger.info(f"installing translator for {locale}")
appInstance.installTranslator(self.translator)
try:
self.ui.retranslateUi(self)
except Exception as e:
logger.error(f"Error retranslating UI: {e}")
def addLanguageOption(self, menu: QMenu, language_name: str, locale: str):
menu.addAction(language_name, lambda: self.changeLanguage(locale))
def toggleUpdateOnChange(self, value):
self.globalSettingsChanged("update_on_change", value)
if self.image_viewer:
self.image_viewer.setUpdateOnChange(value)
def formatPrefixChanged(self, index):
if index == 12:
return # do nothing if "Select Preset" is selected
# based on the selected index, set the format prefix
# change lineEdit_format to the selected format prefix
self.ui.lineEdit_format.setText(format_prefixes[index])
def importConfiguration(self):
# open a file dialog to select a configuration file
file, _ = QFileDialog.getOpenFileName(
self, "Open Configuration File", "", "Configuration Files (*.json)"
)
if not file:
return
# load the configuration from the file
if not self.detectionTargetsStorage.loadBoxesFromFile(file):
# show an error qmessagebox
logger.error("Error loading configuration file")
QMessageBox.critical(
self,
"Error",
"Error loading configuration file",
QMessageBox.StandardButton.Ok,
)
return
def exportConfiguration(self):
# open a file dialog to select the output file
file, _ = QFileDialog.getSaveFileName(
self, "Save Configuration File", "", "Configuration Files (*.json)"
)
if not file:
return
# save the configuration to the file
self.detectionTargetsStorage.saveBoxesToFile(file)
def openOCRTrainingDataDialog(self):
# open the OCR training data dialog
dialog = OCRTrainingDataDialog()
dialog.setWindowTitle("OCR Training Data Setup")
dialog.exec()
def openConfigurationFolder(self):
# open the configuration folder in the file explorer
QDesktopServices.openUrl(
QUrl(
"file:///" + user_data_dir("scoresight"), QUrl.ParsingMode.TolerantMode
)
)
def toggleOSD(self, value):
if self.image_viewer:
self.image_viewer.toggleOSD(value)
def toggleOCRRects(self, value):
if self.image_viewer:
self.image_viewer.toggleOCRRects(value)
def resetZoom(self):
if self.image_viewer:
self.image_viewer.resetZoom()
def detectionCadenceChanged(self, detections_per_second):
self.globalSettingsChanged("detection_cadence", detections_per_second)
if self.image_viewer and self.image_viewer.timerThread:
# convert the detections_per_second to milliseconds
self.image_viewer.timerThread.update_frame_interval = (
1000 / detections_per_second
)
def ocrModelChanged(self, index):
self.globalSettingsChanged("ocr_model", index)
# update the ocr model in the text detector
if (
self.image_viewer
and self.image_viewer.timerThread
and self.image_viewer.timerThread.textDetector
):
self.image_viewer.timerThread.textDetector.setOcrModel(index)
def openLogsDialog(self):
if self.log_dialog is None:
# open the logs dialog
self.log_dialog = LogViewerDialog()
self.log_dialog.setWindowTitle("Logs")
# show the dialog, non modal
self.log_dialog.show()
def openAboutDialog(self):
# open the about dialog
about_dialog = QDialog()
about_dialog_ui = Ui_About()
about_dialog_ui.setupUi(about_dialog)
about_dialog.setWindowTitle("About ScoreSight")
about_dialog.exec()
def toggleStabilize(self):
if not self.image_viewer:
return
# start or stop the stabilization
self.image_viewer.toggleStabilization(self.ui.pushButton_stabilize.isChecked())
def toggleStopUpdates(self, value):
self.updateOCRResults = not value
# change the text on the button
self.ui.pushButton_stopUpdates.setText(
self.translator.translate("MainWindow", "Resume Updates")
if value
else self.translator.translate("MainWindow", "Stop Updates")
)
def selectOutputFolder(self):
# open a Qt dialog to select the output folder
folder = QFileDialog.getExistingDirectory(
self,
"Select Output Folder",
fetch_data("scoresight.json", "output_folder", ""),
options=QFileDialog.Option.ShowDirsOnly,
)
if folder and len(folder) > 0:
self.ui.lineEdit_folder.setText(folder)
self.out_folder = folder
self.globalSettingsChanged("output_folder", folder)
def clearOutputFolder(self):
# clear the output folder
self.ui.lineEdit_folder.setText("")
self.out_folder = None
remove_data("scoresight.json", "output_folder")
def editSettings(self, settingsMutatorCallback):
# update the selected item's settings in the detectionTargetsStorage
item = self.ui.tableWidget_boxes.currentItem()
if item is None:
logger.info("no item selected")
return
item_name = item.text()
item_obj = self.detectionTargetsStorage.find_item_by_name(item_name)
if item_obj is None:
logger.info("item not found: %s", item_name)
return
item_obj = settingsMutatorCallback(item_obj)
self.detectionTargetsStorage.edit_item(item_name, item_obj)
def restoreDefaults(self):
# restore the default settings for the selected item
def restoreDefaultsSettings(item_obj):
info = default_info_for_box_name(item_obj.name)
item_obj.settings = normalize_settings_dict({}, info)
return item_obj
self.editSettings(restoreDefaultsSettings)
self.populateSettings(self.ui.tableWidget_boxes.currentItem().text())
def confThreshChanged(self):
def editConfThreshSettings(item_obj):
item_obj.settings["conf_thresh"] = (
float(self.ui.horizontalSlider_conf_thresh.value()) / 100.0
)
return item_obj
self.editSettings(editConfThreshSettings)
def cleanupThreshChanged(self):
def editCleanupThreshSettings(item_obj):
item_obj.settings["cleanup_thresh"] = (
float(self.ui.horizontalSlider_cleanup.value()) / 100.0
)
return item_obj
self.editSettings(editCleanupThreshSettings)
def genericSettingsChanged(self, settingName, value):
def editGenericSettings(item_obj):
item_obj.settings[settingName] = value
return item_obj
self.editSettings(editGenericSettings)
def vmixConnectionChanged(self):
self.vmixUpdater = VMixAPI(
self.ui.lineEdit_vmixHost.text(),
self.ui.lineEdit_vmixPort.text(),
self.ui.inputLineEdit_vmix.text(),
{},
)
self.globalSettingsChanged("vmix_host", self.ui.lineEdit_vmixHost.text())
self.globalSettingsChanged("vmix_port", self.ui.lineEdit_vmixPort.text())
self.globalSettingsChanged("vmix_input", self.ui.inputLineEdit_vmix.text())
def vmixMappingChanged(self, _):
# store entire mapping data in scoresight.json
mapping = {}
model = self.ui.tableView_vmixMapping.model()
if isinstance(model, QStandardItemModel):
for i in range(model.rowCount()):
item = model.item(i, 0)
value = model.item(i, 1)
if item and value:
mapping[item.text()] = value.text()
self.globalSettingsChanged("vmix_mapping", mapping)
self.vmixUpdater.set_field_mapping(mapping)
else:
logger.error("vmixMappingChanged: model is not a QStandardItemModel")
def vmixUiSetup(self):
# populate the vmix connection from storage
self.ui.lineEdit_vmixHost.setText(
fetch_data("scoresight.json", "vmix_host", "localhost")
)
self.ui.lineEdit_vmixPort.setText(
fetch_data("scoresight.json", "vmix_port", "8099")
)
self.ui.inputLineEdit_vmix.setText(
fetch_data("scoresight.json", "vmix_input", "1")
)
# connect the lineEdits to vmixConnectionChanged
self.ui.lineEdit_vmixHost.textChanged.connect(self.vmixConnectionChanged)
self.ui.lineEdit_vmixPort.textChanged.connect(self.vmixConnectionChanged)
self.ui.inputLineEdit_vmix.textChanged.connect(self.vmixConnectionChanged)
# create the vmixUpdater
self.vmixUpdater = VMixAPI(
self.ui.lineEdit_vmixHost.text(),
self.ui.lineEdit_vmixPort.text(),
self.ui.inputLineEdit_vmix.text(),
{},
)
# add standard item model to the tableView_vmixMapping
self.ui.tableView_vmixMapping.setModel(QStandardItemModel())
mapping = fetch_data("scoresight.json", "vmix_mapping", {})
if mapping:
self.vmixUpdater.set_field_mapping(mapping)
self.ui.tableView_vmixMapping.model().dataChanged.connect(
self.vmixMappingChanged
)
self.ui.pushButton_startvmix.toggled.connect(self.togglevMix)
def togglevMix(self, value):
if not self.vmixUpdater:
return
if value:
self.ui.pushButton_startvmix.setText("🛑 Stop vMix")
self.vmixUpdater.running = True
else:
self.ui.pushButton_startvmix.setText("▶️ Start vMix")
self.vmixUpdater.running = False
def updatevMixTable(self, detectionTargets):
mapping_storage = fetch_data("scoresight.json", "vmix_mapping")
model = QStandardItemModel()
model.blockSignals(True)
for box in detectionTargets:
# add the detection to the vmix output mapping: tableView_vmixMapping
# check if the table already has the detectionTarget
items = model.findItems(box.name, Qt.MatchFlag.MatchExactly)
if len(items) == 0:
# add the item to the list
row = model.rowCount()
model.insertRow(row)
model.setItem(row, 0, QStandardItem(box.name))
# the first item shouldn't be editable
model.item(row, 0).setFlags(Qt.ItemFlag.NoItemFlags)
else:
# update the item in the list
item = items[0]
row = item.row()
# get value from storage or use the box name
if mapping_storage and box.name in mapping_storage:
model.setItem(row, 1, QStandardItem(mapping_storage[box.name]))
else:
model.setItem(row, 1, QStandardItem(box.name))
# remove the items that are not in the detectionTargets
for i in range(model.rowCount()):
item = model.item(i, 0)
if not any([box.name == item.text() for box in detectionTargets]):
model.removeRow(i)
model.blockSignals(False)
self.ui.tableView_vmixMapping.setModel(model)
self.ui.tableView_vmixMapping.model().dataChanged.connect(
self.vmixMappingChanged
)
def detectionTargetsChanged(self, detectionTargets):
for box in detectionTargets:
logger.debug(f"Change: Detection target: {box.name}")
# change the list icon to green checkmark
items = self.ui.tableWidget_boxes.findItems(
box.name, Qt.MatchFlag.MatchExactly
)
if len(items) == 0:
logger.warning(f"Item not found: {box.name}. Adding it to the list.")
# add the item to the list
self.ui.tableWidget_boxes.insertRow(
self.ui.tableWidget_boxes.rowCount()
)
item = QTableWidgetItem(box.name)
self.ui.tableWidget_boxes.setItem(
self.ui.tableWidget_boxes.rowCount() - 1, 0, item
)
disabledItem = QTableWidgetItem()
disabledItem.setFlags(Qt.ItemFlag.NoItemFlags)
self.ui.tableWidget_boxes.setItem(
self.ui.tableWidget_boxes.rowCount() - 1, 1, disabledItem
)
else:
item = items[0]
if not box.settings["templatefield"]:
# this is a detection target
item.setIcon(
QIcon(
path.abspath(
path.join(path.dirname(__file__), "icons/circle-check.svg")
)
)
)
item.setData(Qt.ItemDataRole.UserRole, "checked")
else:
# this is a template field
item.setIcon(
QIcon(
path.abspath(
path.join(
path.dirname(__file__), "icons/template-field.svg"
)
)
)
)
item.setData(Qt.ItemDataRole.UserRole, "templatefield")
self.updatevMixTable(detectionTargets)
# if save_csv is enabled, truncate the aggregate file
if self.ui.checkBox_saveCsv.isChecked() and self.out_folder:
csv_output_file_path = path.abspath(
path.join(self.out_folder, "results.csv")
)
try:
with open(csv_output_file_path, "w") as f:
f.write("")
self.first_csv_append = True
self.last_aggregate_save = datetime.datetime.now()
except Exception as e:
logger.error(f"Error truncating aggregate file: {e}")
def populateSettings(self, name):
self.ui.lineEdit_format.blockSignals(True)
self.ui.comboBox_fieldType.blockSignals(True)
self.ui.checkBox_smoothing.blockSignals(True)
self.ui.checkBox_skip_empty.blockSignals(True)
self.ui.horizontalSlider_conf_thresh.blockSignals(True)
self.ui.checkBox_autocrop.blockSignals(True)
self.ui.checkBox_skip_similar_image.blockSignals(True)
self.ui.horizontalSlider_cleanup.blockSignals(True)
self.ui.horizontalSlider_dilate.blockSignals(True)
self.ui.horizontalSlider_skew.blockSignals(True)
self.ui.horizontalSlider_vscale.blockSignals(True)
self.ui.checkBox_removeLeadingZeros.blockSignals(True)
self.ui.checkBox_rescalePatch.blockSignals(True)
self.ui.checkBox_normWHRatio.blockSignals(True)
self.ui.checkBox_invertPatch.blockSignals(True)
self.ui.checkBox_ordinalIndicator.blockSignals(True)
self.ui.comboBox_binarizationMethod.blockSignals(True)
self.ui.comboBox_formatPrefix.blockSignals(True)
self.ui.checkBox_templatefield.blockSignals(True)
self.ui.lineEdit_templatefield.blockSignals(True)
# populate the settings from the detectionTargetsStorage
item_obj = self.detectionTargetsStorage.find_item_by_name(name)
if item_obj is None:
self.ui.lineEdit_format.setText("")
self.ui.comboBox_fieldType.setCurrentIndex(0)
self.ui.checkBox_smoothing.setChecked(True)
self.ui.checkBox_skip_empty.setChecked(True)
self.ui.horizontalSlider_conf_thresh.setValue(50)
self.ui.checkBox_autocrop.setChecked(False)
self.ui.checkBox_skip_similar_image.setChecked(False)
self.ui.horizontalSlider_cleanup.setValue(0)
self.ui.horizontalSlider_dilate.setValue(1)
self.ui.horizontalSlider_skew.setValue(0)
self.ui.horizontalSlider_vscale.setValue(10)
self.ui.label_selectedInfo.setText("")
self.ui.checkBox_removeLeadingZeros.setChecked(False)
self.ui.checkBox_rescalePatch.setChecked(False)
self.ui.checkBox_normWHRatio.setChecked(False)
self.ui.checkBox_invertPatch.setChecked(False)
self.ui.checkBox_ordinalIndicator.setChecked(False)
self.ui.comboBox_binarizationMethod.setCurrentIndex(0)
self.ui.checkBox_templatefield.setChecked(False)
self.ui.lineEdit_templatefield.setText("")
else:
item_obj.settings = normalize_settings_dict(
item_obj.settings, default_info_for_box_name(item_obj.name)
)
self.ui.label_selectedInfo.setText(f"{item_obj.name}")
self.ui.lineEdit_format.setText(item_obj.settings["format_regex"])
self.ui.comboBox_fieldType.setCurrentIndex(item_obj.settings["type"])
self.ui.checkBox_smoothing.setChecked(item_obj.settings["smoothing"])
self.ui.checkBox_skip_empty.setChecked(item_obj.settings["skip_empty"])
self.ui.horizontalSlider_conf_thresh.setValue(
int(item_obj.settings["conf_thresh"] * 100)
)
self.ui.checkBox_autocrop.setChecked(item_obj.settings["autocrop"])
self.ui.checkBox_skip_similar_image.setChecked(
item_obj.settings["skip_similar_image"]
)
self.ui.horizontalSlider_cleanup.setValue(
int(item_obj.settings["cleanup_thresh"] * 100)
)
self.ui.horizontalSlider_dilate.setValue(item_obj.settings["dilate"])
self.ui.horizontalSlider_skew.setValue(item_obj.settings["skew"])
self.ui.horizontalSlider_vscale.setValue(item_obj.settings["vscale"])
self.ui.checkBox_removeLeadingZeros.setChecked(
item_obj.settings["remove_leading_zeros"]
)
self.ui.checkBox_rescalePatch.setChecked(item_obj.settings["rescale_patch"])
self.ui.checkBox_normWHRatio.setChecked(
item_obj.settings["normalize_wh_ratio"]
)
self.ui.checkBox_invertPatch.setChecked(item_obj.settings["invert_patch"])
self.ui.checkBox_dotDetector.setChecked(item_obj.settings["dot_detector"])
self.ui.checkBox_ordinalIndicator.setChecked(
item_obj.settings["ordinal_indicator"]
)
self.ui.comboBox_binarizationMethod.setCurrentIndex(
item_obj.settings["binarization_method"]
)
self.ui.checkBox_templatefield.setChecked(
item_obj.settings["templatefield"]
)
self.ui.lineEdit_templatefield.setText(
item_obj.settings["templatefield_text"]
)
self.ui.comboBox_formatPrefix.setCurrentIndex(12)
self.ui.lineEdit_format.blockSignals(False)
self.ui.comboBox_fieldType.blockSignals(False)
self.ui.checkBox_smoothing.blockSignals(False)
self.ui.checkBox_skip_empty.blockSignals(False)
self.ui.horizontalSlider_conf_thresh.blockSignals(False)
self.ui.checkBox_autocrop.blockSignals(False)
self.ui.checkBox_skip_similar_image.blockSignals(False)
self.ui.horizontalSlider_cleanup.blockSignals(False)
self.ui.horizontalSlider_dilate.blockSignals(False)
self.ui.horizontalSlider_skew.blockSignals(False)
self.ui.horizontalSlider_vscale.blockSignals(False)
self.ui.checkBox_removeLeadingZeros.blockSignals(False)
self.ui.checkBox_rescalePatch.blockSignals(False)
self.ui.checkBox_normWHRatio.blockSignals(False)
self.ui.checkBox_invertPatch.blockSignals(False)
self.ui.checkBox_ordinalIndicator.blockSignals(False)
self.ui.comboBox_binarizationMethod.blockSignals(False)
self.ui.comboBox_formatPrefix.blockSignals(False)
self.ui.checkBox_templatefield.blockSignals(False)
self.ui.lineEdit_templatefield.blockSignals(False)
def listItemClicked(self, item):
user_role = item.data(Qt.ItemDataRole.UserRole)
if user_role in ["checked", "templatefield"] and item.column() == 0:
# enable the remove box button and disable the make box button
self.ui.pushButton_makeBox.setEnabled(False)
self.ui.pushButton_removeBox.setEnabled(user_role == "checked")
self.ui.groupBox_target_settings.setEnabled(user_role == "checked")
self.populateSettings(item.text())
else:
# enable the make box button and disable the remove box button
self.ui.pushButton_removeBox.setEnabled(False)
self.ui.pushButton_makeBox.setEnabled(item.column() == 0)
self.ui.groupBox_target_settings.setEnabled(False)
self.populateSettings("")
if item.column() == 0:
# if this is not a default box - enable the template field checkbox
if item.text() not in [box["name"] for box in default_boxes]:
self.ui.checkBox_templatefield.setEnabled(True)
self.ui.lineEdit_templatefield.setEnabled(True)
else:
self.ui.checkBox_templatefield.setEnabled(False)
self.ui.lineEdit_templatefield.setEnabled(False)
def openOBSConnectModal(self):
# disable OBS options
self.ui.lineEdit_sceneName.setEnabled(False)
self.ui.checkBox_recreate.setEnabled(False)
self.ui.pushButton_createOBSScene.setEnabled(False)
# load the ui from "connect_obs.ui"
self.obs_modal_ui = Ui_ConnectObs()
self.obs_connect_modal = QDialog()
self.obs_modal_ui.setupUi(self.obs_connect_modal)