-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathapp.py
More file actions
1862 lines (1542 loc) Β· 77.7 KB
/
Copy pathapp.py
File metadata and controls
1862 lines (1542 loc) Β· 77.7 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
"""
YT Short Clipper Desktop App
"""
import customtkinter as ctk
import threading
import json
import os
import sys
import subprocess
import re
import urllib.request
import io
from pathlib import Path
from tkinter import filedialog, messagebox
from openai import OpenAI
from PIL import Image, ImageTk
# Import version info
from version import __version__, UPDATE_CHECK_URL
# Import utilities
from utils.helpers import get_app_dir, get_bundle_dir, get_ffmpeg_path, get_ytdlp_path, extract_video_id
from utils.logger import debug_log, setup_error_logging, log_error, get_error_log_path
from config.config_manager import ConfigManager
from dialogs.model_selector import SearchableModelDropdown
from dialogs.youtube_upload import YouTubeUploadDialog
from dialogs.terms_of_service import TermsOfServiceDialog
from dialogs.autoklip_promo import AutoKlipPromoDialog
from components.progress_step import ProgressStep
from pages.settings_page import SettingsPage
from pages.browse_page import BrowsePage
from pages.results_page import ResultsPage
from pages.status_pages import APIStatusPage, LibStatusPage
from pages.processing_page import ProcessingPage
from pages.clipping_page import ClippingPage
from pages.contact_page import ContactPage
from pages.highlight_selection_page import HighlightSelectionPage
from pages.session_browser_page import SessionBrowserPage
# Fix for PyInstaller windowed mode (console=False)
# When built with console=False, sys.stdout and sys.stderr are None
# This causes 'NoneType' object has no attribute 'flush' errors
if sys.stdout is None:
sys.stdout = open(os.devnull, 'w')
if sys.stderr is None:
sys.stderr = open(os.devnull, 'w')
APP_DIR = get_app_dir()
BUNDLE_DIR = get_bundle_dir()
# Setup error logging to file (for production builds)
setup_error_logging(APP_DIR)
CONFIG_FILE = APP_DIR / "config.json"
OUTPUT_DIR = APP_DIR / "output"
ASSETS_DIR = BUNDLE_DIR / "assets"
ICON_PATH = ASSETS_DIR / "icon.png"
ICON_ICO_PATH = ASSETS_DIR / "icon.ico"
COOKIES_FILE = APP_DIR / "cookies.txt" # NEW: Cookies file path
class YTShortClipperApp(ctk.CTk):
def __init__(self):
super().__init__()
self.config = ConfigManager(CONFIG_FILE, OUTPUT_DIR)
self.client = None
self.current_thumbnail = None
self.processing = False
self.cancelled = False
self.token_usage = {"gpt_input": 0, "gpt_output": 0, "whisper_seconds": 0, "tts_chars": 0}
self.youtube_connected = False
self.youtube_channel = None
self.ytdlp_path = get_ytdlp_path() # NEW: Store yt-dlp path for subtitle fetching
self.cookies_path = COOKIES_FILE # NEW: Store cookies path
# Session data for highlight selection flow
self.session_data = None # Will store result from find_highlights_only
self.title("YT Short Clipper")
self.geometry("780x620")
self.resizable(False, False)
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Set app icon after window is created
self.after(200, self.set_app_icon)
self.container = ctk.CTkFrame(self)
self.container.pack(fill="both", expand=True)
self.pages = {}
self.create_home_page()
self.create_processing_page()
self.create_clipping_page()
self.create_highlight_selection_page()
self.create_session_browser_page()
self.create_results_page()
self.create_browse_page()
self.create_settings_page()
self.create_api_status_page()
self.create_lib_status_page()
self.create_contact_page()
self.show_page("home")
self.load_config()
self.check_youtube_status()
# Update start button state based on cookies
self.update_start_button_state()
# Check for updates on startup
threading.Thread(target=self.check_update_silent, daemon=True).start()
# Show Terms of Service if not yet accepted
if not self.config.get("tos_accepted", False):
self.after(300, self._show_tos_dialog)
else:
# ToS already accepted in a previous session β show AutoKlip promo
# one time only.
self.after(500, self._maybe_show_autoklip_promo)
def _show_tos_dialog(self):
"""Show Terms of Service dialog and block app usage until accepted."""
def on_accept():
self.config.set("tos_accepted", True)
# Queue the AutoKlip promo right after ToS acceptance
self.after(400, self._maybe_show_autoklip_promo)
TermsOfServiceDialog(self, on_accept)
def _maybe_show_autoklip_promo(self):
"""Show AutoKlip promo modal exactly once per install."""
if self.config.get("autoklip_promo_shown", False):
return
try:
AutoKlipPromoDialog(self)
finally:
# Persist immediately so it never shows again, even if user
# closes the app without clicking the CTA.
self.config.set("autoklip_promo_shown", True)
def set_app_icon(self):
"""Set window icon"""
try:
if sys.platform == "win32":
# Use .ico file directly on Windows
if ICON_ICO_PATH.exists():
self.iconbitmap(str(ICON_ICO_PATH))
elif ICON_PATH.exists():
# Convert PNG to ICO if needed
img = Image.open(ICON_PATH)
ico_path = ASSETS_DIR / "icon.ico"
img.save(str(ico_path), format='ICO', sizes=[(16, 16), (32, 32), (48, 48), (256, 256)])
self.iconbitmap(str(ico_path))
else:
if ICON_PATH.exists():
icon_img = Image.open(ICON_PATH)
photo = ImageTk.PhotoImage(icon_img)
self.iconphoto(True, photo)
self._icon_photo = photo
except Exception as e:
print(f"Icon error: {e}")
def show_page(self, name):
for page in self.pages.values():
page.pack_forget()
self.pages[name].pack(fill="both", expand=True)
# Refresh browse list when showing browse page
if name == "browse":
self.pages["browse"].refresh_list()
# Refresh API status when showing api_status page
if name == "api_status":
self.pages["api_status"].refresh_status()
# Refresh lib status when showing lib_status page
if name == "lib_status":
self.pages["lib_status"].refresh_status()
# Reset home page state when returning to home
if name == "home":
self.reset_home_page()
def reset_home_page(self):
"""Reset home page to initial state"""
# Clear URL input
self.url_var.set("")
# Reset thumbnail - recreate preview placeholder
self.current_thumbnail = None
self.create_preview_placeholder()
# Reset subtitle state (keep visible but disabled)
self.subtitle_loaded = False
self.subtitle_loading.pack_forget()
self.subtitle_dropdown.configure(state="disabled", values=["id - Indonesian"])
self.subtitle_var.set("id - Indonesian")
# Reset clips input to default
self.clips_var.set("5")
# Update start button state
self.update_start_button_state()
def create_home_page(self):
page = ctk.CTkFrame(self.container, fg_color=("#1a1a1a", "#0a0a0a"))
self.pages["home"] = page
# Import header and footer components
from components.page_layout import PageHeader, PageFooter
# Top header
header = PageHeader(page, self, show_nav_buttons=True)
header.pack(fill="x", padx=20, pady=(15, 10))
# Load icons for buttons
try:
play_img = Image.open(ASSETS_DIR / "play.png")
play_img.thumbnail((20, 20), Image.Resampling.LANCZOS)
self.play_icon = ctk.CTkImage(light_image=play_img, dark_image=play_img, size=(20, 20))
refresh_img = Image.open(ASSETS_DIR / "refresh.png")
refresh_img.thumbnail((20, 20), Image.Resampling.LANCZOS)
self.refresh_icon = ctk.CTkImage(light_image=refresh_img, dark_image=refresh_img, size=(20, 20))
except Exception as e:
debug_log(f"Icon load error: {e}")
self.play_icon = None
self.refresh_icon = None
# ===== TOP ROW: Left config + Right thumbnail =====
top_row = ctk.CTkFrame(page, fg_color="transparent")
top_row.pack(fill="x", padx=20, pady=(5, 10))
# Left column - URL, Subtitle, Clip Count
left_col = ctk.CTkFrame(top_row, fg_color="transparent")
left_col.pack(side="left", fill="y", padx=(0, 20))
# YouTube URL
ctk.CTkLabel(left_col, text="YouTube URL", font=ctk.CTkFont(size=11, weight="bold"),
anchor="w").pack(fill="x", pady=(0, 3))
url_input_container = ctk.CTkFrame(left_col, fg_color="transparent")
url_input_container.pack(fill="x", pady=(0, 8))
self.url_var = ctk.StringVar()
self.url_var.trace_add("write", self.on_url_change)
self.url_entry = ctk.CTkEntry(url_input_container, textvariable=self.url_var,
placeholder_text="Paste YouTube link...", width=220, height=32, border_width=1,
border_color=("#3a3a3a", "#2a2a2a"), fg_color=("#1a1a1a", "#0a0a0a"))
self.url_entry.pack(side="left", padx=(0, 5))
self.paste_btn = ctk.CTkButton(url_input_container, text="π Paste", width=65, height=32,
fg_color=("#3a3a3a", "#2a2a2a"), hover_color=("#4a4a4a", "#3a3a3a"),
font=ctk.CTkFont(size=10), command=self.paste_url)
self.paste_btn.pack(side="left")
# Subtitle Language
ctk.CTkLabel(left_col, text="Subtitle Language", font=ctk.CTkFont(size=11, weight="bold"),
anchor="w").pack(fill="x", pady=(3, 3))
self.subtitle_frame = ctk.CTkFrame(left_col, fg_color="transparent")
self.subtitle_frame.pack(fill="x", pady=(0, 8))
self.subtitle_loaded = False
self.subtitle_var = ctk.StringVar(value="id - Indonesian")
self.subtitle_dropdown = ctk.CTkOptionMenu(self.subtitle_frame,
variable=self.subtitle_var, values=["id - Indonesian"], width=290,
height=32, fg_color=("#2b2b2b", "#1a1a1a"),
button_color=("#3a3a3a", "#2a2a2a"), button_hover_color=("#4a4a4a", "#3a3a3a"),
state="disabled")
self.subtitle_dropdown.pack(anchor="w")
self.subtitle_loading = ctk.CTkLabel(self.subtitle_frame, text="β³ Loading...",
font=ctk.CTkFont(size=10), text_color="gray")
# Clip Count
ctk.CTkLabel(left_col, text="Clip Count", font=ctk.CTkFont(size=11, weight="bold"),
anchor="w").pack(fill="x", pady=(3, 3))
clips_input_frame = ctk.CTkFrame(left_col, fg_color="transparent")
clips_input_frame.pack(fill="x", pady=(0, 5))
self.clips_var = ctk.StringVar(value="5")
clips_entry = ctk.CTkEntry(clips_input_frame, textvariable=self.clips_var, width=60, height=32,
fg_color=("#2b2b2b", "#1a1a1a"), border_width=1, border_color=("#3a3a3a", "#2a2a2a"), justify="center")
clips_entry.pack(side="left", padx=(0, 8))
ctk.CTkLabel(clips_input_frame, text="(1-10)", font=ctk.CTkFont(size=10),
text_color="gray").pack(side="left")
# Right column - Thumbnail 16:9
right_col = ctk.CTkFrame(top_row, fg_color="transparent")
right_col.pack(side="right", fill="y")
# Video preview frame 16:9 (400x225)
self.thumb_frame = ctk.CTkFrame(right_col, width=400, height=225,
fg_color=("#2b2b2b", "#1a1a1a"), corner_radius=8)
self.thumb_frame.pack(anchor="ne")
self.thumb_frame.pack_propagate(False)
self.create_preview_placeholder()
# ===== MIDDLE ROW: Cookies only (full width) =====
middle_row = ctk.CTkFrame(page, fg_color="transparent")
middle_row.pack(fill="x", padx=20, pady=(0, 10))
# YouTube Cookies card (full width)
cookies_frame = ctk.CTkFrame(middle_row, fg_color=("#2b2b2b", "#1a1a1a"), corner_radius=8)
cookies_frame.pack(fill="x")
ctk.CTkLabel(cookies_frame, text="YouTube Cookies", font=ctk.CTkFont(size=11, weight="bold"),
anchor="w").pack(fill="x", padx=12, pady=(10, 5))
self.cookies_status_label = ctk.CTkLabel(cookies_frame, text="πͺ No cookies",
font=ctk.CTkFont(size=10), anchor="w", text_color="gray")
self.cookies_status_label.pack(fill="x", padx=12, pady=(0, 5))
upload_cookies_btn = ctk.CTkButton(cookies_frame, text="π Upload", height=28,
fg_color=("#3a3a3a", "#2a2a2a"), hover_color=("#4a4a4a", "#3a3a3a"),
font=ctk.CTkFont(size=10), command=self.upload_cookies)
upload_cookies_btn.pack(fill="x", padx=12, pady=(0, 10))
# ===== BOTTOM: Generate button + Browse =====
bottom_section = ctk.CTkFrame(page, fg_color="transparent")
bottom_section.pack(fill="x", padx=20, pady=(0, 5))
self.start_btn = ctk.CTkButton(bottom_section, text="Find Highlights", image=self.play_icon,
compound="left", font=ctk.CTkFont(size=13, weight="bold"),
height=40, command=self.start_processing, state="disabled",
fg_color="gray", hover_color="gray", corner_radius=8)
self.start_btn.pack(fill="x", pady=(0, 5))
sessions_link = ctk.CTkLabel(bottom_section, text="π Browse Sessions",
font=ctk.CTkFont(size=10), text_color=("#3B8ED0", "#1F6AA5"), cursor="hand2")
sessions_link.pack()
sessions_link.bind("<Button-1>", lambda e: self.show_page("session_browser"))
# ===== LIB STATUS =====
self.lib_status_frame = ctk.CTkFrame(page, fg_color="transparent")
self.lib_status_frame.pack(fill="x", padx=20, pady=(5, 0))
self.lib_status_label = ctk.CTkLabel(self.lib_status_frame, text="",
font=ctk.CTkFont(size=10), cursor="hand2")
self.lib_status_label.pack()
self.lib_status_label.bind("<Button-1>", lambda e: self.show_page("lib_status"))
# Check and update lib status
self.check_lib_status()
# Check cookies status
self.check_cookies_status()
# Footer
footer = PageFooter(page, self)
footer.pack(fill="x", padx=20, pady=(5, 8), side="bottom")
def create_preview_placeholder(self):
"""Create placeholder content for video preview"""
# Clear existing content
for widget in self.thumb_frame.winfo_children():
widget.destroy()
# Preview content container - centered
preview_container = ctk.CTkFrame(self.thumb_frame, fg_color="transparent")
preview_container.place(relx=0.5, rely=0.5, anchor="center")
# Placeholder text
self.thumb_label = ctk.CTkLabel(preview_container,
text="πΊ Video thumbnail will appear here",
font=ctk.CTkFont(size=12), text_color="gray", justify="center")
self.thumb_label.pack()
def paste_url(self):
"""Paste URL from clipboard"""
# Check if cookies exist first
if not self.cookies_path.exists():
# Show custom dialog with buttons
self.show_cookies_required_dialog()
return
try:
# Get clipboard content
clipboard_text = self.clipboard_get()
if clipboard_text:
self.url_var.set(clipboard_text.strip())
except Exception as e:
debug_log(f"Paste error: {e}")
# If clipboard is empty or error, do nothing
pass
def show_cookies_required_dialog(self):
"""Show custom dialog for cookies requirement with clickable buttons"""
import webbrowser
# Create dialog window
dialog = ctk.CTkToplevel(self)
dialog.title("YouTube Cookies Required")
dialog.geometry("500x220")
dialog.resizable(False, False)
dialog.transient(self)
dialog.grab_set()
# Center dialog on parent window
dialog.update_idletasks()
x = self.winfo_x() + (self.winfo_width() // 2) - (dialog.winfo_width() // 2)
y = self.winfo_y() + (self.winfo_height() // 2) - (dialog.winfo_height() // 2)
dialog.geometry(f"+{x}+{y}")
# Main content frame
content_frame = ctk.CTkFrame(dialog, fg_color="transparent")
content_frame.pack(fill="both", expand=True, padx=20, pady=20)
# Warning message
ctk.CTkLabel(content_frame,
text="β οΈ Please upload YouTube cookies first!",
font=ctk.CTkFont(size=14, weight="bold"),
text_color=("#e74c3c", "#e74c3c")).pack(pady=(0, 15))
ctk.CTkLabel(content_frame,
text="Click a button below to open the setup guide:",
font=ctk.CTkFont(size=12)).pack(pady=(0, 15))
# Buttons frame
buttons_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
buttons_frame.pack(pady=(0, 10))
# English guide button
english_btn = ctk.CTkButton(buttons_frame,
text="π English Guide",
width=140,
height=35,
font=ctk.CTkFont(size=12),
fg_color=("#3B8ED0", "#1F6AA5"),
hover_color=("#2E7AB8", "#16527D"),
command=lambda: [
webbrowser.open("https://github.com/jipraks/yt-short-clipper/blob/master/GUIDE.md#3-setup-youtube-cookies"),
dialog.destroy()
])
english_btn.pack(side="left", padx=5)
# Indonesian guide button
indonesian_btn = ctk.CTkButton(buttons_frame,
text="π Bahasa Indonesia",
width=140,
height=35,
font=ctk.CTkFont(size=12),
fg_color=("#3B8ED0", "#1F6AA5"),
hover_color=("#2E7AB8", "#16527D"),
command=lambda: [
webbrowser.open("https://github.com/jipraks/yt-short-clipper/blob/master/PANDUAN.md#3-setup-cookies-youtube"),
dialog.destroy()
])
indonesian_btn.pack(side="left", padx=5)
# Close button
close_btn = ctk.CTkButton(content_frame,
text="Close",
width=100,
height=35,
font=ctk.CTkFont(size=12),
fg_color=("#6c757d", "#5a6268"),
hover_color=("#5a6268", "#4e555b"),
command=dialog.destroy)
close_btn.pack(pady=(10, 0))
def upload_cookies(self):
"""Upload cookies.txt file"""
file_path = filedialog.askopenfilename(
title="Select cookies.txt file",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)
if file_path:
try:
# Copy file to app directory
import shutil
shutil.copy(file_path, self.cookies_path)
debug_log(f"Cookies uploaded: {file_path}")
# Update status
self.check_cookies_status()
# Show success message
messagebox.showinfo("Success", "cookies.txt uploaded successfully!")
except Exception as e:
debug_log(f"Upload cookies error: {e}")
messagebox.showerror("Upload Failed", f"Failed to upload cookies.txt:\n{str(e)}")
def check_cookies_status(self):
"""Check if cookies.txt exists and update UI"""
if self.cookies_path.exists():
self.cookies_status_label.configure(
text="β
cookies.txt loaded",
text_color=("#27ae60", "#2ecc71") # Green
)
# Update start button state when cookies status changes
self.update_start_button_state()
return True
else:
self.cookies_status_label.configure(
text="πͺ No cookies.txt found",
text_color="gray"
)
# Update start button state when cookies status changes
self.update_start_button_state()
return False
def create_processing_page(self):
"""Create processing page as embedded frame"""
self.pages["processing"] = ProcessingPage(
self.container,
self.cancel_processing,
lambda: self.show_page("home"),
self.open_output,
self.show_browse_after_complete
)
# Keep reference to steps for update_progress
self.steps = self.pages["processing"].steps
def create_clipping_page(self):
"""Create clipping page as embedded frame"""
self.pages["clipping"] = ClippingPage(
self.container,
self.cancel_processing,
lambda: self.show_page("home"),
self.open_output,
lambda: self.show_page("session_browser")
)
def create_highlight_selection_page(self):
"""Create highlight selection page as embedded frame"""
self.pages["highlight_selection"] = HighlightSelectionPage(
self.container,
lambda: self.show_page("home"), # Back to home
self.process_selected_highlights # Process callback
)
def create_session_browser_page(self):
"""Create session browser page as embedded frame"""
self.pages["session_browser"] = SessionBrowserPage(
self.container,
self.config,
lambda: self.show_page("home"), # Back to home
self.resume_session, # Resume callback
self # Pass app reference
)
def create_results_page(self):
"""Create results page as embedded frame"""
self.pages["results"] = ResultsPage(
self.container,
self.config,
self.client,
lambda: self.show_page("processing"),
lambda: self.show_page("home"),
self.open_output,
self.get_youtube_client
)
def create_settings_page(self):
"""Create settings page as embedded frame"""
self.pages["settings"] = SettingsPage(
self.container,
self.config,
self.on_settings_saved,
lambda: self.show_page("home"),
OUTPUT_DIR,
self.check_update_manual
)
def create_api_status_page(self):
"""Create API status page as embedded frame"""
self.pages["api_status"] = APIStatusPage(
self.container,
lambda: self.client,
lambda: self.config,
lambda: (self.youtube_connected, self.youtube_channel),
lambda: self.show_page("home"),
self.refresh_icon
)
def create_lib_status_page(self):
"""Create library status page as embedded frame"""
self.pages["lib_status"] = LibStatusPage(
self.container,
lambda: self.show_page("home"),
self.refresh_icon
)
def create_browse_page(self):
"""Create browse page as embedded frame"""
self.pages["browse"] = BrowsePage(
self.container,
self.config,
self.client,
lambda: self.show_page("home"),
self.refresh_icon,
self.get_youtube_client
)
def create_contact_page(self):
"""Create contact page as embedded frame"""
self.pages["contact"] = ContactPage(
self.container,
lambda: self.config.get("installation_id", "unknown"),
lambda: self.show_page("home")
)
def load_config(self):
api_key = self.config.get("api_key", "")
base_url = self.config.get("base_url", "https://api.openai.com/v1")
model = self.config.get("model", "")
if api_key:
try:
self.client = OpenAI(api_key=api_key, base_url=base_url)
# Only update UI if widgets exist
if hasattr(self, 'api_dot'):
self.api_dot.configure(text_color="#27ae60") # Green
self.api_status_label.configure(text=model[:15] if model else "Connected")
except:
if hasattr(self, 'api_dot'):
self.api_dot.configure(text_color="#e74c3c") # Red
self.api_status_label.configure(text="Invalid key")
else:
if hasattr(self, 'api_dot'):
self.api_dot.configure(text_color="#e74c3c") # Red
self.api_status_label.configure(text="Not configured")
def check_youtube_status(self):
"""Check YouTube connection status"""
try:
from youtube_uploader import YouTubeUploader
uploader = YouTubeUploader()
if uploader.is_authenticated():
channel = uploader.get_channel_info()
if channel:
self.youtube_connected = True
self.youtube_channel = channel
# Only update UI if widgets exist
if hasattr(self, 'yt_dot'):
self.yt_dot.configure(text_color="#27ae60") # Green
# Show channel name
channel_name = channel['title']
self.yt_status_label_home.configure(text=f"{channel_name[:20]}")
return
self.youtube_connected = False
if hasattr(self, 'yt_dot'):
self.yt_dot.configure(text_color="#e74c3c") # Red
self.yt_status_label_home.configure(text="Not connected")
except:
self.youtube_connected = False
if hasattr(self, 'yt_dot'):
self.yt_dot.configure(text_color="#e74c3c") # Red
self.yt_status_label_home.configure(text="Not available")
def update_connection_status(self):
"""Update connection status cards (called after settings change)"""
self.load_config()
self.check_youtube_status()
def on_settings_saved(self, updated_config):
"""Handle settings saved - accepts config dict"""
# Update internal config
if isinstance(updated_config, dict):
self.config.config.update(updated_config)
self.config.save()
# Update OpenAI client if highlight_finder config changed
ai_providers = updated_config.get("ai_providers", {})
hf_config = ai_providers.get("highlight_finder", {})
if hf_config.get("api_key"):
self.client = OpenAI(
api_key=hf_config.get("api_key"),
base_url=hf_config.get("base_url", "https://api.openai.com/v1")
)
def get_youtube_client(self):
"""Get OpenAI client for YouTube title generation"""
ai_providers = self.config.get("ai_providers", {})
yt_config = ai_providers.get("youtube_title_maker", {})
if yt_config.get("api_key"):
return OpenAI(
api_key=yt_config.get("api_key"),
base_url=yt_config.get("base_url", "https://api.openai.com/v1")
)
else:
# Fallback to main client for backward compatibility
return self.client
def on_url_change(self, *args):
url = self.url_var.get().strip()
video_id = extract_video_id(url)
if video_id:
# Reset subtitle loaded flag when URL changes
self.subtitle_loaded = False
self.load_thumbnail(video_id)
self.load_subtitles(url) # Fetch available subtitles
else:
self.current_thumbnail = None
self.subtitle_loaded = False
# Recreate placeholder
self.create_preview_placeholder()
# Reset subtitle dropdown to disabled state
self.subtitle_loading.pack_forget()
self.subtitle_dropdown.configure(state="disabled", values=["id - Indonesian"])
self.subtitle_var.set("id - Indonesian")
# Disable start button when URL is invalid or cookies missing
self.update_start_button_state()
def update_start_button_state(self):
"""Update start button state based on URL, cookies, and library validation"""
has_cookies = self.cookies_path.exists()
libs_ok = getattr(self, 'libs_installed', True) # Default True if not checked yet
# Always keep paste button enabled (so user can see alert)
self.paste_btn.configure(state="normal")
# If no cookies, disable URL entry and start button
if not has_cookies:
self.url_entry.configure(state="disabled")
self.start_btn.configure(state="disabled", fg_color="gray", hover_color="gray")
return
# Cookies exist - enable URL input
self.url_entry.configure(state="normal")
# Check if URL is valid, subtitle is loaded, and libs are installed
url = self.url_var.get().strip()
video_id = extract_video_id(url)
if video_id and self.subtitle_loaded and libs_ok:
self.start_btn.configure(state="normal", fg_color=("#1f538d", "#14375e"),
hover_color=("#144870", "#0d2a47"))
else:
self.start_btn.configure(state="disabled", fg_color="gray", hover_color="gray")
def check_lib_status(self):
"""Check library installation status and update UI"""
from utils.dependency_manager import check_dependency
from utils.helpers import get_app_dir, is_ytdlp_module_available
app_dir = get_app_dir()
# Check each dependency
ffmpeg_ok = check_dependency('ffmpeg', app_dir)
deno_ok = check_dependency('deno', app_dir)
ytdlp_ok = is_ytdlp_module_available()
all_ok = ffmpeg_ok and deno_ok and ytdlp_ok
self.libs_installed = all_ok
if all_ok:
# All installed - hide lib status
self.lib_status_frame.pack_forget()
else:
# Clear existing widgets
for widget in self.lib_status_frame.winfo_children():
widget.destroy()
# Create status row with colored indicators
status_row = ctk.CTkFrame(self.lib_status_frame, fg_color="transparent")
status_row.pack()
ctk.CTkLabel(status_row, text="Lib Status:", font=ctk.CTkFont(size=10),
text_color="gray").pack(side="left", padx=(0, 5))
# Deno
deno_color = "#4ade80" if deno_ok else "#f87171"
ctk.CTkLabel(status_row, text=f"Deno {'β' if deno_ok else 'β'}",
font=ctk.CTkFont(size=10), text_color=deno_color).pack(side="left", padx=(0, 8))
# YT-DLP
ytdlp_color = "#4ade80" if ytdlp_ok else "#f87171"
ctk.CTkLabel(status_row, text=f"YT-DLP {'β' if ytdlp_ok else 'β'}",
font=ctk.CTkFont(size=10), text_color=ytdlp_color).pack(side="left", padx=(0, 8))
# FFmpeg
ffmpeg_color = "#4ade80" if ffmpeg_ok else "#f87171"
ctk.CTkLabel(status_row, text=f"FFmpeg {'β' if ffmpeg_ok else 'β'}",
font=ctk.CTkFont(size=10), text_color=ffmpeg_color).pack(side="left", padx=(0, 8))
# Install link
install_link = ctk.CTkLabel(status_row, text="(Install required libraries)",
font=ctk.CTkFont(size=10), text_color="#f87171", cursor="hand2")
install_link.pack(side="left")
install_link.bind("<Button-1>", lambda e: self.show_page("lib_status"))
self.lib_status_frame.pack(fill="x", padx=20, pady=(5, 0))
# Update start button state
self.update_start_button_state()
def load_subtitles(self, url: str):
"""Fetch available subtitles for the video"""
def fetch():
try:
# Show loading state
self.after(0, lambda: self.show_subtitle_loading())
# Import here to avoid circular dependency
from clipper_core import AutoClipperCore
# Get available subtitles (pass cookies_path)
debug_log(f"Fetching subtitles for: {url}")
debug_log(f"Cookies path: {self.cookies_path}")
debug_log(f"Cookies exists: {self.cookies_path.exists()}")
cookies_str = str(self.cookies_path) if self.cookies_path.exists() else None
debug_log(f"Passing cookies_path: {cookies_str}")
result = AutoClipperCore.get_available_subtitles(
url,
self.ytdlp_path,
cookies_path=cookies_str
)
debug_log(f"Subtitle fetch result: {result}")
if result.get("error"):
debug_log(f"Subtitle error: {result['error']}")
self.after(0, lambda: self.on_subtitle_error(result["error"]))
return
# Combine manual and auto-generated subtitles
all_subs = []
# Prioritize manual subtitles
for sub in result.get("subtitles", []):
all_subs.append({
"code": sub["code"],
"name": sub["name"],
"type": "manual"
})
# Add auto-generated subtitles
for sub in result.get("automatic_captions", []):
all_subs.append({
"code": sub["code"],
"name": f"{sub['name']} (auto)",
"type": "auto"
})
debug_log(f"Total subtitles found: {len(all_subs)}")
if not all_subs:
# No subtitles β allow proceeding with AI transcription fallback
self.after(0, lambda: self.show_no_subtitle_fallback())
return
self.after(0, lambda: self.show_subtitle_selector(all_subs))
except Exception as e:
debug_log(f"Exception in load_subtitles: {str(e)}")
import traceback
debug_log(traceback.format_exc())
err_msg = str(e)
self.after(0, lambda msg=err_msg: self.on_subtitle_error(msg))
threading.Thread(target=fetch, daemon=True).start()
def show_subtitle_loading(self):
"""Show loading state for subtitle selector"""
# Keep dropdown visible but show loading indicator
self.subtitle_dropdown.configure(state="disabled")
self.subtitle_loading.pack(fill="x", padx=(4, 8), pady=(4, 0))
def on_subtitle_error(self, error: str):
"""Handle subtitle fetch error"""
debug_log(f"Subtitle fetch error: {error}")
self.subtitle_loaded = False
# Hide loading, keep dropdown disabled
self.subtitle_loading.pack_forget()
self.subtitle_dropdown.configure(state="disabled")
# Show error to user
messagebox.showerror("Subtitle Error", f"Failed to fetch subtitles:\n\n{error}")
# Update button state
self.update_start_button_state()
def show_subtitle_selector(self, subtitles: list):
"""Show subtitle selector with available options"""
# Hide loading
self.subtitle_loading.pack_forget()
# Create dropdown options
options = [f"{sub['code']} - {sub['name']}" for sub in subtitles]
# Set default to Indonesian if available, otherwise first option
default_value = options[0]
for opt in options:
if opt.startswith("id "):
default_value = opt
break
self.subtitle_var.set(default_value)
self.subtitle_dropdown.configure(values=options, state="normal")
# Mark subtitles as loaded
self.subtitle_loaded = True
# Update start button state (subtitles loaded successfully)
self.update_start_button_state()
def show_no_subtitle_fallback(self):
"""Handle case where no subtitles are available.
Since the new flow requires subtitles (no video download for Whisper),
we disable the Find Highlights button and inform the user.
"""
# Hide loading
self.subtitle_loading.pack_forget()
# Set dropdown to show no subtitle message
no_sub_option = "none - No subtitle available"
self.subtitle_var.set(no_sub_option)
self.subtitle_dropdown.configure(values=[no_sub_option], state="disabled")
# Do NOT mark as loaded β this prevents Find Highlights button from enabling
self.subtitle_loaded = False
# Update start button state (will be disabled)
self.update_start_button_state()
def load_thumbnail(self, video_id: str):
def fetch():
try:
import ssl
import certifi
# Try with certifi first, fallback to unverified SSL
ssl_context = None
try:
ssl_context = ssl.create_default_context(cafile=certifi.where())
except Exception:
pass
if ssl_context is None:
# Fallback to unverified SSL (for PyInstaller builds)
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
img = None
for quality in ["maxresdefault", "hqdefault", "mqdefault"]:
try:
url = f"https://img.youtube.com/vi/{video_id}/{quality}.jpg"
with urllib.request.urlopen(url, timeout=5, context=ssl_context) as r:
data = r.read()
img = Image.open(io.BytesIO(data))
if img.size[0] > 120:
break
except Exception as e:
debug_log(f"Thumbnail fetch error ({quality}): {e}")
continue
if img is None:
raise Exception("All thumbnail qualities failed")
# Resize to fit preview area in landscape (16:9 aspect ratio)
# Frame is 400x225
img.thumbnail((390, 220), Image.Resampling.LANCZOS)
self.after(0, lambda: self.show_thumbnail(img))
except Exception as e:
debug_log(f"Thumbnail load failed: {e}")
self.after(0, lambda: self.on_thumbnail_error())
# Clear image reference properly before loading new one
self.current_thumbnail = None
# Show loading state
for widget in self.thumb_frame.winfo_children():
widget.destroy()
loading_container = ctk.CTkFrame(self.thumb_frame, fg_color="transparent")
loading_container.place(relx=0.5, rely=0.5, anchor="center")
self.thumb_label = ctk.CTkLabel(loading_container, text="Loading...",
font=ctk.CTkFont(size=13), text_color="gray")
self.thumb_label.pack()
self.start_btn.configure(state="disabled", fg_color="gray", hover_color="gray")
threading.Thread(target=fetch, daemon=True).start()
def on_thumbnail_error(self):
# Clear image reference properly before showing error
self.current_thumbnail = None
# Recreate placeholder with error message
for widget in self.thumb_frame.winfo_children():
widget.destroy()
preview_container = ctk.CTkFrame(self.thumb_frame, fg_color="transparent")