-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvert_to_apple_loops.py
More file actions
executable file
·1675 lines (1390 loc) · 63.3 KB
/
Copy pathconvert_to_apple_loops.py
File metadata and controls
executable file
·1675 lines (1390 loc) · 63.3 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
#!/usr/bin/env python3
"""
Convert audio and MIDI files to Apple Loop CAF format with metadata.
This tool converts audio files (WAV, AIFF, MP3, M4A, ALAC, FLAC, etc.) and
MIDI files (.mid, .midi) to the Apple Loop CAF format used by Logic Pro and
GarageBand. It extracts metadata from filenames and embeds it in the correct
format for the Loop Browser.
For AUDIO files, the output format matches official Apple Loops files exactly:
- CAF container format with AAC/ALAC audio encoding
- UUID chunk with Apple Loop metadata (29819273-b5bf-4aef-b78d-62d1ef90bb2c)
- UUID chunk with beat markers (0352811b-9d5d-42e1-882d-6af61a6b330c)
- info chunk with genre for Spotlight indexing
For MIDI files, the output contains:
- CAF container with embedded MIDI data in standard 'midi' chunk
- Same UUID chunks for Apple Loop metadata and beat markers
- Allows MIDI editing in Logic Pro's Piano Roll
Usage:
# Convert a single audio file
./convert_to_apple_loops.py input.wav -o output.caf --tempo 120 --key Am
# Convert a single MIDI file
./convert_to_apple_loops.py input.mid -o output.caf --category Keyboards
# Bulk convert a directory (auto-detects audio and MIDI files)
./convert_to_apple_loops.py /path/to/loops/ --output-dir "~/Library/Audio/Apple Loops/User Loops/"
# Dry run to preview metadata extraction
./convert_to_apple_loops.py /path/to/loops/ --dry-run
See APPLE_LOOPS_FORMAT.md for detailed format documentation.
"""
import os
import re
import struct
import subprocess
import argparse
import tempfile
import sys
from pathlib import Path
from typing import Optional, Dict, List, Tuple, Set
from dataclasses import dataclass, field
import numpy as np
# Apple Loop metadata UUID
APPLE_LOOP_META_UUID = bytes.fromhex('29819273b5bf4aefb78d62d1ef90bb2c')
# Apple Loop beat markers UUID
BEAT_MARKERS_UUID = bytes.fromhex('0352811b9d5d42e1882d6af61a6b330c')
# CAF file header
CAF_HEADER = b'caff' + struct.pack('>H', 1) + struct.pack('>H', 0)
# Supported audio input formats
AUDIO_EXTENSIONS = (
'.wav', '.aif', '.aiff', '.mp3', '.m4a', '.aac',
'.flac', '.alac', '.caf', '.ogg', '.wma'
)
# Supported MIDI input formats
MIDI_EXTENSIONS = ('.mid', '.midi', '.smf')
# All supported extensions
SUPPORTED_EXTENSIONS = AUDIO_EXTENSIONS + MIDI_EXTENSIONS
@dataclass
class LoopMetadata:
"""Apple Loop metadata structure."""
category: str = "Other Instrument"
subcategory: str = "Other"
genre: str = "Other Genre"
beat_count: int = 0
time_signature: str = "4/4"
key_signature: str = "" # Empty for drums/percussion
key_type: str = "" # major, minor, both, neither
descriptors: str = ""
tempo: Optional[int] = None # Used for beat_count calculation
duration: Optional[float] = None # Duration in seconds
loop_type: str = "audio" # "audio" or "midi"
@dataclass
class MIDIInfo:
"""Information extracted from a MIDI file."""
tempo: int = 120
time_signature: Tuple[int, int] = (4, 4)
key_signature: str = ""
key_type: str = ""
duration: float = 0.0
beat_count: int = 0
ticks_per_beat: int = 480
num_tracks: int = 0
num_notes: int = 0
channels: Set[int] = field(default_factory=set)
programs: Set[int] = field(default_factory=set)
raw_data: bytes = b''
@dataclass
class OnsetDetectionConfig:
"""Configuration for onset/transient detection."""
hop_length: int = 512
backtrack: bool = True
threshold: float = 0.3
wait: float = 0.03
min_markers_per_beat: float = 1.0
class MIDIParser:
"""Parse MIDI files and extract metadata."""
KEY_SIGNATURES = {
(-7, 0): ('Cb', 'major'), (-6, 0): ('Gb', 'major'), (-5, 0): ('Db', 'major'),
(-4, 0): ('Ab', 'major'), (-3, 0): ('Eb', 'major'), (-2, 0): ('Bb', 'major'),
(-1, 0): ('F', 'major'), (0, 0): ('C', 'major'), (1, 0): ('G', 'major'),
(2, 0): ('D', 'major'), (3, 0): ('A', 'major'), (4, 0): ('E', 'major'),
(5, 0): ('B', 'major'), (6, 0): ('F#', 'major'), (7, 0): ('C#', 'major'),
(-7, 1): ('Ab', 'minor'), (-6, 1): ('Eb', 'minor'), (-5, 1): ('Bb', 'minor'),
(-4, 1): ('F', 'minor'), (-3, 1): ('C', 'minor'), (-2, 1): ('G', 'minor'),
(-1, 1): ('D', 'minor'), (0, 1): ('A', 'minor'), (1, 1): ('E', 'minor'),
(2, 1): ('B', 'minor'), (3, 1): ('F#', 'minor'), (4, 1): ('C#', 'minor'),
(5, 1): ('G#', 'minor'), (6, 1): ('D#', 'minor'), (7, 1): ('A#', 'minor'),
}
def parse_file(self, midi_path: Path) -> MIDIInfo:
"""Parse a MIDI file and extract metadata."""
with open(midi_path, 'rb') as f:
raw_data = f.read()
info = MIDIInfo(raw_data=raw_data)
try:
import mido
midi = mido.MidiFile(str(midi_path))
info = self._parse_with_mido(midi, raw_data)
except ImportError:
info = self._parse_basic(raw_data)
return info
def _parse_with_mido(self, midi, raw_data: bytes) -> MIDIInfo:
"""Parse MIDI file using mido library."""
import mido
info = MIDIInfo(raw_data=raw_data)
info.ticks_per_beat = midi.ticks_per_beat
info.num_tracks = len(midi.tracks)
tempo = 500000
total_ticks = 0
for track in midi.tracks:
track_ticks = 0
for msg in track:
track_ticks += msg.time
if msg.type == 'set_tempo':
tempo = msg.tempo
elif msg.type == 'time_signature':
info.time_signature = (msg.numerator, msg.denominator)
elif msg.type == 'key_signature':
key_info = self._parse_key_signature_mido(msg)
if key_info:
info.key_signature, info.key_type = key_info
elif msg.type == 'note_on' and msg.velocity > 0:
info.num_notes += 1
info.channels.add(msg.channel)
elif msg.type == 'program_change':
info.programs.add(msg.program)
total_ticks = max(total_ticks, track_ticks)
info.tempo = round(60000000 / tempo)
info.duration = total_ticks * (tempo / 1e6) / info.ticks_per_beat
if info.duration > 0 and info.tempo > 0:
info.beat_count = round((info.tempo * info.duration) / 60)
return info
def _parse_key_signature_mido(self, msg) -> Optional[Tuple[str, str]]:
"""Parse key signature from mido message."""
try:
key = msg.key
if key.endswith('m'):
return key[:-1], 'minor'
else:
return key, 'major'
except Exception:
return None
def _parse_basic(self, raw_data: bytes) -> MIDIInfo:
"""Basic MIDI parsing without mido library."""
info = MIDIInfo(raw_data=raw_data)
if len(raw_data) < 14 or raw_data[0:4] != b'MThd':
return info
header_length = struct.unpack('>I', raw_data[4:8])[0]
num_tracks = struct.unpack('>H', raw_data[10:12])[0]
division = struct.unpack('>H', raw_data[12:14])[0]
info.num_tracks = num_tracks
info.ticks_per_beat = division if not (division & 0x8000) else 480
pos = 8 + header_length
total_ticks = 0
tempo = 500000
for _ in range(num_tracks):
if pos + 8 > len(raw_data) or raw_data[pos:pos+4] != b'MTrk':
break
track_length = struct.unpack('>I', raw_data[pos+4:pos+8])[0]
track_end = pos + 8 + track_length
track_pos = pos + 8
track_ticks = 0
while track_pos < track_end:
delta = 0
while track_pos < track_end:
byte = raw_data[track_pos]
track_pos += 1
delta = (delta << 7) | (byte & 0x7F)
if not (byte & 0x80):
break
track_ticks += delta
if track_pos >= track_end:
break
status = raw_data[track_pos]
if status == 0xFF:
if track_pos + 2 >= len(raw_data):
break
meta_type = raw_data[track_pos + 1]
meta_length = raw_data[track_pos + 2]
track_pos += 3
if meta_type == 0x51 and meta_length == 3 and track_pos + 3 <= len(raw_data):
tempo = (raw_data[track_pos] << 16 |
raw_data[track_pos + 1] << 8 |
raw_data[track_pos + 2])
elif meta_type == 0x58 and meta_length >= 2 and track_pos + 2 <= len(raw_data):
num = raw_data[track_pos]
denom = 2 ** raw_data[track_pos + 1]
info.time_signature = (num, denom)
elif meta_type == 0x59 and meta_length == 2 and track_pos + 2 <= len(raw_data):
sf = raw_data[track_pos]
if sf > 127:
sf -= 256
mi = raw_data[track_pos + 1]
key_info = self.KEY_SIGNATURES.get((sf, mi))
if key_info:
info.key_signature, info.key_type = key_info
track_pos += meta_length
elif status >= 0xF0:
track_pos += 1
if status == 0xF0 or status == 0xF7:
while track_pos < track_end and raw_data[track_pos] != 0xF7:
track_pos += 1
track_pos += 1
else:
if status >= 0x80:
track_pos += 1
if status >= 0x80 and status < 0xC0:
track_pos += 2
if status >= 0x90 and status < 0xA0:
info.num_notes += 1
elif status >= 0xC0 and status < 0xE0:
track_pos += 1
elif status >= 0xE0:
track_pos += 2
else:
track_pos += 1
total_ticks = max(total_ticks, track_ticks)
pos = track_end
info.tempo = round(60000000 / tempo) if tempo > 0 else 120
info.duration = total_ticks * (tempo / 1e6) / info.ticks_per_beat if info.ticks_per_beat > 0 else 0
if info.duration > 0 and info.tempo > 0:
info.beat_count = round((info.tempo * info.duration) / 60)
return info
class TransientDetector:
"""Detect transients in audio files using librosa onset detection."""
def __init__(self, config: Optional[OnsetDetectionConfig] = None):
self.config = config or OnsetDetectionConfig()
self._librosa_available = None
def _check_librosa(self) -> bool:
if self._librosa_available is None:
try:
import librosa
self._librosa_available = True
except ImportError:
self._librosa_available = False
return self._librosa_available
def detect(self, audio_path: Path, beat_count: int,
sample_rate: Optional[int] = None,
num_frames: Optional[int] = None,
min_markers: Optional[int] = None) -> List[int]:
"""Detect transients in audio file."""
if not self._check_librosa():
raise ImportError("librosa is required for transient detection")
import librosa
y, sr = librosa.load(audio_path, sr=sample_rate, mono=True)
total_frames = len(y)
if num_frames is None:
num_frames = total_frames
onset_env = librosa.onset.onset_strength(
y=y, sr=sr, hop_length=self.config.hop_length
)
onset_frames = librosa.onset.onset_detect(
y=y, sr=sr, hop_length=self.config.hop_length,
backtrack=self.config.backtrack, units='frames',
onset_envelope=onset_env,
wait=int(self.config.wait * sr / self.config.hop_length)
)
onset_samples = librosa.frames_to_samples(
onset_frames, hop_length=self.config.hop_length
)
if min_markers is None:
min_markers = max(beat_count + 1, int(beat_count * self.config.min_markers_per_beat) + 1)
return self._build_marker_list(onset_samples, num_frames, beat_count, min_markers)
def _build_marker_list(self, onsets: np.ndarray, num_frames: int,
beat_count: int, min_markers: int) -> List[int]:
markers = [0]
for onset in onsets:
if onset > 0 and onset < num_frames:
markers.append(int(onset))
markers.append(num_frames)
markers = sorted(set(markers))
if len(markers) < min_markers:
markers = self._add_fallback_markers(markers, num_frames, min_markers)
return markers
def _add_fallback_markers(self, existing: List[int], num_frames: int,
min_markers: int) -> List[int]:
if min_markers <= 1:
return existing
interval = num_frames / (min_markers - 1)
for i in range(min_markers):
pos = int(round(i * interval))
existing.append(min(pos, num_frames))
return sorted(set(existing))
class MetadataExtractor:
"""Extract Apple Loop metadata from filenames, paths, and MIDI content."""
CATEGORIES = {
'Bass', 'Drums', 'Guitars', 'Horn/Wind', 'Keyboards', 'Mallets',
'Mixed', 'Other Instrument', 'Percussion', 'Sound Effect',
'Strings', 'Texture/Atmosphere', 'Vocals'
}
GENRES = {
'Cinematic/New Age', 'Country/Folk', 'Electronic/Dance', 'Experimental',
'Funk', 'Hip Hop', 'Jazz', 'Modern RnB', 'Orchestral', 'Other Genre',
'Rock/Blues', 'Urban', 'World/Ethnic'
}
KEY_TYPES = {'major', 'minor', 'both', 'neither'}
DESCRIPTORS = {
'Acoustic', 'Arrhythmic', 'Cheerful', 'Clean', 'Dark', 'Dissonant',
'Distorted', 'Dry', 'Electric', 'Ensemble', 'Fill', 'Grooving',
'Intense', 'Melodic', 'Part', 'Processed', 'Relaxed', 'Single'
}
INSTRUMENT_MAP = {
'bass': ('Bass', 'Electric Bass'),
'electric bass': ('Bass', 'Electric Bass'),
'acoustic bass': ('Bass', 'Acoustic Bass'),
'synth bass': ('Bass', 'Synthetic Bass'),
'sub bass': ('Bass', 'Synthetic Bass'),
'808': ('Bass', 'Synthetic Bass'),
'drum': ('Drums', 'Drum Kit'),
'drums': ('Drums', 'Drum Kit'),
'beat': ('Drums', 'Electronic Beats'),
'beats': ('Drums', 'Electronic Beats'),
'kick': ('Drums', 'Kick'),
'snare': ('Drums', 'Snare'),
'hihat': ('Drums', 'Hi-hat'),
'hi-hat': ('Drums', 'Hi-hat'),
'hi hat': ('Drums', 'Hi-hat'),
'cymbal': ('Drums', 'Cymbal'),
'tom': ('Drums', 'Drum Kit'),
'guitar': ('Guitars', 'Electric Guitar'),
'electric guitar': ('Guitars', 'Electric Guitar'),
'acoustic guitar': ('Guitars', 'Acoustic Guitar'),
'slide guitar': ('Guitars', 'Slide Guitar'),
'clean guitar': ('Guitars', 'Electric Guitar'),
'distorted guitar': ('Guitars', 'Electric Guitar'),
'piano': ('Keyboards', 'Piano'),
'electric piano': ('Keyboards', 'Electric Piano'),
'rhodes': ('Keyboards', 'Electric Piano'),
'wurlitzer': ('Keyboards', 'Electric Piano'),
'organ': ('Keyboards', 'Organ'),
'clav': ('Keyboards', 'Clavinet'),
'clavinet': ('Keyboards', 'Clavinet'),
'keys': ('Keyboards', 'Piano'),
'keyboard': ('Keyboards', 'Piano'),
'synth': ('Keyboards', 'Synthesizer'),
'synthesizer': ('Keyboards', 'Synthesizer'),
'pad': ('Keyboards', 'Synthesizer'),
'lead': ('Keyboards', 'Synthesizer'),
'arp': ('Keyboards', 'Synthesizer'),
'arpeggio': ('Keyboards', 'Synthesizer'),
'strings': ('Strings', 'Ensemble Strings'),
'violin': ('Strings', 'Violin'),
'viola': ('Strings', 'Viola'),
'cello': ('Strings', 'Cello'),
'orchestral': ('Strings', 'Ensemble Strings'),
'brass': ('Horn/Wind', 'Brass Section'),
'horn': ('Horn/Wind', 'French Horn'),
'horns': ('Horn/Wind', 'Brass Section'),
'trumpet': ('Horn/Wind', 'Trumpet'),
'trombone': ('Horn/Wind', 'Trombone'),
'sax': ('Horn/Wind', 'Saxophone'),
'saxophone': ('Horn/Wind', 'Saxophone'),
'flute': ('Horn/Wind', 'Flute'),
'clarinet': ('Horn/Wind', 'Clarinet'),
'percussion': ('Percussion', 'Shaker'),
'shaker': ('Percussion', 'Shaker'),
'tambourine': ('Percussion', 'Tambourine'),
'conga': ('Percussion', 'Conga'),
'bongo': ('Percussion', 'Bongo'),
'cowbell': ('Percussion', 'Cowbell'),
'clap': ('Percussion', 'Clap'),
'claps': ('Percussion', 'Clap'),
'vibraphone': ('Mallets', 'Vibraphone'),
'vibes': ('Mallets', 'Vibraphone'),
'marimba': ('Mallets', 'Marimba'),
'xylophone': ('Mallets', 'Xylophone'),
'glockenspiel': ('Mallets', 'Glockenspiel'),
'vocal': ('Vocals', 'Male'),
'vocals': ('Vocals', 'Male'),
'voice': ('Vocals', 'Male'),
'vox': ('Vocals', 'Male'),
'choir': ('Vocals', 'Choir'),
'fx': ('Sound Effect', 'Motions & Transitions'),
'effect': ('Sound Effect', 'Motions & Transitions'),
'effects': ('Sound Effect', 'Motions & Transitions'),
'riser': ('Sound Effect', 'Motions & Transitions'),
'sweep': ('Sound Effect', 'Motions & Transitions'),
'impact': ('Sound Effect', 'Motions & Transitions'),
'hit': ('Sound Effect', 'Motions & Transitions'),
'transition': ('Sound Effect', 'Motions & Transitions'),
'ambient': ('Texture/Atmosphere', 'Ambient'),
'atmosphere': ('Texture/Atmosphere', 'Ambient'),
'texture': ('Texture/Atmosphere', 'Ambient'),
'drone': ('Texture/Atmosphere', 'Ambient'),
'noise': ('Texture/Atmosphere', 'Ambient'),
}
# MIDI program to category/subcategory mapping (General MIDI)
PROGRAM_MAP = {
range(0, 8): ('Keyboards', 'Piano'),
range(8, 16): ('Mallets', 'Vibraphone'),
range(16, 24): ('Keyboards', 'Organ'),
range(24, 32): ('Guitars', 'Electric Guitar'),
range(32, 40): ('Bass', 'Electric Bass'),
range(40, 48): ('Strings', 'Ensemble Strings'),
range(48, 56): ('Strings', 'Ensemble Strings'),
range(56, 64): ('Horn/Wind', 'Brass Section'),
range(64, 72): ('Horn/Wind', 'Saxophone'),
range(72, 80): ('Horn/Wind', 'Flute'),
range(80, 88): ('Keyboards', 'Synthesizer'),
range(88, 96): ('Keyboards', 'Synthesizer'),
range(96, 104): ('Sound Effect', 'Motions & Transitions'),
range(104, 112): ('World/Ethnic', 'Other'),
range(112, 120): ('Percussion', 'Shaker'),
range(120, 128): ('Sound Effect', 'Motions & Transitions'),
}
GENRE_MAP = {
'edm': 'Electronic/Dance',
'electronic': 'Electronic/Dance',
'house': 'Electronic/Dance',
'techno': 'Electronic/Dance',
'trance': 'Electronic/Dance',
'dubstep': 'Electronic/Dance',
'dnb': 'Electronic/Dance',
'drum and bass': 'Electronic/Dance',
'electro': 'Electronic/Dance',
'dance': 'Electronic/Dance',
'hip hop': 'Hip Hop',
'hiphop': 'Hip Hop',
'hip-hop': 'Hip Hop',
'rap': 'Hip Hop',
'trap': 'Hip Hop',
'boom bap': 'Hip Hop',
'lofi': 'Hip Hop',
'lo-fi': 'Hip Hop',
'lo fi': 'Hip Hop',
'funk': 'Funk',
'funky': 'Funk',
'disco': 'Funk',
'soul': 'Funk',
'rock': 'Rock/Blues',
'blues': 'Rock/Blues',
'metal': 'Rock/Blues',
'punk': 'Rock/Blues',
'alternative': 'Rock/Blues',
'indie': 'Rock/Blues',
'grunge': 'Rock/Blues',
'jazz': 'Jazz',
'swing': 'Jazz',
'bebop': 'Jazz',
'fusion': 'Jazz',
'country': 'Country/Folk',
'folk': 'Country/Folk',
'bluegrass': 'Country/Folk',
'americana': 'Country/Folk',
'acoustic': 'Country/Folk',
'rnb': 'Modern RnB',
'r&b': 'Modern RnB',
'neo soul': 'Modern RnB',
'urban': 'Urban',
'grime': 'Urban',
'uk garage': 'Urban',
'afrobeat': 'Urban',
'world': 'World/Ethnic',
'ethnic': 'World/Ethnic',
'latin': 'World/Ethnic',
'reggae': 'World/Ethnic',
'african': 'World/Ethnic',
'indian': 'World/Ethnic',
'asian': 'World/Ethnic',
'middle eastern': 'World/Ethnic',
'cinematic': 'Cinematic/New Age',
'film': 'Cinematic/New Age',
'movie': 'Cinematic/New Age',
'trailer': 'Cinematic/New Age',
'new age': 'Cinematic/New Age',
'chill': 'Cinematic/New Age',
'chillout': 'Cinematic/New Age',
'meditation': 'Cinematic/New Age',
'orchestral': 'Orchestral',
'classical': 'Orchestral',
'symphony': 'Orchestral',
'epic': 'Orchestral',
'experimental': 'Experimental',
'avant garde': 'Experimental',
'glitch': 'Experimental',
'idm': 'Experimental',
}
DESCRIPTOR_MAP = {
'clean': 'Clean',
'dirty': 'Distorted',
'distorted': 'Distorted',
'wet': 'Processed',
'dry': 'Dry',
'acoustic': 'Acoustic',
'electric': 'Electric',
'funky': 'Grooving',
'groovy': 'Grooving',
'groove': 'Grooving',
'melodic': 'Melodic',
'melody': 'Melodic',
'harmonic': 'Melodic',
'chords': 'Melodic',
'chord': 'Melodic',
'rhythmic': 'Grooving',
'rhythm': 'Grooving',
'dark': 'Dark',
'bright': 'Cheerful',
'happy': 'Cheerful',
'sad': 'Dark',
'mellow': 'Relaxed',
'chill': 'Relaxed',
'relaxed': 'Relaxed',
'intense': 'Intense',
'aggressive': 'Intense',
'hard': 'Intense',
'soft': 'Relaxed',
'processed': 'Processed',
'effected': 'Processed',
'filtered': 'Processed',
'fill': 'Fill',
'single': 'Single',
'ensemble': 'Ensemble',
'part': 'Part',
'dissonant': 'Dissonant',
}
KEY_PATTERNS = [
r'\b([A-Ga-g][#b]?)\s*(maj(?:or)?|min(?:or)?)\b',
r'\b([A-Ga-g][#b]?)m\b',
r'\b([A-Ga-g][#b])\b',
r'(?:^|[_\s\-])([A-Ga-g])(?:[_\s\-]|$)',
]
TEMPO_PATTERNS = [
r'(\d{2,3})\s*_?bpm',
r'bpm\s*_?(\d{2,3})',
r'\[(\d{2,3})\]',
r'\((\d{2,3})\)',
]
def extract_tempo(self, text: str) -> Optional[int]:
"""Extract tempo (BPM) from text."""
text_lower = text.lower()
for pattern in self.TEMPO_PATTERNS:
match = re.search(pattern, text_lower, re.IGNORECASE)
if match:
tempo = int(match.group(1))
if 40 <= tempo <= 300:
return tempo
underscore_key = re.findall(r'_(\d{2,3})_[A-Ga-g][#b]?(?:[_.\s]|m|$)', text)
for num_str in underscore_key:
num = int(num_str)
if 60 <= num <= 200:
return num
underscore_delimited = re.findall(r'_(\d{2,3})_', text)
tempo_candidates = [int(n) for n in underscore_delimited if 60 <= int(n) <= 200]
if tempo_candidates:
for t in tempo_candidates:
if 90 <= t <= 150:
return t
return tempo_candidates[0]
end_underscore = re.search(r'_(\d{2,3})(?:\.[^.]+)?$', text)
if end_underscore:
num = int(end_underscore.group(1))
if 60 <= num <= 200:
return num
return None
def extract_key(self, text: str) -> Tuple[str, str]:
"""Extract key signature and key type from text."""
text_clean = text.replace('_', ' ').replace('-', ' ')
for pattern in self.KEY_PATTERNS:
match = re.search(pattern, text_clean, re.IGNORECASE)
if match:
key = match.group(1).upper()
if len(key) > 1:
key = key[0].upper() + key[1].lower()
if len(match.groups()) > 1 and match.group(2):
scale = match.group(2).lower()
if scale.startswith('min'):
return key, 'minor'
elif scale.startswith('maj'):
return key, 'major'
if re.search(rf'\b{re.escape(key)}m\b', text_clean, re.IGNORECASE):
return key, 'minor'
return key, 'major'
return '', ''
def extract_instrument(self, text: str,
midi_programs: Optional[Set[int]] = None) -> Tuple[str, str]:
"""Extract instrument category and subcategory from text and MIDI programs."""
text_lower = text.lower().replace('_', ' ').replace('-', ' ')
sorted_keywords = sorted(self.INSTRUMENT_MAP.keys(), key=len, reverse=True)
for keyword in sorted_keywords:
if keyword in text_lower:
return self.INSTRUMENT_MAP[keyword]
if midi_programs:
for program_range, category_info in self.PROGRAM_MAP.items():
for program in midi_programs:
if program in program_range:
return category_info
return 'Other Instrument', 'Other'
def extract_genre(self, text: str, path: str = "") -> str:
"""Extract genre from text and path."""
combined = f"{path} {text}".lower().replace('_', ' ').replace('-', ' ')
sorted_keywords = sorted(self.GENRE_MAP.keys(), key=len, reverse=True)
for keyword in sorted_keywords:
if keyword in combined:
return self.GENRE_MAP[keyword]
return 'Other Genre'
def extract_descriptors(self, text: str) -> List[str]:
"""Extract descriptor tags from text."""
text_lower = text.lower().replace('_', ' ').replace('-', ' ')
descriptors = set()
for keyword, descriptor in self.DESCRIPTOR_MAP.items():
if keyword in text_lower:
descriptors.add(descriptor)
return sorted(descriptors)
def extract_all(self, filename: str, filepath: str = "",
midi_info: Optional[MIDIInfo] = None) -> LoopMetadata:
"""Extract all metadata from filename, path, and optional MIDI info."""
metadata = LoopMetadata()
# Extract tempo from filename first (takes precedence)
filename_tempo = self.extract_tempo(filename)
if filename_tempo:
metadata.tempo = filename_tempo
elif midi_info and midi_info.tempo:
metadata.tempo = midi_info.tempo
# Extract key signature
if midi_info and midi_info.key_signature:
metadata.key_signature = midi_info.key_signature
metadata.key_type = midi_info.key_type
else:
metadata.key_signature, metadata.key_type = self.extract_key(filename)
# Extract time signature from MIDI
if midi_info and midi_info.time_signature:
metadata.time_signature = f"{midi_info.time_signature[0]}/{midi_info.time_signature[1]}"
# Extract duration and beat count from MIDI
if midi_info:
metadata.duration = midi_info.duration
if midi_info.beat_count:
metadata.beat_count = midi_info.beat_count
metadata.loop_type = "midi"
# Extract instrument (category and subcategory)
midi_programs = midi_info.programs if midi_info else None
metadata.category, metadata.subcategory = self.extract_instrument(filename, midi_programs)
# Extract genre
metadata.genre = self.extract_genre(filename, filepath)
# Extract descriptors
descriptors = self.extract_descriptors(filename)
metadata.descriptors = ','.join(descriptors) if descriptors else ''
# Drums/percussion don't have key signatures
if metadata.category in ('Drums', 'Percussion'):
metadata.key_signature = ''
metadata.key_type = 'neither'
return metadata
class TablePrinter:
"""Print a formatted table with real-time row output."""
def __init__(self, columns: List[Tuple[str, int]], separator: str = " | "):
self.columns = columns
self.separator = separator
self.header_printed = False
def _truncate(self, text: str, width: int) -> str:
if len(text) <= width:
return text.ljust(width)
return text[:width-2] + ".."
def print_header(self) -> None:
if self.header_printed:
return
header_parts = [self._truncate(name, width) for name, width in self.columns]
print(self.separator.join(header_parts))
sep_parts = ["-" * width for _, width in self.columns]
print(self.separator.join(sep_parts))
self.header_printed = True
def print_row(self, values: List[str]) -> None:
if not self.header_printed:
self.print_header()
row_parts = []
for i, (_, width) in enumerate(self.columns):
value = values[i] if i < len(values) else ""
row_parts.append(self._truncate(str(value), width))
print(self.separator.join(row_parts))
def print_footer(self, total: int, converted: int = 0, errors: int = 0) -> None:
sep_parts = ["-" * width for _, width in self.columns]
print(self.separator.join(sep_parts))
if errors > 0:
print(f"Total: {total} files, {converted} converted, {errors} errors")
else:
print(f"Total: {total} files, {converted} converted")
def get_convert_table_columns() -> List[Tuple[str, int]]:
"""Get table column definitions for conversion output."""
return [
("Filename", 30),
("Type", 5),
("Tempo", 7),
("Key", 5),
("Scale", 7),
("Beats", 5),
("Duration", 8),
("Category", 18),
("Genre", 18),
("Markers", 7),
("Status", 8),
]
def metadata_to_table_row(filename: str, metadata: LoopMetadata,
markers: int = 0, status: str = "") -> List[str]:
"""Convert metadata to table row values."""
loop_type = "MIDI" if metadata.loop_type == "midi" else "Audio"
tempo = f"{metadata.tempo}" if metadata.tempo else "-"
key = metadata.key_signature if metadata.key_signature else "-"
scale = metadata.key_type if metadata.key_type else "-"
beats = str(metadata.beat_count) if metadata.beat_count > 0 else "-"
duration = f"{metadata.duration:.2f}s" if metadata.duration else "-"
category = metadata.subcategory or metadata.category or "-"
genre = metadata.genre if metadata.genre else "-"
markers_str = str(markers) if markers > 0 else "-"
return [filename, loop_type, tempo, key, scale, beats, duration, category, genre, markers_str, status]
class AppleLoopConverter:
"""Convert audio and MIDI files to Apple Loop CAF format."""
def __init__(self, output_dir: Optional[Path] = None, bitrate: int = 256000,
lossy: bool = False, use_transient_detection: bool = True,
onset_config: Optional[OnsetDetectionConfig] = None):
self.output_dir = output_dir or Path.home() / "Library/Audio/Apple Loops/User Loops"
self.bitrate = bitrate
self.lossy = lossy
self.extractor = MetadataExtractor()
self.midi_parser = MIDIParser()
self.use_transient_detection = use_transient_detection
self.transient_detector = TransientDetector(onset_config)
def is_midi_file(self, file_path: Path) -> bool:
"""Check if file is a MIDI file."""
return file_path.suffix.lower() in MIDI_EXTENSIONS
def get_audio_duration(self, audio_file: Path) -> Optional[float]:
"""Get audio file duration in seconds using afinfo."""
try:
result = subprocess.run(
['afinfo', str(audio_file)],
capture_output=True,
text=True,
timeout=10
)
for line in result.stdout.split('\n'):
if 'estimated duration:' in line.lower():
match = re.search(r'(\d+\.?\d*)\s*sec', line)
if match:
return float(match.group(1))
return None
except Exception as e:
print(f"Warning: Could not get duration: {e}", file=sys.stderr)
return None
def calculate_beat_count(self, tempo: int, duration: float) -> int:
"""Calculate beat count from tempo and duration."""
return int(round((tempo * duration) / 60.0))
def create_info_chunk(self, genre: str) -> bytes:
"""Create CAF info chunk with genre for Spotlight indexing."""
data = struct.pack('>I', 1)
data += b'genre\x00' + genre.encode('ascii', errors='replace') + b'\x00'
return data
def create_uuid_chunk(self, metadata: LoopMetadata) -> bytes:
"""Create Apple Loop metadata UUID chunk."""
data = bytearray(APPLE_LOOP_META_UUID)
kv_pairs = []
if metadata.subcategory:
kv_pairs.append(('subcategory', metadata.subcategory))
if metadata.category:
kv_pairs.append(('category', metadata.category))
if metadata.key_signature:
kv_pairs.append(('key signature', metadata.key_signature))
if metadata.time_signature:
kv_pairs.append(('time signature', metadata.time_signature))
if metadata.beat_count > 0:
kv_pairs.append(('beat count', str(metadata.beat_count)))
if metadata.descriptors:
kv_pairs.append(('descriptors', metadata.descriptors))
if metadata.genre:
kv_pairs.append(('genre', metadata.genre))
if metadata.key_type:
kv_pairs.append(('key type', metadata.key_type))
if metadata.loop_type == "midi":
kv_pairs.append(('loop type', 'midi'))
data.extend(struct.pack('>I', len(kv_pairs)))
for key, value in kv_pairs:
data.extend(key.encode('ascii', errors='replace') + b'\x00')
data.extend(str(value).encode('ascii', errors='replace') + b'\x00')
return bytes(data)
def create_beat_markers_chunk(self, num_valid_frames: int, beat_count: int,
audio_path: Optional[Path] = None,
subdivisions: int = 4) -> bytes:
"""Create Apple Loop beat markers UUID chunk."""
if self.use_transient_detection and audio_path and not self.is_midi_file(audio_path):
try:
marker_positions = self.transient_detector.detect(
audio_path, beat_count, num_frames=num_valid_frames,
min_markers=beat_count + 1
)
except (ImportError, Exception):
marker_positions = self._generate_simple_markers(
num_valid_frames, beat_count, subdivisions
)
else:
marker_positions = self._generate_simple_markers(
num_valid_frames, beat_count, subdivisions
)
return self._encode_beat_markers(marker_positions)
def _generate_simple_markers(self, num_valid_frames: int, beat_count: int,
subdivisions: int) -> List[int]:
"""Generate evenly-spaced markers at quarter-note subdivisions."""
if beat_count <= 0:
return [0, num_valid_frames]
samples_per_beat = num_valid_frames / beat_count
samples_per_subdivision = samples_per_beat / subdivisions
total_markers = beat_count * subdivisions + 1
marker_positions = []
for i in range(total_markers):
position = int(round(i * samples_per_subdivision))
marker_positions.append(min(position, num_valid_frames))
marker_positions[-1] = num_valid_frames
return marker_positions
def _encode_beat_markers(self, marker_positions: List[int]) -> bytes:
"""Encode marker positions into beat markers chunk binary format."""
data = bytearray(BEAT_MARKERS_UUID)
header = struct.pack('>I', 0)
header += struct.pack('>I', 0x00010000)
header += struct.pack('>H', 0x0032)
header += struct.pack('>H', 0x0010)
header += struct.pack('>I', 0)
header += struct.pack('>I', len(marker_positions))
data.extend(header)
for position in marker_positions:
entry = struct.pack('>H', 0x0001)
entry += struct.pack('>H', 0x0000)
entry += struct.pack('>I', 0x0000)
entry += struct.pack('>I', position)
data.extend(entry)