-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipeline.py
More file actions
1784 lines (1452 loc) Β· 79.4 KB
/
Copy pathpipeline.py
File metadata and controls
1784 lines (1452 loc) Β· 79.4 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
"""
pipeline.py
The processing pipeline: which cleaning steps exist, which ones config.ini has switched
on, and how they are run over a single .als file.
Every step has the same shape:
step(xml_text, context) -> (xml_text, log_lines)
so the runner can call them uniformly and report each one as changed / unchanged.
"""
import re
import io
import gzip
import xml.etree.ElementTree as ET
from pathlib import Path
from datetime import datetime
from collections import defaultdict
from als_core import (Context, extract_device_name, find_blocks,
detect_live_version, MIN_SUPPORTED_LIVE)
# ββ Report layout widths ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# The fixed widths the report builders in THIS module draw, kept here so they can be
# re-tuned from one place. Structural β they do NOT track the text inside them. (Each
# module keeps its own copy of the widths it uses; these are pipeline.py's.)
SECTION_BAR_W = 60 # β bar around each section header in the .txt report
SUMMARY_BAR_W = 80 # β bar around the on-screen (terminal) summary box
WRAP_WIDTH = 80 # width the flowing comma-lists (locators, pluginsβ¦) wrap to
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# REGISTRY
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def step_catalog():
"""Canonical ordered catalog of ALL pipeline steps as (config_id, step_func, description).
SINGLE SOURCE OF TRUTH for which steps exist and in what order. load_pipeline() filters this
by config to the enabled ones, and the GUI derives its toggle list (order + id set) from it β
so the runner and the UI can never drift apart. Defined as a function rather than a module
constant so it can reference the step_* funcs defined further down, regardless of order.
"""
return [
("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"),
]
def load_pipeline(config):
"""Build and return the ordered list of enabled pipeline steps from config."""
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()}
return [s for s in step_catalog() if enabled.get(s[0], False)]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# UTILITIES
# Helpers used only by the steps and the runner below.
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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 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 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 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 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 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 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
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 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 track_mute_state(track, automated_ids=frozenset()) -> str:
"""Classify a track's mute (Speaker / activator):
'muted' β statically off: base <Manual Value="false"/> AND not automated β silent for the
whole song (the actionable, forgotten-mute / dead-weight case).
'auto' β the mute is automated: it toggles during the song (intentional arrangement),
whatever the base value β never flagged, counted or removed as muted.
'' β not muted.
Speaker mute lives at <Mixer><Speaker><Manual Value="false"/> with an <AutomationTarget Id="N">;
if N appears as a PointeeId anywhere, the mute is automated. Mirrors the automated-On/Off guard
remove_disabled_devices uses for devices."""
mixer = track.find('.//Mixer')
speaker = mixer.find('Speaker') if mixer is not None else None
if speaker is None:
return ''
at = speaker.find('AutomationTarget')
if at is not None and at.get('Id') in automated_ids:
return 'auto'
manual = speaker.find('Manual')
return 'muted' if (manual is not None and manual.get('Value') == 'false') else ''
def track_is_frozen(track) -> bool:
"""Track has been frozen to audio (<Freeze Value="true"/> child)."""
return any(child.tag == 'Freeze' and child.get('Value') == 'true' for child in track)
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, 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 plugins across the project, keyed by (name, format).
# Format matters when rebuilding on another machine: VST2 and VST3 install
# separately, and AU is macOS-only β so the same plugin in two formats is two
# distinct things to have installed, and is listed as two entries.
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] ', '')
fmt = ('AU' if dtag == 'AuPluginDevice'
else 'VST3' if 'Vst3PluginInfo' in block else 'VST2')
ext_plugins[(bare, fmt)] = ext_plugins.get((bare, fmt), 0) + 1
frozen_count = sum(1 for _, t in all_tracks if track_is_frozen(t))
automation_count = len(set(re.findall(r'<PointeeId\s+Value="(\d+)"', xml_text)))
muted_count = sum(1 for _, t in all_tracks if track_mute_state(t, auto_ids) == 'muted')
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('β' * SECTION_BAR_W)
lines.append(f' PROJECT SUMMARY')
lines.append('β' * SECTION_BAR_W)
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 = WRAP_WIDTH - 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 = WRAP_WIDTH - 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('β' * SECTION_BAR_W)
lines.append(f' EXTERNAL PLUGINS')
lines.append('β' * SECTION_BAR_W)
# Same layout rule as the global list and the collect report: 2-space indent, name
# padded to the longest, then 3 spaces before the format column.
PW = max((len(n) for n, _f in ext_plugins), default=0)
for name, fmt in sorted(ext_plugins.keys(), key=lambda x: (x[0].lower(), x[1])):
lines.append(f' {name:<{PW}} {fmt}')
lines.append('')
# ββ FULL DEVICE LIST ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
lines.append('β' * SECTION_BAR_W)
lines.append(' FULL DEVICE LIST')
lines.append('β' * SECTION_BAR_W)
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} '
m_state = track_mute_state(track, auto_ids)
mute_tag = ' [Muted]' if m_state == 'muted' else ' [Mute auto]' if m_state == 'auto' else ''
status = (' [Frozen]' if track_is_frozen(track) else '') + mute_tag
lines.append('')
lines.append(f'{t_indent} [{TRACK_TYPES.get(tag, tag)}] {num}{eff_name}{status}')
lines.append(f'{t_indent} {"β" * 40}')
for depth, dtag, el in devices:
indent = t_indent + ' ' + (' ' * depth)
block = ET.tostring(el, encoding='unicode')
name_d = extract_device_name(block, dtag) or f'[int] {dtag}'
state = '' if is_enabled(el) else ' [Off]'
auto_count = count_automation(el, auto_ids)
auto = f' [Auto:{auto_count}]' if auto_count else ''
lines.append(f'{indent}{name_d}{state}{auto}')
lines.append('')
# ββ Save report to txt ββββββββββββββββββββββββββββββββββββββββββββββββββββ
als_path = context.als_path
out_path = als_path.parent / f'{als_path.stem}_report.txt'
out_path.write_text('\n'.join(lines), encoding='utf-8')
# ββ Short terminal summary ββββββββββββββββββββββββββββββββββββββββββββββββ
print(f'\n {"β" * SUMMARY_BAR_W}')
print(f' {creator}')
print(f' BPM {float(tempo):.2f} | Time sig {time_sig}')
print()
track_parts = ' | '.join(f'{type_counts[label]} {label}' for label in ['Group', 'Audio', 'MIDI', 'Return'] if label in type_counts)
TW = 12 # fixed label width for terminal summary β adjust to align all colons
frozen_str = f' [{frozen_count} Frozen]' if frozen_count else ''
print(f' {"Tracks":<{TW}}: {len(non_master_tracks)} total ({track_parts}){frozen_str}')
print(f' {"Clips":<{TW}}: {midi_clips + audio_clips} total ({midi_clips} MIDI | {audio_clips} Audio)')
print(f' {"Devices":<{TW}}: {int_devices + ext_devices} total ({int_devices} Native | {ext_devices} External) [{len(ext_plugins)} unique external]')
print(f' {"Automations":<{TW}}: {automation_count}')
flags = []
if muted_count: flags.append(f'{muted_count} muted tracks')
if unnamed_count: flags.append(f'{unnamed_count} unnamed tracks')
if duplicate_count: flags.append(f'{duplicate_count} duplicate track names')
if disabled_devices: flags.append(f'{disabled_devices} disabled devices')
if flags:
print(f'\n β {", ".join(flags)}')
print(f' {"β" * SUMMARY_BAR_W}\n')
context.report_written = True # runner uses this to mark the step β (XML itself didn't change)
return xml_text, [f'Report saved β {out_path.name}']
def aggregate_external_plugins(als_files: list[Path], root: Path) -> Path | None:
"""Compile '@ External Plugins List.txt' across all processed projects, reading each
project's own '_report.txt'. Opens with a HEADER naming the report + every project it
covers (so the scope is clear up front, like the collect report's title box), then:
β’ FULL LIST β every unique external plugin, name padded to the longest + 3 spaces,
then its VST2/VST3/AU format (same column rule as the per-project
and collect reports).
β’ USAGE BY PROJECT β plugins grouped by the set of projects that share them; the format
is dropped (the FULL LIST already carries it) and both the plugin and
project halves wrap at WRAP_WIDTH so a busy line never runs off.
Returns the written path, or None if no external plugins were found across the set.
SHARED by both the CLI (main) and the GUI worker β the single source of truth so the two
can never drift out of sync again. Bars are 60 wide and lists wrap at 80, matching every
other report in the app.
"""
plugin_projects: dict[tuple[str, str], set[str]] = {}
covered: list[str] = [] # every project that contributed a report (incl. plugin-free ones)
for als_path in als_files:
report_path = als_path.parent / f'{als_path.stem}_report.txt'
if not report_path.exists():
continue
covered.append(als_path.name)
text = report_path.read_text(encoding='utf-8')
in_section = False
sep_count = 0
for line in text.splitlines():
if 'EXTERNAL PLUGINS' in line:
in_section = True
continue
if in_section and line.startswith('β'):
sep_count += 1
if sep_count == 2: # second β = end of section
break
continue
if in_section and line.strip():
# Split name from format on the padding run. Keying on the raw line would
# fold this project's column width into the key, so the same plugin would
# land under two different keys across projects.
parts = re.split(r'\s{2,}', line.strip())
plugin_projects.setdefault(
(parts[0], parts[1] if len(parts) > 1 else ''), set()
).add(als_path.name)
if not plugin_projects:
return None
# Group plugins by which projects share them. A plugin used as VST2 in one project and
# VST3 in another groups separately β they are separate installs.
combo_plugins: dict[tuple, set] = {}
for (name, _fmt), projects in plugin_projects.items():
combo_plugins.setdefault(tuple(sorted(projects)), set()).add(name)
out_lines: list[str] = []
# ββ HEADER β what this report covers βββββββββββββββββββββββββββββββββββββββββ
# Names the report and the projects it aggregates up front, so the scope is obvious without
# reverse-engineering it from USAGE BY PROJECT below. Mirrors the collect report's title box.
out_lines += ['β' * SECTION_BAR_W, ' @ External Plugins List', 'β' * SECTION_BAR_W]
LW = len('Generated') # label pad so the colons line up (widest of Generated / Projects)
out_lines.append(f' {"Generated":<{LW}} : {datetime.now().strftime("%Y-%m-%d %H:%M")}')
out_lines.append(f' {"Projects":<{LW}} : {len(covered)}')
for name in sorted(covered, key=str.lower):
out_lines.append(f' {name}')
out_lines.append('')
# ββ FULL LIST ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
GW = max((len(n) for n, _f in plugin_projects), default=0)
out_lines += ['β' * SECTION_BAR_W, ' EXTERNAL PLUGINS β FULL LIST', 'β' * SECTION_BAR_W]
for name, fmt in sorted(plugin_projects.keys(), key=lambda x: (x[0].lower(), x[1])):
out_lines.append(f' {name:<{GW}} {fmt}')
out_lines.append('')
# ββ USAGE BY PROJECT βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Both halves wrap at 80. The "β " prefix marks the project half, and its continuations
# hang 4 so the two halves stay visually separate when both wrap.
def wrap(items, prefix=''):
# Breaks on the comma, never inside an item β textwrap.wrap() would split on the
# spaces within "WLM Plus Stereo" and make one plugin read as two.
indent, hang = ' ' + prefix, ' ' + ' ' * len(prefix)
lines, cur = [], None
for i, item in enumerate(items):
piece = item + (',' if i < len(items) - 1 else '')
if cur is None:
cur = indent + piece
elif len(cur) + 1 + len(piece) <= WRAP_WIDTH:
cur += ' ' + piece
else:
lines.append(cur)
cur = hang + piece
return lines + ([cur] if cur else [])
out_lines += ['β' * SECTION_BAR_W, ' EXTERNAL PLUGINS β USAGE BY PROJECT', 'β' * SECTION_BAR_W]
for projects, names in sorted(combo_plugins.items(), key=lambda x: -len(x[0])):
out_lines += wrap(sorted(names, key=str.lower))
out_lines += wrap(projects, 'β ')
out_lines.append('')
out_path = root / '@ External Plugins List.txt'
out_path.write_text('\n'.join(out_lines), encoding='utf-8')
return out_path
def step_remove_unused_return_tracks(xml_text: str, context: Context) -> tuple:
"""
A return track is considered unused if NO source track (Audio, MIDI, Group)
has an active send routed to it with a value above Ableton's minimum.
Specifically, a return track at index N is removed if every TrackSendHolder
with Id="N" across all source tracks meets at least one of these conditions:
- <Active Value="false" /> β the send is muted/disabled
- <Manual Value="0.0003162277571" /> β Ableton's -inf dB (knob fully left)
When a return track is removed, the function also:
1. Removes ALL TrackSendHolder blocks not pointing to a surviving return track.
This includes both the removed return's holders AND any pre-existing orphaned
holders from return tracks deleted outside this script.
2. Re-indexes remaining TrackSendHolder Ids to be sequential (0, 1, 2...)
so Ableton's send count matches the remaining return track count exactly.
"""
MINUS_INF = 0.0003162277571
return_tracks = []
for start, end, content in find_blocks(xml_text, "ReturnTrack"):
m = re.search(r'<(?:UserName|EffectiveName)\s+Value="([^"]+)"', content)
return_tracks.append({"start": start, "end": end, "name": m.group(1) if m else "Return"})
if not return_tracks:
return xml_text, ["No return tracks found."]
# Find which return indices have at least one active non-zero send
active = set()
for tag in ["AudioTrack", "MidiTrack", "GroupTrack"]:
for _, _, track in find_blocks(xml_text, tag):
for _, _, holder in find_blocks(track, "TrackSendHolder"):
m_id = re.search(r'Id="(\d+)"', holder)
m_val = re.search(r'<Manual\s+Value="([^"]+)"', holder)
m_on = re.search(r'<Active\s+Value="(true|false)"', holder)
if not m_id:
continue
idx = int(m_id.group(1))
val = float(m_val.group(1)) if m_val else 0.0
is_on = (m_on.group(1) == "true") if m_on else True
if is_on and val > MINUS_INF:
active.add(idx)
remove = {i for i in range(len(return_tracks)) if i not in active}
if not remove:
return xml_text, ["No unused return tracks found."]
# Remove ReturnTrack blocks
xml_text = splice_out(xml_text, [return_tracks[i] for i in remove])
kept = {i for i in range(len(return_tracks)) if i not in remove}
holders = []
for tag in ["AudioTrack", "MidiTrack", "GroupTrack", "ReturnTrack"]:
for t_start, _, t_content in find_blocks(xml_text, tag):
for h_rel_start, h_rel_end, c in find_blocks(t_content, "TrackSendHolder"):
m = re.search(r'Id="(\d+)"', c)
if m and int(m.group(1)) not in kept: # remove orphans too
holders.append({"start": t_start + h_rel_start, "end": t_start + h_rel_end})
xml_text = splice_out(xml_text, holders)
# Re-index remaining TrackSendHolder Ids sequentially
remap = {old: new for new, old in enumerate(i for i in range(len(return_tracks)) if i not in remove)}
xml_text = re.sub(
r'<TrackSendHolder\s+Id="(\d+)"',
lambda m: f'<TrackSendHolder Id="{remap.get(int(m.group(1)), int(m.group(1)))}"',
xml_text
)
log = [f" Removed unused return track '{return_tracks[i]['name']}'" for i in remove]
return xml_text, log
def step_remove_disabled_devices(xml_text: str, context: Context) -> tuple:
"""
Remove any device (native or external) that has been disabled in Ableton.
A device is considered disabled if its <On> block contains: <Manual Value="false" />
This covers all device types β native Ableton devices (EQ, Compressor, Reverb etc.)
and external VST devices alike.
Guards:
- Always preserve the first device in each chain β if the sound source is