-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_gui.py
More file actions
2076 lines (1742 loc) · 92.1 KB
/
app_gui.py
File metadata and controls
2076 lines (1742 loc) · 92.1 KB
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
import os
import sys
import json
import glob
import asyncio
import requests
import proglog
# pyrefly: ignore [missing-import]
from PySide6.QtCore import Qt, QThread, Signal, QObject, QSize
# pyrefly: ignore [missing-import]
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QTabWidget, QVBoxLayout,
QHBoxLayout, QLabel, QLineEdit, QTextEdit, QPushButton,
QTableWidget, QTableWidgetItem, QSpinBox, QDoubleSpinBox,
QSlider, QComboBox, QFileDialog, QMessageBox, QProgressBar,
QHeaderView, QFrame, QSplitter, QGroupBox, QStackedWidget,
QDialog, QDialogButtonBox, QCheckBox
)
# pyrefly: ignore [missing-import]
from PySide6.QtGui import QIcon, QFont, QColor
import app_style
import ai_generator
# ==========================================
# 0. PREMIUM SCRIPT TEXT EDITOR DIALOG (MODAL)
# ==========================================
class ScriptEditDialog(QDialog):
def __init__(self, parent=None, title_text="Sunting Naskah Video", initial_text="", show_duration=True):
super().__init__(parent)
self.setWindowTitle(title_text)
self.resize(550, 350)
self.show_duration = show_duration
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(12)
title_lbl = QLabel(title_text)
title_lbl.setObjectName("section_title")
layout.addWidget(title_lbl)
self.text_edit = QTextEdit()
self.text_edit.setPlainText(initial_text)
self.text_edit.setPlaceholderText("Tulis naskah video Anda di sini...")
self.text_edit.setStyleSheet("font-size: 13px; line-height: 1.5; padding: 10px; background-color: #09090b;")
layout.addWidget(self.text_edit)
# Word counter label with optional estimated audio duration
self.word_lbl = QLabel()
self.word_lbl.setStyleSheet("color: #a1a1aa; font-size: 11px;")
self.text_edit.textChanged.connect(self.update_word_count)
self.update_word_count()
layout.addWidget(self.word_lbl)
# Dialog buttons
self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
# Style buttons inside button box
self.button_box.button(QDialogButtonBox.Ok).setText("Simpan")
self.button_box.button(QDialogButtonBox.Ok).setStyleSheet(
"background-color: #2563eb; border: 1px solid #3b82f6; color: #ffffff; font-weight: bold; padding: 6px 16px; border-radius: 6px;"
)
self.button_box.button(QDialogButtonBox.Cancel).setText("Batal")
self.button_box.button(QDialogButtonBox.Cancel).setStyleSheet(
"background-color: #18181b; border: 1px solid #27272a; color: #e4e4e7; padding: 6px 16px; border-radius: 6px;"
)
layout.addWidget(self.button_box)
def update_word_count(self):
txt = self.text_edit.toPlainText().strip()
words = len(txt.split()) if txt else 0
chars = len(txt)
if self.show_duration:
# 0.28 seconds per word at +20% speed on edge-tts
duration = words * 0.28
self.word_lbl.setText(f"📊 Panjang: {words} kata | {chars} karakter | Estimasi Durasi Audio: ~{duration:.1f} detik")
else:
self.word_lbl.setText(f"📊 Panjang: {words} kata | {chars} karakter")
def get_text(self):
return self.text_edit.toPlainText()
# ==========================================
# 0.5 MOVIEPY COOPERATIVE STOP LOGGER
# ==========================================
class MoviePyStopLogger(proglog.ProgressBarLogger):
def __init__(self, worker):
super().__init__()
self.worker = worker
def callback(self, *args, **kwargs):
if self.worker._is_killed:
raise RuntimeError("Rendering dihentikan oleh pengguna!")
def log(self, *args, **kwargs):
if self.worker._is_killed:
raise RuntimeError("Rendering dihentikan oleh pengguna!")
def update_bar(self, *args, **kwargs):
if self.worker._is_killed:
raise RuntimeError("Rendering dihentikan oleh pengguna!")
super().update_bar(*args, **kwargs)
# ==========================================
# 1. THREADED BACKGROUND RENDER WORKER
# ==========================================
class RenderWorker(QThread):
progress_signal = Signal(int, int) # Current index, Total
status_signal = Signal(str)
finished_signal = Signal(bool, str)
def __init__(self, scripts_data, rvc_params, layout_params, workspace_folders):
super().__init__()
self.scripts_data = scripts_data
self.rvc_params = rvc_params
self.layout_params = layout_params
self.workspace_folders = workspace_folders
self._is_killed = False
self._is_paused = False
def stop(self):
self._is_killed = True
def pause(self):
self._is_paused = True
def resume(self):
self._is_paused = False
def check_paused(self):
while self._is_paused:
if self._is_killed:
break
self.msleep(100)
def run(self):
try:
total_videos = len(self.scripts_data)
self.status_signal.emit(f"[INFO] Memulai rendering massal sebanyak {total_videos} video...")
# Dinamis load module batch_generator secara aman agar tidak mengunci thread
import batch_generator
# Sinkronisasi folder kerja dari setelan GUI
batch_generator.VIDEO_INPUT_DIR = self.workspace_folders.get("video_input", batch_generator.VIDEO_INPUT_DIR)
batch_generator.MUSIC_INPUT_DIR = self.workspace_folders.get("music_input", batch_generator.MUSIC_INPUT_DIR)
batch_generator.OUTPUT_DIR = self.workspace_folders.get("output", batch_generator.OUTPUT_DIR)
batch_generator.FONTS_DIR = self.workspace_folders.get("fonts", batch_generator.FONTS_DIR)
# Ambil musik latar yang terdeteksi
bgm_paths = glob.glob(os.path.join(batch_generator.MUSIC_INPUT_DIR, "*.mp3"))
for idx_num, config in enumerate(self.scripts_data):
# 1. Cooperative Stop / Pause check
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
self.check_paused()
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
idx = config["id"]
product_name = config["product"]
category = config["category"]
naskah = config["naskah"]
# Dinamis petakan nama subfolder video B-roll berdasarkan produk
if "perisa" in product_name.lower():
folder_name = "Perisa Cabai"
elif "poc" in product_name.lower():
folder_name = "POC Cabai"
else:
# Fallback jika nama kategori adalah nama subfolder
folder_name = category
self.progress_signal.emit(idx_num + 1, total_videos)
self.status_signal.emit(f"\n[VIDEO {idx_num+1}/{total_videos}] Produk: {product_name} | Kategori: {category}...")
# 1. Pindai video klip mentah untuk produk ini
product_video_dir = os.path.join(batch_generator.VIDEO_INPUT_DIR, folder_name)
# Fallback ke folder utama jika folder kategori spesifik kosong/tidak ditemukan
if not os.path.exists(product_video_dir):
product_video_dir = batch_generator.VIDEO_INPUT_DIR
product_video_paths = []
for ext in ["*.mp4", "*.mov", "*.avi", "*.mkv"]:
product_video_paths.extend(glob.glob(os.path.join(product_video_dir, ext)))
product_video_paths.extend(glob.glob(os.path.join(product_video_dir, ext.upper())))
if not product_video_paths:
self.status_signal.emit(f"[ERROR] Tidak ada file video B-roll di folder: '{product_video_dir}'!")
self.status_signal.emit(f"Melewati Video {idx}...")
continue
self.status_signal.emit(f" -> Terdeteksi {len(product_video_paths)} klip B-roll untuk {folder_name}.")
temp_audio = os.path.join(batch_generator.BASE_DIR, f"temp_vo_{idx}.wav")
temp_vtt = os.path.join(batch_generator.BASE_DIR, f"temp_sub_{idx}.vtt")
# Inisialisasi variabel untuk resource disposal di blok finally
vo_audio = None
bgm_audio = None
mixed_audio = None
compiled_video = None
subtitle_clips = []
watermark_clip = None
final_video = None
try:
# 2. Cooperative Stop / Pause check
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
self.check_paused()
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
# A. Buat Voiceover via RVC
self.status_signal.emit(" -> Menyintesis suara AI via edge-tts & RVC GPU...")
# Menggunakan parameter RVC kustom yang dikirimkan dari Tab GUI
original_rvc_model = batch_generator.RVC_MODEL_PATH
original_rvc_index = batch_generator.RVC_INDEX_PATH
original_pitch_shift = getattr(batch_generator, "RVC_PITCH_SHIFT", 6)
original_index_rate = getattr(batch_generator, "RVC_INDEX_RATE", 0.2)
if self.rvc_params.get("model_path"):
batch_generator.RVC_MODEL_PATH = self.rvc_params["model_path"]
if self.rvc_params.get("index_path"):
batch_generator.RVC_INDEX_PATH = self.rvc_params["index_path"]
if "f0up_key" in self.rvc_params:
batch_generator.RVC_PITCH_SHIFT = self.rvc_params["f0up_key"]
if "index_rate" in self.rvc_params:
batch_generator.RVC_INDEX_RATE = self.rvc_params["index_rate"]
asyncio.run(batch_generator.generate_voiceover_rvc(naskah, temp_audio, temp_vtt))
# Kembalikan model RVC bawaan setelah generasi audio
batch_generator.RVC_MODEL_PATH = original_rvc_model
batch_generator.RVC_INDEX_PATH = original_rvc_index
batch_generator.RVC_PITCH_SHIFT = original_pitch_shift
batch_generator.RVC_INDEX_RATE = original_index_rate
# 3. Cooperative Stop / Pause check
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
self.check_paused()
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
if not os.path.exists(temp_audio):
self.status_signal.emit(f"[ERROR] Generasi audio voiceover gagal untuk Video {idx}.")
continue
vo_audio = batch_generator.AudioFileClip(temp_audio)
target_duration = vo_audio.duration
self.status_signal.emit(f" -> Voiceover siap. Durasi: {target_duration:.2f} detik.")
# B. Assembly B-roll Video
self.status_signal.emit(" -> Menyusun klip B-roll dinamis (Anti-Duplikasi)...")
transition_type = self.layout_params.get("transition", "None")
limit_to_3s = self.layout_params.get("limit_to_3s", False)
compiled_video = batch_generator.buat_video_assembly(
target_duration,
product_video_paths,
transition_type=transition_type,
transition_duration=0.5,
limit_to_3s=limit_to_3s
)
# 4. Cooperative Stop / Pause check
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
self.check_paused()
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
# C. Subtitle Rendering (Custom Font, Size, Color, Position, and Stroke)
self.status_signal.emit(" -> Merender subtitle estetik kata-per-kata...")
raw_subs = batch_generator.parse_vtt(temp_vtt)
grouped_subs = batch_generator.kelompokkan_subtitle(raw_subs, max_words=2, max_duration=1.2)
# Modifikasi batch_generator fungsi buat_subtitle secara dinamis
original_font_path = batch_generator.dapatkan_font_path()
if self.layout_params.get("font_path"):
# Temporarily override font path
font_override = self.layout_params["font_path"]
def custom_font_path(): return font_override
batch_generator.dapatkan_font_path = custom_font_path
# Decode layout styling parameters
color_map = {
"Kuning Cerah": (255, 255, 0, 255),
"Putih Bersih": (255, 255, 255, 255),
"Hijau Neon": (57, 255, 20, 255),
"Cyan Elektrik": (0, 255, 255, 255)
}
text_color = color_map.get(self.layout_params.get("subtitle_color"), (255, 255, 0, 255))
size_val = self.layout_params.get("subtitle_size", 56)
font_size_scale = size_val / 1080.0
stroke_val = self.layout_params.get("subtitle_stroke", 6)
stroke_width_scale = stroke_val / float(size_val) if size_val > 0 else 0.0
vertical_position = self.layout_params.get("subtitle_pos", 74) / 100.0
subtitle_clips = batch_generator.buat_subtitle_overlay_clip(
grouped_subs,
batch_generator.OUTPUT_W,
batch_generator.OUTPUT_H,
font_size_scale=font_size_scale,
text_color=text_color,
stroke_width_scale=stroke_width_scale,
vertical_position=vertical_position
)
# Kembalikan fungsi font bawaan
def restore_font_path(): return original_font_path
batch_generator.dapatkan_font_path = restore_font_path
# D. Composite & Audio Mixing
self.status_signal.emit(" -> Melakukan compositing audio-visual & backsound...")
composite_layers = [compiled_video] + subtitle_clips
# PNG Logo Watermark overlay
watermark_path = self.layout_params.get("watermark_path")
if watermark_path and os.path.exists(watermark_path):
try:
from PIL import Image
import numpy as np
logo_img = Image.open(watermark_path).convert("RGBA")
logo_w, logo_h = logo_img.size
target_w = self.layout_params.get("watermark_size", 150)
target_h = int(logo_h * (target_w / logo_w))
logo_img = logo_img.resize((target_w, target_h), Image.Resampling.LANCZOS)
logo_rgba = np.array(logo_img)
logo_rgb = logo_rgba[:, :, :3]
opacity = self.layout_params.get("watermark_opacity", 0.7)
logo_alpha = ((logo_rgba[:, :, 3] / 255.0) * opacity).astype(np.float32)
watermark_clip = batch_generator.ImageClip(logo_rgb).with_mask(
batch_generator.ImageClip(logo_alpha).with_is_mask(True)
)
watermark_clip = watermark_clip.with_duration(target_duration)
watermark_clip = watermark_clip.with_position((batch_generator.OUTPUT_W - target_w - 50, 50))
composite_layers.append(watermark_clip)
self.status_signal.emit(" -> Menempelkan logo watermark kustom...")
except Exception as e:
self.status_signal.emit(f"[WARNING] Gagal menempelkan logo watermark: {str(e)}")
final_video = batch_generator.CompositeVideoClip(composite_layers)
if bgm_paths:
chosen_bgm = batch_generator.random.choice(bgm_paths)
bgm_audio = batch_generator.AudioFileClip(chosen_bgm)
if bgm_audio.duration < target_duration:
bgm_audio = bgm_audio.with_effects([batch_generator.AudioLoop(duration=target_duration)])
else:
bgm_audio = bgm_audio.subclipped(0, target_duration)
# Backsound volume dari parameter layout
bgm_volume = self.layout_params.get("bgm_volume", 0.08)
bgm_audio = bgm_audio.with_volume_scaled(bgm_volume)
mixed_audio = batch_generator.CompositeAudioClip([vo_audio.with_volume_scaled(1.0), bgm_audio])
else:
mixed_audio = vo_audio
final_video = final_video.with_audio(mixed_audio)
# E. Ekspor Video Final Dinamis
product_clean = product_name.replace(" ", "_")
cat_clean = category.replace(" ", "_")
output_path = os.path.join(batch_generator.OUTPUT_DIR, f"{product_clean}_{cat_clean}_{idx}.mp4")
self.status_signal.emit(f" -> Mulai menulis file MP4 ke: {output_path}...")
# 5. Cooperative Stop / Pause check right before export
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
self.check_paused()
if self._is_killed:
self.finished_signal.emit(False, "Rendering dihentikan oleh pengguna!")
return
final_video.write_videofile(
output_path,
fps=24,
codec="libx264",
audio_codec="aac",
threads=4,
logger=MoviePyStopLogger(self)
)
self.status_signal.emit(f"[SUCCESS] Video {idx} berhasil dirender!")
except Exception as loop_err:
self.status_signal.emit(f"[ERROR] Gagal merender Video {idx}: {str(loop_err)}")
raise loop_err
finally:
# MEMBERSIHKAN MEMORI SECARA TOTAL (Anti-Memory Leak & GC Force)
if vo_audio:
try: vo_audio.close()
except: pass
if bgm_audio:
try: bgm_audio.close()
except: pass
if mixed_audio and mixed_audio is not vo_audio:
try: mixed_audio.close()
except: pass
if compiled_video:
# Tutup semua raw VideoFileClips yang dibuka di buat_video_assembly
for raw_c in getattr(compiled_video, 'opened_raw_clips', []):
try: raw_c.close()
except: pass
try: compiled_video.close()
except: pass
for sub_clip in subtitle_clips:
try:
if sub_clip.mask:
sub_clip.mask.close()
sub_clip.close()
except: pass
if watermark_clip:
try:
if watermark_clip.mask:
watermark_clip.mask.close()
watermark_clip.close()
except: pass
if final_video:
try: final_video.close()
except: pass
# Bersihkan temporary files
for temp_file in [temp_audio, temp_vtt]:
if os.path.exists(temp_file):
try: os.remove(temp_file)
except: pass
# Paksa Garbage Collector membersihkan memori NumPy & PIL
import gc
gc.collect()
self.status_signal.emit(f"[SUCCESS] Video {idx} berhasil dirender!")
self.finished_signal.emit(True, "Seluruh rendering selesai!")
except Exception as e:
self.finished_signal.emit(False, str(e))
# ==========================================
# 2. MAIN APPLICATION GUI (PYSIDE6)
# ==========================================
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("AutoVideo-RVC: AI Automated Video Studio 🚀")
self.resize(1200, 800)
self.setStyleSheet(app_style.dapatkan_style_sheet())
# Inisialisasi folder default
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.video_input = os.path.join(self.base_dir, "video_input")
self.music_input = os.path.join(self.base_dir, "music_input")
self.fonts_dir = os.path.join(self.base_dir, "fonts")
self.output_dir = os.path.join(self.base_dir, "output")
self.rvc_dir = os.path.join(self.base_dir, "RVC")
# Load Workspace Profiles
self.profiles_file = os.path.join(self.base_dir, "workspace_profiles.json")
self.profiles_data = self.load_profiles()
# Override dengan setelan profil aktif
active_prof = self.profiles_data.get("active_profile", "Default")
prof = self.profiles_data["profiles"].get(active_prof, {})
self.video_input = prof.get("video_input", self.video_input)
self.music_input = prof.get("music_input", self.music_input)
self.fonts_dir = prof.get("fonts", self.fonts_dir)
self.output_dir = prof.get("output", self.output_dir)
self.scanned_models = []
self.scripts_list = [] # Menyimpan hasil naskah dinamis dari AI
self.ai_drafts_list = [] # Menyimpan draf hasil AI sebelum dimasukkan ke Script Manager
self.init_ui()
self.scan_workspace()
self.scan_local_rvc_models()
self.detect_ollama_local()
# Terapkan setelan profil lengkap setelah UI diinisialisasi
self.on_profile_changed()
def init_ui(self):
# Master Widget & Layout - Horizontal Split for Left Sidebar Layout
master_widget = QWidget()
self.setCentralWidget(master_widget)
master_layout = QHBoxLayout(master_widget)
master_layout.setContentsMargins(0, 0, 0, 0)
master_layout.setSpacing(0)
# ==========================================
# LEFT SIDEBAR NAVIGATION
# ==========================================
sidebar = QFrame()
sidebar.setObjectName("sidebar_frame")
sidebar.setFixedWidth(240)
sidebar_layout = QVBoxLayout(sidebar)
sidebar_layout.setContentsMargins(20, 24, 20, 24)
sidebar_layout.setSpacing(6)
# Logo Header (Mimicking premium design)
logo_container = QHBoxLayout()
logo_container.setSpacing(12)
logo_container.setContentsMargins(0, 0, 0, 24)
logo_icon = QLabel("AI")
logo_icon.setFixedSize(36, 36)
logo_icon.setAlignment(Qt.AlignCenter)
logo_icon.setStyleSheet(
"background-color: #2563eb; color: #ffffff; font-weight: 800; "
"font-size: 15px; border-radius: 8px;"
)
logo_text = QLabel("AI VIDEO\nCREATOR")
logo_text.setStyleSheet(
"color: #ffffff; font-weight: 700; font-size: 13px; line-height: 1.1;"
)
logo_container.addWidget(logo_icon)
logo_container.addWidget(logo_text)
logo_container.addStretch()
sidebar_layout.addLayout(logo_container)
# Navigation Items mapped to SVG icons
self.nav_buttons = []
nav_items = [
("Workspace", "folder.svg"),
("Script Manager", "document.svg"),
("AI Writer", "pen.svg"),
("RVC Settings", "mic.svg"),
("Layout Editor", "palette.svg"),
("RVC Trainer", "activity.svg"),
("Batch Renderer", "video.svg")
]
for idx, (name, icon_file) in enumerate(nav_items):
btn = QPushButton(" " + name)
btn.setIcon(QIcon(os.path.join(self.base_dir, "icons", icon_file)))
btn.setIconSize(QSize(16, 16))
btn.setCheckable(True)
btn.setAutoExclusive(True)
btn.setObjectName("sidebar_nav_btn")
btn.setCursor(Qt.PointingHandCursor)
# Connect click to switch tab
btn.clicked.connect(lambda checked=False, i=idx: self.switch_page(i))
sidebar_layout.addWidget(btn)
self.nav_buttons.append(btn)
sidebar_layout.addStretch()
# ==========================================
# RIGHT MAIN CONTENT AREA
# ==========================================
main_content = QWidget()
main_content_layout = QVBoxLayout(main_content)
main_content_layout.setContentsMargins(24, 24, 24, 24)
main_content_layout.setSpacing(16)
# 1. TOP HEADER (Premium Glass Title)
header_frame = QFrame()
header_frame.setObjectName("glass_card")
header_layout = QHBoxLayout(header_frame)
header_layout.setContentsMargins(20, 14, 20, 14)
title_layout = QVBoxLayout()
title_label = QLabel("AutoVideo-RVC Studio")
title_label.setObjectName("header_label")
sub_title = QLabel("Workspace Otomatisasi Video Marketing & AI Script Studio")
sub_title.setObjectName("sub_header_label")
title_layout.addWidget(title_label)
title_layout.addWidget(sub_title)
header_layout.addLayout(title_layout)
header_layout.addStretch()
# Workspace Profile Selector inside Header (Global Switcher)
profile_card = QFrame()
profile_card.setObjectName("glass_card")
profile_layout = QHBoxLayout(profile_card)
profile_layout.setContentsMargins(12, 6, 12, 6)
profile_layout.setSpacing(8)
lbl_prof = QLabel("Profile:")
lbl_prof.setStyleSheet("font-size: 10px; font-weight: bold; color: #8c8c9e;")
profile_layout.addWidget(lbl_prof)
self.profile_combo = QComboBox()
self.profile_combo.setMinimumWidth(160)
self.profile_combo.setStyleSheet("padding: 4px 8px; font-size: 12px;")
profile_layout.addWidget(self.profile_combo)
btn_new_profile = QPushButton("➕ New")
btn_new_profile.setStyleSheet("padding: 4px 8px; font-size: 12px;")
btn_new_profile.clicked.connect(self.create_new_profile)
profile_layout.addWidget(btn_new_profile)
btn_save_profile = QPushButton("💾 Save")
btn_save_profile.setStyleSheet(
"background-color: #064e3b; border: 1px solid #059669; color: #a7f3d0; "
"padding: 4px 8px; font-size: 12px; font-weight: bold;"
)
btn_save_profile.clicked.connect(self.save_current_profile_config)
profile_layout.addWidget(btn_save_profile)
btn_del_profile = QPushButton("🗑️ Delete")
btn_del_profile.setObjectName("danger_button")
btn_del_profile.setStyleSheet("padding: 4px 8px; font-size: 12px;")
btn_del_profile.clicked.connect(self.delete_profile)
profile_layout.addWidget(btn_del_profile)
header_layout.addWidget(profile_card)
header_layout.addSpacing(10)
# GPU Status Card
gpu_card = QFrame()
gpu_card.setObjectName("glass_card")
gpu_card_layout = QVBoxLayout(gpu_card)
gpu_card_layout.setContentsMargins(12, 6, 12, 6)
gpu_status_title = QLabel("CUDA GPU ACCELERATION")
gpu_status_title.setStyleSheet("font-size: 10px; font-weight: bold; color: #8c8c9e;")
# Cek ketersediaan RVC
import batch_generator
if batch_generator.RVC_ENABLED:
gpu_status_val = QLabel("✅ ACTIVE (NVIDIA RTX)")
gpu_status_val.setStyleSheet("font-weight: bold; color: #10b981;")
else:
gpu_status_val = QLabel("❌ INACTIVE (CPU FALLBACK)")
gpu_status_val.setStyleSheet("font-weight: bold; color: #ef4444;")
gpu_card_layout.addWidget(gpu_status_title)
gpu_card_layout.addWidget(gpu_status_val)
header_layout.addWidget(gpu_card)
main_content_layout.addWidget(header_frame)
# Stacked Pages Widget instead of QTabWidget
self.tabs = QStackedWidget()
main_content_layout.addWidget(self.tabs)
master_layout.addWidget(sidebar)
master_layout.addWidget(main_content)
# Inisialisasi masing-masing Tab
self.init_tab_workspace()
self.init_tab_script_manager()
self.init_tab_ai_generator()
self.init_tab_rvc_parameters()
self.init_tab_layout_editor()
self.init_tab_rvc_trainer()
self.init_tab_renderer()
# Populate and connect profile switcher signals globally!
self.populate_profiles()
self.profile_combo.currentIndexChanged.connect(self.on_profile_changed)
# Set default active page
self.switch_page(0)
def switch_page(self, index):
self.tabs.setCurrentIndex(index)
# Update active state style of buttons
for i, btn in enumerate(self.nav_buttons):
is_active = (i == index)
btn.setChecked(is_active)
btn.setProperty("active", is_active)
btn.style().unpolish(btn)
btn.style().polish(btn)
def load_profiles(self):
if os.path.exists(self.profiles_file):
try:
with open(self.profiles_file, "r") as f:
return json.load(f)
except:
pass
return {
"active_profile": "Default",
"profiles": {
"Default": {
"video_input": self.video_input,
"music_input": self.music_input,
"fonts": self.fonts_dir,
"output": self.output_dir
}
}
}
def save_profiles_to_disk(self):
try:
with open(self.profiles_file, "w") as f:
json.dump(self.profiles_data, f, indent=4)
except Exception as e:
print("Error saving workspace profiles:", str(e))
def populate_profiles(self):
self.profile_combo.blockSignals(True)
self.profile_combo.clear()
for name in self.profiles_data["profiles"].keys():
self.profile_combo.addItem(name)
active = self.profiles_data.get("active_profile", "Default")
if active in self.profiles_data["profiles"]:
self.profile_combo.setCurrentText(active)
self.profile_combo.blockSignals(False)
def on_profile_changed(self):
name = self.profile_combo.currentText() if hasattr(self, "profile_combo") else self.profiles_data.get("active_profile", "Default")
if not name or name not in self.profiles_data["profiles"]:
return
self.profiles_data["active_profile"] = name
prof = self.profiles_data["profiles"][name]
# Update Directory Inputs
if hasattr(self, "dir_inputs"):
if "video_input" in prof:
self.dir_inputs["video_input"].setText(prof["video_input"])
if "music_input" in prof:
self.dir_inputs["music_input"].setText(prof["music_input"])
if "fonts" in prof:
self.dir_inputs["fonts"].setText(prof["fonts"])
if "output" in prof:
self.dir_inputs["output"].setText(prof["output"])
# Update RVC settings if they were saved in the profile (with cross-slash normalization)
if "rvc_model" in prof and hasattr(self, "rvc_pth_combo"):
model_path = os.path.normpath(prof["rvc_model"])
found = False
for i in range(self.rvc_pth_combo.count()):
if os.path.normpath(self.rvc_pth_combo.itemText(i)) == model_path:
self.rvc_pth_combo.setCurrentIndex(i)
found = True
break
if not found and os.path.exists(model_path):
self.rvc_pth_combo.addItem(model_path)
self.rvc_pth_combo.setCurrentText(model_path)
if "rvc_index" in prof and hasattr(self, "rvc_index_combo"):
index_path = os.path.normpath(prof["rvc_index"])
found = False
for i in range(self.rvc_index_combo.count()):
if os.path.normpath(self.rvc_index_combo.itemText(i)) == index_path:
self.rvc_index_combo.setCurrentIndex(i)
found = True
break
if not found and os.path.exists(index_path):
self.rvc_index_combo.addItem(index_path)
self.rvc_index_combo.setCurrentText(index_path)
if "pitch_shift" in prof and hasattr(self, "pitch_slider"):
self.pitch_slider.setValue(prof["pitch_shift"])
if "index_rate" in prof and hasattr(self, "index_slider"):
self.index_slider.setValue(prof["index_rate"])
# Update Layout settings if they were saved in the profile
if "font_path" in prof and hasattr(self, "font_combo"):
self.font_combo.setCurrentText(prof["font_path"])
if "subtitle_color" in prof and hasattr(self, "subtitle_color_combo"):
self.subtitle_color_combo.setCurrentText(prof["subtitle_color"])
if "subtitle_size" in prof and hasattr(self, "subtitle_size_spin"):
self.subtitle_size_spin.setValue(prof["subtitle_size"])
if "subtitle_stroke" in prof and hasattr(self, "subtitle_stroke_spin"):
self.subtitle_stroke_spin.setValue(prof["subtitle_stroke"])
if "subtitle_pos" in prof and hasattr(self, "subtitle_pos_slider"):
self.subtitle_pos_slider.setValue(prof["subtitle_pos"])
if "watermark_path" in prof and hasattr(self, "watermark_input"):
self.watermark_input.setText(prof["watermark_path"])
if "watermark_opacity" in prof and hasattr(self, "opacity_slider"):
self.opacity_slider.setValue(prof["watermark_opacity"])
if "watermark_size" in prof and hasattr(self, "watermark_size_spin"):
self.watermark_size_spin.setValue(prof["watermark_size"])
if "bgm_volume" in prof and hasattr(self, "bgm_vol_spin"):
self.bgm_vol_spin.setValue(prof["bgm_volume"])
if "transition" in prof and hasattr(self, "transition_combo"):
self.transition_combo.setCurrentText(prof["transition"])
if "limit_to_3s" in prof and hasattr(self, "limit_to_3s_checkbox"):
self.limit_to_3s_checkbox.setChecked(prof["limit_to_3s"])
else:
if hasattr(self, "limit_to_3s_checkbox"):
self.limit_to_3s_checkbox.setChecked(False)
# Update/Reset naskah scripts list specific to this profile!
if "scripts_list" in prof:
self.scripts_list = prof["scripts_list"]
else:
# Fallback for Original Settings profile to load the 40 original scripts automatically
if name == "Original_Terminal_Settings":
self.load_original_scripts()
return # load_original_scripts handles table population and disk save
else:
self.scripts_list = []
# Update the visual naskah table view
if hasattr(self, "naskah_table"):
self.naskah_table.blockSignals(True)
self.naskah_table.setRowCount(len(self.scripts_list))
for r, script in enumerate(self.scripts_list):
self.naskah_table.setItem(r, 0, QTableWidgetItem(str(script["id"])))
self.naskah_table.setItem(r, 1, QTableWidgetItem(script["category"]))
self.naskah_table.setItem(r, 2, QTableWidgetItem(script["product"]))
naskah_item = QTableWidgetItem(script["naskah"])
self.naskah_table.setItem(r, 3, naskah_item)
self.naskah_table.blockSignals(False)
# Hubungkan cellChanged secara aman
try:
self.naskah_table.cellChanged.disconnect(self.on_naskah_cell_changed)
except:
pass
self.naskah_table.cellChanged.connect(self.on_naskah_cell_changed)
self.save_profiles_to_disk()
self.scan_workspace()
def save_current_profile_config(self):
name = self.profile_combo.currentText()
if not name:
return
# Gather all current UI values
prof = {
"video_input": self.dir_inputs["video_input"].text(),
"music_input": self.dir_inputs["music_input"].text(),
"fonts": self.dir_inputs["fonts"].text(),
"output": self.dir_inputs["output"].text(),
"scripts_list": self.scripts_list # Simpan naskah unik milik profil ini!
}
# Gather RVC parameters if they exist (with normalization)
if hasattr(self, "rvc_pth_combo"):
val = self.rvc_pth_combo.currentText()
prof["rvc_model"] = os.path.normpath(val) if val else ""
if hasattr(self, "rvc_index_combo"):
val = self.rvc_index_combo.currentText()
prof["rvc_index"] = os.path.normpath(val) if val else ""
if hasattr(self, "pitch_slider"):
prof["pitch_shift"] = self.pitch_slider.value()
if hasattr(self, "index_slider"):
prof["index_rate"] = self.index_slider.value()
# Gather Layout parameters if they exist
if hasattr(self, "font_combo"):
prof["font_path"] = self.font_combo.currentText()
if hasattr(self, "subtitle_color_combo"):
prof["subtitle_color"] = self.subtitle_color_combo.currentText()
if hasattr(self, "subtitle_size_spin"):
prof["subtitle_size"] = self.subtitle_size_spin.value()
if hasattr(self, "subtitle_stroke_spin"):
prof["subtitle_stroke"] = self.subtitle_stroke_spin.value()
if hasattr(self, "subtitle_pos_slider"):
prof["subtitle_pos"] = self.subtitle_pos_slider.value()
if hasattr(self, "watermark_input"):
prof["watermark_path"] = self.watermark_input.text()
if hasattr(self, "opacity_slider"):
prof["watermark_opacity"] = self.opacity_slider.value()
if hasattr(self, "watermark_size_spin"):
prof["watermark_size"] = self.watermark_size_spin.value()
if hasattr(self, "bgm_vol_spin"):
prof["bgm_volume"] = self.bgm_vol_spin.value()
if hasattr(self, "transition_combo"):
prof["transition"] = self.transition_combo.currentText()
if hasattr(self, "limit_to_3s_checkbox"):
prof["limit_to_3s"] = self.limit_to_3s_checkbox.isChecked()
self.profiles_data["profiles"][name] = prof
self.save_profiles_to_disk()
QMessageBox.information(self, "Profile Saved", f"Workspace profile '{name}' successfully saved!")
def create_new_profile(self):
# pyrefly: ignore [missing-import]
from PySide6.QtWidgets import QInputDialog
name, ok = QInputDialog.getText(self, "New Workspace Profile", "Enter workspace profile name:")
if ok and name.strip():
name = name.strip()
if name in self.profiles_data["profiles"]:
QMessageBox.warning(self, "Error", f"Profile '{name}' already exists!")
return
active_name = self.profile_combo.currentText()
if active_name and active_name in self.profiles_data["profiles"]:
self.profiles_data["profiles"][name] = dict(self.profiles_data["profiles"][active_name])
else:
self.profiles_data["profiles"][name] = {
"video_input": self.video_input,
"music_input": self.music_input,
"fonts": self.fonts_dir,
"output": self.output_dir
}
self.profiles_data["active_profile"] = name
self.save_profiles_to_disk()
self.populate_profiles()
self.profile_combo.setCurrentText(name)
def delete_profile(self):
name = self.profile_combo.currentText()
if not name:
return
if name == "Default":
QMessageBox.warning(self, "Error", "Cannot delete the Default workspace profile!")
return
confirm = QMessageBox.question(
self, "Confirm Delete",
f"Are you sure you want to delete the profile '{name}'?",
QMessageBox.Yes | QMessageBox.No
)
if confirm == QMessageBox.Yes:
del self.profiles_data["profiles"][name]
self.profiles_data["active_profile"] = "Default"
self.save_profiles_to_disk()
self.populate_profiles()
self.profile_combo.setCurrentText("Default")
# ==========================================
# TAB 2: SCRIPT MANAGER (Master Grid)
# ==========================================
def init_tab_script_manager(self):
tab = QWidget()
layout = QVBoxLayout(tab)
layout.setContentsMargins(15, 15, 15, 15)
title = QLabel("WORKSPACE SCRIPT MANAGER (MASTER GRID)")
title.setObjectName("section_title")
layout.addWidget(title)
# Spacious Table Grid
self.naskah_table = QTableWidget(0, 4)
self.naskah_table.setHorizontalHeaderLabels(["ID", "Kategori / Folder B-Roll", "Produk", "Naskah Video"])
self.naskah_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.naskah_table.verticalHeader().setVisible(False)
self.naskah_table.verticalHeader().setDefaultSectionSize(40)
self.naskah_table.setEditTriggers(QTableWidget.NoEditTriggers) # Disable standard inline editing!
self.naskah_table.cellDoubleClicked.connect(self.open_master_script_editor) # Double click modal editor!
layout.addWidget(self.naskah_table)
# Action Buttons Layout
btn_layout = QHBoxLayout()
btn_add = QPushButton("➕ Add Row")
btn_add.clicked.connect(self.add_manual_script_row)
btn_layout.addWidget(btn_add)
btn_del = QPushButton("🗑️ Delete Selected")
btn_del.setObjectName("danger_button")
btn_del.clicked.connect(self.delete_selected_script_row)
btn_layout.addWidget(btn_del)
btn_clear = QPushButton("🧹 Clear All Scripts")
btn_clear.setObjectName("danger_button")
btn_clear.clicked.connect(self.clear_all_scripts)
btn_layout.addWidget(btn_clear)
layout.addLayout(btn_layout)
self.tabs.addWidget(tab)
def add_manual_script_row(self):
row = self.naskah_table.rowCount()
self.naskah_table.insertRow(row)
next_id = 1
if self.scripts_list:
next_id = max(s["id"] for s in self.scripts_list) + 1
self.naskah_table.setItem(row, 0, QTableWidgetItem(str(next_id)))
self.naskah_table.setItem(row, 1, QTableWidgetItem("POC Cabai"))
self.naskah_table.setItem(row, 2, QTableWidgetItem("POC Cabai"))