chordsym 0.0.2__tar.gz → 0.0.4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: chordsym
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Chord symbols without dependencies: parse, pitch classes, key estimation, transposition
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/chordsym
6
6
  Project-URL: Repository, https://github.com/thorwhalen/chordsym
@@ -33,7 +33,18 @@ Chord symbols without dependencies (standard library only): is this token a chor
33
33
  {'G': 'Bb', 'D': 'F', 'Em': 'Gm', 'C': 'Eb'}
34
34
  ```
35
35
 
36
- It reads the spellings found in scraped chord charts (`C6/9`, `Bm5-/7`, Brazilian `7M`, `E7(#9)`, `D/F#`), not only textbook ones. Pitch classes are ints 0-11 (C = 0).
36
+ It reads the spellings found in scraped chord charts (`C6/9`, `Bm5-/7`, Brazilian `7M`, `E7(#9)`, `D/F#`, `Co7`, `CΔ7`, `C∆`, `CmΔ7`), not only textbook ones. Pitch classes are ints 0-11 (C = 0).
37
+
38
+ Other spellings are read through a `dialect=` keyword (on `parse_chord`, `chord_tones`, `is_chord_token`, `chord_function`, `estimate_key`, and `transposition_table` for its key estimate), which rewrites a symbol into the default spelling first. A dialect is a name in `chordsym.DIALECTS` or any pure function `str -> str` (results are cached per function); `chordsym.dialects.register_dialect(name, func)` adds a name. `transpose_chord` takes no dialect, since its output keeps the input's spelling: it moves default spellings only.
39
+
40
+ - `"default"`: the chart spellings above.
41
+ - `"chordonomicon"`: the Chordonomicon corpus, sharps written `s` (`Cs`, `Fsmin`, `A/Cs`) and power chords `no3d` (`Gno3d` is `G5`).
42
+ - `"harte"`: Harte's `root:shorthand` (`C:maj7`, `A:min`, `B:hdim7`), added degrees in parentheses (`C:maj(9)` is `Cadd9`), a degree bass (`C:maj/3` has E in the bass), and the common interval lists `(1,3,5)`, `(1,b3,5)`, `(1,3,5,b7)`, `(1,b3,5,b7)`, `(1,5)`. Any other interval list, an omitted degree (`*3`), `N` (no chord) and `X` are not read as chords.
43
+
44
+ ```python
45
+ >>> parse_chord("Fsmin", dialect="chordonomicon"), chord_tones("B:hdim7", dialect="harte")
46
+ ((6, 'minor'), (11, 2, 5, 9))
47
+ ```
37
48
 
38
49
  ## In the browser: the TypeScript twin
39
50
 
@@ -55,6 +66,19 @@ The two are kept identical by construction, not by care:
55
66
 
56
67
  Where the languages differ, the TypeScript side says so in its types: `transpositionTable(...).chords` is a `Map` (a plain object would reorder integer-like keys), and a `Key` is a plain `{ tonic, minor }` object checked by every function that takes one (`keyEquals` compares two).
57
68
 
69
+ - **CI runs a slice of that net.** `python scripts/twin_differential.py --sample-into-fixtures 500` refreshes 2,500 seeded corpus cases inside `fixtures/cases.json` (tagged `"source": "corpus"`), next to the hand-written ones.
70
+
71
+ Traps the port had to handle, worth knowing before writing any Python/TypeScript twin:
72
+
73
+ - `%` keeps the sign of the dividend in JS (`-1 % 12 === -1`), of the divisor in Python: use a `mod` helper.
74
+ - A JS object reorders integer-like keys (`"2"`, `"10"` come first) and treats `"__proto__"` specially: an ordered mapping is a `Map`.
75
+ - The same holds for a shared table: a Python dict generated as a JS object loses its order if a key is integer-like, so a table whose order matters is a list of pairs (`HARTE_ADDED`), and a test fails if TypeScript iterates a table with integer-like keys. Look keys up with an own-property check (`Object.hasOwn`), or `"constructor"` is found.
76
+ - `re.match` anchors at the start only; in JS that is a sticky (`y`) regex whose `lastIndex` must be reset. `re.fullmatch` is `^(?:…)$`.
77
+ - Python's `\d`, `\s` and `\w` are Unicode-aware and JS's are not, or differ at the edges; `str.strip()` and `String.trim()` remove different characters.
78
+ - `^\s+|\s+$` is quadratic in JS on long runs of spaces; trim with an index loop.
79
+ - Python 3.12's `sum()` compensates float rounding and JS's left-to-right addition does not, so ties can break differently: sum in an explicit loop.
80
+ - Test runners that compare with order-blind equality (`dict ==`, `toStrictEqual`) cannot catch an ordering bug: compare JSON text.
81
+
58
82
  Versions: an npm release carries the version of the Python release it was cut from (lockstep at release points, so `chordsym@X.Y.Z` on npm and PyPI are the same behaviour).
59
83
 
60
- Seeded from songleaf (thorwhalen/songleaf#31). Planned: dialects (Harte, Chordonomicon, Nashville/Roman) as strategies; pychord and music21 as test oracles only.
84
+ Seeded from songleaf (thorwhalen/songleaf#31). Planned: a Nashville/Roman dialect; pychord and music21 as test oracles only.
@@ -0,0 +1,63 @@
1
+ # chordsym
2
+
3
+ Chord symbols without dependencies (standard library only): is this token a chord, which root and quality, which pitch classes, which key does a song's chord list suggest, and how do the chords read moved by N semitones.
4
+
5
+ ```python
6
+ >>> from chordsym import parse_chord, chord_tones, transpose_chord, transposition_table, estimate_key
7
+ >>> parse_chord("F#m7"), chord_tones("Cmaj7")
8
+ ((6, 'minor'), (0, 4, 7, 11))
9
+ >>> transpose_chord("C/E", 3, flats=True)
10
+ 'Eb/G'
11
+ >>> transposition_table(["G", "D", "Em", "C"], 3)["chords"]
12
+ {'G': 'Bb', 'D': 'F', 'Em': 'Gm', 'C': 'Eb'}
13
+ ```
14
+
15
+ It reads the spellings found in scraped chord charts (`C6/9`, `Bm5-/7`, Brazilian `7M`, `E7(#9)`, `D/F#`, `Co7`, `CΔ7`, `C∆`, `CmΔ7`), not only textbook ones. Pitch classes are ints 0-11 (C = 0).
16
+
17
+ Other spellings are read through a `dialect=` keyword (on `parse_chord`, `chord_tones`, `is_chord_token`, `chord_function`, `estimate_key`, and `transposition_table` for its key estimate), which rewrites a symbol into the default spelling first. A dialect is a name in `chordsym.DIALECTS` or any pure function `str -> str` (results are cached per function); `chordsym.dialects.register_dialect(name, func)` adds a name. `transpose_chord` takes no dialect, since its output keeps the input's spelling: it moves default spellings only.
18
+
19
+ - `"default"`: the chart spellings above.
20
+ - `"chordonomicon"`: the Chordonomicon corpus, sharps written `s` (`Cs`, `Fsmin`, `A/Cs`) and power chords `no3d` (`Gno3d` is `G5`).
21
+ - `"harte"`: Harte's `root:shorthand` (`C:maj7`, `A:min`, `B:hdim7`), added degrees in parentheses (`C:maj(9)` is `Cadd9`), a degree bass (`C:maj/3` has E in the bass), and the common interval lists `(1,3,5)`, `(1,b3,5)`, `(1,3,5,b7)`, `(1,b3,5,b7)`, `(1,5)`. Any other interval list, an omitted degree (`*3`), `N` (no chord) and `X` are not read as chords.
22
+
23
+ ```python
24
+ >>> parse_chord("Fsmin", dialect="chordonomicon"), chord_tones("B:hdim7", dialect="harte")
25
+ ((6, 'minor'), (11, 2, 5, 9))
26
+ ```
27
+
28
+ ## In the browser: the TypeScript twin
29
+
30
+ The same functions ship to npm as `chordsym` (in `ts/`), with camelCase names and keyword arguments as an options object:
31
+
32
+ ```ts
33
+ import { parseChord, transposeChord, estimateKey } from "chordsym";
34
+
35
+ parseChord("Am7"); // [9, "minor"]
36
+ transposeChord("C/E", 3, { flats: true }); // "Eb/G"
37
+ estimateKey(["Am", "Dm", "E7"]); // { tonic: 9, minor: true }
38
+ ```
39
+
40
+ The two are kept identical by construction, not by care:
41
+
42
+ - **One grammar.** Every regular expression and table lives in `chordsym/_grammar.py`, written in the subset of regex syntax that means the same in Python and JavaScript (no `\d`, `\s`, `\w`, `\b`). `python -m chordsym._codegen` writes it to `ts/src/grammar.generated.ts`, and a test fails if that file is stale.
43
+ - **One set of golden cases.** `fixtures/cases.json` holds about 1,500 calls with their expected results, errors included (`ValueError` in Python is `RangeError` in TypeScript). pytest and vitest both run every one and compare them as JSON text, so order matters. To add a case, append it and run `python -m chordsym._fixtures`, which records the Python results; review the diff, since a changed expectation is a behaviour change on both sides.
44
+ - **A wide net before releases.** `python scripts/twin_differential.py` (after `cd ts && npm run build`) runs about 75,000 generated chord spellings and 3,000 songs through both and reports any difference.
45
+
46
+ Where the languages differ, the TypeScript side says so in its types: `transpositionTable(...).chords` is a `Map` (a plain object would reorder integer-like keys), and a `Key` is a plain `{ tonic, minor }` object checked by every function that takes one (`keyEquals` compares two).
47
+
48
+ - **CI runs a slice of that net.** `python scripts/twin_differential.py --sample-into-fixtures 500` refreshes 2,500 seeded corpus cases inside `fixtures/cases.json` (tagged `"source": "corpus"`), next to the hand-written ones.
49
+
50
+ Traps the port had to handle, worth knowing before writing any Python/TypeScript twin:
51
+
52
+ - `%` keeps the sign of the dividend in JS (`-1 % 12 === -1`), of the divisor in Python: use a `mod` helper.
53
+ - A JS object reorders integer-like keys (`"2"`, `"10"` come first) and treats `"__proto__"` specially: an ordered mapping is a `Map`.
54
+ - The same holds for a shared table: a Python dict generated as a JS object loses its order if a key is integer-like, so a table whose order matters is a list of pairs (`HARTE_ADDED`), and a test fails if TypeScript iterates a table with integer-like keys. Look keys up with an own-property check (`Object.hasOwn`), or `"constructor"` is found.
55
+ - `re.match` anchors at the start only; in JS that is a sticky (`y`) regex whose `lastIndex` must be reset. `re.fullmatch` is `^(?:…)$`.
56
+ - Python's `\d`, `\s` and `\w` are Unicode-aware and JS's are not, or differ at the edges; `str.strip()` and `String.trim()` remove different characters.
57
+ - `^\s+|\s+$` is quadratic in JS on long runs of spaces; trim with an index loop.
58
+ - Python 3.12's `sum()` compensates float rounding and JS's left-to-right addition does not, so ties can break differently: sum in an explicit loop.
59
+ - Test runners that compare with order-blind equality (`dict ==`, `toStrictEqual`) cannot catch an ordering bug: compare JSON text.
60
+
61
+ Versions: an npm release carries the version of the Python release it was cut from (lockstep at release points, so `chordsym@X.Y.Z` on npm and PyPI are the same behaviour).
62
+
63
+ Seeded from songleaf (thorwhalen/songleaf#31). Planned: a Nashville/Roman dialect; pychord and music21 as test oracles only.
@@ -3,9 +3,12 @@
3
3
  >>> from chordsym import parse_chord, transpose_chord, estimate_key
4
4
  >>> parse_chord("Am7"), transpose_chord("Am7", 2), estimate_key(["Am", "Dm", "E7"])
5
5
  ((9, 'minor'), 'Bm7', Key(tonic=9, minor=True))
6
+ >>> parse_chord("Fsmin", dialect="chordonomicon"), parse_chord("C:maj7", dialect="harte")
7
+ ((6, 'minor'), (0, 'major'))
6
8
  """
7
9
 
8
10
  from chordsym.keys import Key, chord_function, estimate_key
11
+ from chordsym.dialects import DIALECTS, Dialect
9
12
  from chordsym.parse import chord_tones, is_chord_token, parse_chord
10
13
  from chordsym.transpose import (
11
14
  key_name,
@@ -15,6 +18,8 @@ from chordsym.transpose import (
15
18
  )
16
19
 
17
20
  __all__ = [
21
+ "DIALECTS",
22
+ "Dialect",
18
23
  "Key",
19
24
  "chord_function",
20
25
  "chord_tones",
@@ -0,0 +1,238 @@
1
+ """The chord-symbol grammar and tables, shared by the Python package and its TypeScript twin.
2
+
3
+ This module is the single source of truth for every regular expression and lookup table
4
+ chordsym uses. ``chordsym._codegen`` writes it to ``ts/src/grammar.generated.ts``, so the
5
+ TypeScript package reads the same patterns and tables; a test fails when the committed
6
+ TypeScript file is stale.
7
+
8
+ Every pattern here must mean the same thing in Python's ``re`` and in a JavaScript
9
+ ``RegExp`` with the ``u`` flag. Hence:
10
+
11
+ - no ``\\d``, ``\\w``, ``\\s``, ``\\b`` (or their negations): Python's are Unicode-aware,
12
+ JavaScript's are not (``\\d``) or differ at the edges (``\\s``); use ``[0-9]`` and
13
+ :data:`WS` instead;
14
+ - ``.`` only with the DOTALL flag (``s`` in JavaScript), listed in :data:`PATTERNS`;
15
+ - whole-string matches are written by the caller (``fullmatch`` / ``^(?:...)$``), never
16
+ with ``$`` inside a pattern.
17
+
18
+ ``tests/test_grammar.py`` enforces the first rule; ``fixtures/cases.json`` checks the rest
19
+ by running the same cases on both sides.
20
+
21
+ >>> sorted(PATTERNS)[:3]
22
+ ['chord', 'diminished', 'harte']
23
+ """
24
+
25
+ import re
26
+
27
+ #: Whitespace, as a character-class body: exactly the characters Python's ``str.isspace``
28
+ #: accepts (what ``str.strip()`` removes), written out so a JavaScript ``RegExp`` (whose
29
+ #: ``\s`` lacks ``\x1c``-``\x1f`` and ``\x85`` and adds ``\ufeff``) matches the same set.
30
+ WS = (
31
+ "\\t\\n\\x0b\\x0c\\r\\x1c\\x1d\\x1e\\x1f \\x85\\xa0\\u1680"
32
+ "\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000"
33
+ )
34
+
35
+ #: name -> (pattern source, flags). Flags: ``"s"`` means DOTALL.
36
+ PATTERNS: dict[str, tuple[str, str]] = {
37
+ # Is this token a chord symbol? (used with a whole-string match)
38
+ "chord": (
39
+ r"[*.]{0,3}\(?" # leading marks: *D, ...Dm6
40
+ r"[A-G][#b]?" # root
41
+ # quality; o7 = °7; Δ or ∆ = maj7, mΔ7 or -Δ7 = minor-major seventh
42
+ r"(?:maj|min|dim|aug|sus|add|[m\-]?[Δ∆]|m|M|\+|°|º|ø|o(?=7))?"
43
+ r"[0-9]{0,2}[M+\-]?" # extension: 7, 9, 13; Brazilian 7M, 7+, 5-
44
+ r"(?:sus[0-9]{0,2}|(?:maj|add|dim|aug|no|m|b|#|\+|-)[0-9]{1,2}[+\-]?)*" # b5, add9
45
+ r"(?:/(?:[#b]?[0-9]{1,2}[+\-#b]?|sus[0-9]{0,2}))*" # stacked: 7/9, 5-/7, 7/sus4
46
+ r"(?:\([^()" + WS + r"]{1,10}\))*" # parenthesised alterations: (#9), 7(4)(9)
47
+ r"(?:/[A-G][#b]?)?" # bass
48
+ r"\)?\*?",
49
+ "",
50
+ ),
51
+ # Lead marks, root letter, accidental, the rest (used with a whole-string match).
52
+ "root": (r"[*.(" + WS + r"]*([A-G])([#b]?)(.*)", "s"),
53
+ # A diminished quality, at the start of what follows the root.
54
+ "diminished": (r"(?:dim|°|º|ø|o7|m(?:in)?7?\(?b5)", ""),
55
+ # A power chord's 5 (not 5 of 13 or 55), at the start of what follows the root.
56
+ "power": (r"5(?![0-9])", ""),
57
+ # A note name: letter and optional accidental, at the start of a string.
58
+ "note": (r"([A-G])([#b]?)", ""),
59
+ # Seventh and extension markers, searched anywhere in what follows the root.
60
+ # (A bare ``Δ`` or ``∆`` is a major seventh on its own: ``CΔ`` = ``Cmaj7``.)
61
+ "major_seventh": (r"(?:maj|M)(?:7|9|11|13)|[Δ∆]", ""),
62
+ "seventh": (r"(?<!add)(7|9|11|13)", ""),
63
+ "sixth": (r"(?<![0-9])6", ""),
64
+ "ninth": (r"9|add2", ""),
65
+ # Root, suffix, and a final /bass with what trails it (used with a whole-string match).
66
+ # The bass is only a final ``/note`` (``D/F#``); a slash inside the extension
67
+ # (``C6/9``, ``Bm5-/7``) belongs to the chord's suffix.
68
+ "transposable": (
69
+ r"([*.(" + WS + r"]*)([A-G][#b]?)(.*?)(?:/([A-G][#b]?)([^/A-Za-z0-9#]*))?",
70
+ "s",
71
+ ),
72
+ # A Harte label (used with a whole-string match): lead, root letter, accidental, then
73
+ # ``:shorthand`` with an optional ``(interval list)``, then an optional ``/degree``
74
+ # bass, then trailing whitespace. Groups: lead, letter, accidental, shorthand, list,
75
+ # bass, trail.
76
+ "harte": (
77
+ r"([" + WS + r"]*)([A-G])([#b]?)"
78
+ r"(?::([^(/" + WS + r"]*)(?:\(([^()]*)\))?)?"
79
+ r"(?:/([#b]{0,2}[0-9]{1,2}))?([" + WS + r"]*)",
80
+ "",
81
+ ),
82
+ }
83
+
84
+ #: Dialect name -> the rewrites that turn its spelling into the default one, applied in
85
+ #: order as ``(pattern, replacement)``: every match of the pattern is replaced by the
86
+ #: replacement as literal text (no group references, which Python and JavaScript write
87
+ #: differently). Harte is read by structure instead (``PATTERNS["harte"]`` and the
88
+ #: ``HARTE_*`` tables), since its bass is a degree that depends on the root.
89
+ #:
90
+ #: - ``default``: the chart spellings :func:`chordsym.parse_chord` reads; no rewrite.
91
+ #: - ``chordonomicon``: the Chordonomicon corpus writes ``#`` as ``s`` (``Cs``,
92
+ #: ``Fsmin``, ``A/Cs``, ``Emajs9``) and a power chord as ``no3d`` (``Gno3d``).
93
+ DIALECT_REWRITES: dict[str, list[tuple[str, str]]] = {
94
+ "default": [],
95
+ "chordonomicon": [
96
+ (r"(?<=[A-G])s(?!us)", "#"), # a sharp after a root or bass letter, not sus
97
+ (r"(?<!u)s(?=[0-9])", "#"), # a sharp before a number (majs9), not sus4
98
+ (r"(?:(?<=[A-G])|(?<=[A-G][#b]))no3d", "5"), # Gno3d is G5
99
+ ],
100
+ }
101
+
102
+ #: Harte (2005) shorthands and their default spellings (``C:hdim7`` reads as ``Cm7b5``).
103
+ HARTE_SHORTHANDS = {
104
+ "maj": "",
105
+ "min": "m",
106
+ "dim": "dim",
107
+ "aug": "aug",
108
+ "maj7": "maj7",
109
+ "min7": "m7",
110
+ "7": "7",
111
+ "dim7": "dim7",
112
+ "hdim7": "m7b5",
113
+ "minmaj7": "mmaj7",
114
+ "maj6": "6",
115
+ "min6": "m6",
116
+ "9": "9",
117
+ "maj9": "maj9",
118
+ "min9": "m9",
119
+ "11": "11",
120
+ "min11": "m11",
121
+ "13": "13",
122
+ "maj13": "maj13",
123
+ "min13": "m13",
124
+ "sus2": "sus2",
125
+ "sus4": "sus4",
126
+ "5": "5",
127
+ }
128
+
129
+ #: Harte interval lists without a shorthand (``C:(1,b3,5)``) that have a default spelling;
130
+ #: any other list is not read.
131
+ HARTE_INTERVAL_SETS = {
132
+ "1,3,5": "",
133
+ "1,b3,5": "m",
134
+ "1,3,5,b7": "7",
135
+ "1,b3,5,b7": "m7",
136
+ "1,5": "5",
137
+ }
138
+
139
+ #: A seventh added in parentheses, by shorthand: ``C:min(b7)`` is ``Cm7``, ``C:sus4(b7)``
140
+ #: is ``C7sus4``, ``C:dim(b7)`` is ``Cm7b5``. A seventh added to any other shorthand is
141
+ #: not read. (Looked up only: a JavaScript object reorders integer-like keys.)
142
+ HARTE_SEVENTHS = {
143
+ "maj": {"b7": "7", "7": "maj7"},
144
+ "min": {"b7": "m7", "7": "mmaj7"},
145
+ "dim": {"bb7": "dim7", "b7": "m7b5"},
146
+ "aug": {"b7": "aug7", "7": "augmaj7"},
147
+ "sus4": {"b7": "7sus4", "7": "sus4maj7"},
148
+ "sus2": {"b7": "7sus2", "7": "sus2maj7"},
149
+ }
150
+
151
+ #: Other degrees added in parentheses after a shorthand (``C:maj(9)`` is ``Cadd9``), as
152
+ #: default suffix pieces appended in this order (pairs, not a mapping, because the order
153
+ #: matters and a JavaScript object would put integer-like keys first). A list with any
154
+ #: other item (an omission such as ``*3``) is not read.
155
+ HARTE_ADDED = (
156
+ ("2", "add2"),
157
+ ("4", "add4"),
158
+ ("6", "add6"),
159
+ ("9", "add9"),
160
+ ("11", "add11"),
161
+ ("13", "add13"),
162
+ ("b5", "(b5)"),
163
+ ("#5", "(#5)"),
164
+ ("b9", "(b9)"),
165
+ ("#9", "(#9)"),
166
+ ("#11", "(#11)"),
167
+ ("b13", "(b13)"),
168
+ )
169
+
170
+ #: A Harte bass degree -> semitones above the root (``C:maj/3`` has an E in the bass).
171
+ HARTE_DEGREES = {
172
+ "1": 0,
173
+ "b2": 1,
174
+ "2": 2,
175
+ "#2": 3,
176
+ "b3": 3,
177
+ "3": 4,
178
+ "4": 5,
179
+ "#4": 6,
180
+ "b5": 6,
181
+ "5": 7,
182
+ "#5": 8,
183
+ "b6": 8,
184
+ "6": 9,
185
+ "bb7": 9,
186
+ "b7": 10,
187
+ "7": 11,
188
+ "b9": 1,
189
+ "9": 2,
190
+ "#9": 3,
191
+ "11": 5,
192
+ "#11": 6,
193
+ "b13": 8,
194
+ "13": 9,
195
+ }
196
+
197
+
198
+ def compile_pattern(name: str) -> re.Pattern:
199
+ """The compiled :data:`PATTERNS` entry ``name`` (Python side only; not generated)."""
200
+ source, flags = PATTERNS[name]
201
+ return re.compile(source, re.DOTALL if "s" in flags else 0)
202
+
203
+
204
+ #: Natural-note pitch classes and accidental offsets.
205
+ PITCH_CLASSES = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
206
+ ACCIDENTALS = {"#": 1, "b": -1, "": 0}
207
+
208
+ #: Note names by pitch class, spelled with sharps or with flats.
209
+ SHARP_NAMES = ("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
210
+ FLAT_NAMES = ("C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B")
211
+
212
+ #: Keys whose signatures use flats, as tonic pitch classes: F Bb Eb Ab Db Gb; d g c f bb eb.
213
+ FLAT_MAJOR_TONICS = (5, 10, 3, 8, 1, 6)
214
+ FLAT_MINOR_TONICS = (2, 7, 0, 5, 10, 3)
215
+
216
+ #: Qualities each scale degree (semitones above the tonic) takes in a key.
217
+ MAJOR_KEY = {
218
+ 0: ("major",),
219
+ 2: ("minor",),
220
+ 4: ("minor",),
221
+ 5: ("major",),
222
+ 7: ("major",),
223
+ 9: ("minor",),
224
+ 11: ("diminished", "minor"),
225
+ }
226
+ MINOR_KEY = {
227
+ 0: ("minor",),
228
+ 2: ("diminished", "minor"),
229
+ 3: ("major",),
230
+ 5: ("minor",),
231
+ 7: ("minor", "major"), # the harmonic-minor V is at home in a minor key
232
+ 8: ("major",),
233
+ 10: ("major",),
234
+ }
235
+
236
+ #: Key estimation: score of a chord that is the key's tonic, a diatonic chord, and the
237
+ #: bonus for a song starting or ending on the tonic chord.
238
+ KEY_WEIGHTS = {"tonic": 2.0, "diatonic": 1.0, "outside": 0.0, "ends": 2.0}
@@ -0,0 +1,153 @@
1
+ """Dialects: how a chord symbol is spelled, as a function into the default spelling.
2
+
3
+ A dialect is a pure function ``str -> str`` that rewrites a symbol from its own spelling
4
+ into the one :func:`chordsym.parse_chord` reads by default. Every function that reads
5
+ chord symbols takes ``dialect=``: a registered name or the function itself.
6
+
7
+ >>> resolve_dialect("chordonomicon")("Fsmin7/Cs"), resolve_dialect("harte")("Bb:min7/b7")
8
+ ('F#min7/C#', 'Bbm7/Ab')
9
+ >>> list(DIALECTS)
10
+ ['default', 'chordonomicon', 'harte']
11
+
12
+ Built-in names are read-only; :func:`register_dialect` adds others. ``parse_chord``
13
+ remembers results keyed on the dialect's function, so a dialect must be pure (same input,
14
+ same output).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from collections.abc import Callable, Hashable
21
+ from types import MappingProxyType
22
+
23
+ from chordsym import _grammar
24
+
25
+ #: A dialect: rewrites a chord symbol from its own spelling into the default one.
26
+ Dialect = Callable[[str], str]
27
+
28
+
29
+ def _rewriter(rules: list[tuple[str, str]]) -> Dialect:
30
+ compiled = [(re.compile(source), replacement) for source, replacement in rules]
31
+
32
+ def rewrite(symbol: str) -> str:
33
+ for pattern, replacement in compiled:
34
+ # A function replacement keeps the text literal, as the TypeScript twin does.
35
+ symbol = pattern.sub(lambda _, r=replacement: r, symbol)
36
+ return symbol
37
+
38
+ return rewrite
39
+
40
+
41
+ _HARTE_RE = _grammar.compile_pattern("harte")
42
+ _ADDED = dict(_grammar.HARTE_ADDED)
43
+ _ADDED_ORDER = [degree for degree, _ in _grammar.HARTE_ADDED]
44
+
45
+
46
+ def _harte_suffix(shorthand: str, intervals: str) -> str | None:
47
+ """The default suffix of ``shorthand`` with the degrees ``intervals`` added."""
48
+ items = intervals.split(",")
49
+ sevenths = [item for item in items if item in ("b7", "7", "bb7")]
50
+ others = [item for item in items if item not in sevenths]
51
+ if len(sevenths) > 1 or not all(item in _ADDED for item in others):
52
+ return None
53
+ if sevenths:
54
+ suffix = _grammar.HARTE_SEVENTHS.get(shorthand, {}).get(sevenths[0])
55
+ else:
56
+ suffix = _grammar.HARTE_SHORTHANDS.get(shorthand)
57
+ if suffix is None:
58
+ return None
59
+ others.sort(key=_ADDED_ORDER.index)
60
+ return suffix + "".join(_ADDED[item] for item in others)
61
+
62
+
63
+ def harte(symbol: str) -> str:
64
+ """A Harte label (``C:maj7``, ``A:min(9)``, ``C:(1,b3,5)``, ``C:maj/3``) in the default
65
+ spelling; ``""`` (not a chord) for a Harte label it cannot read, the symbol unchanged
66
+ when it is not a Harte label (``N``, ``D/F#``).
67
+
68
+ >>> [harte(s) for s in ("C:maj/b7", "A:min(9)", "C:sus4(b7)", "C:(1,b3,5,b7)", "C:(3,5)", "N")]
69
+ ['C/Bb', 'Amadd9', 'C7sus4', 'Cm7', '', 'N']
70
+ """
71
+ match = _HARTE_RE.fullmatch(symbol)
72
+ if match is None:
73
+ return symbol
74
+ lead, letter, accidental, shorthand, intervals, bass, trail = match.groups()
75
+ if shorthand is None: # no colon: "C" is C:maj
76
+ suffix = ""
77
+ elif shorthand == "": # an interval list alone: "C:(1,b3,5)"
78
+ suffix = _grammar.HARTE_INTERVAL_SETS.get(intervals)
79
+ elif intervals is None:
80
+ suffix = _grammar.HARTE_SHORTHANDS.get(shorthand)
81
+ else:
82
+ suffix = _harte_suffix(shorthand, intervals)
83
+ if suffix is None:
84
+ return ""
85
+ out = lead + letter + accidental + suffix
86
+ if bass is not None:
87
+ interval = _grammar.HARTE_DEGREES.get(bass)
88
+ if interval is None:
89
+ return ""
90
+ root = _grammar.PITCH_CLASSES[letter] + _grammar.ACCIDENTALS[accidental]
91
+ # Spelled with flats under a flat root, or a flat degree under a natural root.
92
+ flats = accidental == "b" or (accidental == "" and bass.startswith("b"))
93
+ names = _grammar.FLAT_NAMES if flats else _grammar.SHARP_NAMES
94
+ out += "/" + names[(root + interval) % 12]
95
+ return out + trail
96
+
97
+
98
+ _BUILTIN: dict[str, Dialect] = {
99
+ **{name: _rewriter(rules) for name, rules in _grammar.DIALECT_REWRITES.items()},
100
+ "harte": harte,
101
+ }
102
+ _REGISTRY: dict[str, Dialect] = dict(_BUILTIN)
103
+
104
+ #: Dialect name -> its function (read-only; add a dialect with :func:`register_dialect`).
105
+ DIALECTS = MappingProxyType(_REGISTRY)
106
+
107
+
108
+ def register_dialect(name: str, normalise: Dialect) -> Dialect:
109
+ """Make ``normalise`` (a pure ``str -> str``) readable as ``dialect=name``; returns it.
110
+
111
+ >>> _ = register_dialect("lower", str.capitalize)
112
+ >>> from chordsym import parse_chord
113
+ >>> parse_chord("am", dialect="lower")
114
+ (9, 'minor')
115
+ >>> unregister_dialect("lower")
116
+ """
117
+ if not isinstance(name, str):
118
+ raise TypeError(f"A dialect name must be a str, not {name!r}")
119
+ if name in _BUILTIN:
120
+ raise ValueError(f"{name!r} is a built-in dialect and cannot be replaced")
121
+ if not callable(normalise):
122
+ raise TypeError(f"A dialect must be a function str -> str, not {normalise!r}")
123
+ _REGISTRY[name] = resolve_dialect(normalise) # checks it is hashable
124
+ return normalise
125
+
126
+
127
+ def unregister_dialect(name: str) -> None:
128
+ """Forget a dialect added with :func:`register_dialect` (built-ins stay)."""
129
+ if name in _BUILTIN:
130
+ raise ValueError(f"{name!r} is a built-in dialect and cannot be removed")
131
+ if name not in _REGISTRY:
132
+ raise ValueError(f"No registered dialect {name!r}; one of {list(_REGISTRY)}")
133
+ del _REGISTRY[name]
134
+
135
+
136
+ def resolve_dialect(dialect: str | Dialect) -> Dialect:
137
+ """The function for ``dialect``: a registered name, or a function passed as is.
138
+
139
+ Raises ValueError for an unknown name (listing the known ones), TypeError for
140
+ anything else, including an unhashable function (results are cached per function).
141
+ """
142
+ if callable(dialect):
143
+ if not isinstance(dialect, Hashable):
144
+ raise TypeError(
145
+ f"A dialect function must be hashable (parse_chord caches per function): {dialect!r}"
146
+ )
147
+ return dialect
148
+ if not isinstance(dialect, str):
149
+ raise TypeError(f"dialect must be a name or a function, not {dialect!r}")
150
+ normalise = _REGISTRY.get(dialect)
151
+ if normalise is None:
152
+ raise ValueError(f"Unknown dialect {dialect!r}; one of {list(_REGISTRY)}")
153
+ return normalise
@@ -11,10 +11,12 @@ Key(tonic=9, minor=True)
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ from collections import Counter
14
15
  from collections.abc import Iterable
15
16
  from dataclasses import dataclass
16
17
 
17
18
  from chordsym import _grammar
19
+ from chordsym.dialects import Dialect, resolve_dialect
18
20
  from chordsym.parse import parse_chord
19
21
 
20
22
  _MAJOR_KEY = {degree: set(qs) for degree, qs in _grammar.MAJOR_KEY.items()}
@@ -45,32 +47,50 @@ def _function(parsed: tuple[int, str], key: Key) -> str:
45
47
  return "tonic" if degree == 0 else "diatonic"
46
48
 
47
49
 
48
- def chord_function(symbol: str, key: Key) -> str | None:
49
- """``"tonic"``, ``"diatonic"`` or ``"outside"`` in ``key``; None if ``symbol`` is not a chord."""
50
- parsed = parse_chord(symbol)
50
+ def chord_function(
51
+ symbol: str, key: Key, *, dialect: str | Dialect = "default"
52
+ ) -> str | None:
53
+ """``"tonic"``, ``"diatonic"`` or ``"outside"`` in ``key``; None if ``symbol`` is not a chord.
54
+
55
+ ``dialect`` names how ``symbol`` is spelled, as in :func:`chordsym.parse_chord`.
56
+ """
57
+ parsed = parse_chord(symbol, dialect=dialect)
51
58
  return None if parsed is None else _function(parsed, key)
52
59
 
53
60
 
54
- def estimate_key(symbols: Iterable[str]) -> Key | None:
61
+ def estimate_key(
62
+ symbols: Iterable[str], *, dialect: str | Dialect = "default"
63
+ ) -> Key | None:
55
64
  """The key that best explains a song's chords, in order; None if there are no chords.
56
65
 
57
66
  Each chord scores for a key when it belongs to it, and more when it is its
58
67
  tonic; a song that starts or ends on a key's tonic chord scores extra for
59
- that key. Ties go to the major key, and to the lower tonic.
68
+ that key. Ties go to the major key, and to the lower tonic. ``dialect`` names
69
+ how ``symbols`` are spelled, as in :func:`chordsym.parse_chord`.
70
+
71
+ >>> estimate_key(["Cs", "Fs", "Gs", "Cs"], dialect="chordonomicon")
72
+ Key(tonic=1, minor=False)
60
73
  """
61
- chords = [parsed for parsed in map(parse_chord, symbols) if parsed]
74
+ normalise = resolve_dialect(
75
+ dialect
76
+ ) # an unknown dialect raises, even with no symbols
77
+ chords = [p for p in (parse_chord(s, dialect=normalise) for s in symbols) if p]
62
78
  if not chords:
63
79
  return None
80
+ # Each distinct chord is scored once per key, times how often it occurs. That equals
81
+ # adding each occurrence's weight in turn because the weights are integers (exact in
82
+ # floating point in any order; tests/test_chordsym.py checks they stay integers).
83
+ # Still an explicit loop, not sum(), which compensates float rounding on Python 3.12+.
84
+ counts = Counter(chords).items()
85
+ ends = (chords[0], chords[-1])
64
86
  best, best_score = None, float("-inf")
65
87
  for tonic in range(12):
66
88
  for minor in (False, True):
67
89
  key = Key(tonic, minor)
68
- # A plain left-to-right sum, as the TypeScript twin does: the builtin sum()
69
- # compensates float rounding (Python 3.12+), which would break ties differently.
70
90
  score = 0.0
71
- for parsed in chords:
72
- score += _WEIGHTS[_function(parsed, key)]
73
- for parsed in (chords[0], chords[-1]):
91
+ for parsed, n in counts:
92
+ score += n * _WEIGHTS[_function(parsed, key)]
93
+ for parsed in ends:
74
94
  if _function(parsed, key) == "tonic":
75
95
  score += _WEIGHTS["ends"]
76
96
  if score > best_score: