chordseq 0.0.2__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.
chordseq/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """chordseq: search chord progressions in any key, count n-grams, name chords by key.
2
+
3
+ >>> from chordseq import find, ngrams, to_roman_sequence
4
+ >>> [(m.start, m.stop) for m in find("Am F C", ["Dm", "Bb", "F", "G", "Em", "Bb", "G"])]
5
+ [(0, 3)]
6
+ >>> to_roman_sequence(["G", "D", "Em", "C", "G"])
7
+ ['I', 'V', 'vi', 'IV', 'I']
8
+ >>> ngrams([["C", "G", "Am", "F"]], n=2).most_common(2)
9
+ [(('I', 'V'), 1), (('V', 'vi'), 1)]
10
+ """
11
+
12
+ from chordseq.ngrams import ngrams
13
+ from chordseq.query import Query, QueryError, parse_query
14
+ from chordseq.roman import parse_roman, to_roman, to_roman_sequence
15
+ from chordseq.search import Match, find, search
16
+ from chordseq.tokens import LEVELS
17
+
18
+ __all__ = [
19
+ "LEVELS",
20
+ "Match",
21
+ "Query",
22
+ "QueryError",
23
+ "find",
24
+ "ngrams",
25
+ "parse_query",
26
+ "parse_roman",
27
+ "search",
28
+ "to_roman",
29
+ "to_roman_sequence",
30
+ ]
chordseq/ngrams.py ADDED
@@ -0,0 +1,121 @@
1
+ """N-gram counts of chord progressions, in the same alphabet the search uses.
2
+
3
+ Each sequence is tokenised as in :mod:`chordseq.search` (level, repeats collapsed), windows
4
+ of ``n`` chords are counted, and a window that holds a non-chord is skipped. How an n-gram is
5
+ *named* decides what counts as the same progression:
6
+
7
+ - ``relative_to="key"`` (default): Roman numerals in the sequence's key (estimated by
8
+ ``chordsym.estimate_key`` unless ``key=`` is given); ``I V vi IV`` however it is transposed.
9
+ - ``relative_to="first"``: Roman numerals measured from the n-gram's first chord, so no key is
10
+ needed (``vi IV I V`` becomes ``I bVI bIII bVII``).
11
+ - ``relative_to=None``: absolute chord names (``Am F C G``).
12
+
13
+ >>> seqs = [["C", "G", "Am", "F", "C", "G", "Am", "F"], ["D", "A", "Bm", "G"]]
14
+ >>> counts = ngrams(seqs, n=4)
15
+ >>> counts[("I", "V", "vi", "IV")], counts[("V", "vi", "IV", "I")]
16
+ (3, 1)
17
+ >>> ngrams(seqs, n=2, relative_to=None)[("C", "G")]
18
+ 2
19
+ >>> ngrams(seqs, n=2, per_sequence=True)[1][("I", "V")]
20
+ 1
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from collections import Counter
26
+ from collections.abc import Iterable
27
+
28
+ from chordsym import Dialect, Key, estimate_key
29
+
30
+ from chordseq.roman import roman_from_parts
31
+ from chordseq.tokens import (
32
+ DEFAULT_LEVEL,
33
+ SEVENTHS,
34
+ TRIADS,
35
+ check_level,
36
+ encode,
37
+ split_item,
38
+ token_parts,
39
+ )
40
+
41
+ DEFAULT_SIZES = (2, 3, 4)
42
+ _RELATIVE_TO = ("key", "first", None)
43
+ _ROOT_NAMES = ("C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
44
+ _TRIAD_SUFFIX = {
45
+ "major": "",
46
+ "minor": "m",
47
+ "diminished": "dim",
48
+ "augmented": "aug",
49
+ "open": "sus",
50
+ }
51
+ _SEVENTH_SUFFIX = {"": "", "7": "7", "maj7": "maj7", "dim7": "7"}
52
+
53
+
54
+ def _chord_name(parts) -> str:
55
+ root, triad, seventh = parts
56
+ kind, sev = TRIADS[triad], SEVENTHS[seventh]
57
+ if kind == "diminished" and sev:
58
+ return _ROOT_NAMES[root] + ("dim7" if sev == "dim7" else "m7b5")
59
+ return _ROOT_NAMES[root] + _TRIAD_SUFFIX[kind] + _SEVENTH_SUFFIX[sev]
60
+
61
+
62
+ def ngrams(
63
+ sequences: Iterable[Iterable],
64
+ n: int | Iterable[int] = DEFAULT_SIZES,
65
+ *,
66
+ level: str = DEFAULT_LEVEL,
67
+ collapse: bool = True,
68
+ relative_to: str | None = "key",
69
+ key: Key | None = None,
70
+ per_sequence: bool = False,
71
+ dialect: str | Dialect = "default",
72
+ ) -> Counter | list[Counter]:
73
+ """Counts of n-grams (tuples of chord names) pooled over ``sequences``.
74
+
75
+ ``n`` is one size or several (default 2, 3 and 4). With ``per_sequence=True`` the result is
76
+ one :class:`~collections.Counter` per sequence, in order, instead of one pooled counter.
77
+ """
78
+ check_level(level)
79
+ if relative_to not in _RELATIVE_TO:
80
+ raise ValueError(
81
+ f"relative_to must be one of {_RELATIVE_TO}, not {relative_to!r}"
82
+ )
83
+ sizes = (n,) if isinstance(n, int) else tuple(n)
84
+ if not sizes or min(sizes) < 1:
85
+ raise ValueError(f"n-gram sizes must be positive, not {sizes!r}")
86
+ results = [
87
+ _count(seq, sizes, level, collapse, relative_to, key, dialect)
88
+ for seq in sequences
89
+ ]
90
+ if per_sequence:
91
+ return results
92
+ pooled: Counter = Counter()
93
+ for counter in results:
94
+ pooled.update(counter)
95
+ return pooled
96
+
97
+
98
+ def _count(sequence, sizes, level, collapse, relative_to, key, dialect) -> Counter:
99
+ items = list(sequence)
100
+ runs, _ = encode(items, level=level, collapse=collapse, dialect=dialect)
101
+ parts = [token_parts(char) for char, _, _ in runs]
102
+ if relative_to == "key" and key is None:
103
+ key = estimate_key((split_item(i)[0] for i in items), dialect=dialect)
104
+ counter: Counter = Counter()
105
+ for size in sizes:
106
+ for start in range(len(parts) - size + 1):
107
+ window = parts[start : start + size]
108
+ if None in window:
109
+ continue
110
+ counter[_name_window(window, relative_to, key, level)] += 1
111
+ return counter
112
+
113
+
114
+ def _name_window(window, relative_to, key, level) -> tuple[str, ...]:
115
+ if relative_to is None:
116
+ return tuple(_chord_name(p) for p in window)
117
+ tonic = window[0][0] if relative_to == "first" else key.tonic
118
+ return tuple(
119
+ roman_from_parts(((root - tonic) % 12, triad, seventh), level=level)
120
+ for root, triad, seventh in window
121
+ )
chordseq/query.py ADDED
@@ -0,0 +1,96 @@
1
+ """The query notation: regex-shaped, over plain chord symbols or Roman numerals.
2
+
3
+ A query is whitespace-separated items:
4
+
5
+ - a chord symbol (``Am``, ``E7``, ``F#m7b5``) or a Roman numeral (``vi``, ``V7``, ``bVII``);
6
+ - ``.`` any one chord;
7
+ - ``|`` between alternatives in one item, no spaces (``E|E7``, ``V|bVII``);
8
+ - ``?`` after an item makes it optional (``E7?``); ``*`` after an item, or alone, any run of
9
+ chords (``.*`` and ``*`` are the same: zero or more chords, as few as will do).
10
+
11
+ ``E(7)`` is refused: parentheses already mean alterations in chord symbols. At the default
12
+ level (``triads``) ``E`` already matches ``E7``; write ``E|E7`` to be explicit, or search
13
+ at ``level="tetrads"`` to tell them apart. Chord symbols and Roman numerals do not mix in
14
+ one query. Chord symbols in a query use the default spelling.
15
+
16
+ >>> [item.text for item in parse_query("Am E7? F").items]
17
+ ['Am', 'E7?', 'F']
18
+ >>> parse_query("vi IV I V").roman
19
+ True
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from dataclasses import dataclass
26
+
27
+ from chordsym import is_chord_token
28
+
29
+ from chordseq.roman import is_roman, parse_roman
30
+ from chordseq.tokens import Parts, chord_parts
31
+
32
+ _PAREN_SEVENTH_RE = re.compile(r"^[A-G][#b]?\(\d+\)")
33
+ _QUANTIFIERS = ("?", "*")
34
+
35
+
36
+ class QueryError(ValueError):
37
+ """A query that cannot be read; the message says which item and why."""
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Item:
42
+ """One query item: alternatives (None = any chord) and a quantifier ('', '?' or '*')."""
43
+
44
+ text: str
45
+ alternatives: tuple[Parts, ...] | None
46
+ quantifier: str = ""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Query:
51
+ """A parsed query. ``roman`` is True when its atoms are degrees, not roots."""
52
+
53
+ items: tuple[Item, ...]
54
+ roman: bool
55
+
56
+
57
+ def _atom(text: str) -> tuple[Parts, bool]:
58
+ if _PAREN_SEVENTH_RE.match(text):
59
+ raise QueryError(
60
+ f"{text!r}: parentheses mean alterations in chord symbols; "
61
+ f"write {text[0]}|{text[0]}7 for 'with or without the seventh' "
62
+ "(at the default level, plain "
63
+ f"{text[0]} already matches {text[0]}7)"
64
+ )
65
+ if is_roman(text):
66
+ return parse_roman(text), True
67
+ if is_chord_token(text):
68
+ return chord_parts(text), False
69
+ raise QueryError(f"{text!r} is neither a chord symbol nor a Roman numeral")
70
+
71
+
72
+ def parse_query(text: str) -> Query:
73
+ """Read a query (see the module docstring for the notation); ``QueryError`` if it is not one."""
74
+ items: list[Item] = []
75
+ kinds: set[bool] = set()
76
+ for word in text.split():
77
+ quantifier = ""
78
+ body = word
79
+ if word == "*":
80
+ body, quantifier = ".", "*"
81
+ elif word[-1] in _QUANTIFIERS and len(word) > 1:
82
+ body, quantifier = word[:-1], word[-1]
83
+ if body == ".":
84
+ items.append(Item(word, None, quantifier))
85
+ continue
86
+ alternatives = []
87
+ for part in body.split("|"):
88
+ parts, is_degree = _atom(part)
89
+ kinds.add(is_degree)
90
+ alternatives.append(parts)
91
+ items.append(Item(word, tuple(alternatives), quantifier))
92
+ if not any(it.alternatives is not None for it in items):
93
+ raise QueryError(f"{text!r} names no chord")
94
+ if len(kinds) > 1:
95
+ raise QueryError(f"{text!r} mixes chord symbols and Roman numerals")
96
+ return Query(tuple(items), roman=kinds == {True})
chordseq/roman.py ADDED
@@ -0,0 +1,140 @@
1
+ """Roman numerals: chords relative to a key, both ways.
2
+
3
+ One chromatic scheme, measured from the key's tonic whether the key is major or minor
4
+ (so ``bIII``, ``bVI``, ``bVII`` in a minor key, and ``to_roman`` and ``parse_roman`` round-trip):
5
+ ``I bII II bIII III IV #IV V bVI VI bVII VII``. Upper case is major, lower case minor,
6
+ ``°`` diminished, ``ø`` half-diminished (``ø7``), ``+`` augmented, ``sus`` suspended or
7
+ power; the seventh follows as ``7``, ``maj7`` or (after ``°``) ``°7``.
8
+
9
+ >>> from chordsym import Key
10
+ >>> to_roman("Am", Key(0)), to_roman("G7", Key(0), level="tetrads"), to_roman("Bb", Key(0))
11
+ ('vi', 'V7', 'bVII')
12
+ >>> to_roman_sequence(["Am", "F", "C", "G"], key=Key(0))
13
+ ['vi', 'IV', 'I', 'V']
14
+ >>> parse_roman("V7"), parse_roman("bVII"), parse_roman("Am")
15
+ ((7, 0, 1), (10, 0, 0), None)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from collections.abc import Iterable
22
+
23
+ from chordsym import Dialect, Key, estimate_key
24
+
25
+ from chordseq.tokens import (
26
+ DEFAULT_LEVEL,
27
+ SEVENTHS,
28
+ TRIADS,
29
+ Parts,
30
+ check_level,
31
+ chord_parts,
32
+ )
33
+
34
+ NUMERALS = (
35
+ "I",
36
+ "bII",
37
+ "II",
38
+ "bIII",
39
+ "III",
40
+ "IV",
41
+ "#IV",
42
+ "V",
43
+ "bVI",
44
+ "VI",
45
+ "bVII",
46
+ "VII",
47
+ )
48
+ _DEGREE = {"I": 0, "II": 2, "III": 4, "IV": 5, "V": 7, "VI": 9, "VII": 11}
49
+ _ROMAN_RE = re.compile(
50
+ r"(?P<acc>[b#]?)(?P<num>VII|VI|IV|V|III|II|I|vii|vi|iv|v|iii|ii|i)"
51
+ r"(?P<q>°|o|ø|\+|sus)?(?P<sev>maj7|M7|7)?"
52
+ )
53
+
54
+
55
+ def is_roman(token: str) -> bool:
56
+ """Whether ``token`` is a Roman-numeral chord as :func:`parse_roman` reads them."""
57
+ return _ROMAN_RE.fullmatch(token) is not None
58
+
59
+
60
+ def parse_roman(token: str) -> Parts | None:
61
+ """``(degree, triad index, seventh index)`` of a Roman numeral; None if it is not one.
62
+
63
+ The degree is semitones above the tonic. Case gives major or minor; ``°7`` is a
64
+ diminished seventh chord, ``ø`` and ``ø7`` a half-diminished one.
65
+ """
66
+ m = _ROMAN_RE.fullmatch(token)
67
+ if m is None:
68
+ return None
69
+ num = m["num"]
70
+ degree = (_DEGREE[num.upper()] + {"b": -1, "#": 1, "": 0}[m["acc"]]) % 12
71
+ q, sev = m["q"], m["sev"]
72
+ if q == "sus":
73
+ triad = TRIADS.index("open")
74
+ elif q == "+":
75
+ triad = TRIADS.index("augmented")
76
+ elif q in ("°", "o", "ø"):
77
+ triad = TRIADS.index("diminished")
78
+ else:
79
+ triad = TRIADS.index("minor" if num.islower() else "major")
80
+ if sev in ("maj7", "M7"):
81
+ seventh = SEVENTHS.index("maj7")
82
+ elif sev == "7" or q == "ø":
83
+ seventh = SEVENTHS.index("dim7" if q in ("°", "o") else "7")
84
+ else:
85
+ seventh = 0
86
+ return degree, triad, seventh
87
+
88
+
89
+ def roman_from_parts(parts: Parts, *, level: str = DEFAULT_LEVEL) -> str:
90
+ """The Roman numeral for ``(degree, triad, seventh)`` (degree = semitones above the tonic)."""
91
+ check_level(level)
92
+ degree, triad, seventh = parts
93
+ if level == "root":
94
+ triad = seventh = 0
95
+ elif level == "triads":
96
+ seventh = 0
97
+ name, kind, sev = NUMERALS[degree % 12], TRIADS[triad], SEVENTHS[seventh]
98
+ if kind == "minor":
99
+ name = name.lower()
100
+ if kind == "diminished":
101
+ name = name.lower()
102
+ if sev == "7":
103
+ return name + "ø7"
104
+ return name + ("°7" if sev == "dim7" else "°")
105
+ if kind == "augmented":
106
+ name += "+"
107
+ elif kind == "open":
108
+ name += "sus"
109
+ return name + sev
110
+
111
+
112
+ def to_roman(
113
+ symbol: str,
114
+ key: Key,
115
+ *,
116
+ level: str = DEFAULT_LEVEL,
117
+ dialect: str | Dialect = "default",
118
+ ) -> str | None:
119
+ """The Roman numeral of ``symbol`` in ``key``; None if ``symbol`` is not a chord."""
120
+ parts = chord_parts(symbol, dialect=dialect)
121
+ if parts is None:
122
+ return None
123
+ root, triad, seventh = parts
124
+ return roman_from_parts(((root - key.tonic) % 12, triad, seventh), level=level)
125
+
126
+
127
+ def to_roman_sequence(
128
+ symbols: Iterable[str],
129
+ *,
130
+ key: Key | None = None,
131
+ level: str = DEFAULT_LEVEL,
132
+ dialect: str | Dialect = "default",
133
+ ) -> list[str | None]:
134
+ """Roman numerals of a chord sequence in ``key`` (estimated from the sequence when None)."""
135
+ symbols = list(symbols)
136
+ if key is None:
137
+ key = estimate_key(symbols, dialect=dialect)
138
+ if key is None:
139
+ return [None] * len(symbols)
140
+ return [to_roman(s, key, level=level, dialect=dialect) for s in symbols]
chordseq/search.py ADDED
@@ -0,0 +1,142 @@
1
+ """Find a chord pattern in chord sequences, in any key.
2
+
3
+ The engine knows nothing about audio, pages or songs: a *sequence* is an iterable of chord
4
+ symbols, each optionally paired with an opaque payload (``("Am", payload)``). A match is an
5
+ index span over the sequence as given; callers map spans back to times, bars or pages
6
+ through the payloads.
7
+
8
+ Defaults: ``level="triads"`` (``E`` matches ``E7``), transposition-invariant, inversions
9
+ ignored, repeated chords collapsed (a chord held for four bars and one written once are the
10
+ same). Matches are overlapping, at most one per start position and transposition, and
11
+ ``*`` takes as few chords as will do.
12
+
13
+ >>> hits = find("Am F", ["C", "G", "Am", "Am", "F", "C"])
14
+ >>> [(m.start, m.stop, m.items) for m in hits]
15
+ [(2, 5, ('Am', 'Am', 'F'))]
16
+ >>> [m.transposition for m in find("C F G", ["A", "D", "E"])] # same shape, up a minor sixth
17
+ [9]
18
+ >>> [m.start for m in find("vi IV I V", ["Dm", "Bb", "F", "C", "Dm", "Bb", "F", "C"])]
19
+ [0, 4]
20
+ >>> find("Am E F", [("Am", "t=0.0"), ("E7", "t=2.1"), ("F", "t=4.0")])[0].payloads
21
+ ('t=0.0', 't=2.1', 't=4.0')
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ from collections.abc import Iterable, Iterator
28
+ from dataclasses import dataclass
29
+ from functools import lru_cache
30
+
31
+ from chordsym import Dialect, Key
32
+
33
+ from chordseq.query import Query, QueryError, parse_query
34
+ from chordseq.tokens import (
35
+ ANY_CHORD,
36
+ DEFAULT_LEVEL,
37
+ check_level,
38
+ encode,
39
+ parts_token,
40
+ split_item,
41
+ )
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Match:
46
+ """A match: the span ``[start, stop)`` of sequence ``sequence_index`` (original indices).
47
+
48
+ ``transposition`` is the number of semitones the query was moved up to match (0 when it
49
+ matched as written).
50
+ """
51
+
52
+ sequence_index: int
53
+ start: int
54
+ stop: int
55
+ items: tuple
56
+ transposition: int = 0
57
+
58
+ @property
59
+ def symbols(self) -> tuple[str, ...]:
60
+ return tuple(split_item(item)[0] for item in self.items)
61
+
62
+ @property
63
+ def payloads(self) -> tuple:
64
+ return tuple(split_item(item)[1] for item in self.items)
65
+
66
+
67
+ def _item_regex(item, *, level: str, shift: int) -> str:
68
+ if item.alternatives is None:
69
+ body = ANY_CHORD
70
+ else:
71
+ chars = dict.fromkeys(
72
+ re.escape(parts_token(((root + shift) % 12, triad, seventh), level=level))
73
+ for root, triad, seventh in item.alternatives
74
+ )
75
+ body = "(?:" + "|".join(chars) + ")"
76
+ if item.quantifier == "*":
77
+ return f"(?:{body})*?"
78
+ return f"(?:{body})?" if item.quantifier == "?" else body
79
+
80
+
81
+ @lru_cache(maxsize=256)
82
+ def _regex(query: Query, level: str, shift: int) -> re.Pattern:
83
+ body = "".join(_item_regex(item, level=level, shift=shift) for item in query.items)
84
+ return re.compile(f"(?=({body}))") # lookahead: overlapping matches
85
+
86
+
87
+ def _shifts(query: Query, *, transposition_invariant: bool, key: Key | None):
88
+ if transposition_invariant:
89
+ return range(12)
90
+ if query.roman:
91
+ if key is None:
92
+ raise ValueError(
93
+ "a Roman-numeral query needs key= when transposition_invariant=False"
94
+ )
95
+ return (key.tonic,)
96
+ return (0,)
97
+
98
+
99
+ def search(
100
+ query: str | Query,
101
+ sequences: Iterable[Iterable],
102
+ *,
103
+ level: str = DEFAULT_LEVEL,
104
+ collapse: bool = True,
105
+ transposition_invariant: bool = True,
106
+ key: Key | None = None,
107
+ dialect: str | Dialect = "default",
108
+ ) -> Iterator[Match]:
109
+ """Matches of ``query`` in each sequence, lazily, in sequence then start order.
110
+
111
+ ``level`` is ``"root"``, ``"triads"`` or ``"tetrads"`` (see :mod:`chordseq.tokens`).
112
+ ``transposition_invariant=False`` matches the query's own key: chord symbols as written,
113
+ Roman numerals against ``key``. ``dialect`` names how the *sequences* spell chords
114
+ (``"chordonomicon"``, ``"harte"``, see :data:`chordsym.DIALECTS`); the query is in the
115
+ default spelling.
116
+ """
117
+ check_level(level)
118
+ if isinstance(query, str):
119
+ query = parse_query(query)
120
+ shifts = _shifts(query, transposition_invariant=transposition_invariant, key=key)
121
+ for index, sequence in enumerate(sequences):
122
+ runs, items = encode(sequence, level=level, collapse=collapse, dialect=dialect)
123
+ text = "".join(char for char, _, _ in runs)
124
+ found: dict[tuple[int, int], int] = {}
125
+ for shift in shifts:
126
+ for m in _regex(query, level, shift).finditer(text):
127
+ first, stop = m.start(), m.end(1)
128
+ if stop > first:
129
+ found.setdefault((first, stop), shift)
130
+ for (first, stop), shift in sorted(found.items()):
131
+ start_item, stop_item = runs[first][1], runs[stop - 1][2] + 1
132
+ yield Match(
133
+ index, start_item, stop_item, tuple(items[start_item:stop_item]), shift
134
+ )
135
+
136
+
137
+ def find(query: str | Query, sequence: Iterable, **kwargs) -> list[Match]:
138
+ """:func:`search` in one sequence; a list of its matches."""
139
+ return list(search(query, [sequence], **kwargs))
140
+
141
+
142
+ __all__ = ["Match", "QueryError", "find", "search"]
chordseq/tokens.py ADDED
@@ -0,0 +1,166 @@
1
+ """Chord symbols to comparable tokens, at one of three levels of detail.
2
+
3
+ A chord is reduced to ``(root, triad, seventh)``: the root pitch class, one of five triad
4
+ classes and one of four seventh classes. The *level* decides how much of that survives
5
+ into the token the search compares (names follow mir_eval's chord-evaluation levels):
6
+
7
+ - ``"root"``: the root only (``E``, ``Em`` and ``E7`` are the same token).
8
+ - ``"triads"`` (default): root and triad (``E`` and ``E7`` match, ``E`` and ``Em`` do not).
9
+ - ``"tetrads"``: root, triad and seventh (``E`` and ``E7`` differ).
10
+
11
+ Inversions are always ignored. Spans of chords that are not chords at all (``N``, section
12
+ markers such as ``<verse_1>``) become the token :data:`NO_CHORD`, which matches nothing.
13
+
14
+ >>> chord_parts("Am7"), chord_parts("E7"), chord_parts("Bdim7"), chord_parts("Bridge")
15
+ ((9, 1, 1), (4, 0, 1), (11, 2, 3), None)
16
+ >>> token("E7", level="triads") == token("E", level="triads")
17
+ True
18
+ >>> token("E7", level="tetrads") == token("E", level="tetrads")
19
+ False
20
+ >>> token("Bridge") == NO_CHORD
21
+ True
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from collections.abc import Iterable
27
+
28
+ from chordsym import Dialect, chord_tones, parse_chord
29
+
30
+ LEVELS = ("root", "triads", "tetrads")
31
+ DEFAULT_LEVEL = "triads"
32
+
33
+ TRIADS = ("major", "minor", "diminished", "augmented", "open")
34
+ SEVENTHS = ("", "7", "maj7", "dim7") # "7" is the minor (flat) seventh
35
+ N_TRIADS, N_SEVENTHS = len(TRIADS), len(SEVENTHS)
36
+ CLASSES_PER_ROOT = N_TRIADS * N_SEVENTHS
37
+
38
+ CHAR_BASE = 0x100 # token characters start here, clear of ASCII and of NO_CHORD
39
+ NO_CHORD = "\x00" # matches nothing, not even the wildcard
40
+ ANY_CHORD = f"[{chr(CHAR_BASE)}-{chr(CHAR_BASE + 12 * CLASSES_PER_ROOT - 1)}]"
41
+
42
+ _MAJOR_SEVENTH, _MINOR_SEVENTH, _SIXTH_OR_DIM_SEVENTH = 11, 10, 9
43
+
44
+ Parts = tuple[int, int, int] # (root, triad index, seventh index)
45
+
46
+
47
+ def check_level(level: str) -> str:
48
+ """``level`` if it is one of :data:`LEVELS`; a ``ValueError`` naming them otherwise."""
49
+ if level not in LEVELS:
50
+ raise ValueError(f"level must be one of {LEVELS}, not {level!r}")
51
+ return level
52
+
53
+
54
+ def chord_parts(symbol: str, *, dialect: str | Dialect = "default") -> Parts | None:
55
+ """``(root, triad index, seventh index)`` of a chord symbol; None if it is not a chord.
56
+
57
+ The indices point into :data:`TRIADS` and :data:`SEVENTHS`. Sixths and added ninths
58
+ are ignored (``C6`` is a C major triad); a bass note is ignored.
59
+ """
60
+ parsed = parse_chord(symbol, dialect=dialect)
61
+ if parsed is None:
62
+ return None
63
+ root, quality = parsed
64
+ tones = chord_tones(symbol, dialect=dialect, bass_first=False) or ()
65
+ intervals = {(tone - root) % 12 for tone in tones}
66
+ if quality == "open":
67
+ triad = TRIADS.index("open")
68
+ elif quality == "diminished":
69
+ triad = TRIADS.index("diminished")
70
+ elif 8 in intervals and 7 not in intervals:
71
+ triad = TRIADS.index("augmented")
72
+ else:
73
+ triad = TRIADS.index(quality)
74
+ if _MAJOR_SEVENTH in intervals:
75
+ seventh = SEVENTHS.index("maj7")
76
+ elif _MINOR_SEVENTH in intervals:
77
+ seventh = SEVENTHS.index("7")
78
+ elif quality == "diminished" and _SIXTH_OR_DIM_SEVENTH in intervals:
79
+ seventh = SEVENTHS.index("dim7")
80
+ else:
81
+ seventh = 0
82
+ return root, triad, seventh
83
+
84
+
85
+ def parts_token(parts: Parts, *, level: str = DEFAULT_LEVEL) -> str:
86
+ """The one-character token for ``(root, triad, seventh)`` at ``level``."""
87
+ root, triad, seventh = parts
88
+ if level == "root":
89
+ triad = seventh = 0
90
+ elif level == "triads":
91
+ seventh = 0
92
+ return chr(CHAR_BASE + root * CLASSES_PER_ROOT + triad * N_SEVENTHS + seventh)
93
+
94
+
95
+ def token_parts(char: str) -> Parts | None:
96
+ """Inverse of :func:`parts_token` (``None`` for :data:`NO_CHORD`)."""
97
+ if char == NO_CHORD:
98
+ return None
99
+ root, rest = divmod(ord(char) - CHAR_BASE, CLASSES_PER_ROOT)
100
+ triad, seventh = divmod(rest, N_SEVENTHS)
101
+ return root, triad, seventh
102
+
103
+
104
+ def transpose_token(char: str, semitones: int) -> str:
105
+ """``char`` moved up ``semitones`` (``NO_CHORD`` stays)."""
106
+ parts = token_parts(char)
107
+ if parts is None:
108
+ return char
109
+ root, triad, seventh = parts
110
+ return parts_token(((root + semitones) % 12, triad, seventh), level="tetrads")
111
+
112
+
113
+ def token(
114
+ symbol: str, *, level: str = DEFAULT_LEVEL, dialect: str | Dialect = "default"
115
+ ) -> str:
116
+ """The one-character token of a chord symbol at ``level``; :data:`NO_CHORD` if not a chord."""
117
+ parts = chord_parts(symbol, dialect=dialect)
118
+ return NO_CHORD if parts is None else parts_token(parts, level=level)
119
+
120
+
121
+ def collapse_runs(chars: Iterable[str]) -> list[tuple[str, int, int]]:
122
+ """Runs of equal tokens as ``(token, first index, last index)``.
123
+
124
+ >>> collapse_runs("aabcc")
125
+ [('a', 0, 1), ('b', 2, 2), ('c', 3, 4)]
126
+ """
127
+ runs: list[tuple[str, int, int]] = []
128
+ for i, char in enumerate(chars):
129
+ if runs and runs[-1][0] == char:
130
+ runs[-1] = (char, runs[-1][1], i)
131
+ else:
132
+ runs.append((char, i, i))
133
+ return runs
134
+
135
+
136
+ def split_item(item) -> tuple[str, object]:
137
+ """``(symbol, payload)`` of a sequence item: a bare symbol, or a ``(symbol, payload)`` pair.
138
+
139
+ >>> split_item("Am"), split_item(("Am", {"t": 1.5}))
140
+ (('Am', None), ('Am', {'t': 1.5}))
141
+ """
142
+ if isinstance(item, str):
143
+ return item, None
144
+ symbol, payload = item
145
+ return symbol, payload
146
+
147
+
148
+ def encode(
149
+ sequence: Iterable,
150
+ *,
151
+ level: str = DEFAULT_LEVEL,
152
+ collapse: bool = True,
153
+ dialect: str | Dialect = "default",
154
+ ) -> tuple[list[tuple[str, int, int]], list]:
155
+ """A sequence as token runs ``(token, first, last)`` over its original indices, plus its items.
156
+
157
+ With ``collapse=True`` (default) consecutive equal tokens share one run, so a chord
158
+ held for four bars and one written once are the same; with ``collapse=False`` every
159
+ item is its own run.
160
+ """
161
+ check_level(level)
162
+ items = list(sequence)
163
+ chars = [token(split_item(item)[0], level=level, dialect=dialect) for item in items]
164
+ if collapse:
165
+ return collapse_runs(chars), items
166
+ return [(c, i, i) for i, c in enumerate(chars)], items
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.5
2
+ Name: chordseq
3
+ Version: 0.0.2
4
+ Summary: Chord-progression search in any key, n-gram counts and Roman numerals over chord-symbol sequences
5
+ Project-URL: Homepage, https://github.com/thorwhalen/chordseq
6
+ Project-URL: Repository, https://github.com/thorwhalen/chordseq
7
+ Project-URL: Documentation, https://thorwhalen.github.io/chordseq
8
+ Author: Thor Whalen
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: chords,harmony,music,n-grams,search
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Sound/Audio
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: chordsym>=0.0.8
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
19
+ Requires-Dist: pytest>=7.0; extra == 'dev'
20
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # chordseq
24
+
25
+ Search chord progressions in any key, count n-grams, and name chords by key. Pure Python, one dependency ([chordsym](https://pypi.org/project/chordsym/)).
26
+
27
+ ```python
28
+ >>> from chordseq import find, ngrams
29
+ >>> sequence = ["Dm", "Bb", "F", "C", "Dm", "Bb", "F", "C"]
30
+ >>> [(m.start, m.stop) for m in find("vi IV I V", sequence)] # Roman numerals: any key
31
+ [(0, 4), (4, 8)]
32
+ >>> [m.transposition for m in find("Am F C G", sequence)] # chord symbols: any key too
33
+ [5, 5]
34
+ ```
35
+
36
+ `pip install chordseq`
37
+
38
+ ## One-command test on real data
39
+
40
+ ```bash
41
+ pytest tests/test_smoke.py
42
+ ```
43
+
44
+ It reads the first Chordonomicon progressions over the public datasets-server API (standard library only; skipped offline), searches them and counts their 4-grams. The same by hand:
45
+
46
+ ```python
47
+ from chordseq import find, ngrams
48
+
49
+ progressions = [row.split() for row in chordonomicon_rows] # "<verse_1> C G Amin F ..."
50
+ hits = [m for p in progressions for m in find("Amin F C G", p, dialect="chordonomicon")]
51
+ ngrams(progressions, n=4, dialect="chordonomicon").most_common(5)
52
+ ```
53
+
54
+ ## The query
55
+
56
+ Whitespace-separated items, like a regular expression over chords:
57
+
58
+ | Item | Means |
59
+ |---|---|
60
+ | `Am`, `E7`, `F#m7b5` | a chord symbol |
61
+ | `vi`, `V7`, `bVII`, `ii`, `viiø7` | a Roman numeral (upper major, lower minor, `°` `ø` `+` `sus`) |
62
+ | `.` | any one chord |
63
+ | `E\|E7` | either (no spaces) |
64
+ | `E7?` | optional |
65
+ | `*` (alone, or after an item) | any run of chords, as few as will do |
66
+
67
+ `E(7)` is refused with a hint: parentheses already mean alterations in chord symbols. Chord symbols and Roman numerals do not mix in a query.
68
+
69
+ ## Defaults
70
+
71
+ `level="triads"` (`E` matches `E7`; `"root"` and `"tetrads"` are the other mir_eval levels), transposition-invariant, inversions ignored, repeated chords collapsed. `transposition_invariant=False` matches the query's own key: chord symbols as written, Roman numerals against `key=`.
72
+
73
+ ## Sequences, payloads, matches
74
+
75
+ A sequence is an iterable of chord symbols, each optionally `(symbol, payload)` with any payload you like (a time, a bar, a page). `find(query, sequence)` returns `Match` objects: `start`/`stop` are indices into the sequence as you gave it (so collapsed repeats are covered), `items`, `symbols`, `payloads`, `transposition`. `search(query, sequences)` does many sequences lazily, with `sequence_index`. The engine knows nothing about audio, pages or songs; you map spans to times or pages through the payloads. Anything that is not a chord (`N`, `<verse_1>`) matches nothing, so no match runs across it: cut a song into sections and the matches stay inside them.
76
+
77
+ ## N-grams and Roman numerals
78
+
79
+ ```python
80
+ ngrams(sequences, n=(2, 3, 4)) # pooled Counter of tuples, in the key of each sequence
81
+ ngrams(
82
+ sequences, relative_to="first"
83
+ ) # keyless: numerals from each n-gram's first chord
84
+ ngrams(sequences, relative_to=None, per_sequence=True)
85
+ to_roman_sequence(["G", "D", "Em", "C"]) # ['I', 'V', 'vi', 'IV']
86
+ ```
87
+
88
+ Roman numerals use one chromatic scheme from the tonic, major or minor key alike (`bIII`, `bVI`, `bVII` in a minor key), so `to_roman` and the query read each other.
89
+
90
+ ## Seams
91
+
92
+ | Seam | Keyword | Default | Replacement that exists |
93
+ |---|---|---|---|
94
+ | Chord spelling of the input | `dialect=` | `"default"` (chart spellings) | `chordsym.DIALECTS` (`chordonomicon`, `harte`), `chordsym.register_dialect` |
95
+ | Detail of comparison | `level=` | `"triads"` | `"root"`, `"tetrads"` (mir_eval names) |
96
+ | Key for Roman numerals | `key=` | estimated by `chordsym.estimate_key` | any `chordsym.Key` |
97
+
98
+ **NOT seams (v1):** the scan engine (one regex pass per transposition over a string of one-character tokens; the packed-byte numpy scan of the phase-1 prototypes, in `misc/docs/research/prototypes/`, is the replacement when a corpus-sized consumer needs it, and then it lands behind the same `search` signature); an index; ranking and popularity; a browser or Web Worker build; a CLI; audio, pages and songs (callers map spans through payloads); chord symbols beyond what `chordsym` parses.
99
+
100
+ ## Design and research
101
+
102
+ The phase-1 design, five research reports and prototypes are in `misc/docs/research/`.
@@ -0,0 +1,10 @@
1
+ chordseq/__init__.py,sha256=SSg1sGldMthDnwOuMPVuDjZeLfhRsTk09pYmad76eoU,853
2
+ chordseq/ngrams.py,sha256=mcW9XuXZ-VFqrIpKhndkIRn1xmvu8My8AVxK8ua05z4,4233
3
+ chordseq/query.py,sha256=NL7VKwknQy7WOmvefLowRZDTao_paTocVXfuJU_x2zA,3362
4
+ chordseq/roman.py,sha256=Il4ON4qM5zfO3UZc6eA_qPcM-zlqg8FexK0yEodOuFY,4324
5
+ chordseq/search.py,sha256=qYu4BRbiOS-oxxqmBvEwi-GHqHiDBBAJUn1GtzFIPgg,5060
6
+ chordseq/tokens.py,sha256=6JEcXK6lSqxF4zrDsBZFMnc5tLY0aUu9tw7qyW-bDwg,6174
7
+ chordseq-0.0.2.dist-info/METADATA,sha256=DgYJu1n01DkbjpUsfe_U53gRHtiTn2JOLpqHangjG-E,5006
8
+ chordseq-0.0.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ chordseq-0.0.2.dist-info/licenses/LICENSE,sha256=ekE13yCE9fWWEJfP1NPnUJabZ_Wwrc6coKJV2ZZx27w,1068
10
+ chordseq-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Whalen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.