-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2175 lines (1882 loc) · 94.5 KB
/
Copy pathmain.py
File metadata and controls
2175 lines (1882 loc) · 94.5 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
"""
main.py
Disc Track Splitter - GUI entry point (v2.0 - three-pane dashboard).
Workflow:
1. Pick (or watch) a folder containing a ripped Blu-ray disc structure
(BDMV/PLAYLIST/*.mpls).
2. Scan playlists, auto-select the best candidate (an Atmos track if
the disc has one, based on the same scoring as before).
3. Choose which audio track to keep - Atmos is pre-selected when
present, otherwise the best lossless option is, but every track
the playlist actually has (LPCM, DTS-HD MA, TrueHD, in whatever
channel layouts/sample rates the disc offers) is listed and can be
picked instead.
4. Enter/paste song names for each chapter.
5. Extract the chosen audio track + split into individually named files.
Layout note (v2.0): the window is a three-pane dashboard -
Pane 1 (top-left card): Source & Configuration - disc folder, playlist
pick, and audio track pick (this app's closest
equivalent to a "format" choice, since it
stream-copies rather than re-encoding).
Pane 2 (top-right card): Track List & Naming - the four naming methods
plus the scrollable chapter table.
Pane 3 (bottom card): Execution & Progress - output folder, the
Extract/Cancel/Open Log controls, an
indeterminate progress bar while a job runs,
and a compact rolling status log.
All structural layout uses .grid() exclusively. This file only changes
presentation - every method that talks to extractor.py/settings.py is
unchanged from the previous version.
"""
from __future__ import annotations
import os
import re
import shutil
import threading
import tkinter as tk
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
import webbrowser
from pathlib import Path
from typing import Callable
import customtkinter as ctk
import extractor
import settings
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# ---------------------------------------------------------------------------
# Style constants (Section 2 of the brief: global styling & layout rules)
# ---------------------------------------------------------------------------
PAD_SMALL = 5
PAD_MED = 12
PAD_LARGE = 20
COLOR_BG = "#1A1A1A" # deep charcoal window background
COLOR_CARD = "#2B2B2B" # lighter card overlay for each pane
COLOR_CARD_INSET = "#232323" # slightly recessed box inside a card (e.g. the track picker box)
COLOR_BLUE = "#1F6AA5" # focus / informational accent
COLOR_BLUE_HOVER = "#17527f"
COLOR_GREEN = "#2EA043" # primary action accent
COLOR_GREEN_HOVER = "#268239"
COLOR_DANGER = "#a33"
COLOR_DANGER_HOVER = "#822"
COLOR_NEUTRAL = "#3a3a3a"
COLOR_NEUTRAL_HOVER = "#4a4a4a"
COLOR_INVALID_BORDER = "#e5484d"
COLOR_TEXT_MUTED = "gray70"
FONT_FAMILY = "Segoe UI"
FONT_TITLE = (FONT_FAMILY, 16, "bold")
FONT_HEADER = (FONT_FAMILY, 13, "normal")
FONT_BODY = (FONT_FAMILY, 11, "normal")
def enable_clipboard(
widget: ctk.CTkEntry | ctk.CTkTextbox, on_change: "Callable[[], None] | None" = None
) -> None:
"""
customtkinter's Entry/Textbox widgets don't reliably inherit the OS's
default copy/cut/paste keyboard or right-click behaviour on every
platform/version. This adds both explicitly so Ctrl+V and right-click
-> Paste always work.
on_change: if given, called (with a short delay so the widget's own
insert/delete has already landed) after a paste or cut actually
changes this widget's content. Used so pasting a tracklist auto-fills
the chapter table without a separate "Fill" click, without this
generic clipboard helper needing to know anything about that.
"""
# The actual tkinter widget underneath is .entry for CTkEntry-like
# widgets, or the CTkTextbox itself acts as a Text widget directly.
target = getattr(widget, "_entry", None) or getattr(widget, "_textbox", None) or widget
def _notify_change() -> None:
if on_change is not None:
widget.after(10, on_change)
def paste(_event=None) -> str:
try:
clipboard_text = widget.clipboard_get()
except tk.TclError:
return "break"
try:
if isinstance(widget, ctk.CTkTextbox):
widget.insert("insert", clipboard_text)
else:
widget.insert("insert", clipboard_text)
except Exception:
pass
_notify_change()
return "break"
def copy(_event=None) -> str:
try:
if isinstance(widget, ctk.CTkTextbox):
selected = widget.get("sel.first", "sel.last")
else:
selected = widget.get()
widget.clipboard_clear()
widget.clipboard_append(selected)
except Exception:
pass
return "break"
def cut(_event=None) -> str:
copy(_event)
try:
if isinstance(widget, ctk.CTkTextbox):
widget.delete("sel.first", "sel.last")
else:
widget.delete(0, "end")
except Exception:
pass
_notify_change()
return "break"
def select_all(_event=None) -> str:
try:
if isinstance(widget, ctk.CTkTextbox):
widget.tag_add("sel", "1.0", "end")
else:
widget.select_range(0, "end")
except Exception:
pass
return "break"
for seq in ("<Control-v>", "<Control-V>"):
widget.bind(seq, paste)
for seq in ("<Control-c>", "<Control-C>"):
widget.bind(seq, copy)
for seq in ("<Control-x>", "<Control-X>"):
widget.bind(seq, cut)
for seq in ("<Control-a>", "<Control-A>"):
widget.bind(seq, select_all)
menu = tk.Menu(widget, tearoff=0)
menu.add_command(label="Cut", command=cut)
menu.add_command(label="Copy", command=copy)
menu.add_command(label="Paste", command=paste)
menu.add_separator()
menu.add_command(label="Select All", command=select_all)
def show_menu(event) -> None:
try:
widget.focus_set()
menu.tk_popup(event.x_root, event.y_root)
finally:
menu.grab_release()
widget.bind("<Button-3>", show_menu)
REPO_URL = "https://github.com/quinnuk/DiscTrackSplitter"
HELP_TEXT = """DISC TRACK SPLITTER - TIPS & TROUBLESHOOTING
WORKFLOW
1. Point the source field at a folder containing a ripped Blu-ray disc
(it needs the standard BDMV/PLAYLIST/*.mpls structure - not a
flattened single MKV), by typing/pasting the path, hitting Enter, or
using Browse. It scans automatically - no Scan button needed.
2. The app inspects every playlist and ranks them by likelihood of
being "the" concert/album feature - has an Atmos track, has
chapters, includes video, sensible duration. If there's only one
plausible candidate it's picked automatically and the reasoning is
shown right there; the playlist dropdown only appears when two or
more candidates are genuinely close enough to be worth choosing
between yourself.
3. Pick which audio track to keep. If the playlist has a Dolby Atmos
track it's pre-selected automatically (matching the old behaviour);
otherwise the best lossless option is pre-selected. Every audio
track the playlist actually has - different codecs, channel layouts
(2.0/5.1/7.1), sample rates, whatever the disc offers - is listed in
the dropdown with its codec, channels, bitrate, and bit depth, so you
can pick a different one if you'd rather have, say, the 2.0 mix
instead of 5.1, or LPCM instead of DTS-HD MA.
4. Name each chapter, using whichever of the four methods below suits
the disc, then click Extract & Split.
NAMING CHAPTERS - FOUR WAYS
- From disc: if the playlist has chapter names embedded on it, they're
filled in automatically as soon as you select the playlist - no
button needed. The "from disc" tag next to a field shows this
happened; it flips to "edited" if you change that name yourself.
- Paste: paste a plain tracklist (one song per line, in the same order
as the chapters) into the box - it fills the chapter fields
automatically as you type or paste, no button to click. Leading
numbering like "1." or "01 -" is stripped automatically.
- Import Tracklist...: reads a tracklist file. Handles plain .txt,
.cue, .json, and disc-meta .nfo files. If the app found candidate
files sitting in the disc folder (BDInfo.txt, Track Listing.txt,
bdmt_*.xml etc), it'll mention them - these usually came bundled
with the rip and are normally exactly the right tracklist.
- Search Online...: looks up the album on MusicBrainz, by artist/album
text or by the disc's barcode (the UPC/EAN under the barcode lines on
the case). The barcode identifies the exact edition, so it's worth
using instead of artist/album when a release has multiple regional
pressings or reissues with different bonus tracks. Good for
well-known standard releases either way. LIMITED/BOUTIQUE EDITIONS
(small-run audiophile Blu-ray Pure Audio / Surround Series discs,
mail-order exclusives, etc) are very often missing from MusicBrainz
entirely, or only the parent CD/digital release is indexed - if the
track count shown looks nothing like your chapter count, that's the
usual reason. Import Tracklist is more reliable for that kind of disc.
Whichever method you use, nothing is applied until you review and
accept the proposed matches - matched chapters are pre-checked,
mismatched/unmatched ones are left for you to decide.
COMMON ERRORS
- "mkvextract failed" / "Could not read chapters": usually means the
selected file wasn't readable as-is (e.g. a corrupted or incomplete
rip). Try re-scanning, or check the file plays correctly elsewhere.
- "X output file(s) already exist": the app never overwrites existing
files silently - you'll be asked to confirm before anything in the
output folder gets replaced.
- Tool not found on startup: mkvmerge, mkvextract, ffmpeg, and ffprobe
all need to be installed and reachable - either on your system PATH,
or pointed at directly via the Browse button in that dialog. MKVToolNix
provides mkvmerge/mkvextract together; ffmpeg provides ffmpeg/ffprobe
together, so locating one usually finds its pair automatically too.
IF AN EXTRACTION IS INTERRUPTED
If the app is closed, crashes, or a job is cancelled partway through,
just select the same source and output folders and click
Extract & Split again. The app detects the in-progress manifest in
the work folder and offers to resume exactly where it left off -
skipping the extraction step entirely if it already finished, and
skipping any chapters that were already split.
For advanced/manual recovery (e.g. the manifest was deleted, or
extraction finished but you want different track names), the
intermediate _audio_extracted.mkv is left in the work folder and can
be split directly from the command line with split_now.py - see the
README for the exact syntax.
SETTINGS & LOGS
Tool paths and last-used folders are remembered in
%USERPROFILE%\\.disc_track_splitter\\settings.json. Use "Open Log"
during/after a run to see exactly what each external tool was told to
do - the most useful thing to include if you're reporting a bug.
MORE HELP
Full README, known limitations, and issue tracker: see the other items
on this Help menu.
"""
class DiscTrackSplitterApp(ctk.CTk):
def __init__(self) -> None:
super().__init__()
self.title("Disc Track Splitter")
self.geometry("1180x760")
self.minsize(980, 640)
self.resizable(True, True)
try:
self.configure(fg_color=COLOR_BG)
except Exception:
pass
self.cfg = settings.load()
self.playlists: list[extractor.Playlist] = []
self.playlist_scores: list[extractor.PlaylistScore] = []
self.selected_playlist: extractor.Playlist | None = None
self.selected_playlist_score: extractor.PlaylistScore | None = None
self.selected_audio_track: extractor.Track | None = None
self.selected_playlist_chapters: list[extractor.Chapter] = []
self.disc_folder: Path | None = None
self.chapter_name_vars: dict[int, ctk.StringVar] = {}
self.chapter_source_labels: dict[int, ctk.CTkLabel] = {}
self.chapter_duration_labels: dict[int, ctk.CTkLabel] = {}
self.cancel_event: threading.Event | None = None
self.current_log_path: Path | None = None
self._resumable_manifest: extractor.JobManifest | None = None
self._resumable_work_folder: Path | None = None
self._source_debounce_id: str | None = None
self._paste_debounce_id: str | None = None
self._last_scanned_folder: Path | None = None
self.output_var = ctk.StringVar(value=self.cfg.get("last_output_folder", ""))
self._output_editing = not bool(self.cfg.get("last_output_folder"))
self._apply_tool_paths()
self._build_layout()
self._build_menu_bar()
self.after(200, self._check_tools_on_startup)
self.after(200, self._refresh_resume_banner)
def _apply_tool_paths(self) -> None:
"""
Push any custom tool paths from settings.json into extractor.py.
Without this, a custom mkvmerge_path/ffmpeg_path etc set in settings
would be silently ignored and the bare command name used instead.
"""
extractor.set_tool_path("mkvmerge", self.cfg.get("mkvmerge_path", "mkvmerge"))
extractor.set_tool_path("mkvextract", self.cfg.get("mkvextract_path", "mkvextract"))
extractor.set_tool_path("ffmpeg", self.cfg.get("ffmpeg_path", "ffmpeg"))
extractor.set_tool_path("ffprobe", self.cfg.get("ffprobe_path", "ffprobe"))
def _check_tools_on_startup(self) -> None:
found = extractor.check_tools()
missing = [name for name, ok in found.items() if not ok]
if missing:
self._show_missing_tools_dialog(missing)
def _show_missing_tools_dialog(self, missing: list[str]) -> None:
remaining = set(missing)
dialog = ctk.CTkToplevel(self)
dialog.title("Missing required tools")
dialog.geometry("560x380")
dialog.transient(self)
dialog.grab_set()
try:
dialog.configure(fg_color=COLOR_BG)
except Exception:
pass
dialog.grid_columnconfigure(0, weight=1)
heading = ctk.CTkLabel(
dialog,
text="These required tools weren't found on your PATH:",
font=(FONT_FAMILY, 12, "bold"),
wraplength=500,
justify="left",
)
heading.grid(row=0, column=0, sticky="w", padx=PAD_LARGE, pady=(PAD_LARGE, PAD_MED))
rows_frame = ctk.CTkFrame(dialog, fg_color=COLOR_CARD, corner_radius=8)
rows_frame.grid(row=1, column=0, sticky="ew", padx=PAD_LARGE)
rows_frame.grid_columnconfigure(1, weight=1)
row_widgets: dict[str, dict] = {}
def mark_resolved(name: str, version_text: str) -> None:
remaining.discard(name)
widgets = row_widgets[name]
widgets["status"].configure(text=f"OK ({version_text})", text_color=COLOR_GREEN)
widgets["browse_btn"].configure(state="disabled")
widgets["download_btn"].configure(state="disabled")
if not remaining:
heading.configure(text="All required tools are now available.")
def browse_for(name: str) -> None:
path_str = filedialog.askopenfilename(
title=f"Locate {name}",
filetypes=[
("Executable", "*.exe"),
("All files", "*.*"),
],
)
if not path_str:
return
ok, message = extractor.verify_tool_at_path(path_str, name)
if not ok:
messagebox.showerror(
"Not a working tool",
f"This doesn't look like a working {name}:\n\n{message}",
parent=dialog,
)
return
extractor.set_tool_path(name, path_str)
settings.update(**{f"{name}_path": path_str})
mark_resolved(name, message)
self.set_status(f"Using {name} at {path_str}")
# ffmpeg/ffprobe and mkvmerge/mkvextract always ship together in
# the same folder - if the other half of this pair is also
# still missing, check right there before asking the user to
# browse a second time for what's really one install.
sibling_name = extractor.SIBLING_TOOL_NAMES.get(name)
sibling_path = extractor.guess_sibling_tool_path(path_str, name)
if sibling_path and sibling_name and sibling_name in remaining:
sib_ok, sib_message = extractor.verify_tool_at_path(sibling_path, sibling_name)
if sib_ok:
extractor.set_tool_path(sibling_name, sibling_path)
settings.update(**{f"{sibling_name}_path": sibling_path})
mark_resolved(sibling_name, sib_message)
self.set_status(f"Also found {sibling_name} alongside it at {sibling_path}")
for i, name in enumerate(missing):
row = ctk.CTkFrame(rows_frame, fg_color="transparent")
row.grid(row=i, column=0, columnspan=4, sticky="ew", padx=PAD_SMALL, pady=PAD_SMALL)
row.grid_columnconfigure(1, weight=1)
ctk.CTkLabel(row, text=f"\u2022 {name}", width=110, anchor="w", font=FONT_BODY).grid(
row=0, column=0, sticky="w"
)
status_label = ctk.CTkLabel(
row, text="not found", anchor="w", text_color="gray60", font=FONT_BODY
)
status_label.grid(row=0, column=1, sticky="w", padx=(8, 8))
url = extractor.TOOL_DOWNLOAD_URLS.get(name, "")
download_btn = ctk.CTkButton(
row, text="Download", width=90, font=FONT_BODY,
fg_color=COLOR_NEUTRAL, hover_color=COLOR_NEUTRAL_HOVER,
command=lambda u=url: webbrowser.open(u),
)
download_btn.grid(row=0, column=2, padx=(0, 4))
browse_btn = ctk.CTkButton(
row, text="Browse...", width=90, font=FONT_BODY,
command=lambda n=name: browse_for(n),
)
browse_btn.grid(row=0, column=3)
row_widgets[name] = {
"status": status_label, "browse_btn": browse_btn, "download_btn": download_btn,
}
ctk.CTkLabel(
dialog,
text=(
"Already have these installed? Click Browse and point at the "
"actual .exe - it's checked and saved automatically, no need "
"to edit settings.json by hand. Otherwise, install and make "
"sure they're on your system PATH, then restart the app."
),
wraplength=500,
justify="left",
font=FONT_BODY,
text_color=COLOR_TEXT_MUTED,
).grid(row=2, column=0, sticky="w", padx=PAD_LARGE, pady=(PAD_MED, PAD_LARGE))
ctk.CTkButton(dialog, text="Continue anyway", font=FONT_BODY, command=dialog.destroy).grid(
row=3, column=0, pady=(0, PAD_LARGE)
)
# ------------------------------------------------------------------
# Help menu
# ------------------------------------------------------------------
def _build_menu_bar(self) -> None:
"""
A native Windows menu bar. customtkinter doesn't provide its own
menu bar widget, so this uses plain tkinter's Menu directly - it
renders as a normal top-of-window dropdown menu either way.
Currently just a single Help menu: in-app tips/troubleshooting,
plus links out to the README and issue tracker for anything not
covered there.
"""
menu_bar = tk.Menu(self)
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="Tips & Troubleshooting", command=self._show_help_dialog)
help_menu.add_separator()
help_menu.add_command(
label="View README on GitHub",
command=lambda: webbrowser.open(f"{REPO_URL}#readme"),
)
help_menu.add_command(
label="Report an Issue",
command=lambda: webbrowser.open(f"{REPO_URL}/issues/new/choose"),
)
help_menu.add_separator()
help_menu.add_command(label="About", command=self._show_about_dialog)
menu_bar.add_cascade(label="Help", menu=help_menu)
self.config(menu=menu_bar)
def _show_help_dialog(self) -> None:
dialog = ctk.CTkToplevel(self)
dialog.title("Tips & Troubleshooting")
dialog.geometry("640x560")
dialog.transient(self)
dialog.grab_set()
try:
dialog.configure(fg_color=COLOR_BG)
except Exception:
pass
dialog.grid_columnconfigure(0, weight=1)
dialog.grid_rowconfigure(0, weight=1)
textbox = ctk.CTkTextbox(dialog, wrap="word", font=FONT_BODY, fg_color=COLOR_CARD)
textbox.grid(row=0, column=0, sticky="nsew", padx=PAD_LARGE, pady=(PAD_LARGE, PAD_MED))
textbox.insert("1.0", HELP_TEXT)
# Left editable (rather than state="disabled") purely so normal
# text selection/copy behaves exactly as expected on every
# platform - nothing typed here is read back or saved anywhere,
# so there's no real downside to it being technically editable.
enable_clipboard(textbox)
ctk.CTkButton(dialog, text="Close", font=FONT_BODY, command=dialog.destroy).grid(
row=1, column=0, pady=(0, PAD_LARGE)
)
def _show_about_dialog(self) -> None:
messagebox.showinfo(
"About Disc Track Splitter",
"Disc Track Splitter\n\n"
"Split a ripped Blu-ray concert/music disc into individual, "
"chapter-named song files, using whichever audio track you "
"choose (Atmos, TrueHD, DTS-HD MA, LPCM...) - no re-encoding.\n\n"
f"{REPO_URL}",
parent=self,
)
# ------------------------------------------------------------------
# Layout - three-pane dashboard, .grid() only
# ------------------------------------------------------------------
def _build_layout(self) -> None:
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(2, weight=1) # the two-pane content row stretches
# --- Title bar ---
title_bar = ctk.CTkFrame(self, fg_color="transparent")
title_bar.grid(row=0, column=0, sticky="ew", padx=PAD_LARGE, pady=(PAD_LARGE, PAD_SMALL))
title_bar.grid_columnconfigure(0, weight=1)
ctk.CTkLabel(title_bar, text="DiscTrackSplitter v2.0", font=FONT_TITLE).grid(
row=0, column=0, sticky="w"
)
# --- Resume banner (hidden unless a paused/interrupted job is found) ---
self.resume_banner = ctk.CTkFrame(self, fg_color=COLOR_BLUE, corner_radius=8)
self.resume_banner.grid(row=1, column=0, sticky="ew", padx=PAD_LARGE, pady=(0, PAD_SMALL))
self.resume_banner.grid_columnconfigure(0, weight=1)
self.resume_banner_label = ctk.CTkLabel(
self.resume_banner, text="", justify="left", wraplength=640, anchor="w",
font=(FONT_FAMILY, 12, "bold"), text_color="white",
)
self.resume_banner_label.grid(row=0, column=0, sticky="w", padx=(PAD_MED, PAD_SMALL), pady=10)
ctk.CTkButton(
self.resume_banner, text="Resume Job", width=120, font=FONT_BODY,
fg_color=COLOR_GREEN, hover_color=COLOR_GREEN_HOVER,
command=self._resume_from_banner,
).grid(row=0, column=1, padx=(0, PAD_SMALL), pady=10)
ctk.CTkButton(
self.resume_banner, text="Discard & Start Fresh", width=180, font=FONT_BODY,
fg_color=COLOR_DANGER, hover_color=COLOR_DANGER_HOVER,
command=self._discard_resumable_job,
).grid(row=0, column=2, padx=(0, PAD_MED), pady=10)
self.resume_banner.grid_remove() # shown only once _refresh_resume_banner finds a job
# --- Two-pane content row: Pane 1 (source/config) | Pane 2 (tracklist/naming) ---
content = ctk.CTkFrame(self, fg_color="transparent")
content.grid(row=2, column=0, sticky="nsew", padx=PAD_LARGE, pady=PAD_SMALL)
content.grid_columnconfigure(0, weight=2)
content.grid_columnconfigure(1, weight=3)
content.grid_rowconfigure(0, weight=1)
self._build_pane_source(content)
self._build_pane_tracklist(content)
# --- Pane 3: execution & progress (full width, bottom) ---
self._build_pane_execution()
# --- Status line ---
self.status_label = ctk.CTkLabel(self, text="Ready.", anchor="w", font=FONT_BODY)
self.status_label.grid(row=4, column=0, sticky="ew", padx=PAD_LARGE, pady=(0, PAD_LARGE))
def _build_pane_source(self, parent: ctk.CTkFrame) -> None:
"""Pane 1 - Source & Configuration: disc folder, playlist pick, audio track pick."""
card = ctk.CTkFrame(parent, fg_color=COLOR_CARD, corner_radius=10)
card.grid(row=0, column=0, sticky="nsew", padx=(0, PAD_SMALL))
card.grid_columnconfigure(0, weight=1)
ctk.CTkLabel(card, text="Source & Configuration", font=FONT_HEADER).grid(
row=0, column=0, sticky="w", padx=PAD_MED, pady=(PAD_MED, PAD_SMALL)
)
# --- Source folder row ---
source_row = ctk.CTkFrame(card, fg_color="transparent")
source_row.grid(row=1, column=0, sticky="ew", padx=PAD_MED, pady=PAD_SMALL)
source_row.grid_columnconfigure(0, weight=1)
self.source_entry = ctk.CTkEntry(
source_row, placeholder_text="Path to ripped Blu-ray folder...", font=FONT_BODY
)
self.source_entry.grid(row=0, column=0, sticky="ew", padx=(0, PAD_SMALL))
if self.cfg.get("last_source_folder"):
self.source_entry.insert(0, self.cfg["last_source_folder"])
enable_clipboard(self.source_entry)
# No separate "Scan" button: typing/pasting a valid disc folder (or
# picking one via Browse) scans it automatically, debounced so a
# folder being typed out character-by-character doesn't trigger a
# scan attempt on every keystroke. Enter forces it immediately.
self.source_entry.bind("<KeyRelease>", self._on_source_entry_changed)
self.source_entry.bind("<Return>", lambda _e: self.scan_folder())
ctk.CTkButton(
source_row, text="Browse...", width=90, font=FONT_BODY, command=self.browse_source
).grid(row=0, column=1)
# --- Playlist selection ---
self.playlist_select_label = ctk.CTkLabel(card, text="Playlist:", font=FONT_BODY)
self.playlist_select_label.grid(row=2, column=0, sticky="w", padx=PAD_MED, pady=(PAD_SMALL, 0))
self.playlist_option = ctk.CTkOptionMenu(
card, values=["(scan a folder first)"], font=FONT_BODY,
command=self.on_playlist_selected,
)
self.playlist_option.grid(row=3, column=0, sticky="ew", padx=PAD_MED, pady=(PAD_SMALL, 0))
self.playlist_info_label = ctk.CTkLabel(
card, text="", justify="left", wraplength=360, font=FONT_BODY, text_color=COLOR_TEXT_MUTED
)
self.playlist_info_label.grid(row=4, column=0, sticky="w", padx=PAD_MED, pady=(PAD_SMALL, PAD_SMALL))
self.playlist_select_label.grid_remove()
self.playlist_option.grid_remove()
# --- Audio track selection (this app's "format" pick - which audio
# stream is kept, since it stream-copies rather than re-encoding) ---
ctk.CTkLabel(card, text="Audio Track", font=FONT_HEADER).grid(
row=5, column=0, sticky="w", padx=PAD_MED, pady=(PAD_MED, PAD_SMALL)
)
track_box = ctk.CTkFrame(card, fg_color=COLOR_CARD_INSET, corner_radius=8)
track_box.grid(row=6, column=0, sticky="ew", padx=PAD_MED, pady=(0, PAD_MED))
track_box.grid_columnconfigure(0, weight=1)
self.track_select_label = ctk.CTkLabel(track_box, text="Track:", font=FONT_BODY)
self.track_select_label.grid(row=0, column=0, sticky="w", padx=PAD_SMALL, pady=(PAD_SMALL, 0))
self.track_option = ctk.CTkOptionMenu(
track_box, values=["(scan a folder first)"], font=FONT_BODY,
command=self.on_audio_track_selected,
)
self.track_option.grid(row=1, column=0, sticky="ew", padx=PAD_SMALL, pady=PAD_SMALL)
self.track_info_label = ctk.CTkLabel(
track_box, text="", justify="left", wraplength=340, font=FONT_BODY, text_color=COLOR_TEXT_MUTED
)
self.track_info_label.grid(row=2, column=0, sticky="w", padx=PAD_SMALL, pady=(0, PAD_SMALL))
self.track_select_label.grid_remove()
self.track_option.grid_remove()
card.grid_rowconfigure(7, weight=1) # let the card stretch without leaving a dead gap
def _build_pane_tracklist(self, parent: ctk.CTkFrame) -> None:
"""Pane 2 - Track List & Naming: the four naming methods + the chapter table."""
card = ctk.CTkFrame(parent, fg_color=COLOR_CARD, corner_radius=10)
card.grid(row=0, column=1, sticky="nsew", padx=(PAD_SMALL, 0))
card.grid_columnconfigure(0, weight=1)
card.grid_rowconfigure(2, weight=1)
ctk.CTkLabel(card, text="Track List & Naming", font=FONT_HEADER).grid(
row=0, column=0, sticky="w", padx=PAD_MED, pady=(PAD_MED, PAD_SMALL)
)
# --- Paste tracklist row ---
paste_frame = ctk.CTkFrame(card, fg_color="transparent")
paste_frame.grid(row=1, column=0, sticky="ew", padx=PAD_MED, pady=(0, PAD_SMALL))
paste_frame.grid_columnconfigure(0, weight=1)
ctk.CTkLabel(
paste_frame,
text="Paste tracklist (one song per line, in order) - fills the chapters below automatically:",
font=FONT_BODY, wraplength=520, justify="left",
).grid(row=0, column=0, columnspan=2, sticky="w")
self.paste_textbox = ctk.CTkTextbox(paste_frame, height=64, font=FONT_BODY, fg_color=COLOR_CARD_INSET)
self.paste_textbox.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(PAD_SMALL, PAD_SMALL))
# Paste/cut (mouse or keyboard) and ordinary typing all funnel into
# the same debounced auto-fill - no separate "Fill" click needed.
enable_clipboard(self.paste_textbox, on_change=self._debounced_fill_from_paste)
self.paste_textbox.bind("<KeyRelease>", lambda _e: self._debounced_fill_from_paste())
btn_row = ctk.CTkFrame(paste_frame, fg_color="transparent")
btn_row.grid(row=2, column=0, columnspan=2, sticky="ew")
btn_row.grid_columnconfigure(0, weight=1)
btn_row.grid_columnconfigure(1, weight=1)
ctk.CTkButton(
btn_row, text="Import Tracklist...", font=FONT_BODY,
fg_color=COLOR_NEUTRAL, hover_color=COLOR_NEUTRAL_HOVER,
command=self.import_tracklist,
).grid(row=0, column=0, sticky="ew", padx=(0, PAD_SMALL // 2 or 1))
ctk.CTkButton(
btn_row, text="Search Online...", font=FONT_BODY,
fg_color=COLOR_NEUTRAL, hover_color=COLOR_NEUTRAL_HOVER,
command=self.search_online_tracklist,
).grid(row=0, column=1, sticky="ew", padx=(PAD_SMALL // 2 or 1, 0))
# --- Chapter/track name table (scrollable) ---
self.chapter_scroll = ctk.CTkScrollableFrame(
card, label_text="Chapters", fg_color=COLOR_CARD_INSET
)
self.chapter_scroll.grid(row=2, column=0, sticky="nsew", padx=PAD_MED, pady=(0, PAD_MED))
self.chapter_scroll.grid_columnconfigure(1, weight=1)
def _build_pane_execution(self) -> None:
"""Pane 3 - Execution & Progress: output folder, run controls, progress, rolling log."""
card = ctk.CTkFrame(self, fg_color=COLOR_CARD, corner_radius=10)
card.grid(row=3, column=0, sticky="ew", padx=PAD_LARGE, pady=PAD_SMALL)
card.grid_columnconfigure(0, weight=1)
ctk.CTkLabel(card, text="Execution & Progress", font=FONT_HEADER).grid(
row=0, column=0, sticky="w", padx=PAD_MED, pady=(PAD_MED, PAD_SMALL)
)
# --- Output folder + run row ---
bottom_frame = ctk.CTkFrame(card, fg_color="transparent")
bottom_frame.grid(row=1, column=0, sticky="ew", padx=PAD_MED, pady=(0, PAD_SMALL))
bottom_frame.grid_columnconfigure(0, weight=1)
# The output folder rarely changes run to run, so once one is set
# it's shown as a compact "Output: <path> Change" line instead of
# a full entry+browse row demanding review on every single run.
# The full row only reappears on first run (nothing set yet) or
# when "Change" is clicked.
self.output_compact_frame = ctk.CTkFrame(bottom_frame, fg_color="transparent")
self.output_compact_frame.grid(row=0, column=0, sticky="ew")
self.output_compact_frame.grid_columnconfigure(0, weight=1)
self.output_compact_label = ctk.CTkLabel(
self.output_compact_frame, text="", anchor="w", justify="left", font=FONT_BODY
)
self.output_compact_label.grid(row=0, column=0, sticky="w", padx=(PAD_SMALL, PAD_SMALL), pady=PAD_SMALL)
ctk.CTkButton(
self.output_compact_frame, text="Change", width=80, font=FONT_BODY, fg_color="transparent",
border_width=1, command=self._start_editing_output,
).grid(row=0, column=1, padx=(0, PAD_SMALL), pady=PAD_SMALL)
self.output_edit_frame = ctk.CTkFrame(bottom_frame, fg_color="transparent")
self.output_edit_frame.grid(row=0, column=0, sticky="ew")
self.output_edit_frame.grid_columnconfigure(0, weight=1)
self.output_entry = ctk.CTkEntry(
self.output_edit_frame,
textvariable=self.output_var,
font=FONT_BODY,
placeholder_text="Music library folder (an album subfolder is created automatically)...",
)
self.output_entry.grid(row=0, column=0, sticky="ew", padx=(PAD_SMALL, PAD_SMALL), pady=PAD_SMALL)
enable_clipboard(self.output_entry)
self.output_var.trace_add("write", self._on_output_var_changed)
ctk.CTkButton(
self.output_edit_frame, text="Browse...", width=100, font=FONT_BODY, command=self.browse_output
).grid(row=0, column=1, padx=(0, PAD_SMALL), pady=PAD_SMALL)
ctk.CTkButton(
self.output_edit_frame, text="Done", width=70, font=FONT_BODY, command=self._stop_editing_output,
).grid(row=0, column=2, padx=(0, PAD_SMALL), pady=PAD_SMALL)
# --- Action buttons row: primary action gets the bright accent,
# secondary actions stay neutral, destructive stays red. ---
controls_row = ctk.CTkFrame(card, fg_color="transparent")
controls_row.grid(row=2, column=0, sticky="ew", padx=PAD_MED, pady=(PAD_SMALL, 0))
self.extract_button = ctk.CTkButton(
controls_row, text="Extract & Split", width=150, font=(FONT_FAMILY, 12, "bold"),
fg_color=COLOR_GREEN, hover_color=COLOR_GREEN_HOVER,
command=self.start_extraction,
)
self.extract_button.grid(row=0, column=0, padx=(0, PAD_SMALL))
self.cancel_button = ctk.CTkButton(
controls_row, text="Cancel", width=90, font=FONT_BODY,
fg_color=COLOR_DANGER, hover_color=COLOR_DANGER_HOVER,
command=self.cancel_extraction, state="disabled",
)
self.cancel_button.grid(row=0, column=1, padx=(0, PAD_SMALL))
self.open_log_button = ctk.CTkButton(
controls_row, text="Open Log", width=100, font=FONT_BODY,
fg_color=COLOR_NEUTRAL, hover_color=COLOR_NEUTRAL_HOVER,
command=self.open_log, state="disabled",
)
self.open_log_button.grid(row=0, column=2)
# --- Progress bar (indeterminate: the pipeline reports text
# status, not a percentage, so this shows "something's running"
# honestly rather than fabricating a fake completion percentage) ---
self.progress_bar = ctk.CTkProgressBar(card, mode="indeterminate", progress_color=COLOR_GREEN)
self.progress_bar.grid(row=3, column=0, sticky="ew", padx=PAD_MED, pady=(PAD_MED, PAD_SMALL))
self.progress_bar.set(0)
self.progress_bar.grid_remove() # shown only while a job is running
# --- Compact rolling log (mirrors set_status() calls; full detail
# is still in the on-disk extraction.log via "Open Log") ---
self._log_lines: list[str] = []
self.log_view = ctk.CTkTextbox(
card, height=70, font=(FONT_FAMILY, 10, "normal"), fg_color=COLOR_CARD_INSET,
)
self.log_view.grid(row=4, column=0, sticky="ew", padx=PAD_MED, pady=(0, PAD_MED))
self.log_view.configure(state="disabled")
self._refresh_output_display()
# ------------------------------------------------------------------
# Source folder / scanning
# ------------------------------------------------------------------
def browse_source(self) -> None:
folder = filedialog.askdirectory(title="Select ripped Blu-ray disc folder")
if folder:
self._clear_invalid(self.source_entry)
self.source_entry.delete(0, "end")
self.source_entry.insert(0, folder)
self._refresh_resume_banner()
self.scan_folder()
def _on_source_entry_changed(self, _event=None) -> None:
if self.source_entry.get().strip():
self._clear_invalid(self.source_entry)
self._refresh_resume_banner()
if self._source_debounce_id is not None:
self.after_cancel(self._source_debounce_id)
self._source_debounce_id = self.after(500, self._autoscan_if_valid)
def _autoscan_if_valid(self) -> None:
"""
Fires ~500ms after the source field stops changing. Silently does
nothing if the folder isn't (yet) a valid disc folder - the user
might still be mid-paste or mid-type - rather than popping an
error dialog on every keystroke. Also skips re-scanning a folder
that was just scanned, so finishing a paste doesn't trigger a
second scan on top of the one Enter or Browse already started.
"""
self._source_debounce_id = None
folder_str = self.source_entry.get().strip()
if not folder_str:
return
folder = Path(folder_str)
if not (folder / "BDMV" / "PLAYLIST").is_dir():
return
if folder == self._last_scanned_folder:
return
self.scan_folder()
def scan_folder(self) -> None:
folder_str = self.source_entry.get().strip()
if not folder_str:
self._mark_invalid(self.source_entry)
messagebox.showwarning("No folder", "Pick a folder first.")
return
folder = Path(folder_str)
if not (folder / "BDMV" / "PLAYLIST").is_dir():
self._mark_invalid(self.source_entry)
messagebox.showerror(
"Not a disc folder", "No BDMV/PLAYLIST found in that folder."
)
return
self._clear_invalid(self.source_entry)
self.disc_folder = folder
self._last_scanned_folder = folder
self.set_status(f"Scanning playlists in {folder.name}...")
settings.update(last_source_folder=str(folder))
def work() -> None:
try:
playlists = extractor.scan_disc_folder(folder)
except Exception as exc: # noqa: BLE001
self.after(0, lambda: self._on_scan_failed(exc))
return
self.after(0, lambda: self._on_scan_complete(playlists))
threading.Thread(target=work, daemon=True).start()
def _on_scan_failed(self, exc: Exception) -> None:
self.set_status("Scan failed - see error dialog.")
messagebox.showerror(
"Scan failed",
f"{exc}\n\nCheck that mkvmerge is installed and on PATH "
"(or its path is set correctly in settings).",
)
def _on_scan_complete(self, playlists: list[extractor.Playlist]) -> None:
self._refresh_resume_banner()
self.playlists = playlists
if not playlists:
self.set_status("No playlists found.")
return
# Score every playlist as a candidate instead of silently picking
# whichever Atmos playlist has the most chapters - the dropdown
# is sorted best-first and the reasons behind each score are
# shown below it so the choice can actually be reviewed, not just
# accepted on faith.
self.playlist_scores = extractor.score_playlists(playlists)
self.playlists = [s.playlist for s in self.playlist_scores]
labels = [self._playlist_label(s) for s in self.playlist_scores]
self.playlist_option.configure(values=labels)
self.playlist_option.set(labels[0])
self.on_playlist_selected(labels[0])
# Only ask the user to choose when there's a real choice: 2+
# playlists that both have at least one usable audio track and
# aren't flagged as a duplicate/alternate angle of each other.
# Otherwise the dropdown is a decision UI for a non-decision, so
# it stays hidden - the reasoning label below it is never hidden
# either way.
real_candidates = [
s for s in self.playlist_scores if s.playlist.audio_tracks and s.duplicate_of is None
]
if len(real_candidates) > 1:
self.playlist_select_label.grid()
self.playlist_option.grid()
else:
self.playlist_select_label.grid_remove()
self.playlist_option.grid_remove()
top = self.playlist_scores[0]
if not top.playlist.audio_tracks:
status = "No audio tracks found in any playlist."
elif top.playlist.has_atmos:
status = f"Best candidate: {top.playlist.path.name} (score {top.score:.0f}) - review below."
else:
status = (
f"Best candidate: {top.playlist.path.name} (score {top.score:.0f}) - "
"no Atmos track, choose an audio track below."
)
if self.disc_folder is not None:
sidecar_files = extractor.find_sidecar_tracklist_files(self.disc_folder)
if sidecar_files:
names = ", ".join(f.name for f in sidecar_files[:3])
if len(sidecar_files) > 3:
names += f", +{len(sidecar_files) - 3} more"
status += f" Possible tracklist file(s) found in the disc folder: {names} - use Import Tracklist to review."
self.set_status(status)
@staticmethod
def _playlist_label(score: extractor.PlaylistScore) -> str:
tag = " [possible duplicate]" if score.duplicate_of else ""
atmos_note = ", atmos: yes" if score.playlist.has_atmos else ""
return (
f"{score.playlist.path.name} - score {score.score:.0f} "
f"(chapters: {score.playlist.chapter_count}, audio tracks: "
f"{len(score.playlist.audio_tracks)}{atmos_note}){tag}"
)
def on_playlist_selected(self, label: str) -> None:
idx = self.playlist_option.cget("values").index(label)
score = self.playlist_scores[idx]
self.selected_playlist_score = score
self.selected_playlist = score.playlist
pl = self.selected_playlist
info_lines = [f"{len(pl.tracks)} tracks, {pl.chapter_count} chapters."]
if pl.duration_seconds:
info_lines[0] += f" Runs {pl.duration_seconds / 60:.0f} minutes."
real_candidates = [
s for s in self.playlist_scores if s.playlist.audio_tracks and s.duplicate_of is None
]
if len(real_candidates) > 1:
info_lines.append("Why this ranking:")
else:
info_lines.append("Why this one was picked automatically:")
info_lines.extend(f" - {r}" for r in score.reasons)
self.playlist_info_label.configure(text="\n".join(info_lines))
self._populate_audio_track_options(pl)
# Preserve anything already typed for chapter numbers that still
# exist in the new playlist, so switching between candidate
# playlists (e.g. a different angle/cut with matching chapter
# positions) doesn't throw away names entered by hand.
preserved = {
i: var.get() for i, var in self.chapter_name_vars.items() if var.get().strip()
}
self._rebuild_chapter_table(pl.chapter_count, preserve=preserved)
self.selected_playlist_chapters = [] # stale until _load_embedded_chapter_names finishes for this playlist
self._load_embedded_chapter_names(pl)
# ------------------------------------------------------------------
# Audio track selection
# ------------------------------------------------------------------
def _populate_audio_track_options(self, pl: extractor.Playlist) -> None:
"""