-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathview_av.py
4947 lines (4537 loc) · 220 KB
/
view_av.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
# -*- coding: utf-8 -*-
"""
This file is part of QualCoder.
QualCoder is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
QualCoder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with QualCoder.
If not, see <https://www.gnu.org/licenses/>.
Author: Colin Curtain (ccbogel)
https://github.com/ccbogel/QualCoder
https://qualcoder.wordpress.com/
"""
import sqlite3
from copy import copy, deepcopy
import datetime
import difflib
import logging
import os
import platform
import qtawesome as qta # see: https://pictogrammers.com/library/mdi/
from random import randint
import re
import subprocess
import time
import webbrowser
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QBrush, QColor
from .add_item_name import DialogAddItemName
from .code_in_all_files import DialogCodeInAllFiles
from .color_selector import DialogColorSelect
from .color_selector import colors, TextColor
from .confirm_delete import DialogConfirmDelete
from .GUI.ui_dialog_code_av import Ui_Dialog_code_av
from .GUI.ui_dialog_view_av import Ui_Dialog_view_av
from .helpers import msecs_to_hours_mins_secs, Message, ExportDirectoryPathDialog
from .memo import DialogMemo
from .report_attributes import DialogSelectAttributeParameters
from .reports import DialogReportCoderComparisons, DialogReportCodeFrequencies # for isinstance()
from .report_codes import DialogReportCodes
from .select_items import DialogSelectItems
# from .speech_to_text import SpeechToText # Removed as pydub module has error re pyaudioop
# If VLC not installed, it will not crash
vlc = None
try:
import vlc
except Exception as e:
print(e)
path = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
class DialogCodeAV(QtWidgets.QDialog):
""" View and code audio and video segments.
Create codes and categories. """
app = None
parent_textEdit = None
tab_reports = None # Tab widget reports, used for updates to codes
files = []
file_ = None
codes = []
recent_codes = [] # list of recent codes (up to 5) for textedit context menu
categories = []
ddialog = None
instance = None
mediaplayer = None
media = None
metadata = None
is_paused = False
segment = {}
segments = []
text_for_segment = {} # when linking text to segment
segment_for_text = None # when linking segment to text
timer = QtCore.QTimer()
play_segment_end = None
undo_deleted_codes = [] # Undo last deleted segment code, or text code(s).
# For transcribed text
annotations = []
code_text = []
transcription = None # A tuple of id, fulltext, name
# transcribed time positions as list of [text_pos0, text_pos1, milliseconds]
time_positions = []
important = False # Flag to show or hide important coded text and segments
attributes = [] # Show selected files in list widget
# Overlapping codes in text index
overlap_code_index = 0
# Timers to reduce overly sensitive key events: overlap, re-size oversteps by multiple characters
code_resize_timer = 0
overlap_timer = 0
def __init__(self, app, parent_text_edit, tab_reports):
""" Show list of audio and video files.
Can code a transcribed text file for the audio / video.
"""
super(DialogCodeAV, self).__init__()
self.app = app
self.tab_reports = tab_reports
self.parent_textEdit = parent_text_edit
self.codes = []
self.recent_codes = []
self.categories = []
self.annotations = []
self.code_text = []
self.time_positions = []
self.important = False
self.attributes = []
self.code_resize_timer = datetime.datetime.now()
self.overlap_timer = datetime.datetime.now()
self.transcription = None
self.file_ = None
self.segment['start'] = None
self.segment['end'] = None
self.segment['start_msecs'] = None
self.segment['end_msecs'] = None
self.play_segment_end = None
self.segments = []
self.media_duration_text = ""
self.segment_for_text = None
self.undo_deleted_codes = []
self.get_codes_and_categories()
QtWidgets.QDialog.__init__(self)
self.ui = Ui_Dialog_code_av()
self.ui.setupUi(self)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowType.WindowContextHelpButtonHint)
try:
s0 = int(self.app.settings['dialogcodeav_splitter0'])
s1 = int(self.app.settings['dialogcodeav_splitter1'])
if s0 > 10 and s1 > 10:
self.ui.splitter.setSizes([s0, 30, s1])
h0 = int(self.app.settings['dialogcodeav_splitter_h0'])
h1 = int(self.app.settings['dialogcodeav_splitter_h1'])
if h0 > 10 and h1 > 10:
self.ui.splitter_2.setSizes([h0, h1])
except KeyError:
pass
self.ui.splitter.splitterMoved.connect(self.update_sizes)
self.ui.splitter_2.splitterMoved.connect(self.update_sizes)
self.ui.label_volume.setPixmap(qta.icon('mdi6.volume-high').pixmap(22, 22))
self.ui.pushButton_play.setIcon(qta.icon('mdi6.play', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_rewind_30.setIcon(qta.icon('mdi6.rewind-30', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_rewind_30.pressed.connect(self.rewind_30_seconds)
self.ui.pushButton_rewind_5.setIcon(qta.icon('mdi6.rewind-5', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_rewind_5.pressed.connect(self.rewind_5_seconds)
self.ui.pushButton_forward_30.setIcon(qta.icon('mdi6.fast-forward-30', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_forward_30.pressed.connect(self.forward_30_seconds)
self.ui.pushButton_rate_down.setIcon(qta.icon('mdi6.speedometer-slow', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_rate_down.pressed.connect(self.decrease_play_rate)
self.ui.pushButton_rate_up.setIcon(qta.icon('mdi6.speedometer', options=[{'scale_factor': 1.4}]))
self.ui.pushButton_rate_up.pressed.connect(self.increase_play_rate)
self.ui.pushButton_help.setIcon(qta.icon('mdi6.help'))
self.ui.pushButton_help.pressed.connect(self.help)
# The buttons in the splitter are smaller 24x24 pixels
self.ui.pushButton_latest.setIcon(qta.icon('mdi6.arrow-collapse-right', options=[{'scale_factor': 1.3}]))
self.ui.pushButton_latest.pressed.connect(self.go_to_latest_coded_file)
self.ui.pushButton_next_file.setIcon(qta.icon('mdi6.arrow-right', options=[{'scale_factor': 1.3}]))
self.ui.pushButton_next_file.pressed.connect(self.go_to_next_file)
self.ui.pushButton_document_memo.setIcon(qta.icon('mdi6.text-box-outline', options=[{'scale_factor': 1.3}]))
self.ui.pushButton_document_memo.pressed.connect(self.active_file_memo)
self.ui.pushButton_important.setIcon(qta.icon('mdi6.star-outline', options=[{'scale_factor': 1.3}]))
self.ui.pushButton_important.pressed.connect(self.show_important_coded)
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag-outline', options=[{'scale_factor': 1.3}]))
self.ui.pushButton_file_attributes.pressed.connect(self.get_files_from_attributes)
# Until any media is selected disable some widgets
self.ui.pushButton_play.setEnabled(False)
self.ui.pushButton_coding.setEnabled(False)
self.ui.horizontalSlider.setEnabled(False)
self.installEventFilter(self) # for rewind, play/stop
# Prepare textEdit for coding transcribed text
self.ui.textEdit.setPlainText("")
self.ui.textEdit.setAutoFillBackground(True)
self.ui.textEdit.setToolTip("")
self.ui.textEdit.setMouseTracking(True)
self.ui.textEdit.setReadOnly(True)
self.eventFilterTT = ToolTipEventFilter()
self.ui.textEdit.installEventFilter(self.eventFilterTT)
self.ui.textEdit.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.ui.textEdit.customContextMenuRequested.connect(self.textedit_menu)
self.ui.pushButton_segment_menu.pressed.connect(self.label_segment_menu)
font = f'font: {self.app.settings["fontsize"]}pt "{self.app.settings["font"]}";'
self.setStyleSheet(font)
tree_font = f'font: {self.app.settings["treefontsize"]}pt "{self.app.settings["font"]}";'
self.ui.treeWidget.setStyleSheet(tree_font)
doc_font = f'font: {self.app.settings["docfontsize"]}pt "{self.app.settings["font"]}";'
self.ui.textEdit.setStyleSheet(doc_font)
self.ui.label_coder.setText(_("Coder: ") + self.app.settings['codername'])
self.setWindowTitle(_("Media coding"))
self.ui.listWidget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.ui.listWidget.customContextMenuRequested.connect(self.file_menu)
self.ui.listWidget.setStyleSheet(tree_font)
self.ui.listWidget.selectionModel().selectionChanged.connect(self.file_selection_changed)
self.ui.treeWidget.setDragEnabled(True)
self.ui.treeWidget.setAcceptDrops(True)
self.ui.treeWidget.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.InternalMove)
self.ui.treeWidget.viewport().installEventFilter(self)
self.ui.treeWidget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.ui.treeWidget.customContextMenuRequested.connect(self.tree_menu)
self.ui.treeWidget.itemClicked.connect(self.assign_selected_text_to_code)
self.fill_tree()
self.get_files()
# My solution to getting gui mouse events by putting vlc video in another dialog
# A display-dialog named ddialog
# Otherwise, the vlc player hogs all the mouse events
self.ddialog = QtWidgets.QDialog()
# Enable custom window hint
self.ddialog.setWindowFlags(self.ddialog.windowFlags() | QtCore.Qt.WindowType.CustomizeWindowHint)
# Disable close button, only close through closing the Ui_Dialog_code_av
self.ddialog.setWindowFlags(self.ddialog.windowFlags() & ~QtCore.Qt.WindowType.WindowCloseButtonHint)
self.ddialog.gridLayout = QtWidgets.QGridLayout(self.ddialog)
self.ddialog.dframe = QtWidgets.QFrame(self.ddialog)
self.ddialog.dframe.setObjectName("frame")
'''if platform.system() == "Darwin": # For MacOS
self.ddialog.dframe = QtWidgets.QMacCocoaViewContainer(0)'''
self.palette = self.ddialog.dframe.palette()
self.palette.setColor(QtGui.QPalette.ColorRole.Window, QColor(30, 30, 30))
self.ddialog.dframe.setPalette(self.palette)
self.ddialog.dframe.setAutoFillBackground(True)
self.ddialog.gridLayout.addWidget(self.ddialog.dframe, 0, 0, 0, 0)
# enable custom window hint - must be set to enable customizing window controls
self.ddialog.setWindowFlags(self.ddialog.windowFlags() | QtCore.Qt.WindowType.CustomizeWindowHint)
# disable close button, only close through closing the Ui_Dialog_view_av
self.ddialog.setWindowFlags(self.ddialog.windowFlags() & ~QtCore.Qt.WindowType.WindowCloseButtonHint)
self.ddialog.setWindowFlags(self.ddialog.windowFlags() & ~QtCore.Qt.WindowType.WindowContextHelpButtonHint)
# add context menu for ddialog
self.ddialog.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.ddialog.customContextMenuRequested.connect(self.ddialog_menu)
# Create a vlc instance with an empty vlc media player
# Fix an Ubuntu error but, makes no difference self.instance = vlc.Instance("--no-xlib")
# Fedora 39: NameError: no function 'libvlc_new'
try:
self.instance = vlc.Instance()
except NameError as name_err:
logger.error(f"{name_err}")
msg = f"{name_err}"
Message(self.app, _("QualCoder will crash") + " " * 20, msg).exec()
# Ubuntu 22.04 hide - self.ddialog.hide() as vlc is not inside dialog
self.mediaplayer = self.instance.media_player_new()
self.mediaplayer.video_set_mouse_input(False)
self.mediaplayer.video_set_key_input(False)
self.ui.horizontalSlider.setTickPosition(QtWidgets.QSlider.TickPosition.NoTicks)
self.ui.horizontalSlider.setMouseTracking(True)
self.ui.horizontalSlider.sliderMoved.connect(self.set_position)
self.ui.pushButton_play.clicked.connect(self.play_pause)
self.ui.horizontalSlider_vol.valueChanged.connect(self.set_volume)
self.ui.pushButton_coding.pressed.connect(self.create_or_clear_segment)
self.ui.comboBox_tracks.currentIndexChanged.connect(self.audio_track_changed)
# Set the scene for coding stripes
# Matches the designer file graphics view size
self.scene_width = 990
self.scene_height = 110
self.scene = GraphicsScene(self.scene_width, self.scene_height)
self.ui.graphicsView.setScene(self.scene)
self.ui.graphicsView.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
@staticmethod
def help():
""" Open help for transcribe section in browser. """
url = "https://github.com/ccbogel/QualCoder/wiki/4.5.-Coding-Audio-and-Video"
webbrowser.open(url)
def ddialog_menu(self, position):
""" Context menu to export a screenshot, to resize dialog. """
menu = QtWidgets.QMenu()
menu.setStyleSheet("QMenu {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
action_screenshot = menu.addAction(_("Screenshot"))
action_resize = menu.addAction(_("Resize"))
action = menu.exec(self.ddialog.mapToGlobal(position))
if action == action_screenshot:
time.sleep(0.5)
screen = QtWidgets.QApplication.primaryScreen()
screenshot = screen.grabWindow(self.ddialog.winId())
screenshot.save(self.app.settings['directory'] + '/Frame_' + datetime.datetime.now().astimezone().strftime(
"%Y%m%d_%H_%M_%S") + '.jpg', 'jpg')
if action == action_resize:
w = self.ddialog.size().width()
h = self.ddialog.size().height()
res_w = QtWidgets.QInputDialog.getInt(self, _("Width"), _("Width:"), w, 100, 2000, 5)
if res_w[1]:
w = res_w[0]
res_h = QtWidgets.QInputDialog.getInt(self, _("Height"), _("Height:"), h, 80, 2000, 5)
if res_h[1]:
h = res_h[0]
self.ddialog.resize(w, h)
def get_codes_and_categories(self):
""" Called from init, delete category/code, event_filter. """
self.codes, self.categories = self.app.get_codes_categories()
def get_files(self, ids=None):
""" Get AV files and exclude those with bad links.
Fill list widget with file names.
param:
ids : list of Integer ids to restrict files """
if ids is None:
ids = []
bad_links = self.app.check_bad_file_links()
bl_sql = ""
for bl in bad_links:
bl_sql += f",{bl['id']}"
if len(bl_sql) > 0:
bl_sql = f" and id not in ({bl_sql[1:]}) "
self.files = []
cur = self.app.conn.cursor()
sql = "select name, id, ifnull(memo,''), owner, date, mediapath, av_text_id from source where "
sql += "substr(mediapath,1,6) in ('/audio','/video', 'audio:', 'video:') " + bl_sql + " "
if ids:
str_ids = list(map(str, ids))
sql += " and id in (" + ",".join(str_ids) + ")"
sql += " order by name"
cur.execute(sql)
result = cur.fetchall()
self.files = []
keys = 'name', 'id', 'memo', 'owner', 'date', 'mediapath', 'av_text_id'
for row in result:
self.files.append(dict(zip(keys, row)))
self.ui.listWidget.clear()
for f in self.files:
item = QtWidgets.QListWidgetItem(f['name'])
item.setToolTip(f['memo'])
self.ui.listWidget.addItem(item)
self.clear_file()
def get_files_from_attributes(self):
""" Select files based on attribute selections.
Attribute results are a dictionary of:
first item is a Boolean AND or OR list item
Followed by each attribute list item
"""
# Clear ui
self.ui.pushButton_file_attributes.setToolTip(_("Attributes"))
ui = DialogSelectAttributeParameters(self.app)
ui.fill_parameters(self.attributes)
temp_attributes = deepcopy(self.attributes)
self.attributes = []
ok = ui.exec()
if not ok:
self.attributes = temp_attributes
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag-outline'))
self.ui.pushButton_file_attributes.setToolTip(_("Attributes"))
if self.attributes:
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag'))
return
self.attributes = ui.parameters
if len(self.attributes) == 1:
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag-outline'))
self.ui.pushButton_file_attributes.setToolTip(_("Attributes"))
self.get_files()
return
if not ui.result_file_ids:
Message(self.app, _("Nothing found") + " " * 20, _("No matching files found")).exec()
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag-outline'))
self.ui.pushButton_file_attributes.setToolTip(_("Attributes"))
return
self.ui.pushButton_file_attributes.setIcon(qta.icon('mdi6.tag'))
self.ui.pushButton_file_attributes.setToolTip(ui.tooltip_msg)
self.get_files(ui.result_file_ids)
def show_important_coded(self):
""" Show codes flagged as important.
Hide the remaining coded text and segments. """
if self.media is None:
return
self.important = not self.important
if self.important:
self.ui.pushButton_important.setToolTip(_("Showing important codings"))
self.ui.pushButton_important.setIcon(qta.icon('mdi6.star'))
else:
self.ui.pushButton_important.setToolTip(_("Show codings flagged important"))
self.ui.pushButton_important.setIcon(qta.icon('mdi6.star-outline'))
self.get_coded_text_update_eventfilter_tooltips()
# Draw coded segments in scene
scaler = self.scene_width / self.media.get_duration()
self.scene.clear()
for s in self.segments:
if not self.important:
self.scene.addItem(SegmentGraphicsItem(self.app, s, scaler, self))
if self.important and s['important'] == 1:
self.scene.addItem(SegmentGraphicsItem(self.app, s, scaler, self))
# Set the scene to the top
self.ui.graphicsView.verticalScrollBar().setValue(0)
def assign_selected_text_to_code(self):
""" Assign selected text on left-click on code in tree. """
current = self.ui.treeWidget.currentItem()
if current.text(1)[0:3] == 'cat':
return
selected_text = self.ui.textEdit.textCursor().selectedText()
if len(selected_text) > 0:
self.mark()
def tree_traverse_for_non_expanded(self, item, non_expanded):
""" Find all categories and codes
Recurse through all child categories.
Called by: fill_tree
param:
item: a QTreeWidgetItem
list of non-expanded categories as String if catid:#
"""
child_count = item.childCount()
for i in range(child_count):
if "catid:" in item.child(i).text(1) and not item.child(i).isExpanded():
non_expanded.append(item.child(i).text(1))
self.tree_traverse_for_non_expanded(item.child(i), non_expanded)
def fill_tree(self):
""" Fill tree widget, tope level items are main categories and unlinked codes. """
non_expanded = []
self.tree_traverse_for_non_expanded(self.ui.treeWidget.invisibleRootItem(), non_expanded)
cats = deepcopy(self.categories)
codes = deepcopy(self.codes)
self.ui.treeWidget.clear()
self.ui.treeWidget.setColumnCount(4)
self.ui.treeWidget.setHeaderLabels([_("Name"), _("Id"), _("Memo"), _("Count")])
if not self.app.settings['showids']:
self.ui.treeWidget.setColumnHidden(1, True)
else:
self.ui.treeWidget.setColumnHidden(1, False)
self.ui.treeWidget.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
self.ui.treeWidget.header().setStretchLastSection(False)
# add top level categories
remove_list = []
for c in cats:
if c['supercatid'] is None:
memo = ""
if c['memo'] != "":
memo = "Memo"
top_item = QtWidgets.QTreeWidgetItem([c['name'], 'catid:' + str(c['catid']), memo])
top_item.setToolTip(0, c['name'])
if len(c['name']) > 52:
top_item.setText(0, c['name'][:25] + '..' + c['name'][-25:])
top_item.setToolTip(0, c['name'])
top_item.setToolTip(2, c['memo'])
self.ui.treeWidget.addTopLevelItem(top_item)
if 'catid:' + str(c['catid']) in non_expanded:
top_item.setExpanded(False)
else:
top_item.setExpanded(True)
remove_list.append(c)
for item in remove_list:
cats.remove(item)
''' Add child categories. Look at each unmatched category, iterate through tree
to add as child, then remove matched categories from the list. '''
count = 0
while len(cats) > 0 and count < 10000:
remove_list = []
# logger.debug("cats:" + str(cats))
for c in cats:
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count2 = 0
while item and count2 < 10000: # while there is an item in the list
if item.text(1) == 'catid:' + str(c['supercatid']):
memo = ""
if c['memo'] != "":
memo = "Memo"
child = QtWidgets.QTreeWidgetItem([c['name'], 'catid:' + str(c['catid']), memo])
child.setToolTip(0, c['name'])
if len(c['name']) > 52:
child.setText(0, c['name'][:25] + '..' + c['name'][-25:])
child.setToolTip(0, c['name'])
child.setToolTip(2, c['memo'])
item.addChild(child)
if 'catid:' + str(c['catid']) in non_expanded:
child.setExpanded(False)
else:
child.setExpanded(True)
remove_list.append(c)
it += 1
item = it.value()
count2 += 1
for item in remove_list:
cats.remove(item)
count += 1
# Add unlinked codes as top level items
remove_items = []
for c in codes:
if c['catid'] is None:
memo = ""
if c['memo'] != "":
memo = "Memo"
top_item = QtWidgets.QTreeWidgetItem([c['name'], 'cid:' + str(c['cid']), memo])
top_item.setToolTip(0, c['name'])
if len(c['name']) > 52:
top_item.setText(0, c['name'][:25] + '..' + c['name'][-25:])
top_item.setToolTip(0, c['name'])
top_item.setToolTip(2, c['memo'])
top_item.setBackground(0, QBrush(QColor(c['color']), Qt.BrushStyle.SolidPattern))
color = TextColor(c['color']).recommendation
top_item.setForeground(0, QBrush(QColor(color)))
top_item.setFlags(
Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsUserCheckable |
Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsDragEnabled)
self.ui.treeWidget.addTopLevelItem(top_item)
remove_items.append(c)
for item in remove_items:
codes.remove(item)
# Add codes as children
for c in codes:
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count = 0
while item and count < 10000:
if item.text(1) == 'catid:' + str(c['catid']):
memo = ""
if c['memo'] != "":
memo = _("Memo")
child = QtWidgets.QTreeWidgetItem([c['name'], 'cid:' + str(c['cid']), memo])
child.setBackground(0, QBrush(QColor(c['color']), Qt.BrushStyle.SolidPattern))
color = TextColor(c['color']).recommendation
child.setForeground(0, QBrush(QColor(color)))
child.setToolTip(0, c['name'])
if len(c['name']) > 52:
child.setText(0, c['name'][:25] + '..' + c['name'][-25:])
child.setToolTip(0, c['name'])
child.setToolTip(2, c['memo'])
child.setFlags(
Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsUserCheckable |
Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsDragEnabled)
item.addChild(child)
c['catid'] = -1 # make unmatchable
it += 1
item = it.value()
count += 1
# self.ui.treeWidget.expandAll()
self.ui.treeWidget.sortByColumn(0, QtCore.Qt.SortOrder.AscendingOrder)
self.fill_code_counts_in_tree()
def fill_code_counts_in_tree(self):
""" Count instances of each code for current coder and in the selected file.
Called by fill_tree """
if self.file_ is None:
return
cur = self.app.conn.cursor()
sql = "select count(cid) from code_av where cid=? and id=? and owner=?"
sql_txt = "select count(cid) from code_text where cid=? and fid=? and owner=?"
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count = 0
while item and count < 10000:
if item.text(1)[0:4] == "cid:":
cid = str(item.text(1)[4:])
cur.execute(sql, [cid, self.file_['id'], self.app.settings['codername']])
result_av = cur.fetchone()
result_txt = [0]
try: # May not have a text file
cur.execute(sql_txt, [cid, self.transcription[0], self.app.settings['codername']])
result_txt = cur.fetchone()
except Exception as e_:
print(e_)
logger.warning(str(e_))
result = result_av[0] + result_txt[0]
if result > 0:
item.setText(3, str(result))
else:
item.setText(3, "")
it += 1
item = it.value()
count += 1
def file_menu(self, position):
""" Context menu to select the next image alphabetically, or
to select the image that was most recently coded """
if len(self.files) == 0:
return
selected = self.ui.listWidget.currentItem()
file_ = None
for f in self.files:
if selected.text() == f['name']:
file_ = f
menu = QtWidgets.QMenu()
menu.setStyleSheet("QMenu {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
memo_action = menu.addAction(_("Open memo"))
action_next = menu.addAction(_("Next file"))
action_latest = menu.addAction(_("File with latest coding"))
action_show_files_like = menu.addAction(_("Show files like"))
action_show_case_files = menu.addAction(_("Show case files"))
action_show_by_attribute = menu.addAction(_("Show files by attributes"))
action = menu.exec(self.ui.listWidget.mapToGlobal(position))
if action is None:
return
if action == memo_action:
self.file_memo(file_)
if action == action_next:
if self.file_ is None:
self.file_ = self.files[0]
self.load_media()
self.load_segments()
self.fill_code_counts_in_tree()
return
for i in range(0, len(self.files) - 1):
if self.file_ == self.files[i]:
found = self.files[i + 1]
self.file_ = found
self.load_media()
self.load_segments()
self.fill_code_counts_in_tree()
return
if action == action_latest:
sql = "SELECT id FROM code_av where owner=? order by date desc limit 1"
cur = self.app.conn.cursor()
cur.execute(sql, [self.app.settings['codername'], ])
result = cur.fetchone()
if result is None:
return
for f in self.files:
if f['id'] == result[0]:
self.file_ = f
self.load_media()
self.load_segments()
self.fill_code_counts_in_tree()
return
if action == action_show_files_like:
self.show_files_like()
if action == action_show_case_files:
self.show_case_files()
if action == action_show_by_attribute:
self.get_files_from_attributes()
def show_case_files(self):
""" Show files of specified case.
Or show all files. """
cases = self.app.get_casenames()
cases.insert(0, {"name": _("Show all files"), "id": -1})
ui = DialogSelectItems(self.app, cases, _("Select case"), "single")
ok = ui.exec()
if not ok:
return
selection = ui.get_selected()
if not selection:
return
if selection['id'] == -1:
self.get_files()
return
cur = self.app.conn.cursor()
cur.execute('select fid from case_text where caseid=?', [selection['id']])
res = cur.fetchall()
file_ids = [r[0] for r in res]
'''for r in res:
file_ids.append(r[0])'''
self.get_files(file_ids)
def show_files_like(self):
""" Show files that contain specified filename text.
If blank, show all files. """
dialog = QtWidgets.QInputDialog(self)
dialog.setStyleSheet("* {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
dialog.setWindowTitle(_("Show files like"))
dialog.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowType.WindowContextHelpButtonHint)
dialog.setInputMode(QtWidgets.QInputDialog.InputMode.TextInput)
dialog.setLabelText(_("Show files containing the text. (Blank for all)"))
dialog.resize(200, 20)
ok = dialog.exec()
if not ok:
return
text_ = str(dialog.textValue())
if text_ == "":
self.get_files()
return
cur = self.app.conn.cursor()
cur.execute('select id from source where name like ?', ['%' + text_ + '%'])
res = cur.fetchall()
file_ids = [r[0] for r in res]
self.get_files(file_ids)
def active_file_memo(self):
""" Send active file to file_memo method.
Called by pushButton_document_memo for loaded text.
"""
self.file_memo(self.file_)
def file_memo(self, file_):
""" Open file memo to view or edit.
Called by pushButton_document_memo for loaded text, via active_file_memo
and through file_menu for any file.
param: file_ : Dictionary of file values
"""
if file_ is None:
return
ui = DialogMemo(self.app, _("Memo for file: ") + file_['name'], file_['memo'])
ui.exec()
memo = ui.memo
if memo == file_['memo']:
return
file_['memo'] = memo
cur = self.app.conn.cursor()
cur.execute("update source set memo=? where id=?", (memo, file_['id']))
self.app.conn.commit()
self.get_files()
self.app.delete_backup = False
def go_to_latest_coded_file(self):
""" Vertical splitter button activates this """
sql = "SELECT id FROM code_av where owner=? order by date desc limit 1"
cur = self.app.conn.cursor()
cur.execute(sql, [self.app.settings['codername'], ])
result = cur.fetchone()
if result is None:
return
for i, f in enumerate(self.files):
if f['id'] == result[0]:
self.file_ = f
self.ui.listWidget.setCurrentRow(i)
self.load_media()
break
def go_to_next_file(self):
""" Vertical splitter button activates this.
Assumes one or more items in the list widget.
As the coding dialog will not open with no AV files. """
if self.file_ is None:
self.file_ = self.files[0]
self.load_media()
self.ui.listWidget.setCurrentRow(0)
return
for i in range(0, len(self.files) - 1):
if self.file_ == self.files[i]:
found = self.files[i + 1]
self.file_ = found
self.ui.listWidget.setCurrentRow(i + 1)
self.load_media()
return
def file_selection_changed(self):
""" Listwidget file name selected so fill current file variable and load. """
if len(self.files) == 0:
return
itemname = self.ui.listWidget.currentItem().text()
for f in self.files:
if f['name'] == itemname:
self.file_ = f
self.load_media()
self.load_segments()
self.fill_code_counts_in_tree()
break
def load_segments(self):
""" Get coded segments for this file and for this coder.
Called from select_media. """
if self.file_ is None:
return
# 10 is assigned as an initial default for y values for segments
sql = "select avid, id, pos0, pos1, code_av.cid, ifnull(code_av.memo,''), code_av.date, "
sql += " code_av.owner, code_name.name, code_name.color, 10, code_av.important from code_av"
sql += " join code_name on code_name.cid=code_av.cid"
sql += " where id=? "
sql += " and code_av.owner=? "
sql += " order by pos0, pos1"
values = [self.file_['id'], self.app.settings['codername']]
cur = self.app.conn.cursor()
cur.execute(sql, values)
results = cur.fetchall()
keys = 'avid', 'id', 'pos0', 'pos1', 'cid', 'memo', 'date', 'owner', 'codename', 'color', 'y', 'important'
self.segments = []
for row in results:
self.segments.append(dict(zip(keys, row)))
# Fix overlapping segments by incrementing y values so segment is shown on a different line
for i in range(0, len(self.segments) - 1):
for j in range(i + 1, len(self.segments)):
if (self.segments[i]['pos0'] <= self.segments[j]['pos0'] <= self.segments[i]['pos1'] and
self.segments[i]['y'] == self.segments[j]['y']) or \
(self.segments[j]['pos0'] <= self.segments[i]['pos0'] <= self.segments[j]['pos1'] and
self.segments[i]['y'] == self.segments[j]['y']):
# to overcome the overlap, add to the y value of the i segment
self.segments[j]['y'] += 10
# Add seltext, the text link to the segment
sql = "select seltext from code_text where avid=?"
for s in self.segments:
# Use this name with label_segment context menu
s['name'] = f"{msecs_to_hours_mins_secs(s['pos0'])}-{msecs_to_hours_mins_secs(s['pos1'])}: {s['codename']}"
cur.execute(sql, [s['avid']])
res = cur.fetchall()
txt = ""
for r in res:
txt += str(r[0]) + "\n"
s['seltext'] = txt
# Draw coded segments in scene
scaler = self.scene_width / self.media.get_duration()
self.scene.clear()
for s in self.segments:
self.scene.addItem(SegmentGraphicsItem(self.app, s, scaler, self))
# Set te scene to the top
self.ui.graphicsView.verticalScrollBar().setValue(0)
def clear_file(self):
""" When AV file removed clear all details.
Called by null file with load_media, ManageFiles.delete, get_files """
self.stop()
self.media = None
self.file_ = None
self.setWindowTitle(_("Media coding"))
self.ui.pushButton_play.setEnabled(False)
self.ui.horizontalSlider.setEnabled(False)
self.ui.pushButton_coding.setEnabled(False)
self.ui.textEdit.clear()
self.transcription = None
# None on init
if self.ddialog is not None:
self.ddialog.hide()
def load_media(self):
""" Add media to media dialog. """
try:
if self.file_['mediapath'][0:6] in ('/audio', '/video'):
self.media = self.instance.media_new(self.app.project_path + self.file_['mediapath'])
if self.file_['mediapath'][0:6] in ('audio:', 'video:'):
self.media = self.instance.media_new(self.file_['mediapath'][6:])
except Exception as e_:
Message(self.app, _('Media not found'), str(e_) + "\n" + self.app.project_path + self.file_['mediapath'],
"warning").exec()
self.clear_file()
return
title = self.file_['name'].split('/')[-1]
self.ddialog.setWindowTitle(title)
self.setWindowTitle(_("Media coding: ") + title)
self.ui.pushButton_play.setEnabled(True)
self.ui.horizontalSlider.setEnabled(True)
self.ui.pushButton_coding.setEnabled(True)
if self.file_['mediapath'][0:6] not in ("/audio", "audio:"):
self.ddialog.show()
try:
w = int(self.app.settings['video_w'])
h = int(self.app.settings['video_h'])
if w < 100 or h < 80:
w = 100
h = 80
self.ddialog.resize(w, h)
except KeyError:
self.ddialog.resize(500, 400)
else:
self.ddialog.hide()
# Clear comboBox tracks options and reload when playing/pausing
self.ui.comboBox_tracks.clear()
# Put the media in the media player
self.mediaplayer.set_media(self.media)
# Parse the metadata of the file
self.media.parse()
self.mediaplayer.video_set_mouse_input(False)
self.mediaplayer.video_set_key_input(False)
# The media player has to be connected to the QFrame (otherwise the
# video would be displayed in it's own window). This is platform
# specific, so we must give the ID of the QFrame (or similar object) to
# vlc. Different platforms have different functions for this
if platform.system() == "Linux": # for Linux using the X Server
# self.mediaplayer.set_xwindow(int(self.ui.frame.winId()))
self.mediaplayer.set_xwindow(int(self.ddialog.winId()))
elif platform.system() == "Windows": # for Windows
self.mediaplayer.set_hwnd(int(self.ddialog.winId()))
elif platform.system() == "Darwin": # for MacOS
self.mediaplayer.set_nsobject(int(self.ddialog.winId()))
msecs = self.media.get_duration()
self.media_duration_text = " / " + msecs_to_hours_mins_secs(msecs)
self.ui.label_time.setText("0.00" + self.media_duration_text)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(100)
self.timer.timeout.connect(self.update_ui)
# Need this for helping set the slider on user sliding before play begins
# Also need to determine how many tracks available
self.mediaplayer.play()
self.mediaplayer.audio_set_volume(0)
time.sleep(0.2)
# print( self.mediaplayer.audio_get_track_count()) # > 0
tracks = self.mediaplayer.audio_get_track_description()
good_tracks = [] # note where track [0] == -1 is a disabled track
for track in tracks:
if track[0] >= 0:
good_tracks.append(track)
if len(good_tracks) < 2:
self.ui.comboBox_tracks.setEnabled(False)
self.mediaplayer.pause()
self.mediaplayer.audio_set_volume(100)
# Get the transcription text
self.transcription = None
cur = self.app.conn.cursor()
if self.file_['av_text_id'] is not None:
cur.execute("select id, fulltext, name from source where id=?", [self.file_['av_text_id']])
self.transcription = cur.fetchone()
if self.transcription is None:
# Create or re-link to the transcription text
# Check if an existing matching text entry name is present, despite no linkage to the av source
name = self.file_['name'] + ".txt"
name2 = self.file_['name'] + ".transcribed"
cur.execute("select id from source where name=? or name=?", [name, name2])
existing_name_res = cur.fetchone()
tr_id = None
if existing_name_res is not None:
cur.execute("update source set av_text_id=? where id=?", [existing_name_res[0], self.file_['id']])
self.app.conn.commit()
tr_id = existing_name_res[0]
if existing_name_res is None:
# Create a blank transcription file
entry = {'name': self.file_['name'] + ".txt", 'id': -1, 'fulltext': "", 'mediapath': None, 'memo': "",
'owner': self.app.settings['codername'],
'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
cur.execute("insert into source(name,fulltext,mediapath,memo,owner,date) values(?,?,?,?,?,?)",
(entry['name'], entry['fulltext'], entry['mediapath'], entry['memo'], entry['owner'],
entry['date']))
self.app.conn.commit()
cur.execute("select last_insert_rowid()")
tr_id = cur.fetchone()[0]
# Create link from av entry to existing or new text entry
self.file_['av_text_id'] = tr_id
cur.execute("update source set av_text_id=? where id=?", [tr_id, self.file_['id']])
self.app.conn.commit()
cur.execute("select id, fulltext, name from source where id=?", [tr_id])
self.transcription = cur.fetchone()
'''print("transcription", self.transcription)
if self.transcription is None:
print("tr_id", tr_id)'''
self.ui.textEdit.setText(self.transcription[1])
self.ui.textEdit.ensureCursorVisible()
self.get_timestamps_from_transcription()
# Get text annotations
cur = self.app.conn.cursor()
cur.execute(
"select anid, fid, pos0, pos1, ifnull(memo,''), owner, date from annotation where owner=? and fid=?",
[self.app.settings['codername'], self.transcription[0]])
result = cur.fetchall()
keys = 'anid', 'fid', 'pos0', 'pos1', 'memo', 'owner', 'date'
for row in result:
self.annotations.append(dict(zip(keys, row)))
self.get_coded_text_update_eventfilter_tooltips()
def get_coded_text_update_eventfilter_tooltips(self):
""" Called by load_media, update_dialog_codes_and_categories,
Segment_Graphics_Item.link_text_to_segment.
"""
if self.transcription is None:
return
# Get code text for this file and for this coder
values = [self.transcription[0], self.app.settings['codername']]
cur = self.app.conn.cursor()
self.code_text = []
# seltext length, longest first, so overlapping shorter text is superimposed.
sql = "select code_text.cid, code_text.fid, seltext, code_text.pos0, code_text.pos1, "
sql += "code_text.owner, code_text.date, ifnull(code_text.memo,''), code_text.avid,code_av.pos0, code_av.pos1, "
sql += "code_text.important, code_text.ctid "
sql += "from code_text left join code_av on code_text.avid = code_av.avid "
sql += " where code_text.fid=? and code_text.owner=? order by length(seltext) desc"
cur.execute(sql, values)
code_results = cur.fetchall()
keys = 'cid', 'fid', 'seltext', 'pos0', 'pos1', 'owner', 'date', 'memo', 'avid', 'av_pos0', 'av_pos1', \
'important', 'ctid'