-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1642 lines (1366 loc) · 64.9 KB
/
main.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
"""
VoiceControlled-BackgroundChanger - Utility Module
Author: Official J-Wise (@daniel4_kodua)
Copyright (c) 2024 Official J-Wise
Licensed under MIT License
GitHub: https://github.com/officialjwise/VoiceControlled-BackgroundChanger
This application provides real-time background replacement, AR effects, and voice control
capabilities for video calls and content creation.
Copyright (c) 2024 Official J-Wise
Licensed under the MIT License (see LICENSE file for details)
THIS CODE IS PROVIDED AS-IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
"""
__author__ = "Official J-Wise"
__copyright__ = "Copyright (c) 2024 Official J-Wise"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Official J-Wise"
__email__ = "[email protected]"
__status__ = "Production"
########################################################################################
# #
# NOTICE: This code is the intellectual property of Official J-Wise #
# While this is an open-source project, proper attribution is required when using #
# or modifying this code. #
# #
########################################################################################
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QVBoxLayout,
QPushButton, QWidget, QHBoxLayout, QComboBox,
QStatusBar, QScrollArea, QGridLayout, QSlider,
QFrame, QSpinBox, QSizePolicy, QTabWidget, QProgressBar)
from PyQt5.QtGui import QImage, QPixmap, QPalette, QColor, QPainter
from PyQt5.QtCore import QTimer, Qt, QSize, pyqtSignal, QThread
from scipy.io import wavfile
import sys
import cv2
import numpy as np
import mediapipe as mp
import pyaudio
from datetime import datetime
import os
import time
import speech_recognition as sr
import threading
import wave
import pyaudio
class BackgroundPreviewWidget(QWidget):
def __init__(self, image_path, parent=None):
super().__init__(parent)
self.setFixedSize(160, 90) # 16:9 aspect ratio
self.image_path = image_path
self.selected = False
self.scroll_area = parent # Store reference to scroll area
try:
# Handle both file paths and numpy arrays
if isinstance(image_path, str):
self.image = cv2.imread(image_path)
if self.image is not None:
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
else:
# Handle numpy array input
self.image = image_path.copy()
if self.image.shape[2] == 3: # BGR to RGB
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
# Resize image if it exists
if self.image is not None:
self.image = cv2.resize(self.image, (160, 90))
except Exception as e:
print(f"Preview widget initialization error: {e}")
self.image = None
def paintEvent(self, event):
if self.image is None:
return
painter = QPainter(self)
height, width, channel = self.image.shape
bytes_per_line = 3 * width
qt_image = QImage(self.image.data, width, height, bytes_per_line, QImage.Format_RGB888)
painter.drawImage(self.rect(), qt_image)
# Draw border if selected
if self.selected:
painter.setPen(Qt.blue)
painter.drawRect(0, 0, self.width() - 1, self.height() - 1)
def mousePressEvent(self, event):
if self.scroll_area and hasattr(self.scroll_area, 'select_background'):
self.scroll_area.select_background(self)
class BackgroundPreviewScrollArea(QScrollArea):
backgroundSelected = pyqtSignal(int) # Add signal
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent
self.setWidgetResizable(True)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.setMinimumHeight(110)
self.setMaximumHeight(110)
# Container widget
container = QWidget()
self.layout = QHBoxLayout(container)
self.layout.setSpacing(10)
self.layout.setAlignment(Qt.AlignLeft)
self.setWidget(container)
self.previews = []
self.selected_preview = None
def add_preview(self, image_path):
try:
preview = BackgroundPreviewWidget(image_path, self) # Pass self as parent
self.layout.addWidget(preview)
self.previews.append(preview)
return preview
except Exception as e:
print(f"Error adding preview: {e}")
return None
def select_background(self, preview):
try:
if self.selected_preview:
self.selected_preview.selected = False
self.selected_preview.update()
preview.selected = True
preview.update()
self.selected_preview = preview
# Notify main window
if preview in self.previews and self.main_window:
index = self.previews.index(preview)
if hasattr(self.main_window, 'background_selected'):
self.main_window.background_selected(index)
else:
print("Main window does not have background_selected method")
except Exception as e:
print(f"Error selecting background: {e}")
class EffectsWidget(QFrame):
def __init__(self, parent=None):
super().__init__(parent)
self.setFrameStyle(QFrame.Panel | QFrame.Raised)
layout = QVBoxLayout(self)
# Blur control
blur_layout = QHBoxLayout()
self.blur_slider = QSlider(Qt.Horizontal)
self.blur_slider.setRange(1, 99)
self.blur_slider.setValue(21)
self.blur_slider.setTickPosition(QSlider.TicksBelow)
self.blur_slider.setTickInterval(10)
blur_layout.addWidget(QLabel("Blur:"))
blur_layout.addWidget(self.blur_slider)
# Segmentation threshold control
threshold_layout = QHBoxLayout()
self.threshold_slider = QSlider(Qt.Horizontal)
self.threshold_slider.setRange(1, 99)
self.threshold_slider.setValue(60)
self.threshold_slider.setTickPosition(QSlider.TicksBelow)
self.threshold_slider.setTickInterval(10)
threshold_layout.addWidget(QLabel("Threshold:"))
threshold_layout.addWidget(self.threshold_slider)
# AR size control
ar_size_layout = QHBoxLayout()
self.ar_size_spin = QSpinBox()
self.ar_size_spin.setRange(50, 200)
self.ar_size_spin.setValue(100)
self.ar_size_spin.setSuffix("%")
ar_size_layout.addWidget(QLabel("AR Size:"))
ar_size_layout.addWidget(self.ar_size_spin)
# Add all controls to main layout
layout.addLayout(blur_layout)
layout.addLayout(threshold_layout)
layout.addLayout(ar_size_layout)
class VirtualBackgroundApp(QMainWindow):
def __init__(self):
super().__init__()
try:
self.init_variables()
self.init_processing_tools()
self.init_camera()
self.load_resources()
self.initUI()
self.setup_audio_visualization()
self.setup_voice_commands()
self.setup_video_processing()
except Exception as e:
print(f"Initialization error: {e}")
raise
def initUI(self):
"""Initialize the user interface"""
try:
self.setWindowTitle("Enhanced Virtual Background App")
self.setGeometry(100, 100, 1280, 900)
# Main widget and layout
main_widget = QWidget()
self.setCentralWidget(main_widget)
layout = QVBoxLayout(main_widget)
# Video display
self.setup_video_display(layout)
# Background preview
self.setup_preview_area(layout)
# Controls
self.setup_controls(layout)
# Status bar
self.setup_status_bar()
print("UI initialized successfully")
except Exception as e:
print(f"UI initialization error: {e}")
raise
def init_video_background(self):
"""Initialize video background"""
try:
if self.video_backgrounds:
# Close existing video if any
if hasattr(self, 'current_video') and self.current_video is not None:
self.current_video.release()
# Open new video
video_path = self.video_backgrounds[self.current_video_index]
self.current_video = cv2.VideoCapture(video_path)
if not self.current_video.isOpened():
print(f"Failed to open video: {video_path}")
else:
print(f"Successfully opened video: {video_path}")
except Exception as e:
print(f"Video initialization error: {e}")
def setup_audio_visualization(self):
"""Setup audio visualization with proper UI integration"""
try:
# Create container for audio visualization
audio_container = QWidget()
audio_layout = QVBoxLayout(audio_container)
# Create mic label
mic_label = QLabel("Mic")
mic_label.setAlignment(Qt.AlignCenter)
audio_layout.addWidget(mic_label)
# Create progress bar for audio level
self.audio_level = QProgressBar()
self.audio_level.setOrientation(Qt.Vertical)
self.audio_level.setRange(0, 100)
self.audio_level.setValue(0)
self.audio_level.setFixedWidth(20)
self.audio_level.setFixedHeight(100)
self.audio_level.setTextVisible(False)
self.audio_level.setStyleSheet("""
QProgressBar {
background-color: #2d2d2d;
border: 2px solid grey;
border-radius: 2px;
}
QProgressBar::chunk {
background-color: #4CAF50;
}
""")
audio_layout.addWidget(self.audio_level)
# Add stretch to keep widgets at top
audio_layout.addStretch()
# Add to the right side of the main window
if hasattr(self, 'right_controls'):
self.right_controls.addWidget(audio_container)
else:
print("Warning: right_controls not found")
# Fallback to main controls if available
if hasattr(self, 'controls_layout'):
self.controls_layout.addWidget(audio_container)
else:
print("Error: No suitable layout found for audio visualization")
# Setup audio monitoring in a separate thread
self.start_audio_monitoring()
print("Audio visualization setup complete")
except Exception as e:
print(f"Audio visualization setup error: {e}")
def start_audio_monitoring(self):
"""Start monitoring audio levels in a separate thread"""
try:
# Initialize PyAudio
self.audio = pyaudio.PyAudio()
# Setup stream
self.audio_stream = self.audio.open(
format=pyaudio.paFloat32,
channels=1,
rate=44100,
input=True,
frames_per_buffer=1024,
stream_callback=self.audio_callback
)
# Start the stream
self.audio_stream.start_stream()
print("Audio monitoring started")
except Exception as e:
print(f"Audio monitoring start error: {e}")
def audio_callback(self, in_data, frame_count, time_info, status):
"""Process audio data and update visualization"""
try:
# Convert audio data to numpy array
audio_data = np.frombuffer(in_data, dtype=np.float32)
# Calculate volume level (0-100)
volume = min(100, int(np.abs(audio_data).mean() * 400))
# Update progress bar
self.audio_level.setValue(volume)
return (in_data, pyaudio.paContinue)
except Exception as e:
print(f"Audio callback error: {e}")
return (in_data, pyaudio.paContinue)
def audio_callback(self, in_data, frame_count, time_info, status):
"""Handle audio data for visualization"""
try:
audio_data = np.frombuffer(in_data, dtype=np.float32)
level = int(np.abs(audio_data).mean() * 100)
self.audio_level.setValue(level)
return (in_data, pyaudio.paContinue)
except Exception as e:
print(f"Audio callback error: {e}")
return (in_data, pyaudio.paContinue)
def setup_voice_commands(self):
"""Setup voice command recognition"""
try:
self.recognizer = sr.Recognizer()
# Set sensitivity
self.recognizer.energy_threshold = 4000
self.recognizer.dynamic_energy_threshold = True
# Start voice command thread
self.voice_command_thread = threading.Thread(target=self.listen_for_commands, daemon=True)
self.voice_command_thread.start()
print("Voice commands initialized")
except Exception as e:
print(f"Voice command setup error: {e}")
def listen_for_commands(self):
"""Listen for voice commands"""
while True:
try:
with sr.Microphone() as source:
print("Listening for commands...")
self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
audio = self.recognizer.listen(source, timeout=1, phrase_time_limit=2)
try:
text = self.recognizer.recognize_google(audio).lower()
print(f"Heard: {text}")
if "next" in text:
if self.bg_combo.currentText() == "Video Backgrounds":
self.next_video_background()
else:
self.next_background()
print("Switching to next background")
elif "previous" in text or "back" in text:
if self.bg_combo.currentText() == "Video Backgrounds":
self.previous_video_background()
else:
self.previous_background()
print("Switching to previous background")
except sr.UnknownValueError:
print("Could not understand audio")
except sr.RequestError as e:
print(f"Could not request results; {e}")
except Exception as e:
print(f"Voice recognition error: {e}")
time.sleep(0.1)
def previous_background(self):
"""Switch to previous background"""
try:
if self.backgrounds:
self.current_bg_index = (self.current_bg_index - 1) % len(self.backgrounds)
except Exception as e:
print(f"Previous background error: {e}")
def previous_video_background(self):
"""Switch to previous video background"""
try:
if self.video_backgrounds:
self.current_video_index = (self.current_video_index - 1) % len(self.video_backgrounds)
self.init_video_background()
except Exception as e:
print(f"Previous video error: {e}")
def change_background_mode(self, index):
"""Handle background mode changes"""
try:
mode = self.bg_combo.currentText()
print(f"Changing to mode: {mode}")
if mode == "Video Backgrounds":
if self.video_backgrounds:
self.current_video_index = 0
self.init_video_background()
print("Initialized video background")
else:
print("No video backgrounds available")
else:
# Clean up video if switching away from video mode
if hasattr(self, 'current_video') and self.current_video is not None:
self.current_video.release()
self.current_video = None
self.statusBar.showMessage(f"Switched to {mode}")
except Exception as e:
print(f"Mode change error: {e}")
def setup_video_display(self, layout):
"""Set up the main video display area"""
try:
self.video_label = QLabel()
self.video_label.setAlignment(Qt.AlignCenter)
self.video_label.setMinimumSize(1280, 720)
layout.addWidget(self.video_label)
except Exception as e:
print(f"Video display setup error: {e}")
raise
def setup_preview_area(self, layout):
"""Set up the background preview area with separate sections"""
try:
# Create tab widget for different background types
self.preview_tabs = QTabWidget()
layout.addWidget(self.preview_tabs)
# Static backgrounds tab
self.static_preview_area = BackgroundPreviewScrollArea(self)
self.preview_tabs.addTab(self.static_preview_area, "Static Backgrounds")
# Video backgrounds tab
self.video_preview_area = BackgroundPreviewScrollArea(self)
self.preview_tabs.addTab(self.video_preview_area, "Video Backgrounds")
# Add static backgrounds to preview
for bg in self.backgrounds:
if bg is not None and isinstance(bg, np.ndarray):
try:
self.static_preview_area.add_preview(bg)
except Exception as e:
print(f"Error adding background preview: {e}")
# Add video previews
for video_path in self.video_backgrounds:
try:
# Get first frame of video for preview
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
if ret:
preview = self.video_preview_area.add_preview(frame)
preview.video_path = video_path # Store video path
cap.release()
except Exception as e:
print(f"Error adding video preview: {e}")
except Exception as e:
print(f"Preview area setup error: {e}")
raise
def setup_voice_commands(self):
"""Initialize voice command recognition"""
try:
self.recognizer = sr.Recognizer()
self.voice_thread = threading.Thread(target=self.listen_for_commands, daemon=True)
self.voice_thread.start()
print("Voice commands initialized")
except Exception as e:
print(f"Voice command setup error: {e}")
def listen_for_commands(self):
"""Listen for voice commands"""
while True:
try:
with sr.Microphone() as source:
print("Listening...")
self.recognizer.adjust_for_ambient_noise(source)
audio = self.recognizer.listen(source, timeout=1, phrase_time_limit=1)
text = self.recognizer.recognize_google(audio).lower()
print(f"Heard: {text}")
if "next" in text:
self.next_background()
print("Switching to next background")
except sr.WaitTimeoutError:
continue
except sr.UnknownValueError:
continue
except Exception as e:
print(f"Voice recognition error: {e}")
time.sleep(0.1)
def get_video_background(self, h, w):
"""Get current video background frame"""
try:
if not self.video_backgrounds:
return np.ones((h, w, 3), dtype=np.uint8) * [0, 120, 255]
# Initialize video if needed
if not hasattr(self, 'current_video') or self.current_video is None:
self.init_video_background()
if self.current_video is not None and self.current_video.isOpened():
ret, frame = self.current_video.read()
if not ret:
# Reset video to beginning
self.current_video.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = self.current_video.read()
if ret and frame is not None:
# Resize frame to match dimensions
frame = cv2.resize(frame, (w, h))
return frame
return np.ones((h, w, 3), dtype=np.uint8) * [0, 120, 255]
except Exception as e:
print(f"Video background error: {e}")
return np.ones((h, w, 3), dtype=np.uint8) * [0, 120, 255]
def change_background_mode(self, index):
"""Handle background mode changes"""
try:
# Clean up previous video
if hasattr(self, 'current_video') and self.current_video is not None:
self.current_video.release()
self.current_video = None
mode = self.bg_combo.currentText()
if mode == "Static Backgrounds":
self.preview_area.setVisible(True)
self.effects_widget.blur_slider.setEnabled(False)
# Show only static background previews
for i, preview in enumerate(self.preview_area.previews):
preview.setVisible(i < len(self.backgrounds))
elif mode == "Video Backgrounds":
self.preview_area.setVisible(True)
self.effects_widget.blur_slider.setEnabled(False)
# Show only video previews
for i, preview in enumerate(self.preview_area.previews):
preview.setVisible(i >= len(self.backgrounds))
if not hasattr(self, 'current_video_path'):
self.current_video_path = self.video_backgrounds[0] if self.video_backgrounds else None
elif mode == "Blur Background":
self.preview_area.setVisible(False)
self.effects_widget.blur_slider.setEnabled(True)
elif mode == "Portrait Mode":
self.preview_area.setVisible(False)
self.effects_widget.blur_slider.setEnabled(True)
self.statusBar.showMessage(f"Switched to {mode}")
except Exception as e:
print(f"Mode change error: {e}")
def background_selected(self, index):
"""Handle background selection"""
try:
mode = self.bg_combo.currentText()
if mode == "Static Backgrounds":
if 0 <= index < len(self.backgrounds):
self.current_bg_index = index
print(f"Selected static background {index}")
elif mode == "Video Backgrounds":
video_index = index - len(self.backgrounds)
if 0 <= video_index < len(self.video_backgrounds):
self.current_video_index = video_index
self.current_video_path = self.video_backgrounds[video_index]
print(f"Selected video background {video_index}")
except Exception as e:
print(f"Background selection error: {e}")
def setup_controls(self, layout):
"""Set up all control elements"""
try:
controls_container = QWidget()
controls_layout = QHBoxLayout(controls_container)
# Left controls
self.setup_left_controls(controls_layout)
# Effects widget
self.setup_effects_widget(controls_layout)
# Right controls
self.setup_right_controls(controls_layout)
layout.addWidget(controls_container)
except Exception as e:
print(f"Controls setup error: {e}")
raise
def setup_left_controls(self, parent_layout):
"""Set up left side controls"""
try:
left_controls = QVBoxLayout()
# Background type selection
self.bg_combo = QComboBox()
self.bg_combo.addItems(["Static Backgrounds", "Video Backgrounds", "Blur Background", "Portrait Mode"])
self.bg_combo.currentIndexChanged.connect(self.change_background_mode)
left_controls.addWidget(self.bg_combo)
# AR controls
self.ar_toggle = QPushButton("Toggle AR Effects")
self.ar_toggle.setCheckable(True)
self.ar_toggle.clicked.connect(self.toggle_ar_effects)
left_controls.addWidget(self.ar_toggle)
parent_layout.addLayout(left_controls)
except Exception as e:
print(f"Left controls setup error: {e}")
raise
def setup_effects_widget(self, parent_layout):
"""Set up effects controls"""
try:
self.effects_widget = EffectsWidget()
self.effects_widget.blur_slider.valueChanged.connect(self.update_blur)
self.effects_widget.threshold_slider.valueChanged.connect(self.update_threshold)
self.effects_widget.ar_size_spin.valueChanged.connect(self.update_ar_size)
parent_layout.addWidget(self.effects_widget)
except Exception as e:
print(f"Effects widget setup error: {e}")
raise
def setup_right_controls(self, parent_layout):
"""Set up right side controls"""
try:
right_controls = QVBoxLayout()
# Recording controls
self.record_btn = QPushButton("Start Recording")
self.record_btn.clicked.connect(self.toggle_recording)
right_controls.addWidget(self.record_btn)
# Screenshot button
self.screenshot_btn = QPushButton("Take Screenshot")
self.screenshot_btn.clicked.connect(self.take_screenshot)
right_controls.addWidget(self.screenshot_btn)
parent_layout.addLayout(right_controls)
except Exception as e:
print(f"Right controls setup error: {e}")
raise
def setup_status_bar(self):
"""Set up the status bar"""
try:
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)
self.statusBar.showMessage("Ready")
except Exception as e:
print(f"Status bar setup error: {e}")
raise
def setup_video_processing(self):
"""Set up video processing timer"""
try:
self.timer = QTimer()
self.timer.timeout.connect(self.update_frame)
self.timer.start(33) # ~30 FPS
print("Video processing setup complete")
except Exception as e:
print(f"Video processing setup error: {e}")
raise
def toggle_ar_effects(self):
"""Toggle AR effects on/off"""
try:
self.show_ar = not self.show_ar
self.ar_toggle.setChecked(self.show_ar)
self.statusBar.showMessage(f"AR Effects: {'On' if self.show_ar else 'Off'}")
except Exception as e:
print(f"AR toggle error: {e}")
def update_blur(self, value):
"""Update blur amount"""
try:
self.blur_amount = value
except Exception as e:
print(f"Blur update error: {e}")
def update_threshold(self, value):
"""Update segmentation threshold"""
try:
self.segmentation_threshold = value / 100.0
except Exception as e:
print(f"Threshold update error: {e}")
def update_ar_size(self, value):
"""Update AR prop size"""
try:
self.ar_scale_factor = value / 100.0
except Exception as e:
print(f"AR size update error: {e}")
def toggle_recording(self):
"""Toggle recording state"""
try:
if not self.is_recording:
self.start_recording()
else:
self.stop_recording()
except Exception as e:
print(f"Recording toggle error: {e}")
def take_screenshot(self):
"""Take and save screenshot"""
try:
if hasattr(self, 'video_label') and self.video_label.pixmap():
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"screenshot_{timestamp}.png"
filepath = os.path.join('screenshots', filename)
if self.video_label.pixmap().save(filepath):
self.statusBar.showMessage(f"Screenshot saved: {filename}")
else:
self.statusBar.showMessage("Failed to save screenshot")
except Exception as e:
print(f"Screenshot error: {e}")
self.statusBar.showMessage("Screenshot error occurred")
def setup_audio_visualization(self):
"""Setup audio level visualization"""
try:
# Create audio level indicator
self.audio_level = QProgressBar()
self.audio_level.setOrientation(Qt.Vertical)
self.audio_level.setRange(0, 100)
self.audio_level.setValue(0)
self.audio_level.setTextVisible(False)
self.audio_level.setFixedWidth(20)
# Add to UI
audio_container = QWidget()
audio_layout = QVBoxLayout(audio_container)
audio_layout.addWidget(QLabel("Mic"))
audio_layout.addWidget(self.audio_level)
self.controls_layout.addWidget(audio_container)
# Setup audio monitor
self.audio_thread = threading.Thread(target=self.monitor_audio_level, daemon=True)
self.audio_thread.start()
except Exception as e:
print(f"Audio visualization setup error: {e}")
def monitor_audio_level(self):
"""Monitor audio level for visualization"""
try:
with sr.Microphone() as source:
while True:
if hasattr(self, 'audio_level'):
# Get audio level
audio = self.recognizer.listen(source, timeout=0.1, phrase_time_limit=0.1)
level = np.abs(np.frombuffer(audio.get_raw_data(), np.int16)).mean()
normalized_level = min(100, int(level / 100))
self.audio_level.setValue(normalized_level)
time.sleep(0.1)
except Exception as e:
print(f"Audio monitoring error: {e}")
def start_recording(self):
"""Start recording with audio"""
try:
if not self.is_recording:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join('recordings', f"recording_{timestamp}.mp4")
# Initialize video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Try 'avc1' if this doesn't work
self.recording_data = cv2.VideoWriter(filename, fourcc, 30.0, (1280, 720))
# Initialize audio recording
self.audio_frames = []
self.audio_recording = True
# Start audio recording thread
self.audio_thread = threading.Thread(target=self.record_audio)
self.audio_thread.start()
self.is_recording = True
self.record_btn.setText("Stop Recording")
self.statusBar.showMessage("Recording started...")
except Exception as e:
print(f"Recording start error: {e}")
def record_audio(self):
"""Record audio"""
try:
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while self.audio_recording:
data = stream.read(CHUNK)
self.audio_frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
except Exception as e:
print(f"Audio recording error: {e}")
def stop_recording(self):
"""Stop recording and save"""
try:
if self.is_recording:
self.is_recording = False
self.audio_recording = False
if hasattr(self, 'audio_thread'):
self.audio_thread.join()
if self.recording_data:
self.recording_data.release()
# Save audio
if hasattr(self, 'audio_frames') and self.audio_frames:
audio_filename = os.path.join('recordings', 'temp_audio.wav')
wf = wave.open(audio_filename, 'wb')
wf.setnchannels(2)
wf.setsampwidth(pyaudio.PyAudio().get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(self.audio_frames))
wf.close()
# Combine audio and video
self.combine_audio_video()
self.record_btn.setText("Start Recording")
self.statusBar.showMessage("Recording saved")
except Exception as e:
print(f"Recording stop error: {e}")
def combine_audio_video(self):
"""Combine audio and video using ffmpeg"""
try:
import ffmpeg
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
input_video = ffmpeg.input(os.path.join('recordings', 'temp_video.mp4'))
input_audio = ffmpeg.input(os.path.join('recordings', 'temp_audio.wav'))
output_filename = os.path.join('recordings', f"final_recording_{timestamp}.mp4")
ffmpeg.output(input_video, input_audio, output_filename).run(overwrite_output=True)
# Clean up temporary files
os.remove(os.path.join('recordings', 'temp_video.mp4'))
os.remove(os.path.join('recordings', 'temp_audio.wav'))
except Exception as e:
print(f"Combine audio/video error: {e}")
def setup_speech_recognition(self):
"""Setup speech recognition"""
try:
self.recognizer = sr.Recognizer()
self.speech_thread = threading.Thread(target=self.listen_for_commands, daemon=True)
self.speech_thread.start()
print("Speech recognition initialized")
except Exception as e:
print(f"Speech recognition setup error: {e}")
def next_video_background(self):
"""Switch to next video background"""
try:
if self.video_backgrounds:
self.current_video_index = (self.current_video_index + 1) % len(self.video_backgrounds)
self.init_video_background()
print(f"Switched to video {self.current_video_index}")
except Exception as e:
print(f"Next video error: {e}")
def load_video_backgrounds(self):
"""Load and validate video backgrounds"""
try:
video_folder = "video_backgrounds"
for file in os.listdir(video_folder):
if file.lower().endswith(('.mp4', '.avi')):
video_path = os.path.join(video_folder, file)
# Test if video is readable
test_cap = cv2.VideoCapture(video_path)
if test_cap.isOpened():
self.video_backgrounds.append(video_path)
print(f"Successfully loaded video: {file}")
else:
print(f"Failed to load video: {file}")
test_cap.release()
print(f"Total videos loaded: {len(self.video_backgrounds)}")
except Exception as e:
print(f"Video loading error: {e}")
def listen_for_commands(self):
"""Listen for voice commands"""
while True:
try:
with sr.Microphone() as source:
print("Listening for commands...")
self.recognizer.adjust_for_ambient_noise(source)
audio = self.recognizer.listen(source)
text = self.recognizer.recognize_google(audio).lower()
print(f"Heard: {text}")
if "next" in text:
print("Executing next command...")
mode = self.bg_combo.currentText()
if mode == "Static Backgrounds":
self.next_background()
elif mode == "Video Backgrounds":
self.next_video_background()
except sr.RequestError as e:
print(f"Could not request results; {e}")
except sr.UnknownValueError:
print("Could not understand audio")
except Exception as e:
print(f"Speech recognition error: {e}")
time.sleep(0.1)
def record_frame(self, frame):
"""Record a single frame"""
try:
if self.recording_data:
self.recording_data.write(frame)
except Exception as e:
print(f"Frame recording error: {e}")
self.stop_recording()
def update_frame(self):
"""Process and update each video frame"""
if not self.cap.isOpened():