-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathWaveformViewRewrite.py
994 lines (921 loc) · 54 KB
/
WaveformViewRewrite.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
#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# generated by wxGlade 0.3.5.1 on Thu Apr 21 12:10:56 2005
# Papagayo-NG, a lip-sync tool for use with several different animation suites
# Original Copyright (C) 2005 Mike Clifton
# Contact information at http://www.lostmarble.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
import time
import PySide2.QtWidgets as QtWidgets
import numpy as np
from PySide2 import QtGui
from LipsyncDoc import *
# from utilities import Worker, WorkerSignals
def normalize(x):
x = np.asarray(x)
return ((x - x.min()) / (np.ptp(x))) * 0.8
font = QtGui.QFont("Swiss", 6)
# default_sample_width = 2
# default_samples_per_frame = 4
default_sample_width = 4
default_samples_per_frame = 2
class SceneWithDrag(QtWidgets.QGraphicsScene):
def dragEnterEvent(self, e):
e.acceptProposedAction()
def dropEvent(self, e):
# find item at these coordinates
item = self.itemAt(e.scenePos(), QtGui.QTransform())
if item:
if item.setAcceptDrops:
# pass on event to item at the coordinates
item.dropEvent(e)
try:
item.dropEvent(e)
except RuntimeError:
pass # This will suppress a Runtime Error generated when dropping into a widget with no MyProxy
def dragMoveEvent(self, e):
e.acceptProposedAction()
class MovableButton(QtWidgets.QPushButton):
def __init__(self, lipsync_object, wfv_parent, phoneme_offset=None):
super(MovableButton, self).__init__(lipsync_object.text, None)
ini_path = os.path.join(utilities.get_app_data_path(), "settings.ini")
self.settings = QtCore.QSettings(ini_path, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False) # File only, not registry or or.
self.title = lipsync_object.text
self.node = lipsync_object
self.phoneme_offset = phoneme_offset
self.style = None
self.is_resizing = False
self.is_moving = False
self.resize_origin = 0 # 0 = left 1 = right
self.hot_spot = 0
self.wfv_parent = wfv_parent
self.setToolTip(lipsync_object.text)
self.create_and_set_style()
self.set_tags(self.node.tags)
self.setMinimumWidth(self.convert_to_pixels(1))
self.fit_text_to_size()
def text_size(self):
font_metrics = QtGui.QFontMetrics(self.font())
return font_metrics.horizontalAdvance(self.title)
def text_fits_in_button(self):
if not self.is_phoneme():
return self.text_size() < self.convert_to_pixels(
self.node.get_frame_size()) + self.convert_to_pixels(0.5)
else:
return self.text_size() < self.convert_to_pixels(
self.node.get_frame_size()) - self.convert_to_pixels(0.5)
def fit_text_to_size(self):
self.title = self.node.text
while not self.text_fits_in_button():
if len(self.title) > 1:
self.title = self.title[:-1]
else:
break
self.setText(self.title)
def get_handle_width(self):
resize_handle_width = 1.5
return int(min(self.wfv_parent.frame_width * resize_handle_width,
self.convert_to_pixels(self.node.get_frame_size()) / 4))
def create_and_set_style(self):
if not self.style:
if self.is_phrase():
self.style = "QPushButton {{color: #000000; background-color:{0};".format(
QtGui.QColor(self.settings.value("/Graphics/{}".format("phrase_fill_color"),
utilities.original_colors["phrase_fill_color"])).name())
self.style += "border-color: {0};".format(
QtGui.QColor(self.settings.value("/Graphics/{}".format("phrase_line_color"),
utilities.original_colors["phrase_line_color"])).name())
self.style += "border-style: solid solid solid solid; border-width: 1px {0}px}};".format(
str(self.get_handle_width()))
elif self.is_word():
self.style = "QPushButton {{color: #000000; background-color:{0};".format(
QtGui.QColor(self.settings.value("/Graphics/{}".format("word_fill_color"),
utilities.original_colors["word_fill_color"])).name())
self.style += "border-color: {0};".format(
QtGui.QColor(self.settings.value("/Graphics/{}".format("word_line_color"),
utilities.original_colors["word_line_color"])).name())
self.style += "border-style: solid solid solid solid; border-width: 1px {0}px}};".format(
str(self.get_handle_width()))
elif self.is_phoneme():
self.style = "QPushButton {{color: #000000; background-color:{0};".format(
QtGui.QColor(
self.settings.value("/Graphics/{}".format("phoneme_fill_color"),
utilities.original_colors["phoneme_fill_color"])).name())
self.style += "border:1px solid {0};}};".format(
QtGui.QColor(
self.settings.value("/Graphics/{}".format("phoneme_line_color"),
utilities.original_colors["phoneme_line_color"])).name())
self.setStyleSheet(self.style)
def is_phoneme(self):
return self.node.object_type == "phoneme"
def is_word(self):
return self.node.object_type == "word"
def is_phrase(self):
return self.node.object_type == "phrase"
def object_type(self):
return self.node.object_type
def after_reposition(self):
self.setGeometry(self.convert_to_pixels(self.node.start_frame), self.y(),
self.convert_to_pixels(self.node.get_frame_size()), self.height())
replaced = re.sub('(border-width: \dpx) \d+px', r'\1 {}px'.format(str(self.get_handle_width())),
self.styleSheet())
self.setStyleSheet(replaced)
self.update()
def convert_to_pixels(self, frame_pos):
return frame_pos * self.wfv_parent.frame_width
def convert_to_frames(self, pixel_pos):
return pixel_pos / self.wfv_parent.frame_width
def mouseMoveEvent(self, event):
if not self.wfv_parent.doc.sound.is_playing():
if event.buttons() == QtCore.Qt.LeftButton:
if not self.is_phoneme():
if (self.x() + event.x() >= self.convert_to_pixels(
self.node.end_frame) - self.get_handle_width()):
self.is_resizing = True
self.resize_origin = 1
if (self.x() + event.x() <= self.x() + self.get_handle_width()):
self.is_resizing = True
self.resize_origin = 0
else:
self.is_resizing = False
self.is_moving = True
else:
self.is_moving = True
if self.is_resizing and not self.is_moving:
self.wfv_parent.doc.dirty = True
if self.resize_origin == 1: # start resize from right side
if self.convert_to_frames(
event.x() + self.x()) >= self.node.start_frame + self.node.get_min_size():
if self.convert_to_frames(event.x() + self.x()) <= self.node.get_right_max():
self.node.end_frame = math.ceil(self.convert_to_frames(event.x() + self.x()))
self.wfv_parent.doc.dirty = True
self.resize(self.convert_to_pixels(self.node.end_frame) -
self.convert_to_pixels(self.node.start_frame), self.height())
elif self.resize_origin == 0: # start resize from left side
if self.convert_to_frames(event.x() + self.x()) < self.node.end_frame:
if self.convert_to_frames(event.x() + self.x()) >= self.node.get_left_max():
self.node.start_frame = math.floor(self.convert_to_frames(event.x() + self.x()))
if self.node.get_frame_size() < self.node.get_min_size():
self.node.start_frame = self.node.end_frame - self.node.get_min_size()
new_length = self.convert_to_pixels(self.node.end_frame) - self.convert_to_pixels(
self.node.start_frame)
self.resize(new_length, self.height())
self.move(self.convert_to_pixels(self.node.start_frame), self.y())
self.after_reposition()
else:
self.is_moving = True
mime_data = QtCore.QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mime_data)
drag.setHotSpot(event.pos() - self.rect().topLeft())
self.hot_spot = drag.hotSpot().x()
# PyQt5 and PySide use different function names here, likely a Qt4 vs Qt5 problem.
try:
exec("dropAction = drag.exec(QtCore.Qt.MoveAction)")
except (SyntaxError, AttributeError):
dropAction = drag.start(QtCore.Qt.MoveAction)
def mousePressEvent(self, event):
if not self.wfv_parent.doc.sound.is_playing():
if event.button() == QtCore.Qt.RightButton and self.is_word():
# manually enter the pronunciation for this word
list_of_new_phonemes = []
prev_phoneme_list = ""
for p in self.node.children:
prev_phoneme_list += " " + p.text
return_value = show_pronunciation_dialog(self, self.wfv_parent.doc.parent.phonemeset.set,
self.node.text, prev_text=prev_phoneme_list)
if return_value == -1:
pass
elif not return_value:
pass
else:
list_of_new_phonemes = return_value
if list_of_new_phonemes:
if list_of_new_phonemes != prev_phoneme_list.split():
for proxy in self.wfv_parent.items():
if isinstance(proxy, QtWidgets.QGraphicsProxyWidget):
for old_node in self.node.children:
if proxy.widget() == old_node.move_button:
self.wfv_parent.scene().removeItem(proxy)
self.node.children = []
font_metrics = QtGui.QFontMetrics(font)
text_width, text_height = font_metrics.width("Ojyg"), font_metrics.height() + 6
for phoneme_count, p in enumerate(list_of_new_phonemes):
phoneme = LipSyncObject(object_type="phoneme", parent=self.node)
phoneme.text = p
phoneme.start_frame = phoneme.end_frame = self.node.start_frame + phoneme_count
temp_button = MovableButton(phoneme, self.wfv_parent, phoneme_count % 2)
phoneme.move_button = temp_button
temp_scene_widget = self.wfv_parent.scene().addWidget(temp_button)
temp_rect = QtCore.QRect(phoneme.start_frame * self.wfv_parent.frame_width,
int(self.wfv_parent.height() -
(self.wfv_parent.horizontalScrollBar().height() * 1.5) -
(text_height + (text_height * (phoneme_count % 2)))),
self.wfv_parent.frame_width, text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.wfv_parent.doc.dirty = True
def mouseDoubleClickEvent(self, event):
if not self.wfv_parent.doc.sound.is_playing() and not self.is_phoneme():
start = self.node.start_frame / self.wfv_parent.doc.fps
length = (self.node.end_frame - self.node.start_frame) / self.wfv_parent.doc.fps
self.wfv_parent.doc.sound.play_segment(start, length)
old_cur_frame = 0
start_time = 0
self.wfv_parent.temp_play_marker.setVisible(True)
self.wfv_parent.main_window.action_stop.setEnabled(True)
self.wfv_parent.main_window.action_play.setEnabled(False)
while self.wfv_parent.doc.sound.is_playing():
QtCore.QCoreApplication.processEvents()
cur_frame = int(self.wfv_parent.doc.sound.current_time() * self.wfv_parent.doc.fps)
if old_cur_frame != cur_frame:
old_cur_frame = cur_frame
self.wfv_parent.main_window.mouth_view.set_frame(old_cur_frame)
self.wfv_parent.set_frame(old_cur_frame)
try:
fps = 1.0 / (time.time() - start_time)
except ZeroDivisionError:
fps = 60
self.wfv_parent.main_window.statusbar.showMessage(
"Frame: {:d} FPS: {:d}".format((cur_frame + 1), int(fps)))
self.wfv_parent.scroll_position = self.wfv_parent.horizontalScrollBar().value()
start_time = time.time()
self.wfv_parent.update()
self.wfv_parent.temp_play_marker.setVisible(False)
self.wfv_parent.main_window.action_stop.setEnabled(False)
self.wfv_parent.main_window.action_play.setEnabled(True)
self.wfv_parent.main_window.statusbar.showMessage("Stopped")
self.wfv_parent.main_window.waveform_view.horizontalScrollBar().setValue(
self.wfv_parent.main_window.waveform_view.scroll_position)
self.wfv_parent.main_window.waveform_view.update()
def mouseReleaseEvent(self, event):
if self.is_moving:
self.is_moving = False
print("end_move")
if self.is_resizing:
self.reposition_descendants2(True)
self.is_resizing = False
if self.is_phoneme():
self.wfv_parent.main_window.mouth_view.set_phoneme_picture(self.node.text)
def set_tags(self, new_taglist):
self.node.tags = new_taglist
self.setToolTip("".join("{}\n".format(entry) for entry in self.node.tags)[:-1])
# Change the border-style or something like that depending on whether there are tags or not
if len(self.node.tags) > 0:
if "solid" in self.styleSheet():
self.setStyleSheet(self.styleSheet().replace("solid solid solid solid", "dashed solid dashed solid"))
else:
if "dashed" in self.styleSheet():
self.setStyleSheet(self.styleSheet().replace("dashed solid dashed solid", "solid solid solid solid"))
def reposition_descendants(self, did_resize=False, x_diff=0):
self.node.reposition_descendants(did_resize, x_diff)
self.wfv_parent.doc.dirty = True
def reposition_descendants2(self, did_resize=False, x_diff=0):
self.node.reposition_descendants2(did_resize, x_diff)
def reposition_to_left(self):
self.node.reposition_to_left()
self.after_reposition()
self.wfv_parent.doc.dirty = True
def __del__(self):
try:
self.deleteLater()
except RuntimeError:
pass
class WaveformView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(WaveformView, self).__init__(parent)
self.setScene(SceneWithDrag(self))
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.setViewportUpdateMode(QtWidgets.QGraphicsView.NoViewportUpdate)
self.setAcceptDrops(True)
self.setMouseTracking(True)
self.translator = utilities.ApplicationTranslator()
ini_path = os.path.join(utilities.get_app_data_path(), "settings.ini")
self.settings = QtCore.QSettings(ini_path, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False) # File only, not registry or or.
# Other initialization
self.main_window = None
for widget in QtWidgets.QApplication.instance().topLevelWidgets():
if isinstance(widget, QtWidgets.QMainWindow):
self.main_window = widget
self.doc = None
self.currently_selected_object = None
self.is_scrubbing = False
self.cur_frame = 0
self.old_frame = 0
self.default_sample_width = default_sample_width
self.default_samples_per_frame = default_samples_per_frame
self.sample_width = self.default_sample_width
self.samples_per_frame = self.default_samples_per_frame
self.samples_per_sec = int(self.settings.value("LastFPS", 24)) * self.samples_per_frame
self.frame_width = self.sample_width * self.samples_per_frame
self.phrase_bottom = 16
self.word_bottom = 32
self.phoneme_top = 128
self.waveform_polygon = None
self.wv_height = 1
self.temp_phrase = None
self.temp_word = None
self.temp_phoneme = None
self.temp_button = None
self.draw_play_marker = False
self.num_samples = 0
self.list_of_lines = []
self.amp = []
self.temp_play_marker = None
self.scroll_position = 0
self.first_update = True
self.node = None
self.did_resize = None
self.threadpool = QtCore.QThreadPool.globalInstance()
self.scene().setSceneRect(0, 0, self.width(), self.height())
self.resize_timer = QtCore.QTimer(self)
self.resize_timer.setSingleShot(True)
self.connect(self.resize_timer, QtCore.SIGNAL("timeout()"), self.resize_finished)
def dropEvent(self, event):
print("DragLeave") # Strangely no dragLeaveEvent fires but a dropEvent instead...
if event.mimeData().hasUrls():
# event.accept()
for url in event.mimeData().urls():
if sys.platform == "darwin":
from Foundation import NSURL
fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
self.main_window.lip_sync_frame.open(fname)
else:
fname = str(url.toLocalFile())
self.main_window.lip_sync_frame.open(fname)
return True
else:
if event.source():
event.source().is_moving = False
event.accept()
def dragEnterEvent(self, e):
print("DragEnter!")
e.accept()
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
possible_item = self.itemAt(event.pos())
if type(possible_item) == QtWidgets.QGraphicsPolygonItem:
possible_item = None
if not possible_item:
if self.currently_selected_object:
try:
new_style = self.currently_selected_object.styleSheet()
if "2px" in new_style:
new_style = new_style.replace("2px", "1px")
else:
pass
self.currently_selected_object.setStyleSheet(new_style)
except RuntimeError:
pass # The real object was deleted, instead of carefully tracking we simply do this
self.currently_selected_object = None
self.main_window.list_of_tags.clear()
self.main_window.tag_list_group.setEnabled(False)
self.main_window.tag_list_group.setTitle(self.translator.translate("WaveformView", "Selected Object Tags"))
self.main_window.parent_tags.clear()
self.main_window.parent_tags.setEnabled(False)
self.is_scrubbing = True
else:
self.main_window.tag_list_group.setEnabled(True)
if self.currently_selected_object:
try:
new_style = self.currently_selected_object.styleSheet()
if "2px" in new_style:
new_style = new_style.replace("2px", "1px")
else:
pass
self.currently_selected_object.setStyleSheet(new_style)
except RuntimeError:
pass # The real object was deleted, instead of carefully tracking we simply do this
self.currently_selected_object = possible_item.widget()
new_style = self.currently_selected_object.styleSheet()
if "1px" in new_style:
new_style = new_style.replace("1px", "2px")
else:
pass
self.currently_selected_object.setStyleSheet(new_style)
self.main_window.list_of_tags.clear()
self.main_window.list_of_tags.addItems(self.currently_selected_object.node.tags)
title_part_two = self.currently_selected_object.node.text
if len(self.currently_selected_object.node.text) > 40:
title_part_two = self.currently_selected_object.node.text[0:40] + "..."
new_title = self.currently_selected_object.object_type().title() + ": " + title_part_two
self.main_window.tag_list_group.setTitle(new_title)
self.main_window.parent_tags.clear()
self.main_window.parent_tags.setEnabled(False)
if self.currently_selected_object.object_type() == "phoneme":
parent_word = self.currently_selected_object.node.get_parent()
parent_phrase = parent_word.get_parent()
word_tags = parent_word.tags
phrase_tags = parent_phrase.tags
if word_tags or phrase_tags:
self.main_window.parent_tags.setEnabled(True)
if phrase_tags:
list_of_phrase_tags = []
for tag in phrase_tags:
new_tag = QtWidgets.QTreeWidgetItem([tag])
list_of_phrase_tags.append(new_tag)
phrase_tree = QtWidgets.QTreeWidgetItem([self.translator.translate("WaveformView", "Phrase: ") + parent_phrase.text])
phrase_tree.addChildren(list_of_phrase_tags)
self.main_window.parent_tags.addTopLevelItem(phrase_tree)
phrase_tree.setExpanded(True)
if word_tags:
list_of_word_tags = []
for tag in word_tags:
new_tag = QtWidgets.QTreeWidgetItem([tag])
list_of_word_tags.append(new_tag)
word_tree = QtWidgets.QTreeWidgetItem([self.translator.translate("WaveformView", "Word: ") + parent_word.text])
word_tree.addChildren(list_of_word_tags)
self.main_window.parent_tags.addTopLevelItem(word_tree)
word_tree.setExpanded(True)
elif self.currently_selected_object.object_type() == "word":
parent_phrase = self.currently_selected_object.node.get_parent()
parent_tags = parent_phrase.tags
list_of_tags = []
if parent_tags:
self.main_window.parent_tags.setEnabled(True)
for tag in parent_tags:
new_tag = QtWidgets.QTreeWidgetItem([tag])
list_of_tags.append(new_tag)
phrase_tree = QtWidgets.QTreeWidgetItem([self.translator.translate("WaveformView", "Phrase: ") + parent_phrase.text])
phrase_tree.addChildren(list_of_tags)
self.main_window.parent_tags.addTopLevelItem(phrase_tree)
phrase_tree.setExpanded(True)
else:
self.main_window.parent_tags.setEnabled(False)
event.accept()
super(WaveformView, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if self.is_scrubbing:
self.is_scrubbing = False
self.doc.sound.stop()
self.temp_play_marker.setVisible(False)
self.main_window.mouth_view.set_frame(0)
super(WaveformView, self).mouseReleaseEvent(event)
def mouseMoveEvent(self, event):
if self.is_scrubbing:
mouse_scene_pos = self.mapToScene(event.pos()).x()
if not self.doc.sound.is_playing():
start = round(mouse_scene_pos / self.frame_width) / self.doc.fps
length = self.frame_width / self.doc.fps
self.doc.sound.play_segment(start, length)
self.draw_play_marker = True
self.temp_play_marker.setVisible(True)
self.temp_play_marker.setPos(round(mouse_scene_pos / self.frame_width) * self.frame_width, 0)
self.main_window.mouth_view.set_frame(round(mouse_scene_pos / self.frame_width))
else:
super(WaveformView, self).mouseMoveEvent(event)
def dragMoveEvent(self, e):
if not self.doc.sound.is_playing():
if e.source():
position = e.pos()
if self.width() > self.sceneRect().width():
new_x = e.pos().x() + self.horizontalScrollBar().value() - \
((self.width() - self.sceneRect().width()) / 2) - e.source().hot_spot
else:
new_x = e.pos().x() + self.horizontalScrollBar().value() - e.source().hot_spot
dropped_widget = e.source()
if new_x >= dropped_widget.node.get_left_max() * self.frame_width:
if new_x + dropped_widget.width() <= dropped_widget.node.get_right_max() * self.frame_width:
x_diff = 0
dropped_widget.move(new_x, dropped_widget.y())
# after moving save the position and align to the grid based on that. Hacky but works!
if dropped_widget.is_phoneme():
x_diff = round(
dropped_widget.x() / self.frame_width) - dropped_widget.node.start_frame
dropped_widget.node.start_frame = round(new_x / self.frame_width)
dropped_widget.move(dropped_widget.node.start_frame * self.frame_width,
dropped_widget.y())
else:
x_diff = round(
dropped_widget.x() / self.frame_width) - dropped_widget.node.start_frame
dropped_widget.node.start_frame = round(dropped_widget.x() / self.frame_width)
dropped_widget.end_frame = round(
(dropped_widget.x() + dropped_widget.width()) / self.frame_width)
dropped_widget.move(dropped_widget.node.start_frame * self.frame_width,
dropped_widget.y())
# Move the children!
dropped_widget.reposition_descendants(False, x_diff)
self.doc.dirty = True
e.accept()
def set_frame(self, frame):
if self.temp_play_marker not in self.scene().items():
self.temp_play_marker = self.scene().addRect(0, 1, self.frame_width + 1, self.height(),
QtGui.QPen(QtGui.QColor(
self.settings.value(
"/Graphics/{}".format("playback_line_color"),
utilities.original_colors[
"playback_line_color"]))),
QtGui.QBrush(QtGui.QColor(
self.settings.value(
"/Graphics/{}".format("playback_fill_color"),
utilities.original_colors[
"playback_fill_color"])), QtCore.Qt.SolidPattern))
self.temp_play_marker.setZValue(1000)
self.temp_play_marker.setOpacity(0.5)
self.temp_play_marker.setVisible(True)
self.centerOn(self.temp_play_marker)
self.temp_play_marker.setPos(frame * self.frame_width, 0)
self.update()
self.scene().update()
def drawBackground(self, painter, rect):
background_brush = QtGui.QBrush(
QtGui.QColor(self.settings.value("/Graphics/{}".format("bg_fill_color"),
utilities.original_colors["bg_fill_color"])),
QtCore.Qt.SolidPattern)
painter.fillRect(rect, background_brush)
if self.doc is not None:
pen = QtGui.QPen(
QtGui.QColor(self.settings.value("/Graphics/{}".format("frame_color"),
utilities.original_colors["frame_color"])))
# pen.setWidth(5)
painter.setPen(pen)
painter.setFont(font)
first_sample = 0
last_sample = len(self.amp)
bg_height = self.height() + self.horizontalScrollBar().height()
half_client_height = bg_height / 2
font_metrics = QtGui.QFontMetrics(font)
text_width, top_border = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() * 2
x = first_sample * self.sample_width
frame = first_sample / self.samples_per_frame
fps = int(round(self.doc.fps))
sample = first_sample
self.list_of_lines = []
list_of_textmarkers = []
for i in range(int(first_sample), int(last_sample)):
if (i + 1) % self.samples_per_frame == 0:
frame_x = (frame + 1) * self.frame_width
if (self.frame_width > 2) or ((frame + 1) % fps == 0):
self.list_of_lines.append(QtCore.QLineF(frame_x, top_border, frame_x, bg_height))
# draw frame label
if (self.frame_width > 30) or ((int(frame) + 1) % 5 == 0):
self.list_of_lines.append(QtCore.QLineF(frame_x, 0, frame_x, top_border))
self.list_of_lines.append(QtCore.QLineF(frame_x + 1, 0, frame_x + 1, bg_height))
temp_rect = QtCore.QRectF(int(frame_x + 4), font_metrics.height() - 2, text_width, top_border)
# Positioning is a bit different in QT here
list_of_textmarkers.append((temp_rect, str(int(frame + 1))))
x += self.sample_width
sample += 1
if sample % self.samples_per_frame == 0:
frame += 1
painter.drawLines(self.list_of_lines)
for text_marker in list_of_textmarkers:
painter.drawText(text_marker[0], QtCore.Qt.AlignLeft, text_marker[1])
def start_create_waveform(self):
worker = utilities.Worker(self.create_waveform)
worker.signals.finished.connect(self.waveform_finished)
worker.signals.progress.connect(self.main_window.lip_sync_frame.status_bar_progress)
self.main_window.lip_sync_frame.status_progress.show()
available_height = int(self.height() / 2)
fitted_samples = self.amp * available_height
self.main_window.lip_sync_frame.status_progress.setMaximum(len(fitted_samples))
self.threadpool.start(worker)
self.threadpool.waitForDone()
def waveform_finished(self):
self.main_window.lip_sync_frame.status_progress.hide()
update_rect = self.scene().sceneRect()
update_rect.setHeight(self.size().height() - 1)
if self.doc:
update_rect.setWidth(self.waveform_polygon.polygon().boundingRect().width())
self.setSceneRect(update_rect)
self.scene().setSceneRect(update_rect)
# We need to at least update the Y Position of the Phonemes
font_metrics = QtGui.QFontMetrics(font)
text_width, top_border = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() * 2
text_width, text_height = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() + 6
top_border += 4
self.horizontalScrollBar().setValue(self.scroll_position)
try:
if self.temp_play_marker:
self.temp_play_marker.setRect(self.temp_play_marker.rect().x(), 1, self.frame_width + 1, self.height())
except RuntimeError:
pass # When changing a file we get a RuntimeError from QT because it deletes the temp_play_marker
self.waveform_polygon.resetTransform() # Change the transform back when resize is finished.
self.scene().update()
def create_waveform(self, progress_callback):
available_height = int(self.height() / 2)
fitted_samples = self.amp * available_height
offset = 0 # available_height / 2
temp_polygon = QtGui.QPolygonF()
for x, y in enumerate(fitted_samples):
progress_callback.emit((x / 2))
self.main_window.statusbar.showMessage(
self.translator.translate("WaveformView", "Preparing Waveform: {0}%").format(str(int(((x / 2) / len(fitted_samples)) * 100))))
temp_polygon.append(QtCore.QPointF(x * self.sample_width, available_height - y + offset))
if x < len(fitted_samples):
temp_polygon.append(QtCore.QPointF((x + 1) * self.sample_width, available_height - y + offset))
for x, y in enumerate(fitted_samples[::-1]):
progress_callback.emit((len(fitted_samples) / 2) + (x / 2))
self.main_window.statusbar.showMessage(
self.translator.translate("WaveformView", "Preparing Waveform: {0}%").format(str(int(((x / 2) / len(fitted_samples)) * 100) + 50)))
temp_polygon.append(QtCore.QPointF((len(fitted_samples) - x) * self.sample_width,
available_height + y + offset))
if x > 0:
temp_polygon.append(QtCore.QPointF((len(fitted_samples) - x - 1) * self.sample_width,
available_height + y + offset))
if self.waveform_polygon:
self.waveform_polygon.setPolygon(temp_polygon)
else:
self.waveform_polygon = self.scene().addPolygon(temp_polygon, QtGui.QColor(
self.settings.value("/Graphics/{}".format("wave_line_color"),
utilities.original_colors["wave_line_color"])),
QtGui.QColor(
self.settings.value(
"/Graphics/{}".format("wave_fill_color"),
utilities.original_colors["wave_fill_color"])))
self.waveform_polygon.setZValue(1)
self.main_window.statusbar.showMessage("Papagayo-NG")
def start_create_movbuttons(self):
if self.doc is not None:
worker = Worker(self.create_movbuttons)
worker.signals.finished.connect(self.movbuttons_finished)
worker.signals.progress.connect(self.main_window.lip_sync_frame.status_bar_progress)
self.main_window.lip_sync_frame.status_progress.show()
self.main_window.lip_sync_frame.status_progress.setMaximum(self.doc.current_voice.num_children)
self.threadpool.start(worker)
self.threadpool.waitForDone()
def movbuttons_finished(self):
self.main_window.lip_sync_frame.status_progress.hide()
self.start_recalc()
def create_movbuttons(self, progress_callback):
if self.doc is not None:
self.setUpdatesEnabled(False)
font_metrics = QtGui.QFontMetrics(font)
text_width, top_border = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() * 2
text_width, text_height = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() + 6
top_border += 4
current_num = 0
for phrase in self.doc.current_voice.children:
if not phrase.move_button:
self.temp_button = MovableButton(phrase, self)
phrase.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.main_node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(phrase.start_frame * self.frame_width, top_border,
(phrase.end_frame - phrase.start_frame) * self.frame_width + 1,
text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_phrase = self.temp_button
else:
try:
phrase.move_button.setVisible(True)
except RuntimeError:
self.temp_button = MovableButton(phrase, self)
phrase.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.main_node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(phrase.start_frame * self.frame_width, top_border,
(phrase.end_frame - phrase.start_frame) * self.frame_width + 1,
text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_phrase = self.temp_button
word_count = 0
current_num += 1
progress_callback(current_num)
if self.doc.current_voice.num_children:
self.main_window.statusbar.showMessage(self.translator.translate("WaveformView", "Preparing Buttons: {0}%").format(
str(int((current_num / self.doc.current_voice.num_children) * 100))))
for word in phrase.children:
if not word.move_button:
self.temp_button = MovableButton(word, self)
word.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.temp_phrase.node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(word.start_frame * self.frame_width, top_border + 4 + text_height +
(text_height * (word_count % 2)), (word.end_frame - word.start_frame) *
self.frame_width + 1, text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_word = self.temp_button
else:
try:
word.move_button.setVisible(True)
except RuntimeError:
self.temp_button = MovableButton(word, self)
word.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.temp_phrase.node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(word.start_frame * self.frame_width, top_border + 4 + text_height +
(text_height * (word_count % 2)),
(word.end_frame - word.start_frame) *
self.frame_width + 1, text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_word = self.temp_button
word_count += 1
phoneme_count = 0
current_num += 1
progress_callback(current_num)
if self.doc.current_voice.num_children:
self.main_window.statusbar.showMessage(self.translator.translate("WaveformView", "Preparing Buttons: {0}%").format(
str(int((current_num / self.doc.current_voice.num_children) * 100))))
for phoneme in word.children:
if not phoneme.move_button:
self.temp_button = MovableButton(phoneme, self, phoneme_count % 2)
phoneme.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.temp_word.node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(phoneme.start_frame * self.frame_width, self.height() -
int(self.horizontalScrollBar().height() * 1.5) -
(text_height + (text_height * (phoneme_count % 2))),
self.frame_width, text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_phoneme = self.temp_button
else:
try:
phoneme.move_button.setVisible(True)
except RuntimeError:
self.temp_button = MovableButton(phoneme, self, phoneme_count % 2)
phoneme.move_button = self.temp_button
# self.temp_button.node = Node(self.temp_button, parent=self.temp_word.node)
temp_scene_widget = self.scene().addWidget(self.temp_button)
temp_rect = QtCore.QRect(phoneme.start_frame * self.frame_width, self.height() -
int(self.horizontalScrollBar().height() * 1.5) -
(text_height + (text_height * (phoneme_count % 2))),
self.frame_width, text_height)
temp_scene_widget.setGeometry(temp_rect)
temp_scene_widget.setZValue(99)
self.temp_phoneme = self.temp_button
phoneme_count += 1
current_num += 1
progress_callback(current_num)
if self.doc.current_voice.num_children:
self.main_window.statusbar.showMessage(
self.translator.translate("WaveformView", "Preparing Buttons: {0}%").format(
str(int((current_num / self.doc.current_voice.num_children) * 100))))
self.main_window.statusbar.showMessage("Papagayo-NG")
self.setUpdatesEnabled(True)
def start_recalc(self, wait_for_done=True):
worker = utilities.Worker(self.recalc_waveform)
worker.signals.finished.connect(self.recalc_finished)
worker.signals.progress.connect(self.main_window.lip_sync_frame.status_bar_progress)
self.main_window.lip_sync_frame.status_progress.show()
self.main_window.lip_sync_frame.status_progress.setMaximum(self.doc.sound.Duration())
self.threadpool.start(worker)
if wait_for_done:
self.threadpool.waitForDone()
def recalc_finished(self):
self.main_window.lip_sync_frame.status_progress.hide()
self.start_create_waveform()
def recalc_waveform(self, progress_callback):
duration = self.doc.sound.Duration()
time_pos = 0.0
sample_dur = 1.0 / self.samples_per_sec
max_amp = 0.0
self.amp = []
while time_pos < duration:
progress_callback.emit(time_pos)
self.num_samples += 1
amp = self.doc.sound.GetRMSAmplitude(time_pos, sample_dur)
self.amp.append(amp)
max_amp = max(max_amp, amp)
time_pos += sample_dur
self.amp = normalize(self.amp)
def set_document(self, document, force=False, clear_scene=False):
if document != self.doc or force:
if document != self.doc or clear_scene:
self.scene().clear()
self.waveform_polygon = None
self.doc = document
if (self.doc is not None) and (self.doc.sound is not None):
for l_object in self.doc.project_node.descendants:
try:
if l_object.move_button:
l_object.move_button.setVisible(False)
except RuntimeError:
pass
self.create_movbuttons(self.main_window.lip_sync_frame.status_bar_progress)
self.start_recalc()
if self.temp_play_marker not in self.scene().items():
self.temp_play_marker = self.scene().addRect(0, 1, self.frame_width + 1, self.height(),
QtGui.QPen(QtGui.QColor(
self.settings.value(
"/Graphics/{}".format("playback_line_color"),
utilities.original_colors[
"playback_line_color"]))),
QtGui.QBrush(QtGui.QColor(
self.settings.value(
"/Graphics/{}".format("playback_fill_color"),
utilities.original_colors[
"playback_fill_color"])),
QtCore.Qt.SolidPattern))
self.temp_play_marker.setZValue(1000)
self.temp_play_marker.setOpacity(0.5)
self.temp_play_marker.setVisible(False)
self.setViewportUpdateMode(QtWidgets.QGraphicsView.FullViewportUpdate)
self.scene().update()
def on_slider_change(self, value):
self.scroll_position = value
def wheelEvent(self, event):
self.scroll_position = self.horizontalScrollBar().value() + (event.delta() / 1.2)
self.horizontalScrollBar().setValue(self.scroll_position)
def resize_finished(self):
self.start_create_waveform()
def resizeEvent(self, event):
update_rect = self.scene().sceneRect()
width_factor = 1 # Only the height needs to change.
try:
height_factor = event.size().height() / event.oldSize().height()
except ZeroDivisionError:
height_factor = 1
update_rect.setHeight(event.size().height())
if self.doc:
update_rect.setWidth(self.waveform_polygon.polygon().boundingRect().width())
self.setSceneRect(update_rect)
self.scene().setSceneRect(update_rect)
origin_x, origin_y = 0, 0
height_factor = height_factor * self.waveform_polygon.transform().m22() # We need to add the factors
self.waveform_polygon.setTransform(QtGui.QTransform().translate(
origin_x, origin_y).scale(width_factor, height_factor).translate(-origin_x, -origin_y))
# We need to at least update the Y Position of the Phonemes
font_metrics = QtGui.QFontMetrics(font)
text_width, top_border = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() * 2
text_width, text_height = font_metrics.horizontalAdvance("Ojyg"), font_metrics.height() + 6
top_border += 4
for phoneme_node in self.doc.current_voice.leaves: # this should be all phonemes
if phoneme_node.move_button:
widget = phoneme_node.move_button
if widget.is_phoneme(): # shouldn't be needed, just to be sure
widget.setGeometry(widget.x(), self.height() - (self.horizontalScrollBar().height() * 1.5) -
(text_height + (text_height * widget.phoneme_offset)), self.frame_width + 5,
text_height)
self.resize_timer.start(150)
self.horizontalScrollBar().setValue(self.scroll_position)
if self.temp_play_marker:
self.temp_play_marker.setRect(self.temp_play_marker.rect().x(), 1, self.frame_width + 1, self.height())
def on_zoom_in(self, event=None):
if (self.doc is not None) and (self.samples_per_frame < 16):
self.samples_per_frame *= 2
self.samples_per_sec = self.doc.fps * self.samples_per_frame
self.frame_width = self.sample_width * self.samples_per_frame
for node in self.doc.current_voice.descendants:
node.move_button.after_reposition()
node.move_button.fit_text_to_size()
self.start_recalc()
if self.temp_play_marker:
self.temp_play_marker.setRect(self.temp_play_marker.rect().x(), 1, self.frame_width + 1, self.height())
self.scene().setSceneRect(self.scene().sceneRect().x(), self.scene().sceneRect().y(),
self.sceneRect().width() * 2, self.scene().sceneRect().height())
self.setSceneRect(self.scene().sceneRect())
self.scroll_position *= 2
self.horizontalScrollBar().setValue(self.scroll_position)
self.start_create_waveform()
def on_zoom_out(self, event=None):
if (self.doc is not None) and (self.samples_per_frame > 1):
self.samples_per_frame /= 2
self.samples_per_sec = self.doc.fps * self.samples_per_frame
self.frame_width = self.sample_width * self.samples_per_frame
for node in self.doc.current_voice.descendants:
node.move_button.after_reposition()
node.move_button.fit_text_to_size()
self.start_recalc()
if self.temp_play_marker:
self.temp_play_marker.setRect(self.temp_play_marker.rect().x(), 1, self.frame_width + 1, self.height())
self.scene().setSceneRect(self.scene().sceneRect().x(), self.scene().sceneRect().y(),
self.scene().sceneRect().width() / 2, self.scene().sceneRect().height())
self.setSceneRect(self.scene().sceneRect())
self.scroll_position /= 2
self.horizontalScrollBar().setValue(self.scroll_position)
self.start_create_waveform()
def on_zoom_reset(self, event=None):
if self.doc is not None:
if self.samples_per_frame != self.default_samples_per_frame:
self.scroll_position /= (self.samples_per_frame / self.default_samples_per_frame)
factor = (self.samples_per_frame / self.default_samples_per_frame)
self.sample_width = self.default_sample_width
self.samples_per_frame = self.default_samples_per_frame
self.samples_per_sec = self.doc.fps * self.samples_per_frame
self.frame_width = self.sample_width * self.samples_per_frame
for node in self.doc.current_voice.descendants:
node.move_button.after_reposition()
node.move_button.fit_text_to_size()
self.start_recalc()
if self.temp_play_marker:
self.temp_play_marker.setRect(self.temp_play_marker.rect().x(), 1, self.frame_width + 1,
self.height())
self.scene().setSceneRect(self.scene().sceneRect().x(), self.scene().sceneRect().y(),
self.scene().sceneRect().width() / factor, self.scene().sceneRect().height())
self.setSceneRect(self.scene().sceneRect())
self.horizontalScrollBar().setValue(self.scroll_position)
self.start_create_waveform()
# end of class WaveformView