-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbpm_manager.py
More file actions
719 lines (595 loc) · 27.7 KB
/
bpm_manager.py
File metadata and controls
719 lines (595 loc) · 27.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
#!/usr/bin/env python3
"""
BPM Manager - A tool for managing BPM tags in audio files
Supports MP3, FLAC, M4A, OGG, and other common formats
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path
import mutagen
from mutagen.id3 import ID3, TBPM
from mutagen.mp4 import MP4
from mutagen.flac import FLAC
from mutagen.oggvorbis import OggVorbis
import threading
import time
class TapTempoWindow:
def __init__(self, parent, callback):
self.window = tk.Toplevel(parent)
self.window.title("Tap Tempo")
self.window.geometry("400x350")
self.callback = callback
self.tap_times = []
self.bpm = None
# Configure dark mode
self.window.configure(bg='#2b2b2b')
# Main display
self.bpm_label = tk.Label(self.window, text="--",
font=("Arial", 60, "bold"),
bg='#2b2b2b', fg='#4a9eff')
self.bpm_label.pack(pady=20)
# Tap count
self.tap_count_label = tk.Label(self.window, text="0 taps",
bg='#2b2b2b', fg='#888888',
font=("Arial", 10))
self.tap_count_label.pack()
# Instructions
instructions = tk.Label(self.window,
text="Press SPACE or click button to tap the beat\n(need at least 2 taps, better with 10+)",
bg='#2b2b2b', fg='#cccccc',
font=("Arial", 9))
instructions.pack(pady=15)
# Tap button
self.tap_button = tk.Button(self.window, text="TAP",
command=self.tap,
font=("Arial", 24, "bold"),
bg='#1a1a1a', fg='#e0e0e0',
activebackground='#2a2a2a',
relief=tk.RAISED,
bd=3,
width=12, height=2)
self.tap_button.pack(pady=15)
# Modify buttons
modify_frame = tk.Frame(self.window, bg='#2b2b2b')
modify_frame.pack(pady=10)
tk.Button(modify_frame, text="÷ 2", command=self.halve,
bg='#444444', fg='#ffffff',
activebackground='#555555',
font=("Arial", 10),
width=6).pack(side=tk.LEFT, padx=5)
tk.Button(modify_frame, text="× 2", command=self.double,
bg='#444444', fg='#ffffff',
activebackground='#555555',
font=("Arial", 10),
width=6).pack(side=tk.LEFT, padx=5)
# Action buttons
btn_frame = tk.Frame(self.window, bg='#2b2b2b')
btn_frame.pack(pady=10)
tk.Button(btn_frame, text="Reset", command=self.reset,
bg='#444444', fg='#ffffff',
activebackground='#555555',
width=10).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Apply BPM", command=self.apply_bpm,
bg='#006600', fg='#ffffff',
activebackground='#008800',
width=10).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Cancel", command=self.window.destroy,
bg='#660000', fg='#ffffff',
activebackground='#880000',
width=10).pack(side=tk.LEFT, padx=5)
# Bind spacebar and R key
self.window.bind('<space>', lambda e: self.tap())
self.window.bind('r', lambda e: self.reset())
self.window.bind('R', lambda e: self.reset())
self.window.focus_set()
def tap(self):
current_time = time.time()
self.tap_times.append(current_time)
# Keep only taps from last 10 seconds
cutoff_time = current_time - 10.0
self.tap_times = [t for t in self.tap_times if t > cutoff_time]
# Update tap count
tap_count = len(self.tap_times)
self.tap_count_label.config(text=f"{tap_count} tap{'s' if tap_count != 1 else ''}")
# Calculate BPM if we have at least 2 taps
if len(self.tap_times) >= 2:
intervals = []
for i in range(1, len(self.tap_times)):
intervals.append(self.tap_times[i] - self.tap_times[i-1])
avg_interval = sum(intervals) / len(intervals)
self.bpm = round(60.0 / avg_interval)
self.bpm_label.config(text=str(self.bpm))
# Visual feedback
self.tap_button.config(relief=tk.SUNKEN, bg='#2a2a2a')
self.window.after(100, lambda: self.tap_button.config(relief=tk.RAISED, bg='#1a1a1a'))
def halve(self):
if self.bpm is not None:
self.bpm = round(self.bpm / 2)
self.bpm_label.config(text=str(self.bpm))
def double(self):
if self.bpm is not None:
self.bpm = self.bpm * 2
self.bpm_label.config(text=str(self.bpm))
def reset(self):
self.tap_times = []
self.bpm = None
self.bpm_label.config(text="--")
self.tap_count_label.config(text="0 taps")
def apply_bpm(self):
if self.bpm is not None and self.bpm > 0:
self.callback(self.bpm)
self.window.destroy()
else:
messagebox.showwarning("No BPM", "Tap at least twice to calculate BPM", parent=self.window)
class BPMManager:
def __init__(self, root):
self.root = root
self.root.title("BPM Manager")
self.root.geometry("1100x700")
self.files = []
self.selected_indices = []
self.stats = None
self.marked_items = set() # Track marked/flagged items
self.setup_dark_mode()
self.setup_ui()
self.setup_keyboard_shortcuts()
def setup_dark_mode(self):
"""Configure dark mode colors"""
self.colors = {
'bg': '#2b2b2b',
'fg': '#e0e0e0',
'select_bg': '#404040',
'select_fg': '#ffffff',
'button_bg': '#3c3c3c',
'button_fg': '#e0e0e0',
'entry_bg': '#333333',
'entry_fg': '#e0e0e0',
'marked': '#ff4444' # Red for marked files
}
self.root.configure(bg=self.colors['bg'])
# Configure ttk styles
style = ttk.Style()
style.theme_use('clam')
# Configure Treeview
style.configure("Treeview",
background=self.colors['bg'],
foreground=self.colors['fg'],
fieldbackground=self.colors['bg'],
borderwidth=0)
style.map('Treeview', background=[('selected', self.colors['select_bg'])])
# Configure other widgets
style.configure("TFrame", background=self.colors['bg'])
style.configure("TLabel", background=self.colors['bg'], foreground=self.colors['fg'])
style.configure("TLabelFrame", background=self.colors['bg'], foreground=self.colors['fg'])
style.configure("TLabelFrame.Label", background=self.colors['bg'], foreground=self.colors['fg'])
style.configure("TButton", background=self.colors['button_bg'], foreground=self.colors['button_fg'])
style.configure("Accent.TButton", background='#006600', foreground='#ffffff')
def setup_keyboard_shortcuts(self):
"""Setup keyboard shortcuts"""
self.root.bind('<Control-a>', lambda e: self.select_all())
self.root.bind('<Control-A>', lambda e: self.select_all())
self.root.bind('<Control-r>', lambda e: self.reverse_selection())
self.root.bind('<Control-R>', lambda e: self.reverse_selection())
self.root.bind('<Control-d>', lambda e: self.deselect_all())
self.root.bind('<Control-D>', lambda e: self.deselect_all())
self.root.bind('<Control-m>', lambda e: self.toggle_mark())
self.root.bind('<Control-M>', lambda e: self.toggle_mark())
def setup_ui(self):
# Top frame - folder selection and stats
top_frame = ttk.Frame(self.root, padding="10")
top_frame.pack(fill=tk.X)
# Buttons
button_frame = ttk.Frame(top_frame)
button_frame.pack(side=tk.LEFT)
ttk.Button(button_frame, text="Load Folder", command=self.load_folder).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Load Files", command=self.load_files).pack(side=tk.LEFT, padx=5)
self.status_label = ttk.Label(button_frame, text="No files loaded")
self.status_label.pack(side=tk.LEFT, padx=20)
# Stats panel
self.stats_frame = ttk.LabelFrame(top_frame, text="BPM Statistics", padding="10")
self.stats_frame.pack(side=tk.RIGHT, padx=10)
self.stats_text = tk.Text(self.stats_frame, height=4, width=50,
font=("Courier", 9), state="disabled",
relief=tk.FLAT,
bg=self.colors['bg'],
fg=self.colors['fg'])
self.stats_text.pack()
self.update_stats_display(None)
# Middle frame - file list
middle_frame = ttk.Frame(self.root, padding="10")
middle_frame.pack(fill=tk.BOTH, expand=True)
# Scrollbar
scrollbar = ttk.Scrollbar(middle_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Treeview for file list
columns = ("filename", "current_bpm", "new_bpm")
self.tree = ttk.Treeview(middle_frame, columns=columns, show="headings",
yscrollcommand=scrollbar.set, selectmode="extended")
self.tree.heading("filename", text="Filename")
self.tree.heading("current_bpm", text="Current BPM")
self.tree.heading("new_bpm", text="New BPM")
self.tree.column("filename", width=550)
self.tree.column("current_bpm", width=150)
self.tree.column("new_bpm", width=150)
# Configure tag for marked files
self.tree.tag_configure('marked', foreground=self.colors['marked'])
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=self.tree.yview)
self.tree.bind("<<TreeviewSelect>>", self.on_select)
# Bottom frame - controls
bottom_frame = ttk.Frame(self.root, padding="10")
bottom_frame.pack(fill=tk.X)
# BPM modification buttons (first row)
mod_frame = ttk.LabelFrame(bottom_frame, text="BPM Modifications", padding="10")
mod_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
ttk.Button(mod_frame, text="Round to Integer",
command=self.round_bpm).pack(side=tk.LEFT, padx=5)
ttk.Button(mod_frame, text="÷ 2 (Halve)",
command=self.halve_bpm).pack(side=tk.LEFT, padx=5)
ttk.Button(mod_frame, text="× 2 (Double)",
command=self.double_bpm).pack(side=tk.LEFT, padx=5)
ttk.Button(mod_frame, text="Set Blank",
command=self.set_blank_bpm).pack(side=tk.LEFT, padx=5)
ttk.Button(mod_frame, text="🎹 Tap Tempo",
command=self.open_tap_tempo).pack(side=tk.LEFT, padx=5)
# Manual entry
manual_frame = ttk.Frame(mod_frame)
manual_frame.pack(side=tk.LEFT, padx=10)
ttk.Label(manual_frame, text="Set BPM:").pack(side=tk.LEFT, padx=2)
self.manual_bpm_entry = ttk.Entry(manual_frame, width=8)
self.manual_bpm_entry.pack(side=tk.LEFT, padx=2)
ttk.Button(manual_frame, text="Apply",
command=self.set_manual_bpm).pack(side=tk.LEFT, padx=2)
# Selection and action buttons (second row)
action_container = ttk.Frame(bottom_frame)
action_container.pack(side=tk.TOP, fill=tk.X, padx=5)
# Selection controls
select_frame = ttk.LabelFrame(action_container, text="Selection (Ctrl+A/R/D/M)", padding="10")
select_frame.pack(side=tk.LEFT, padx=5)
ttk.Button(select_frame, text="Select All",
command=self.select_all).pack(side=tk.LEFT, padx=5)
ttk.Button(select_frame, text="Reverse",
command=self.reverse_selection).pack(side=tk.LEFT, padx=5)
ttk.Button(select_frame, text="Deselect",
command=self.deselect_all).pack(side=tk.LEFT, padx=5)
ttk.Button(select_frame, text="🚩 Mark/Unmark",
command=self.toggle_mark).pack(side=tk.LEFT, padx=5)
# Action buttons
action_frame = ttk.LabelFrame(action_container, text="Actions", padding="10")
action_frame.pack(side=tk.LEFT, padx=5)
ttk.Button(action_frame, text="✓ Apply Changes",
command=self.apply_changes,
style="Accent.TButton").pack(side=tk.LEFT, padx=5)
ttk.Button(action_frame, text="Clear Preview",
command=self.clear_preview).pack(side=tk.LEFT, padx=5)
ttk.Button(action_frame, text="Filter: Decimals Only",
command=self.filter_decimals).pack(side=tk.LEFT, padx=5)
ttk.Button(action_frame, text="Show All",
command=self.show_all).pack(side=tk.LEFT, padx=5)
def load_folder(self):
folder = filedialog.askdirectory(title="Select Music Folder")
if folder:
self.load_audio_files(Path(folder))
def load_files(self):
files = filedialog.askopenfilenames(
title="Select Audio Files",
filetypes=[
("Audio Files", "*.mp3 *.flac *.m4a *.ogg *.opus *.wma"),
("All Files", "*.*")
]
)
if files:
self.load_audio_files([Path(f) for f in files])
def load_audio_files(self, paths):
self.tree.delete(*self.tree.get_children())
self.files = []
self.stats = None
self.marked_items.clear()
if isinstance(paths, Path):
# Single folder
audio_extensions = {'.mp3', '.flac', '.m4a', '.ogg', '.opus', '.wma'}
file_list = [f for f in paths.rglob('*') if f.suffix.lower() in audio_extensions]
else:
# List of files
file_list = paths
bpm_values = []
files_with_bpm = 0
files_with_decimals = 0
for file_path in sorted(file_list):
try:
bpm = self.get_bpm(file_path)
file_info = {
'path': file_path,
'current_bpm': bpm,
'new_bpm': None
}
self.files.append(file_info)
# Collect stats
if bpm is not None:
bpm_values.append(bpm)
files_with_bpm += 1
if bpm != int(bpm):
files_with_decimals += 1
bpm_display = f"{bpm:.2f}" if bpm else "No BPM"
self.tree.insert("", tk.END, values=(file_path.name, bpm_display, ""))
except Exception as e:
print(f"Error loading {file_path}: {e}")
# Calculate statistics
if bpm_values:
self.stats = {
'total_files': len(self.files),
'files_with_bpm': files_with_bpm,
'files_with_decimals': files_with_decimals,
'min_bpm': min(bpm_values),
'max_bpm': max(bpm_values),
'avg_bpm': sum(bpm_values) / len(bpm_values)
}
self.status_label.config(text=f"{len(self.files)} files loaded")
self.update_stats_display(self.stats)
def update_stats_display(self, stats):
"""Update the statistics display panel"""
self.stats_text.config(state="normal")
self.stats_text.delete(1.0, tk.END)
if stats:
text = f"Files: {stats['total_files']} | With BPM: {stats['files_with_bpm']} | With Decimals: {stats['files_with_decimals']}\n"
text += f"Min: {stats['min_bpm']:.1f} | Max: {stats['max_bpm']:.1f} | Avg: {stats['avg_bpm']:.1f}\n"
# Add genre suggestions based on BPM ranges
avg = stats['avg_bpm']
if 60 <= avg <= 90:
text += f"Range suggests: Downtempo, Trip-Hop, Dub"
elif 90 <= avg <= 130:
text += f"Range suggests: Hip-Hop, House, Techno"
elif 130 <= avg <= 150:
text += f"Range suggests: Trance, Hard House"
elif 150 <= avg <= 180:
text += f"Range suggests: Drum & Bass, Jungle"
elif 180 <= avg <= 220:
text += f"Range suggests: Hardcore, Breakcore"
else:
text += f"Mixed tempo range"
else:
text = "Load files to see BPM statistics"
self.stats_text.insert(1.0, text)
self.stats_text.config(state="disabled")
def get_bpm(self, file_path):
"""Extract BPM from audio file"""
try:
audio = mutagen.File(file_path)
if audio is None:
return None
# Try different tag formats
if isinstance(audio, mutagen.mp3.MP3):
if 'TBPM' in audio.tags:
return float(audio.tags['TBPM'].text[0])
elif isinstance(audio, MP4):
if '----:com.apple.iTunes:BPM' in audio.tags:
return float(audio.tags['----:com.apple.iTunes:BPM'][0].decode())
elif 'tmpo' in audio.tags:
return float(audio.tags['tmpo'][0])
elif isinstance(audio, (FLAC, OggVorbis)):
if 'bpm' in audio:
return float(audio['bpm'][0])
return None
except:
return None
def on_select(self, event):
self.selected_indices = [self.tree.index(item) for item in self.tree.selection()]
def select_all(self):
"""Select all files in the list"""
for item in self.tree.get_children():
self.tree.selection_add(item)
def reverse_selection(self):
"""Reverse the current selection"""
all_items = self.tree.get_children()
current_selection = set(self.tree.selection())
# Clear current selection
self.tree.selection_remove(*current_selection)
# Select everything that wasn't selected
for item in all_items:
if item not in current_selection:
self.tree.selection_add(item)
def deselect_all(self):
"""Deselect all files"""
self.tree.selection_remove(*self.tree.selection())
def toggle_mark(self):
"""Mark/unmark selected files (visual flag for files needing attention)"""
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
for idx in self.selected_indices:
item = self.tree.get_children()[idx]
if item in self.marked_items:
# Unmark
self.marked_items.remove(item)
self.tree.item(item, tags=())
else:
# Mark
self.marked_items.add(item)
self.tree.item(item, tags=('marked',))
def open_tap_tempo(self):
"""Open the tap tempo window"""
TapTempoWindow(self.root, self.apply_tap_bpm)
def apply_tap_bpm(self, bpm):
"""Apply BPM from tap tempo to selected files"""
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files to apply tapped BPM")
return
for idx in self.selected_indices:
file_info = self.files[idx]
file_info['new_bpm'] = bpm
self.update_tree_item(idx, bpm)
def round_bpm(self):
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
for idx in self.selected_indices:
file_info = self.files[idx]
if file_info['current_bpm']:
new_bpm = round(file_info['current_bpm'])
file_info['new_bpm'] = new_bpm
self.update_tree_item(idx, new_bpm)
def halve_bpm(self):
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
for idx in self.selected_indices:
file_info = self.files[idx]
if file_info['current_bpm']:
new_bpm = round(file_info['current_bpm'] / 2)
file_info['new_bpm'] = new_bpm
self.update_tree_item(idx, new_bpm)
def double_bpm(self):
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
for idx in self.selected_indices:
file_info = self.files[idx]
if file_info['current_bpm']:
new_bpm = round(file_info['current_bpm'] * 2)
file_info['new_bpm'] = new_bpm
self.update_tree_item(idx, new_bpm)
def set_blank_bpm(self):
"""Set BPM to blank/empty for ambient tracks or tracks without rhythm"""
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
for idx in self.selected_indices:
file_info = self.files[idx]
file_info['new_bpm'] = 0 # 0 means remove BPM tag
self.update_tree_item(idx, "Blank")
def set_manual_bpm(self):
if not self.selected_indices:
messagebox.showwarning("No Selection", "Please select files first")
return
try:
bpm = float(self.manual_bpm_entry.get())
if bpm <= 0 or bpm > 500:
messagebox.showerror("Invalid BPM", "BPM must be between 0 and 500")
return
for idx in self.selected_indices:
file_info = self.files[idx]
new_bpm = round(bpm)
file_info['new_bpm'] = new_bpm
self.update_tree_item(idx, new_bpm)
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid number")
def update_tree_item(self, idx, new_bpm):
item = self.tree.get_children()[idx]
values = self.tree.item(item)['values']
display_value = str(new_bpm) if new_bpm != "Blank" else "Blank"
self.tree.item(item, values=(values[0], values[1], display_value))
def clear_preview(self):
for idx in self.selected_indices:
self.files[idx]['new_bpm'] = None
item = self.tree.get_children()[idx]
values = self.tree.item(item)['values']
self.tree.item(item, values=(values[0], values[1], ""))
def apply_changes(self):
files_to_update = [f for f in self.files if f['new_bpm'] is not None]
if not files_to_update:
messagebox.showinfo("No Changes", "No BPM changes to apply")
return
if not messagebox.askyesno("Confirm",
f"Apply BPM changes to {len(files_to_update)} files?"):
return
# Run in thread to avoid freezing UI
thread = threading.Thread(target=self.apply_changes_thread, args=(files_to_update,))
thread.start()
def apply_changes_thread(self, files_to_update):
success_count = 0
error_count = 0
for file_info in files_to_update:
try:
if file_info['new_bpm'] == 0:
# Remove BPM tag
self.remove_bpm(file_info['path'])
file_info['current_bpm'] = None
else:
self.set_bpm(file_info['path'], file_info['new_bpm'])
file_info['current_bpm'] = file_info['new_bpm']
file_info['new_bpm'] = None
success_count += 1
except Exception as e:
print(f"Error updating {file_info['path']}: {e}")
error_count += 1
# Update UI in main thread
self.root.after(0, lambda: self.apply_complete(success_count, error_count))
def apply_complete(self, success_count, error_count):
# Refresh display and recalculate stats
bpm_values = []
files_with_bpm = 0
files_with_decimals = 0
for idx, file_info in enumerate(self.files):
item = self.tree.get_children()[idx]
bpm = file_info['current_bpm']
bpm_display = f"{bpm:.2f}" if bpm else "No BPM"
self.tree.item(item, values=(file_info['path'].name, bpm_display, ""))
if bpm is not None:
bpm_values.append(bpm)
files_with_bpm += 1
if bpm != int(bpm):
files_with_decimals += 1
# Update stats
if bpm_values:
self.stats = {
'total_files': len(self.files),
'files_with_bpm': files_with_bpm,
'files_with_decimals': files_with_decimals,
'min_bpm': min(bpm_values),
'max_bpm': max(bpm_values),
'avg_bpm': sum(bpm_values) / len(bpm_values)
}
self.update_stats_display(self.stats)
msg = f"Updated {success_count} files successfully"
if error_count:
msg += f"\n{error_count} files had errors"
messagebox.showinfo("Complete", msg)
def set_bpm(self, file_path, bpm):
"""Write BPM to audio file"""
audio = mutagen.File(file_path)
if isinstance(audio, mutagen.mp3.MP3):
if audio.tags is None:
audio.add_tags()
audio.tags['TBPM'] = TBPM(encoding=3, text=str(bpm))
elif isinstance(audio, MP4):
audio.tags['tmpo'] = [bpm]
elif isinstance(audio, (FLAC, OggVorbis)):
audio['bpm'] = str(bpm)
audio.save()
def remove_bpm(self, file_path):
"""Remove BPM tag from audio file"""
audio = mutagen.File(file_path)
if isinstance(audio, mutagen.mp3.MP3):
if audio.tags and 'TBPM' in audio.tags:
del audio.tags['TBPM']
elif isinstance(audio, MP4):
if 'tmpo' in audio.tags:
del audio.tags['tmpo']
elif isinstance(audio, (FLAC, OggVorbis)):
if 'bpm' in audio:
del audio['bpm']
audio.save()
def filter_decimals(self):
for item in self.tree.get_children():
values = self.tree.item(item)['values']
bpm_str = values[1]
# Hide if no decimal or if it's "No BPM"
if bpm_str == "No BPM" or '.' not in bpm_str:
self.tree.detach(item)
else:
# Check if has non-zero decimals
try:
bpm = float(bpm_str)
if bpm == int(bpm):
self.tree.detach(item)
except:
pass
def show_all(self):
for item in self.tree.get_children():
self.tree.reattach(item, '', tk.END)
def main():
root = tk.Tk()
app = BPMManager(root)
root.mainloop()
if __name__ == "__main__":
main()