-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathableton_project_processor.py
More file actions
2009 lines (1613 loc) Β· 85.2 KB
/
ableton_project_processor.py
File metadata and controls
2009 lines (1613 loc) Β· 85.2 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
"""
ableton_project_processor.py
A swiss army knife for processing Ableton projects β batch clean tracks, ungroup,
strip unused devices, sort & recolor, quantize/transpose MIDI, convert mixer automation
to utility, and generate detailed per-project reports with external plugin aggregation,
all at the XML level without opening Live once.
Operates on raw decompressed XML inside .als gzip archives.
Original files are never overwritten β a new _processed.als is always created.
Usage:
python ableton_project_processor.py
Β© 2026 Hodel33
"""
import gzip
import re
import sys
import os
import io
import configparser
from dataclasses import dataclass, field
from pathlib import Path
import xml.etree.ElementTree as ET
from collections import defaultdict
from urllib.parse import unquote
CONFIG_LOCATION = "config.ini"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CONTEXT
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class Context:
"""Config + runtime state passed to every pipeline step."""
track_config: dict # prefix β {color, ...} map (from track_config.ini)
dedupe_devices: list = field(default_factory=list) # device names to deduplicate
exclude_conversion_types: list = field(default_factory=list) # track types skipped by mixer-automation step
exclude_midi_prefixes: list = field(default_factory=list) # track-name prefixes skipped by MIDI-affecting steps
chain_suffix: str = '' # suffix appended to cloned device chains
transpose_semitones: int = 0 # MIDI transpose amount
lane_height: int = 68 # Track height
als_path: Path | None = None # current .als being processed (set per-file by runner)
report_written: bool = False # runtime flag: step_project_report sets this so the runner marks it β even though the XML didn't change
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SHARED UTILITIES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def find_blocks(xml_text: str, tag: str) -> list:
"""Find all <tag>...</tag> blocks via depth tracking. Returns (start, end, content) tuples."""
results = []
open_pat = re.compile(r"<" + re.escape(tag) + r"[\s>]")
cls_pat = re.compile(r"</" + re.escape(tag) + r">")
sc_pat = re.compile(r"<" + re.escape(tag) + r"(?:\s[^>]*)?\/>")
pos = 0
while True:
m = open_pat.search(xml_text, pos)
if not m:
break
start = m.start()
if sc := sc_pat.match(xml_text, start):
results.append((start, sc.end(), xml_text[start:sc.end()]))
pos = sc.end()
continue
depth, pos = 1, m.end()
while depth > 0:
mo = open_pat.search(xml_text, pos)
mc = cls_pat.search(xml_text, pos)
if not mc:
break
if mo and mo.start() < mc.start():
depth += 1; pos = mo.end()
else:
depth -= 1; pos = mc.end()
results.append((start, pos, xml_text[start:pos]))
return results
def extract_device_name(block: str, tag: str = "") -> str | None:
"""Extract device name β checks VST2 PlugName, VST3/AU BrowserContentPath, then native tag."""
if not tag:
if m := re.match(r'<(\w+)\s', block.strip()):
tag = m.group(1)
is_external = tag in ("PluginDevice", "AuPluginDevice")
prefix = "ext" if is_external else "int"
# Slice off everything from <Branches> onward so nested chain names
# don't pollute name searches with their own EffectiveName/UserName values
shallow = block[:block.index('<Branches>')] if '<Branches>' in block else block
patterns = [
(r'<PlugName\s+Value="([^"]+)"', 1, None),
(r'<EffectiveName\s+Value="([^"]+)"', 1, None),
]
if is_external:
# VST3/AU store the plugin name inside the browser path after the last : or #
patterns.insert(1, (r'BrowserContentPath\s+Value="[^"]*[:#]([^"#:/]+)"', 1, unquote))
for pat, group, transform in patterns:
if m := re.search(pat, shallow):
val = m.group(group)
val = transform(val) if transform else val
if re.match(r'FileId_\d+', val):
continue # skip internal Ableton file IDs, fall through to tag name
return f"[{prefix}] {val}"
# Fallback: use the XML tag itself (e.g. MultibandDynamics β [int] MultibandDynamics)
return f"[{prefix}] {tag}" if tag else None
def find_all_devices(xml_text: str) -> list:
"""
Find all user-inserted devices (native + external) in the project.
Scopes search to <DeviceChain><Devices> blocks only.
Ableton track structure:
<AudioTrack> / <MidiTrack> / <MainTrack>
<FreezeSequencer> β internal engine, SIBLING of DeviceChain
<AudioSequencer> β NOT a user device, excluded by this scope
</FreezeSequencer>
<DeviceChain> β user device chain lives here
<Devices> β only place we scan
<Eq8 Id="..."> β real user device β
...
</Devices>
</DeviceChain>
By finding only top-level DeviceChain blocks (not rack-internal ones),
we naturally exclude FreezeSequencer, Mixer, MidiSequencer etc.
Rack containers (DrumGroupDevice, AudioEffectGroupDevice etc.) are returned
as single top-level entries β their internal chains are never descended into,
since pos advances past the entire rack block after it is added to results.
Device identity is confirmed by the <On><LomId/><Manual Value= structure
present in every real Ableton device, which naturally filters out any
non-device XML elements that match the tag pattern.
Returns (start, end, content, tag_name) tuples with global offsets.
"""
results = []
tag_pat = re.compile(r'<([A-Z][A-Za-z0-9]+)\s+Id="\d+"')
device_pat = re.compile(r'<On>\s*<LomId\b[^/]*/>\s*<Manual\s+Value=', re.DOTALL)
# Find all DeviceChain blocks, keep only top-level ones (not rack-internal)
all_chains = find_blocks(xml_text, "DeviceChain")
top_chains = [
(s, e, c) for s, e, c in all_chains
if not any(os < s and e < oe for os, oe, _ in all_chains)
]
for dc_start, _, dc_content in top_chains:
# Find Devices blocks inside this DeviceChain, keep top-level only
all_dev_blocks = find_blocks(dc_content, "Devices")
top_dev_blocks = [
(s, e, c) for s, e, c in all_dev_blocks
if not any(os < s and e < oe for os, oe, _ in all_dev_blocks)
]
for d_rel_start, _, d_content in top_dev_blocks:
d_start = dc_start + d_rel_start
pos = 0
while m := tag_pat.search(d_content, pos):
tag = m.group(1)
rel_start = m.start()
blocks = find_blocks(d_content[rel_start:], tag)
if not blocks:
pos = m.end()
continue
b_start, b_end, content = blocks[0]
# Every real Ableton device has <On><LomId/><Manual Value= structure
if device_pat.search(content):
g_start = d_start + rel_start + b_start
g_end = d_start + rel_start + b_end
results.append((g_start, g_end, content, tag))
pos = rel_start + b_end
return results
def get_track_ranges(xml_text: str) -> list:
"""Return (start, end, name) for every track in the project.
Handles both Live 11 (<MasterTrack>) and Live 12 (<MainTrack>).
"""
tags = ["AudioTrack", "MidiTrack", "ReturnTrack", "GroupTrack", "MasterTrack", "MainTrack"]
tracks = []
# Collect all tracks then sort by byte offset to match visual order in Ableton
all_tracks = []
for tag in tags:
for start, end, content in find_blocks(xml_text, tag):
all_tracks.append((start, end, content, tag))
idx = 1
for start, end, content, tag in sorted(all_tracks, key=lambda x: x[0]):
if tag in ("MasterTrack", "MainTrack"):
tracks.append((start, end, "Master"))
continue
m = re.search(r'<(?:UserName|EffectiveName)\s+Value="([^"]+)"', content)
name = m.group(1) if m else tag
tracks.append((start, end, f"#{idx:02d} {name}"))
idx += 1
return tracks
def get_track_prefix(name: str, track_config: dict) -> str:
"""Extract the prefix used for color/sort lookup from a track name.
Strips leading '#NN ' numbering, then takes the first word:
- ALL-CAPS word known in track_config β use as-is (e.g. 'DRUM', 'FX')
- otherwise the first 2 chars (e.g. 'Kick' β 'Ki')
- empty / single-char first word β '??' (falls back to DEF in lookups)
"""
raw = re.sub(r'^#\d+\s+', '', name)
first_word = raw.split()[0] if raw.split() else ""
if first_word.isupper() and first_word in track_config:
return first_word
return first_word[:2] if len(first_word) >= 2 else "??"
def get_excluded_track_ranges(xml_text: str, context: Context, track_config: dict) -> list:
"""Return byte ranges for tracks whose prefix (or parent group prefix) is in exclude_midi_prefixes."""
exclude = set(context.exclude_midi_prefixes)
if not exclude:
return []
track_data = []
for tag in ("MidiTrack", "AudioTrack", "GroupTrack"):
for start, end, content in find_blocks(xml_text, tag):
m = re.search(r'<(?:UserName|EffectiveName)\s+Value="([^"]+)"', content)
name = m.group(1) if m else ""
prefix = get_track_prefix(name, track_config)
xid_m = re.search(r'<(?:MidiTrack|AudioTrack|GroupTrack)\s+Id="(\d+)"', content)
gid_m = re.search(r'<TrackGroupId\s+Value="(\d+)"', content)
track_data.append({
'start': start, 'end': end, 'prefix': prefix,
'xid': xid_m.group(1) if xid_m else None,
'gid': gid_m.group(1) if gid_m else None
})
id_to_prefix = {t['xid']: t['prefix'] for t in track_data if t['xid']}
ranges = []
for t in track_data:
parent_prefix = id_to_prefix.get(t['gid'], '') if t['gid'] else ''
if t['prefix'] in exclude or parent_prefix in exclude:
ranges.append((t['start'], t['end']))
return ranges
def sub_outside_ranges(pattern, repl, xml_text: str, excluded: list) -> str:
"""Apply re.sub only to segments of xml_text outside excluded byte ranges."""
parts, prev = [], 0
for start, end in sorted(excluded):
parts.append(re.sub(pattern, repl, xml_text[prev:start]))
parts.append(xml_text[start:end])
prev = end
parts.append(re.sub(pattern, repl, xml_text[prev:]))
return "".join(parts)
def track_of(offset: int, track_ranges: list) -> str:
"""Return the track name that contains the given offset."""
for start, end, name in track_ranges:
if start <= offset <= end:
return name
return "Unknown"
def splice_out(xml_text: str, blocks: list) -> str:
"""Remove blocks (sorted descending by start) from raw XML string."""
for block in sorted(blocks, key=lambda b: b["start"], reverse=True):
s, e = block["start"], block["end"]
# Also eat the preceding newline+indent to avoid blank lines
while s > 0 and xml_text[s - 1] in (" ", "\t"):
s -= 1
if s > 0 and xml_text[s - 1] == "\n":
s -= 1
xml_text = xml_text[:s] + xml_text[e:]
return xml_text
def format_device_log_line(track: str, name: str) -> tuple[str, str, str]:
"""Split a track name and device name into log-ready parts.
Returns (track_str, tag_str, dev_name).
track='1 Drums' β track_str="1 'Drums'"; track='Master' β track_str="'Master'"
name='[FX] Reverb' β tag_str='[FX]', dev_name='Reverb'; name='Reverb' β tag_str='', dev_name='Reverb'
"""
t_parts = track.split(' ', 1)
track_str = f"{t_parts[0]} '{t_parts[1]}'" if len(t_parts) == 2 else f"'{track}'"
n_parts = name.split('] ', 1)
tag_str = n_parts[0] + ']' if len(n_parts) == 2 else ''
dev_name = n_parts[1] if len(n_parts) == 2 else name
return track_str, tag_str, dev_name
def remove_empty_groups(xml_text: str, group_id_to_name: dict) -> tuple[str, list[str]]:
"""Iteratively remove GroupTrack blocks that no longer contain any tracks.
Runs up to 10 passes: removing a group may empty its parent group, so
a single pass isn't enough. Returns (new_xml, log_lines).
"""
log = []
for _ in range(10):
group_ids_in_use = set(re.findall(r'<TrackGroupId\s+Value="(\d+)"', xml_text))
empty_groups = []
for s, e, c in find_blocks(xml_text, "GroupTrack"):
gid = re.search(r'<GroupTrack\s+Id="(\d+)"', c)
if gid and gid.group(1) not in group_ids_in_use:
empty_groups.append({"start": s, "end": e, "gid": gid.group(1)})
if not empty_groups:
break
for r in empty_groups:
name = group_id_to_name.get(r['gid'], 'Group')
parts = name.split(' ', 1)
log.append(f" Removed empty group {parts[0]} '{parts[1]}'" if len(parts) == 2 else f" Removed empty group '{name}'")
xml_text = splice_out(xml_text, empty_groups)
return xml_text, log
def find_als_files(root: Path) -> list:
"""
Find all .als files recursively below root.
Skips: any file inside a 'Backup' folder (Ableton's own backups)
Skips: files ending in '_processed' (already handled by the script)
"""
als_files = []
for f in root.rglob("*.als"):
if "Backup" in f.parts:
continue
if f.stem.endswith("_processed"):
continue
als_files.append(f)
return sorted(als_files)
def print_main_header():
"""Clear the terminal and print the ASCII art header."""
os.system("cls" if os.name == "nt" else "clear") # cls on Windows, clear on macOS/Linux
print("\033[H", end="") # move cursor to top-left
print("\033[38;5;208m") # orange-ish color
print(r'''
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
''')
print("Β© 2026 Hodel33")
print("βΎ" * 96)
print("\033[0;0m")
def print_pipeline_header():
"""Print the processing settings section header."""
print("************ PROCESSING SETTINGS ************")
print()
def print_pipeline_info(root: Path, pipeline: list):
"""Print the project folder and the enabled pipeline steps."""
print(f" Project folder : {root}")
print(f" Active steps :")
print()
for step_id, step_fn, description in pipeline:
print(f" [+] {description}")
print()
if any(step_id == "convert_mixer_automation_to_utility" for step_id, _, _ in pipeline):
print(" Note: project must have at least one Utility device anywhere to use as clone template.")
print()
print()
def confirm_start() -> bool:
"""Prompt the user to confirm. Returns False if they chose to quit."""
return input("Press ENTER to start processing (q + ENTER to exit): ").strip().lower() != "q"
def load_config(config_file=CONFIG_LOCATION):
"""Load and return the config.ini file as a ConfigParser object."""
config = configparser.ConfigParser()
config.optionxform = str
try:
if not config.read(config_file, encoding='utf-8'):
raise FileNotFoundError(f"{config_file} not found")
except configparser.DuplicateOptionError as e:
raise ValueError(f"[{e.section}] duplicate prefix '{e.option}' β prefix names must be unique")
return config
def load_pipeline(config):
"""Build and return the ordered list of enabled pipeline steps from config."""
all_steps = [
("remove_empty_tracks", step_remove_empty_tracks, "Remove empty tracks"),
("remove_muted_tracks", step_remove_muted_tracks, "Remove muted tracks"),
("ungroup_tracks", step_ungroup_tracks, "Ungroup all grouped tracks"),
("remove_unused_return_tracks", step_remove_unused_return_tracks, "Remove unused return tracks"),
("remove_disabled_devices", step_remove_disabled_devices, "Remove disabled devices"),
("remove_non_automated_devices", step_remove_non_automated_devices, "Remove non-automated insert devices"),
("deduplicate_devices", step_deduplicate_devices, "Deduplicate specific devices per track"),
("convert_mixer_automation_to_utility", step_convert_mixer_automation_to_utility, "Convert Mixer Vol/Pan automation to Utility device"),
("sort_color_tracks", step_sort_color_tracks, "Sort & Recolor tracks/clips"),
("duplicate_device_chain", step_duplicate_device_chain, "Duplicate device chains to new tracks"),
("quantize_midi_notes", step_quantize_midi_notes, "Quantize all MIDI notes to 1/16"),
("transpose_midi_notes", step_transpose_midi_notes, "Transpose all MIDI notes"),
("set_track_heights", step_set_track_heights, "Set all track heights to a custom size"),
("get_project_report", step_project_report, "Export full project report to txt"),
]
if 'PIPELINE' not in config:
raise ValueError("Missing [PIPELINE] section")
cleaned = {k: v.split('#')[0].strip() for k, v in config['PIPELINE'].items()}
enabled = {k: v == 'true' for k, v in cleaned.items()}
pipeline = [s for s in all_steps if enabled.get(s[0], False)]
return pipeline
def load_settings(config):
"""Load global settings from [SETTINGS] section."""
if 'SETTINGS' not in config:
return {}
# Strip comments + convert to int, list or str where appropriate
settings = {}
for k, v in config['SETTINGS'].items():
clean = v.split('#')[0].strip()
if clean == '':
settings[k] = []
elif ',' in clean:
settings[k] = [item.strip() for item in clean.split(',')]
else:
try:
settings[k] = int(clean)
except ValueError:
settings[k] = clean
return settings
def load_track_config(config):
"""Load track prefixes, sort order, and colors from config."""
if 'TRACK_PREFIXES' not in config:
raise ValueError("Missing [TRACK_PREFIXES] section")
if 'DEF' not in config['TRACK_PREFIXES']:
raise ValueError("[TRACK_PREFIXES] is missing required 'DEF' fallback entry")
track_config = {}
for prefix, value in config['TRACK_PREFIXES'].items():
clean_value = value.split('#')[0].strip()
try:
sort_order, color_idx = map(int, clean_value.split(','))
except (ValueError, TypeError):
raise ValueError(f"[TRACK_PREFIXES] invalid format for '{prefix}' β expected 'sort_order, color_idx'")
track_config[prefix] = {'sort': sort_order, 'color': color_idx}
# Reject duplicate sort orders β specials (DEF/RTN/MST) all share 99 by design, so skip them.
specials = {'DEF', 'RTN', 'MST'}
seen: dict[int, list[str]] = {}
for prefix, cfg in track_config.items():
if prefix in specials:
continue
seen.setdefault(cfg['sort'], []).append(prefix)
dupes = {s: names for s, names in sorted(seen.items()) if len(names) > 1}
if dupes:
details = '; '.join(f"sort {s} used by {', '.join(names)}" for s, names in dupes.items())
raise ValueError(f"[TRACK_PREFIXES] duplicate sort order(s) β {details}")
return track_config
def get_track_info(xml_text: str) -> list[dict]:
"""Extract all tracks: pos, content, name, type and color."""
track_tags = ["AudioTrack", "MidiTrack", "ReturnTrack", "GroupTrack", "MasterTrack", "MainTrack"]
tracks = []
for tag in track_tags:
for start, end, content in find_blocks(xml_text, tag):
name_match = re.search(r'<(?:UserName|EffectiveName)\s+Value="([^"]*)"', content)
color_match = re.search(r'<Color\s+Value="(\d+)"', content)
name = name_match.group(1) if name_match else tag
color = color_match.group(1) if color_match else "0"
tracks.append({
'start': start,
'end': end,
'content': content,
'name': name,
'type': tag,
'color': color
})
return tracks
def set_track_color(track_content: str, color_idx: int) -> str:
"""Set <Color Value="N"/> - Ableton track color tag."""
color_pat = r'<Color\s+Value\s*=\s*"(\d+)"'
if re.search(color_pat, track_content):
return re.sub(color_pat, f'<Color Value="{color_idx}"', track_content, count=1)
name_pat = r'</Name>'
return re.sub(name_pat, f'</Name>\n <Color Value="{color_idx}"/>', track_content, count=1)
def set_clip_colors(track_content: str, color_idx: int) -> str:
"""Set <Color Value="N"/> inside ALL clips (MidiClip + AudioClip) to match track color."""
clip_pat = r'(<(?:MidiClip|AudioClip)\b[^>]*>.*?)<Color\s+Value\s*=\s*"\d+"'
return re.sub(
clip_pat,
lambda m: f'{m.group(1)}<Color Value="{color_idx}"',
track_content,
flags=re.DOTALL
)
def validate_xml(xml_text: str, original: str | None = None) -> list[str]:
"""Check processed XML for corruption causes introduced by processing."""
errors = []
# Check TrackSendHolder count vs ReturnTrack count
return_count = len(find_blocks(xml_text, "ReturnTrack"))
source_tracks = [
t_content
for tag in ("AudioTrack", "MidiTrack", "GroupTrack")
for _, _, t_content in find_blocks(xml_text, tag)
]
for t_content in source_tracks:
holder_count = len(find_blocks(t_content, "TrackSendHolder"))
if holder_count != return_count:
errors.append(f"TrackSendHolder count ({holder_count}) doesn't match ReturnTrack count ({return_count})")
break
# Check for duplicate track Ids β Ableton requires globally unique Ids across all tracks.
# Duplicates here cause the "non-unique list ids" corruption error on project load.
# Note: device Ids (StereoGain, PluginDevice etc.) are context-scoped and legitimately repeat.
track_id_pattern = re.compile(
r'<(?:AudioTrack|MidiTrack|ReturnTrack|GroupTrack|MasterTrack)\s+Id="(\d+)"'
)
track_ids = track_id_pattern.findall(xml_text)
seen, dupes = set(), set()
for i in track_ids:
if i in seen:
dupes.add(i)
seen.add(i)
if dupes:
errors.append(f"Duplicate track Id values found: {sorted(dupes, key=int)[:10]}")
# Check NextPointeeId is above all used IDs
max_id = max((int(i) for i in re.findall(r'Id="(\d+)"', xml_text)), default=0)
next_id_m = re.search(r'<NextPointeeId\s+Value="(\d+)"', xml_text)
if next_id_m and int(next_id_m.group(1)) <= max_id:
# Only flag if this is a NEW issue β not pre-existing in the original file
if original is not None:
orig_max = max((int(i) for i in re.findall(r'Id="(\d+)"', original)), default=0)
orig_nxt_m = re.search(r'<NextPointeeId\s+Value="(\d+)"', original)
if not (orig_nxt_m and int(orig_nxt_m.group(1)) <= orig_max):
errors.append(f"NextPointeeId ({next_id_m.group(1)}) is not above max Id ({max_id})")
else:
errors.append(f"NextPointeeId ({next_id_m.group(1)}) is not above max Id ({max_id})")
# Check no NEW dangling PointeeIds
def get_dangling(xml):
target_ids = set(re.findall(r'<(?:Automation|Modulation)Target\s+Id="(\d+)"', xml))
return {pid for pid in re.findall(r'<PointeeId\s+Value="(\d+)"', xml) if pid not in target_ids}
# Flag any dangling PointeeIds already present in the original file (pre-existing corruption)
if original is None:
existing_dangling = get_dangling(xml_text)
if existing_dangling:
errors.append(f"Pre-existing dangling PointeeIds (not caused by script): {len(existing_dangling)} total")
# Only flag PointeeIds that our script introduced β not pre-existing ones in the original file
else:
new_dangling = get_dangling(xml_text) - get_dangling(original)
if new_dangling:
errors.append(f"NEW dangling PointeeIds introduced by script: {len(new_dangling)} total")
# Check XML is not truncated
if "</LiveSet>" not in xml_text:
errors.append("Missing </LiveSet> β file appears truncated")
return errors
def cleanup_project(xml_text: str) -> str:
"""
Silent post-processing pass β always runs before validation.
Fixes pre-existing or step-induced issues that are safe to auto-correct:
1. Remove AutomationEnvelopes whose PointeeId has no living AutomationTarget
2. Bump NextPointeeId above the highest Id in the project
"""
# Remove dead automation envelopes (orphaned by removed tracks/devices)
surviving = set(re.findall(r'<AutomationTarget\s+Id="(\d+)"', xml_text))
dead = [
{"start": s, "end": e}
for s, e, c in find_blocks(xml_text, "AutomationEnvelope")
if (pid := re.search(r'<PointeeId\s+Value="(\d+)"', c)) and pid.group(1) not in surviving
]
if dead:
xml_text = splice_out(xml_text, dead)
# Fix NextPointeeId counter if it has fallen behind the highest Id
xml_text = update_next_pointee_id(xml_text)
return xml_text
def update_next_pointee_id(xml_text: str) -> str:
"""Bump NextPointeeId to one above the highest Id currently in the project."""
max_id = max((int(i) for i in re.findall(r'Id="(\d+)"', xml_text)), default=0)
return re.sub(
r'(<NextPointeeId\s+Value=")[^"]+(")',
lambda m: f'{m.group(1)}{max_id + 1}{m.group(2)}',
xml_text
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DEBUG
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def debug_raw_dump(als_path: Path) -> None:
with gzip.open(als_path, "rb") as f:
xml_text = f.read().decode("utf-8")
print("\nAll devices found (native + external):")
for start, end, content, tag in find_all_devices(xml_text):
name = extract_device_name(content, tag) or tag
track = track_of(start, get_track_ranges(xml_text))
print(f" [{tag}] '{name}' on track '{track}'")
def debug_colors(als_path):
"""Show ALL tracks: positions + names + colors."""
print(f"\n--- ALL TRACKS: POSITIONS + NAMES + COLORS ---")
with gzip.open(als_path, "rb") as f:
xml = f.read().decode("utf-8")
tracks = get_track_info(xml)
print(f"Found {len(tracks)} tracks:\n")
for i, track in enumerate(tracks, 1):
prefix = track['name'][:2].upper() if len(track['name']) >= 2 else "??"
print(f" {i:2d} | Pos {track['start']:>10,}β{track['end']:>10,} | {track['type']:<12s} | {track['name']:<12} [{prefix}] | Color={track['color']}")
def debug_track_heights(als_path):
"""Show all LaneHeight values across the project."""
with gzip.open(als_path, "rb") as f:
xml = f.read().decode("utf-8")
tracks = get_track_info(xml)
print(f"\n--- TRACK LANE HEIGHTS ---")
print(f"{'#':>3} | {'Name':<20} | {'Type':<12} | {'Height':>6}")
print("-" * 52)
heights = []
for i, track in enumerate(tracks, 1):
match = re.search(r'<LaneHeight\s+Value\s*=\s*"(\d+)"', track['content'])
height = int(match.group(1)) if match else 0
heights.append(height)
print(f" {i:>2} | {track['name']:<20} | {track['type']:<12} | {height:>6}")
print("-" * 52)
print(f" Min: {min(heights)} | Max: {max(heights)} | Avg: {sum(heights)//len(heights)}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CLEANING STEPS
# Signature: step(xml_text, context) -> (xml_text, log_lines)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def step_deduplicate_devices(xml_text: str, context: Context) -> tuple:
"""Keep only the first instance of each named device per track.
Target names are set via dedupe_devices in config and matched as
case-insensitive substrings β e.g. 'saus' matches 'Sausage Fattener'.
"""
targets = context.dedupe_devices
tracks = get_track_ranges(xml_text)
seen, to_remove = set(), []
for start, end, content, tag in find_all_devices(xml_text):
name = extract_device_name(content, tag)
track = track_of(start, tracks)
if not name or not any(t.lower() in name.lower() for t in targets):
continue
key = (track, name)
if key in seen:
to_remove.append({"start": start, "end": end, "name": name, "track": track})
else:
seen.add(key)
if not to_remove:
return xml_text, ["No duplicates found."]
log = []
for r in to_remove:
track_str, tag_str, dev_name = format_device_log_line(r['track'], r['name'])
log.append(f" Removed duplicate {tag_str} '{dev_name}' on track {track_str}")
return splice_out(xml_text, to_remove), log
def step_project_report(xml_text: str, context: Context) -> tuple:
"""
Export a full project report to _report.txt β read-only, never modifies the project.
PROJECT SUMMARY β Creator, BPM, time signature, key/scale, locators, track counts,
return tracks, clips, automations, muted/frozen/unnamed/duplicate
tracks, device counts, disabled devices.
EXTERNAL PLUGINS β alphabetical list of all external plugins used.
FULL DEVICE LIST β nested device tree per track with on/off and automation counts.
"""
TRACK_TYPES = {
'MidiTrack': 'MIDI', 'AudioTrack': 'Audio', 'ReturnTrack': 'Return',
'GroupTrack': 'Group', 'MasterTrack': 'Master', 'MainTrack': 'Master',
}
def collect_devices(element, depth=0):
results = []
for child in element:
if child.tag == 'Devices':
for device in child:
block = ET.tostring(device, encoding='unicode')
if '<On>' in block and '<Manual Value=' in block:
results.append((depth, device.tag, device))
results.extend(collect_devices(device, depth + 1))
else:
results.extend(collect_devices(child, depth))
return results
def is_enabled(el):
manual = el.find('On/Manual')
return manual is None or manual.get('Value', 'true').lower() == 'true'
def count_automation(el, auto_ids):
targets = {t.get('Id') for t in el.findall('.//AutomationTarget')}
return len(targets & auto_ids)
root = ET.parse(io.StringIO(xml_text)).getroot()
auto_ids = {el.get('Value') for el in root.findall('.//PointeeId')}
# Collect all tracks in true document order
TRACK_TAGS = set(TRACK_TYPES.keys())
tracks_el = root.find('.//Tracks')
all_tracks = [(c.tag, c) for c in (tracks_el or []) if c.tag in TRACK_TAGS]
for tag in ('MasterTrack', 'MainTrack'):
master = root.find(f'.//{tag}')
if master is not None:
all_tracks.append((tag, master))
break
non_master_tracks = [(tag, t) for tag, t in all_tracks if tag not in ('MasterTrack', 'MainTrack')]
# Fetch duplicate/unnamed counts
track_names = [t.find('.//Name/EffectiveName').get('Value', '')
for _, t in all_tracks
if t.find('.//Name/EffectiveName') is not None]
duplicate_names = {n: track_names.count(n) for n in set(track_names) if n and track_names.count(n) > 1}
duplicate_count = len(duplicate_names)
unnamed_count = sum(1 for n in track_names if not n or re.match(r'^\d+-', n))
# Build group hierarchy and numbering
group_ids, track_numbers = {}, {}
for idx, (tag, t) in enumerate(all_tracks, 1):
xid = t.get('Id', '')
gid = next((child.get('Value', '-1') for child in t if child.tag == 'TrackGroupId'), '-1')
if xid:
group_ids[xid] = gid
track_numbers[xid] = idx
def get_depth(xid):
depth, gid = 0, group_ids.get(xid, '-1')
while gid and gid != '-1' and gid in group_ids:
depth += 1
gid = group_ids.get(gid, '-1')
return depth
# ββ Gather summary stats ββββββββββββββββββββββββββββββββββββββββββββββββββ
tempo_el = root.find('.//Tempo/Manual')
tempo = tempo_el.get('Value', '?') if tempo_el is not None else '?'
creator_m = re.search(r'<Ableton\b[^>]*\bCreator="([^"]+)"', xml_text[:500])
creator = creator_m.group(1) if creator_m else '?'
type_counts = {}
for tag, _ in all_tracks:
label = TRACK_TYPES.get(tag, tag)
type_counts[label] = type_counts.get(label, 0) + 1
# Collect all device data once β reused for ext_plugins, device counts and device tree
track_devices = {i: collect_devices(t) for i, (_, t) in enumerate(all_tracks)}
# Collect all external plugin names across the project
ext_plugins = {}
for i, (tag, track) in enumerate(all_tracks):
for _, dtag, el in track_devices[i]:
if dtag in ('PluginDevice', 'AuPluginDevice'):
block = ET.tostring(el, encoding='unicode')
name_d = extract_device_name(block, dtag)
if name_d:
bare = name_d.replace('[ext] ', '')
ext_plugins[bare] = ext_plugins.get(bare, 0) + 1
frozen_count = sum(
1 for _, t in all_tracks
if any(child.tag == 'Freeze' and child.get('Value') == 'true' for child in t)
)
automation_count = len(set(re.findall(r'<PointeeId\s+Value="(\d+)"', xml_text)))
muted_count = 0
for _, t in all_tracks:
mixer = t.find('.//Mixer')
if mixer is None:
continue
speaker = mixer.find('Speaker')
if speaker is None:
continue
manual = speaker.find('Manual')
if manual is not None and manual.get('Value') == 'false':
muted_count += 1
int_devices, ext_devices, disabled_devices = 0, 0, 0
for i, (_, track) in enumerate(all_tracks):
for _, dtag, el in track_devices[i]:
if dtag in ('PluginDevice', 'AuPluginDevice'):
ext_devices += 1
else:
int_devices += 1
if not is_enabled(el):
disabled_devices += 1
midi_clips = len(re.findall(r'<MidiClip\b', xml_text))
audio_clips = len(re.findall(r'<AudioClip\b', xml_text))
return_names = [
t.find('.//Name/EffectiveName').get('Value', '')
for tag, t in all_tracks
if tag == 'ReturnTrack' and t.find('.//Name/EffectiveName') is not None
]
# Time signature
ts_num = root.find('.//TimeSignature/TimeSignatures/AutomationEvent')
time_sig = '4/4'
if ts_num is not None:
num = ts_num.get('Numerator', '4')
den = ts_num.get('Denominator', '4')
time_sig = f'{num}/{den}'
# Locators
locators = []
for el in root.findall('.//Locators/Locator'):
name_el = el.find('Name')
name = name_el.get('Value', '') if name_el is not None else el.get('Name', '')
if name:
locators.append(name)
# ββ Build report lines ββββββββββββββββββββββββββββββββββββββββββββββββββββ
lines = []
# ββ PROJECT SUMMARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
lines.append('β' * 60)
lines.append(f' PROJECT SUMMARY')
lines.append('β' * 60)
W = 17 # fixed label width β adjust this single value to shift all colons together
lines.append(f' {"Creator":<{W}}: {creator}')
lines.append(f' {"BPM":<{W}}: {float(tempo):.2f}')
lines.append(f' {"Time signature":<{W}}: {time_sig}')
if locators:
pad = ' ' * (W + 10)
max_width = 80 - len(pad)
lines_out, current = [], ''
for loc in locators:
test = f'{current}, {loc}' if current else loc
if current and len(test) > max_width:
lines_out.append(current + ',')
current = loc
else:
current = test
lines_out.append(current)
lines.append(f' {"Locators":<{W}}: {len(locators)} ({lines_out[0]}')
for l in lines_out[1:]:
lines.append(f'{pad}{l}')
lines[-1] += ')'
lines.append('')
lines.append(f' {"Total tracks":<{W}}: {len(non_master_tracks)}')
for label in ['Group', 'Audio', 'MIDI', 'Return']:
count = type_counts.get(label, 0)
if count:
lines.append(f' {label:<{W-2}}: {count}')
if return_names:
lines.append('')
lines.append(f' {"Return tracks":<{W}}: {len(return_names)}')
for name in return_names:
lines.append(f' {name:<{W-2}}')
lines.append('')
lines.append(f' {"Clips":<{W}}: {midi_clips} MIDI / {audio_clips} Audio')
lines.append(f' {"Automations":<{W}}: {automation_count}')
if frozen_count:
lines.append(f' {"Frozen tracks":<{W}}: {frozen_count}')
if muted_count:
lines.append(f' {"Muted tracks":<{W}}: {muted_count}')
if unnamed_count:
lines.append(f' {"Unnamed tracks":<{W}}: {unnamed_count}')
if duplicate_count:
names_sorted = sorted(duplicate_names.items(), key=lambda x: x[0])
name_strs = [f"'{n}'x{c}" for n, c in names_sorted]
pad = ' ' * (W + 10)
max_width = 80 - len(pad)
lines_out, current = [], ''
for name in name_strs:
test = f'{current}, {name}' if current else name
if current and len(test) > max_width:
lines_out.append(current + ',')
current = name
else:
current = test
lines_out.append(current)
lines.append(f' {"Duplicate names":<{W}}: {duplicate_count} ({lines_out[0]}')
for l in lines_out[1:]:
lines.append(f'{pad}{l}')
lines[-1] += ')'
lines.append('')
lines.append(f' {"Total devices":<{W}}: {int_devices + ext_devices}')
lines.append(f' {"Native":<{W-2}}: {int_devices}')
lines.append(f' {"External":<{W-2}}: {ext_devices}')
if disabled_devices:
lines.append('')
lines.append(f' {"Disabled devices":<{W}}: {disabled_devices}')
lines.append('')
# ββ EXTERNAL PLUGINS ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
lines.append('β' * 60)
lines.append(f' EXTERNAL PLUGINS')
lines.append('β' * 60)
for name in sorted(ext_plugins.keys(), key=lambda x: x.lower()):
lines.append(f' {name}')
lines.append('')
# ββ FULL DEVICE LIST ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
lines.append('β' * 60)
lines.append(' FULL DEVICE LIST')
lines.append('β' * 60)
for i, (tag, track) in enumerate(all_tracks):
devices = track_devices[i]
if not devices:
continue
name_el = track.find('.//Name/EffectiveName')
eff_name = name_el.get('Value', track.tag) if name_el is not None else track.tag
xid = track.get('Id', '')
t_indent = ' ' * get_depth(xid)
num = '' if tag in ('MasterTrack', 'MainTrack') else f'#{track_numbers.get(xid, 0):02d} '
lines.append('')
lines.append(f'{t_indent} [{TRACK_TYPES.get(tag, tag)}] {num}{eff_name}')
lines.append(f'{t_indent} {"β" * 40}')
for depth, dtag, el in devices:
indent = t_indent + ' ' + (' ' * depth)
block = ET.tostring(el, encoding='unicode')