loopcutter 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ """Reading key data out of a spreadsheet and rendering the plan.
2
+
3
+ Accepts CSV, XLSX or a loopcutter manifest. It looks for a column named key,
4
+ camelot, initial key or initialkey, case-insensitively, so it works on exports
5
+ from Mixed In Key, Serato and rekordbox without editing them first.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from .keys import (COMFORT_SEMITONES, Key, KeyParseError, Plan, SweepRow,
15
+ key_histogram, parse_key)
16
+
17
+ KEY_COLUMNS = ("key", "camelot", "initial key", "initialkey", "initial_key", "tone")
18
+ LABEL_COLUMNS = ("label", "track", "title", "name", "sample", "file", "filename")
19
+ ARTIST_COLUMNS = ("artist", "source")
20
+
21
+
22
+ @dataclass
23
+ class LoadResult:
24
+ entries: list[tuple[str, Key]]
25
+ total_rows: int
26
+ unparsed: list[tuple[str, str]]
27
+ no_key: int
28
+
29
+
30
+ def _pick(fieldnames: list[str], candidates: tuple[str, ...]) -> str | None:
31
+ lowered = {name.strip().lower(): name for name in fieldnames if name}
32
+ for candidate in candidates:
33
+ if candidate in lowered:
34
+ return lowered[candidate]
35
+ return None
36
+
37
+
38
+ def _rows_from_csv(path: Path) -> tuple[list[dict], list[str]]:
39
+ with path.open(newline="", encoding="utf-8-sig") as handle:
40
+ reader = csv.DictReader(handle)
41
+ if reader.fieldnames is None:
42
+ raise ValueError(f"{path} has no header row")
43
+ return list(reader), list(reader.fieldnames)
44
+
45
+
46
+ def _rows_from_xlsx(path: Path, sheet: str | None) -> tuple[list[dict], list[str]]:
47
+ try:
48
+ from openpyxl import load_workbook
49
+ except ImportError as exc: # pragma: no cover
50
+ raise ImportError(
51
+ "reading .xlsx needs openpyxl: pip install 'loopcutter[sheets]'"
52
+ ) from exc
53
+
54
+ book = load_workbook(str(path), data_only=True)
55
+ ws = book[sheet] if sheet else book[book.sheetnames[0]]
56
+
57
+ header_row = None
58
+ for row in ws.iter_rows(min_row=1, max_row=12, values_only=True):
59
+ cells = [str(c).strip().lower() if c is not None else "" for c in row]
60
+ if any(c in KEY_COLUMNS for c in cells):
61
+ header_row = row
62
+ break
63
+ if header_row is None:
64
+ raise ValueError(
65
+ f"no key column found in the first 12 rows of {path.name}"
66
+ f" (sheet {ws.title!r}). Looked for: {', '.join(KEY_COLUMNS)}"
67
+ )
68
+
69
+ headers = [str(c).strip() if c is not None else "" for c in header_row]
70
+ start = None
71
+ for index, row in enumerate(ws.iter_rows(values_only=True), start=1):
72
+ if row == header_row:
73
+ start = index + 1
74
+ break
75
+
76
+ rows = []
77
+ for row in ws.iter_rows(min_row=start, values_only=True):
78
+ if all(c is None or str(c).strip() == "" for c in row):
79
+ continue
80
+ rows.append({h: ("" if v is None else str(v))
81
+ for h, v in zip(headers, row) if h})
82
+ return rows, headers
83
+
84
+
85
+ def load_keys(path: str | Path, sheet: str | None = None) -> LoadResult:
86
+ path = Path(path)
87
+ if not path.exists():
88
+ raise FileNotFoundError(f"no such file: {path}")
89
+
90
+ if path.suffix.lower() in {".xlsx", ".xlsm"}:
91
+ rows, headers = _rows_from_xlsx(path, sheet)
92
+ else:
93
+ rows, headers = _rows_from_csv(path)
94
+
95
+ key_col = _pick(headers, KEY_COLUMNS)
96
+ if key_col is None:
97
+ raise ValueError(
98
+ f"no key column in {path.name}. Looked for: {', '.join(KEY_COLUMNS)}"
99
+ )
100
+ label_col = _pick(headers, LABEL_COLUMNS)
101
+ artist_col = _pick(headers, ARTIST_COLUMNS)
102
+
103
+ entries: list[tuple[str, Key]] = []
104
+ unparsed: list[tuple[str, str]] = []
105
+ no_key = 0
106
+
107
+ for number, row in enumerate(rows, start=2):
108
+ raw = (row.get(key_col) or "").strip()
109
+ parts = [row.get(artist_col) or "", row.get(label_col) or ""]
110
+ label = " - ".join(p for p in parts if p) or f"row {number}"
111
+
112
+ if not raw:
113
+ no_key += 1
114
+ continue
115
+ try:
116
+ entries.append((label, parse_key(raw)))
117
+ except KeyParseError:
118
+ unparsed.append((label, raw))
119
+
120
+ return LoadResult(entries=entries, total_rows=len(rows),
121
+ unparsed=unparsed, no_key=no_key)
122
+
123
+
124
+ def _shift_text(shift: int, comfort: int = COMFORT_SEMITONES) -> str:
125
+ if shift == 0:
126
+ return "as is"
127
+ text = f"{shift:+d} semitone{'s' if abs(shift) != 1 else ''}"
128
+ if abs(shift) > comfort:
129
+ text += " <-- stretched, audition this"
130
+ return text
131
+
132
+
133
+ def render(plan: Plan, load: LoadResult, verbose: bool = False,
134
+ comfort: int = COMFORT_SEMITONES) -> str:
135
+ out: list[str] = []
136
+ add = out.append
137
+
138
+ add(f"{load.total_rows} rows, {plan.total_keyed} with a readable key")
139
+ if load.no_key:
140
+ add(f" {load.no_key} with no key (percussion and texture, presumably)")
141
+ if load.unparsed:
142
+ add(f" {len(load.unparsed)} unreadable:")
143
+ for label, raw in load.unparsed[:8]:
144
+ add(f" {label}: {raw!r}")
145
+ if len(load.unparsed) > 8:
146
+ add(f" ...and {len(load.unparsed) - 8} more")
147
+ add("")
148
+ add(f"Transposition limit: +/-{plan.max_semitones} semitones"
149
+ + (", relative major/minor allowed" if plan.allow_relative else ""))
150
+ if plan.max_semitones > comfort:
151
+ add(f" Beyond +/-{comfort} is past the usual comfort zone. Loops needing")
152
+ add(" more than that are marked below. Trust your ears, not the table.")
153
+ add("")
154
+
155
+ if not plan.options:
156
+ add("No session key covers anything. Check the key column.")
157
+ return "\n".join(out)
158
+
159
+ running = 0
160
+ for index, option in enumerate(plan.options, start=1):
161
+ running += option.count
162
+ share = 100 * option.count / plan.total_keyed if plan.total_keyed else 0
163
+ add(f"Session key {index}: {option.key}")
164
+ noun = "loop" if option.count == 1 else "loops"
165
+ add(f" covers {option.count} {noun} ({share:.0f}%), "
166
+ f"{option.untransposed} of them untransposed")
167
+ add(f" running total: {running}/{plan.total_keyed} "
168
+ f"({100 * running / plan.total_keyed:.0f}%)")
169
+
170
+ if index == 1 and plan.runners_up:
171
+ close = ", ".join(f"{k.camelot} ({n})" for k, n in plan.runners_up)
172
+ add(f" next best were: {close}")
173
+
174
+ if verbose:
175
+ add(" loops:")
176
+ for a in sorted(option.covered, key=lambda x: (abs(x.shift), x.label)):
177
+ via = " via relative" if a.via_relative else ""
178
+ add(f" {a.label} [{a.key.camelot}] "
179
+ f"{_shift_text(a.shift, comfort)}{via}")
180
+ add("")
181
+
182
+ if plan.unreachable:
183
+ add(f"Not covered by {len(plan.options)} key"
184
+ f"{'s' if len(plan.options) != 1 else ''}: {len(plan.unreachable)} loops")
185
+ for label, key in sorted(plan.unreachable, key=lambda e: e[1].camelot):
186
+ add(f" {label} [{key.camelot}] {key.name}")
187
+ add("")
188
+ add("Options: raise the transposition limit, add a fourth key, allow")
189
+ add("relative major/minor with --relative, or leave these out of the set.")
190
+ else:
191
+ add(f"All {plan.total_keyed} keyed loops are covered.")
192
+
193
+ return "\n".join(out)
194
+
195
+
196
+ def render_histogram(entries: list[tuple[str, Key]]) -> str:
197
+ rows = key_histogram(entries)
198
+ if not rows:
199
+ return "No keys to chart."
200
+ widest = max(count for _, count in rows)
201
+ lines = ["Key distribution:"]
202
+ for key, count in rows:
203
+ bar = "#" * max(1, round(24 * count / widest))
204
+ lines.append(f" {key.camelot:>3} {key.name:<9} {count:>4} {bar}")
205
+ return "\n".join(lines)
206
+
207
+
208
+ def render_sweep(rows: list[SweepRow], max_keys: int,
209
+ comfort: int = COMFORT_SEMITONES) -> str:
210
+ """Show what relaxing the transposition limit actually buys."""
211
+ lines = [
212
+ f"Coverage by transposition limit (with {max_keys} session key"
213
+ f"{'s' if max_keys != 1 else ''}):",
214
+ "",
215
+ " limit covered keys to cover all stretched",
216
+ ]
217
+ previous = None
218
+ for row in rows:
219
+ full = str(row.keys_for_full) if row.keys_for_full else ">8"
220
+ gain = ""
221
+ if previous is not None and row.covered > previous:
222
+ gain = f" (+{row.covered - previous})"
223
+ flag = " *" if row.semitones > comfort else " "
224
+ lines.append(
225
+ f" +/-{row.semitones}{flag} {row.covered:>3}/{row.total} "
226
+ f"({row.share:>3.0f}%){gain:<7} {full:>3}"
227
+ f" {row.stretched if row.stretched else '-':>3}"
228
+ )
229
+ previous = row.covered
230
+
231
+ lines.append("")
232
+ lines.append(f" * beyond the usual +/-{comfort} comfort zone")
233
+ lines.append("")
234
+ lines.append("Read the middle column first. Dropping from three session keys")
235
+ lines.append("to two is usually worth more than a few percent of coverage.")
236
+ return "\n".join(lines)
loopcutter/keys.py ADDED
@@ -0,0 +1,346 @@
1
+ """Session-key planning.
2
+
3
+ Given a library of loops with known keys, work out which session key lets you
4
+ use the most of them, which ones that excludes, and what second and third keys
5
+ would pick up the remainder.
6
+
7
+ The model is transposition, not harmonic mixing. A loop is usable in a session
8
+ key if you can pitch it there without audible artifacts—consensus is about
9
+ three semitones either way. Beyond that you should find a different loop rather
10
+ than force the one you have.
11
+
12
+ Relative major/minor is offered as an option (--relative) because the two share
13
+ the same notes: an A minor loop sits inside C major untransposed. It is off by
14
+ default because sharing notes is not the same as sharing a tonic, and a loop
15
+ with a strong root note will still pull against the session.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from collections import Counter
22
+ from dataclasses import dataclass, field
23
+
24
+ # C = 0 .. B = 11
25
+ PITCH_CLASSES = {
26
+ "C": 0, "C#": 1, "DB": 1, "D": 2, "D#": 3, "EB": 3, "E": 4, "FB": 4,
27
+ "E#": 5, "F": 5, "F#": 6, "GB": 6, "G": 7, "G#": 8, "AB": 8, "A": 9,
28
+ "A#": 10, "BB": 10, "B": 11, "CB": 11,
29
+ }
30
+
31
+ PC_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
32
+
33
+ # Camelot wheel. The A series is minor, the B series its relative major.
34
+ CAMELOT_MINOR = {1: 8, 2: 3, 3: 10, 4: 5, 5: 0, 6: 7,
35
+ 7: 2, 8: 9, 9: 4, 10: 11, 11: 6, 12: 1}
36
+ CAMELOT_MAJOR = {1: 11, 2: 6, 3: 1, 4: 8, 5: 3, 6: 10,
37
+ 7: 5, 8: 0, 9: 7, 10: 2, 11: 9, 12: 4}
38
+
39
+ _TO_CAMELOT = {}
40
+ for _n, _pc in CAMELOT_MINOR.items():
41
+ _TO_CAMELOT[(_pc, "minor")] = f"{_n}A"
42
+ for _n, _pc in CAMELOT_MAJOR.items():
43
+ _TO_CAMELOT[(_pc, "major")] = f"{_n}B"
44
+
45
+ _CAMELOT_RE = re.compile(r"^\s*(\d{1,2})\s*([AB])\s*$", re.IGNORECASE)
46
+ _NAMED_RE = re.compile(
47
+ r"^\s*([A-Ga-g][#b♯♭]?)\s*"
48
+ r"(m|min|minor|maj|major|M)?\s*$"
49
+ )
50
+
51
+ MAX_SEMITONES_DEFAULT = 3
52
+ COMFORT_SEMITONES = 3
53
+ MAX_POSSIBLE_SEMITONES = 6 # a tritone; beyond this you are going the other way
54
+
55
+
56
+ class KeyParseError(ValueError):
57
+ """Raised when a key string cannot be interpreted."""
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Key:
62
+ """A musical key as a tonic pitch class plus a mode."""
63
+
64
+ pitch_class: int
65
+ mode: str # "major" or "minor"
66
+
67
+ @property
68
+ def camelot(self) -> str:
69
+ return _TO_CAMELOT[(self.pitch_class, self.mode)]
70
+
71
+ @property
72
+ def name(self) -> str:
73
+ suffix = "minor" if self.mode == "minor" else "major"
74
+ return f"{PC_NAMES[self.pitch_class]} {suffix}"
75
+
76
+ def __str__(self) -> str:
77
+ return f"{self.name} ({self.camelot})"
78
+
79
+ @property
80
+ def relative(self) -> "Key":
81
+ """The relative major of a minor key, or relative minor of a major."""
82
+ if self.mode == "minor":
83
+ return Key((self.pitch_class + 3) % 12, "major")
84
+ return Key((self.pitch_class - 3) % 12, "minor")
85
+
86
+
87
+ def parse_key(text: str) -> Key:
88
+ """Parse Camelot ("8A") or named ("Am", "F# minor", "Bb") notation.
89
+
90
+ Open Key notation (1m / 1d) is not supported—it is offset from Camelot by
91
+ five positions and silently misreading it would be worse than refusing.
92
+ """
93
+ if text is None:
94
+ raise KeyParseError("empty key")
95
+ raw = str(text).strip().replace("♯", "#").replace("♭", "b")
96
+ if not raw:
97
+ raise KeyParseError("empty key")
98
+
99
+ match = _CAMELOT_RE.match(raw)
100
+ if match:
101
+ number = int(match.group(1))
102
+ letter = match.group(2).upper()
103
+ if not 1 <= number <= 12:
104
+ raise KeyParseError(f"Camelot number out of range: {raw!r}")
105
+ if letter == "A":
106
+ return Key(CAMELOT_MINOR[number], "minor")
107
+ return Key(CAMELOT_MAJOR[number], "major")
108
+
109
+ match = _NAMED_RE.match(raw)
110
+ if match:
111
+ tonic = match.group(1)
112
+ quality = (match.group(2) or "").strip()
113
+ pc = PITCH_CLASSES.get(tonic.upper())
114
+ if pc is None:
115
+ raise KeyParseError(f"unknown tonic in {raw!r}")
116
+ # Bare "m" is minor; bare "M", "maj" or nothing at all is major.
117
+ mode = "minor" if quality.lower() in {"m", "min", "minor"} else "major"
118
+ if quality == "M":
119
+ mode = "major"
120
+ return Key(pc, mode)
121
+
122
+ raise KeyParseError(f"cannot parse key {raw!r}")
123
+
124
+
125
+ def semitone_distance(a: int, b: int) -> int:
126
+ """Shortest distance between two pitch classes, 0 to 6."""
127
+ gap = abs(a - b) % 12
128
+ return min(gap, 12 - gap)
129
+
130
+
131
+ def signed_shift(source: int, target: int) -> int:
132
+ """Semitones to move `source` onto `target`, choosing the shorter route.
133
+
134
+ Positive is up. Ties (a tritone) resolve downward, which is the gentler
135
+ choice for loops with bass content.
136
+ """
137
+ up = (target - source) % 12
138
+ down = up - 12
139
+ return up if up < abs(down) else down
140
+
141
+
142
+ def is_reachable(loop: Key, session: Key, max_semitones: int,
143
+ allow_relative: bool) -> bool:
144
+ if loop.mode == session.mode:
145
+ return semitone_distance(loop.pitch_class, session.pitch_class) <= max_semitones
146
+ if allow_relative:
147
+ rel = loop.relative
148
+ return semitone_distance(rel.pitch_class, session.pitch_class) <= max_semitones
149
+ return False
150
+
151
+
152
+ def all_keys() -> list[Key]:
153
+ return [Key(pc, mode) for mode in ("minor", "major") for pc in range(12)]
154
+
155
+
156
+ @dataclass
157
+ class Assignment:
158
+ """One loop placed in a session key."""
159
+
160
+ label: str
161
+ key: Key
162
+ shift: int
163
+ via_relative: bool = False
164
+
165
+
166
+ @dataclass
167
+ class Option:
168
+ """A candidate session key and what it covers."""
169
+
170
+ key: Key
171
+ covered: list[Assignment] = field(default_factory=list)
172
+
173
+ @property
174
+ def count(self) -> int:
175
+ return len(self.covered)
176
+
177
+ @property
178
+ def untransposed(self) -> int:
179
+ return sum(1 for a in self.covered if a.shift == 0)
180
+
181
+
182
+ @dataclass
183
+ class Plan:
184
+ """The full result: ranked session keys and what each picks up."""
185
+
186
+ options: list[Option]
187
+ unreachable: list[tuple[str, Key]]
188
+ total_keyed: int
189
+ total_rows: int
190
+ max_semitones: int
191
+ allow_relative: bool
192
+ runners_up: list[tuple[Key, int]] = field(default_factory=list)
193
+
194
+ @property
195
+ def covered_count(self) -> int:
196
+ return sum(o.count for o in self.options)
197
+
198
+
199
+ def _assign(label: str, loop: Key, session: Key,
200
+ max_semitones: int, allow_relative: bool) -> Assignment | None:
201
+ if loop.mode == session.mode:
202
+ if semitone_distance(loop.pitch_class, session.pitch_class) <= max_semitones:
203
+ return Assignment(label, loop,
204
+ signed_shift(loop.pitch_class, session.pitch_class))
205
+ return None
206
+ if allow_relative:
207
+ rel = loop.relative
208
+ if semitone_distance(rel.pitch_class, session.pitch_class) <= max_semitones:
209
+ return Assignment(label, loop,
210
+ signed_shift(rel.pitch_class, session.pitch_class),
211
+ via_relative=True)
212
+ return None
213
+
214
+
215
+ def plan_sessions(
216
+ entries: list[tuple[str, Key]],
217
+ max_keys: int = 3,
218
+ max_semitones: int = MAX_SEMITONES_DEFAULT,
219
+ allow_relative: bool = False,
220
+ total_rows: int | None = None,
221
+ ) -> Plan:
222
+ """Greedy set cover: pick the key covering most loops, then repeat.
223
+
224
+ Greedy is not guaranteed optimal for set cover, but with 24 candidate keys
225
+ and a coverage function this smooth, the first pick is always the true
226
+ maximum and later picks are near it. Exhaustive search over triples is
227
+ 2024 combinations and would also be fine—greedy is chosen for readable
228
+ output ordering, not speed.
229
+ """
230
+ if max_keys < 1:
231
+ raise ValueError("max_keys must be at least 1")
232
+
233
+ remaining = list(entries)
234
+ options: list[Option] = []
235
+ runners_up: list[tuple[Key, int]] = []
236
+
237
+ for round_index in range(max_keys):
238
+ if not remaining:
239
+ break
240
+
241
+ scored: list[tuple[int, int, Key, list[Assignment]]] = []
242
+ for session in all_keys():
243
+ hits = [
244
+ a for a in (
245
+ _assign(label, loop, session, max_semitones, allow_relative)
246
+ for label, loop in remaining
247
+ ) if a is not None
248
+ ]
249
+ # Rank by coverage, then by how many need no transposition at all.
250
+ scored.append((len(hits), sum(1 for h in hits if h.shift == 0),
251
+ session, hits))
252
+
253
+ scored.sort(key=lambda s: (-s[0], -s[1], s[2].pitch_class, s[2].mode))
254
+ best = scored[0]
255
+ if best[0] == 0:
256
+ break
257
+
258
+ if round_index == 0:
259
+ runners_up = [(s[2], s[0]) for s in scored[1:4]]
260
+
261
+ options.append(Option(key=best[2], covered=best[3]))
262
+ taken = {id_ for id_ in range(len(remaining))
263
+ if _assign(remaining[id_][0], remaining[id_][1], best[2],
264
+ max_semitones, allow_relative) is not None}
265
+ remaining = [e for i, e in enumerate(remaining) if i not in taken]
266
+
267
+ return Plan(
268
+ options=options,
269
+ unreachable=remaining,
270
+ total_keyed=len(entries),
271
+ total_rows=total_rows if total_rows is not None else len(entries),
272
+ max_semitones=max_semitones,
273
+ allow_relative=allow_relative,
274
+ runners_up=runners_up,
275
+ )
276
+
277
+
278
+ def key_histogram(entries: list[tuple[str, Key]]) -> list[tuple[Key, int]]:
279
+ counts = Counter(key for _, key in entries)
280
+ return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].pitch_class))
281
+
282
+
283
+ @dataclass
284
+ class SweepRow:
285
+ """Coverage at one transposition limit."""
286
+
287
+ semitones: int
288
+ covered: int
289
+ total: int
290
+ keys_used: int
291
+ keys_for_full: int | None
292
+ stretched: int # covered only by exceeding the comfort threshold
293
+
294
+ @property
295
+ def share(self) -> float:
296
+ return 100 * self.covered / self.total if self.total else 0.0
297
+
298
+
299
+ def sweep(
300
+ entries: list[tuple[str, Key]],
301
+ max_keys: int = 3,
302
+ allow_relative: bool = False,
303
+ comfort: int = COMFORT_SEMITONES,
304
+ full_cover_ceiling: int = 8,
305
+ ) -> list[SweepRow]:
306
+ """Coverage at every transposition limit from 0 to a tritone.
307
+
308
+ Two numbers per row that answer different questions. `covered` is how much
309
+ of the library `max_keys` session keys reach at that limit. `keys_for_full`
310
+ is how many session keys it would take to reach everything—which is often
311
+ the more useful figure, because relaxing the limit by one semitone can drop
312
+ you from three session keys to two.
313
+
314
+ `stretched` counts loops that only come along because the limit exceeds the
315
+ comfort threshold. Those are the ones to audition before trusting them.
316
+ """
317
+ rows: list[SweepRow] = []
318
+ total = len(entries)
319
+
320
+ for limit in range(MAX_POSSIBLE_SEMITONES + 1):
321
+ plan = plan_sessions(entries, max_keys=max_keys,
322
+ max_semitones=limit, allow_relative=allow_relative)
323
+ stretched = sum(
324
+ 1 for option in plan.options for a in option.covered
325
+ if abs(a.shift) > comfort
326
+ )
327
+
328
+ keys_for_full = None
329
+ for candidate in range(1, full_cover_ceiling + 1):
330
+ trial = plan_sessions(entries, max_keys=candidate,
331
+ max_semitones=limit,
332
+ allow_relative=allow_relative)
333
+ if not trial.unreachable:
334
+ keys_for_full = candidate
335
+ break
336
+
337
+ rows.append(SweepRow(
338
+ semitones=limit,
339
+ covered=plan.covered_count,
340
+ total=total,
341
+ keys_used=len(plan.options),
342
+ keys_for_full=keys_for_full,
343
+ stretched=stretched,
344
+ ))
345
+
346
+ return rows