4esv commited on
Commit
d09f52e
·
verified ·
1 Parent(s): f2f88d7

Rameau v1: 21,940 records, 4 configs, verified gold, eval harness

Browse files
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.14
README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: "Rameau: Functional Harmony from Notation (Roman Numerals, Cadence, Key)"
3
+ license: cc-by-4.0
4
+ language:
5
+ - en
6
+ task_categories:
7
+ - text2text-generation
8
+ tags:
9
+ - music
10
+ - music-theory
11
+ - functional-harmony
12
+ - roman-numeral-analysis
13
+ - chord-progression
14
+ - cadence
15
+ - key-detection
16
+ - benchmark
17
+ - synthetic
18
+ size_categories:
19
+ - 10K<n<100K
20
+ annotations_creators:
21
+ - machine-generated
22
+ source_datasets:
23
+ - original
24
+ configs:
25
+ - config_name: symbol_to_rn
26
+ data_files:
27
+ - split: train
28
+ path: data/symbol_to_rn/train.jsonl
29
+ - split: validation
30
+ path: data/symbol_to_rn/validation.jsonl
31
+ - split: test
32
+ path: data/symbol_to_rn/test.jsonl
33
+ - config_name: notes_to_rn
34
+ default: true
35
+ data_files:
36
+ - split: train
37
+ path: data/notes_to_rn/train.jsonl
38
+ - split: validation
39
+ path: data/notes_to_rn/validation.jsonl
40
+ - split: test
41
+ path: data/notes_to_rn/test.jsonl
42
+ - config_name: pcset_to_rn
43
+ data_files:
44
+ - split: train
45
+ path: data/pcset_to_rn/train.jsonl
46
+ - split: validation
47
+ path: data/pcset_to_rn/validation.jsonl
48
+ - split: test
49
+ path: data/pcset_to_rn/test.jsonl
50
+ - config_name: key_id
51
+ data_files:
52
+ - split: train
53
+ path: data/key_id/train.jsonl
54
+ - split: validation
55
+ path: data/key_id/validation.jsonl
56
+ - split: test
57
+ path: data/key_id/test.jsonl
58
+ ---
59
+
60
+ # Rameau: functional harmony from notation
61
+
62
+ A **text-to-text** dataset and benchmark for functional-harmony understanding in
63
+ music notation: Roman-numeral analysis, cadence classification, and key
64
+ identification. Progressions are generated by a probabilistic common-practice
65
+ grammar and framed as four tasks of increasing difficulty — the harder tasks
66
+ **hide the answer**, so the data tests harmonic reasoning, not chord-symbol lookup.
67
+
68
+ Named for Jean-Philippe Rameau, whose *Traité de l'harmonie* (1722) founded the
69
+ theory of functional harmony this dataset teaches.
70
+
71
+ ```
72
+ symbol_to_rn key: C major / progression: Dm7 G7 Cmaj7 -> ii7 V7 IM7 / cadence: PAC
73
+ notes_to_rn key: C major / notes: D4 F4 A4 C5 | ... -> ii7 V7 IM7 / cadence: PAC
74
+ pcset_to_rn key: C major / pitch classes: [2 5 9 0]|... -> ii7 V7 IM7 / cadence: PAC
75
+ key_id notes: D4 F4 A4 C5 | G3 B3 D4 F4 | ... -> C major
76
+ ```
77
+
78
+ ## Configs (tasks)
79
+
80
+ Load one with `load_dataset("4esv/rameau", "<config>")`. Default: `notes_to_rn`.
81
+
82
+ | config | task | rows |
83
+ |---|---|---|
84
+ | `symbol_to_rn` | key + chord symbols -> Roman numerals + cadence (easy: chord quality is given) | 5715 |
85
+ | `notes_to_rn` | key + spelled notes -> Roman numerals + cadence (must read each chord) | 5715 |
86
+ | `pcset_to_rn` | key + bass-first pitch-class lists -> Roman numerals + cadence (no spelling) | 5715 |
87
+ | `key_id` | spelled notes, no key -> identify the key (only key-unambiguous phrases) | 4795 |
88
+ | | **total** | **21940** |
89
+
90
+ ## How the gold labels are generated (and why they are trustworthy)
91
+
92
+ Labels are **not hand-annotated**. A probabilistic functional grammar
93
+ (tonic -> predominant -> dominant -> cadence, with sevenths, inversions,
94
+ cadential 6-4s and secondary dominants) generates each progression *together with*
95
+ its intended Roman-numeral analysis. Every chord is then checked two independent
96
+ ways with [`music21`](https://web.mit.edu/music21/):
97
+
98
+ - the Roman-numeral label rendered to pitch classes by the roman engine;
99
+ - the printed chord symbol parsed to pitch classes by the chord-symbol parser;
100
+
101
+ and the item is kept only if the two agree on pitch content **and** bass. On this
102
+ release: **100.00%** chord-level agreement
103
+ (27480/27480 chords;
104
+ 5715/5715 instances kept). See `VERIFY.md`.
105
+
106
+ Built from **845 distinct progression shapes** (key-independent), transposed
107
+ across keys. All content is synthetic; no third-party corpus is redistributed.
108
+
109
+ ## Label convention
110
+
111
+ Roman numerals follow the **DCML harmony standard**'s feature decomposition
112
+ (`numeral` / `form` / `figbass` / `changes` / `relativeroot`), spec at
113
+ <https://github.com/DCMLab/standards> — we conform to the notation, we do not copy
114
+ DCML data. Major-seventh tonic is `IM7`; secondary dominants use `/` (e.g. `V7/vi`).
115
+ Cadence codes: `PAC` perfect authentic, `IAC` imperfect authentic, `HC` half, `DC` deceptive, `PC` plagal.
116
+
117
+ ## Fields
118
+
119
+ Common to every config: `input`, `target`, `key`, `mode`, `labels`, `cadence`,
120
+ `analysis` (per-chord DCML features), `source` (`grammar`/`curated`/`single`),
121
+ `category`, `shape_id`. Plus the input representation for the config: `chords`
122
+ (symbols), `notes` (spelled, bass-first), or `pitch_classes` (bass-first).
123
+
124
+ Accidentals are written the standard way (`Bb`, `F#`, `Cb`). Note for music21
125
+ users: its parsers want `-` for flats — convert `b -> -` in note/root names
126
+ before calling `ChordSymbol` or `Pitch`.
127
+
128
+ ## Splits (leakage-free; test doubles as a benchmark)
129
+
130
+ The atomic unit is a **shape** (a key-independent Roman-numeral sequence). Each
131
+ shape is hashed to exactly one split, so a shape — and all of its transpositions
132
+ **and all of its task framings** — never crosses splits. Split sizes (rows):
133
+ train 14725 / validation 3571 / test 3644.
134
+
135
+ ## Known limitations
136
+
137
+ - **Synthetic distribution.** Grammar-generated common-practice progressions, not
138
+ sampled from real repertoire; the chord distribution is not naturalistic.
139
+ - **PAC vs IAC** is decided by inversion (no notated soprano voice). Cadence rules
140
+ are strict: an HC must end on a root-position V *triad* (a terminal V7 is not
141
+ labelled), and a DC requires a root-position dominant (`V65 -> vi` is not one).
142
+ - **key_id** includes only cadence-terminated progressions of >= 3 chords whose
143
+ notes contain both key-defining degrees (scale degree 4 and the leading tone),
144
+ so the key is uniquely determined. Without this gate, gold labels can be
145
+ contestable — e.g. `I V7/V V` in C is note-identical to `IV V7 I` in G, and the
146
+ G-major reading (a PAC) is arguably stronger. Such phrases are excluded.
147
+ - Harmony only — no voice-leading, melody, or rhythm. No modal mixture / Neapolitan
148
+ / augmented sixths yet.
149
+
150
+ ## Evaluation
151
+
152
+ The `test` split is a benchmark: gold is deterministic, so scoring is **exact
153
+ match — no LLM judge**. The repo ships a self-contained harness under `eval/`:
154
+
155
+ ```bash
156
+ # query any OpenAI-compatible endpoint (ollama, vLLM, OpenAI, ...):
157
+ python eval/run_model.py --config notes_to_rn --model <model> --out preds.jsonl
158
+ # score predictions (stdlib only):
159
+ python eval/score.py preds.jsonl --config notes_to_rn --split test
160
+ ```
161
+
162
+ Metrics: `exact` (Roman numerals **and** cadence correct — the headline number),
163
+ `labels_exact`, `chord_acc` (positional), `cadence_acc`; for `key_id`: `exact`,
164
+ `tonic_acc`, `mode_acc`. The zero-shot prompts are versioned in
165
+ `eval/prompts.py`; parsing rules are documented in `eval/README.md`.
166
+
167
+ ## Reproduce
168
+
169
+ The full generation pipeline ships in this repo (`src/harmony_dataset/`):
170
+
171
+ ```bash
172
+ uv sync && uv run pytest # full suite, incl. the eval harness
173
+ uv run python -m harmony_dataset.export # regenerates data/, README, VERIFY.md
174
+ ```
175
+
176
+ ## Licensing
177
+
178
+ **CC-BY-4.0.** Content is generated by this repository's pipeline from music theory;
179
+ the underlying facts are not copyrightable and no source corpus is redistributed.
180
+
181
+ ## Citation
182
+
183
+ ```
184
+ @misc{rameau,
185
+ title = {Rameau: Functional Harmony from Notation (Roman Numerals, Cadence, Key)},
186
+ author = {Stevens, Axel},
187
+ year = {2026},
188
+ url = {https://huggingface.co/datasets/4esv/rameau},
189
+ note = {Synthetic, grammar-generated, music21-verified, DCML-convention labels}
190
+ }
191
+ ```
VERIFY.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Verification report
2
+
3
+ ## Gold gate (dual-derivation agreement)
4
+
5
+ | metric | value |
6
+ |---|---|
7
+ | distinct shapes | 845 |
8
+ | instances (shape x key) | 5715 |
9
+ | instances dropped | 0 |
10
+ | chords attempted | 27480 |
11
+ | chord disagreements | 0 |
12
+ | **chord agreement rate** | **100.000%** |
13
+ | total records | 21940 |
14
+
15
+ ## Distribution
16
+
17
+ - by source: {'curated': 230, 'single': 1440, 'grammar': 20270}
18
+ - by cadence: {'PAC': 7902, 'HC': 3903, None: 1458, 'DC': 4460, 'IAC': 3645, 'PC': 572}
19
+
20
+ ## Same progression, four framings (brief example in C major)
21
+
22
+ - **symbol_to_rn**
23
+ - in: `key: C major // progression: Dm7 G7 Cmaj7`
24
+ - out: `ii7 V7 IM7 // cadence: PAC`
25
+ - **notes_to_rn**
26
+ - in: `key: C major // notes: D4 F4 A4 C5 | G4 B4 D5 F5 | C4 E4 G4 B4`
27
+ - out: `ii7 V7 IM7 // cadence: PAC`
28
+ - **pcset_to_rn**
29
+ - in: `key: C major // pitch classes: [2 5 9 0] | [7 11 2 5] | [0 4 7 11]`
30
+ - out: `ii7 V7 IM7 // cadence: PAC`
31
+ - **key_id**
32
+ - in: `notes: D4 F4 A4 C5 | G4 B4 D5 F5 | C4 E4 G4 B4`
33
+ - out: `C major`
34
+
35
+ ## Grammar phrases (notes_to_rn, in C major / A minor)
36
+
37
+ - `A minor` A4 C5 E5 | D5 F5 A5 | B4 D5 G#5 | E5 G#5 B5 D6 | F5 A5 C6
38
+ -> `i iv viio6 V7 VI` (DC)
39
+ - `A minor` A4 C5 E5 | C5 E5 A5 | D5 F5 B5 | E5 G#5 B5
40
+ -> `i i6 iio6 V` (HC)
41
+ - `C major` C4 E4 G4 | F4 A4 D5 | G4 C5 E5 | G4 B4 D5
42
+ -> `I ii6 I64 V` (HC)
43
+ - `A minor` A4 C5 E5 | A4 C#5 E5 G5 | D5 F5 A5 | E5 G#5 B5
44
+ -> `i V7/iv iv V` (HC)
45
+ - `A minor` A4 C5 E5 | F5 A5 C6 | B4 D5 F5 A5 | E5 G#5 B5 D6 | F5 A5 C6
46
+ -> `i VI ii%7 V7 VI` (DC)
47
+ - `C major` C4 E4 G4 | D4 F4 A4 C5 | D4 F4 B4 | G4 B4 D5 F5 | A4 C5 E5
48
+ -> `I ii7 viio6 V7 vi` (DC)
49
+ - `C major` C4 E4 G4 | E4 G4 B4 | A4 C5 E5 | F4 A4 C5 | G4 B4 D5
50
+ -> `I iii vi IV V` (HC)
51
+ - `A minor` A4 C5 E5 | C5 E5 A5 | D5 F5 A5 | E5 G#5 B5
52
+ -> `i i6 iv V` (HC)
53
+ - `A minor` C5 E5 A5 | D5 F5 A5 | D5 F5 B5 | E5 G#5 B5 | A4 C5 E5
54
+ -> `i6 iv iio6 V i` (PAC)
55
+ - `A minor` A4 C5 E5 | C5 E5 A5 | D5 F5 A5 | B4 D5 G#5 | E5 G#5 B5 D6 | F5 A5 C6
56
+ -> `i i6 iv viio6 V7 VI` (DC)
57
+ - `A minor` A4 C5 E5 | F5 A5 C6 | C5 E5 G5 | D5 F5 A5 | E5 G#5 B5 | F5 A5 C6
58
+ -> `i VI III iv V VI` (DC)
59
+ - `A minor` A4 C5 E5 | F5 A5 C6 | D5 F5 A5 | E5 G#5 B5
60
+ -> `i VI iv V` (HC)
data/key_id/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/key_id/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/key_id/validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/notes_to_rn/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/notes_to_rn/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/notes_to_rn/validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/pcset_to_rn/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/pcset_to_rn/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/pcset_to_rn/validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/symbol_to_rn/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/symbol_to_rn/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/symbol_to_rn/validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rameau evaluation protocol
2
+
3
+ Gold labels are deterministic and machine-verified, so scoring is **exact
4
+ match** — no LLM judge, no partial credit beyond the metrics defined below.
5
+
6
+ ## Protocol
7
+
8
+ - **Split:** `test` (leakage-free by construction: no progression shape in
9
+ `test` appears in `train`/`validation` in any key or any task framing).
10
+ - **Prompts:** zero-shot, versioned in `prompts.py` (`PROMPT_VERSION`).
11
+ Scores are comparable only at equal prompt versions.
12
+ - **Decoding:** temperature 0. `run_model.py` defaults to this.
13
+
14
+ ## Running
15
+
16
+ ```bash
17
+ # any OpenAI-compatible endpoint (ollama, vLLM, LM Studio, OpenAI, OpenRouter)
18
+ python eval/run_model.py --config notes_to_rn --model <model> --out preds.jsonl
19
+ python eval/score.py preds.jsonl --config notes_to_rn --split test
20
+ ```
21
+
22
+ Both scripts are stdlib-only. Predictions are JSONL rows carrying
23
+ `shape_id` + `key` (joined against gold) and a `prediction` string.
24
+
25
+ ## Parsing (lenient wrapper, strict answer)
26
+
27
+ Before comparison the scorer:
28
+
29
+ - strips markdown code fences and surrounding prose (the answer is taken from
30
+ the **last** matching lines of the response);
31
+ - maps unicode music symbols to the dataset's ASCII conventions
32
+ (`♭→b`, `♯→#`, `°→o`, `ø→%`, superscript digits → digits);
33
+ - drops separator tokens between numerals (`–`, `|`, `,`, `·`, `->`).
34
+
35
+ It does **not** forgive wrong case (`i64` ≠ `I64` — minor vs major tonic is
36
+ the answer), wrong figures, or missing chords.
37
+
38
+ ## Metrics
39
+
40
+ | config | metrics |
41
+ |---|---|
42
+ | `*_to_rn` | `exact` (labels **and** cadence correct — headline), `labels_exact`, `chord_acc` (positional), `cadence_acc`, `parse_failures` |
43
+ | `key_id` | `exact` (headline), `tonic_acc`, `mode_acc`, `parse_failures` |
44
+
45
+ A record whose response cannot be parsed at all counts as wrong (and is
46
+ reported in `parse_failures` so prompt-format problems are visible rather
47
+ than silently penalized).
eval/prompts.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned zero-shot prompts for the Rameau benchmark.
2
+
3
+ Bump PROMPT_VERSION whenever any prompt text changes; scores are only
4
+ comparable at equal prompt versions.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ PROMPT_VERSION = "1"
9
+
10
+ _RN_FORMAT = """\
11
+ Respond with EXACTLY this format and nothing else:
12
+ <Roman numerals separated by single spaces>
13
+ cadence: <PAC|IAC|HC|DC|PC>
14
+ If the phrase does not end with a cadence, output only the Roman-numeral line.
15
+ Use DCML-style Roman numerals as in these examples: I, ii7, V65, viio6, IM7, V7/vi, ii%7, i64.
16
+ (%7 = half-diminished seventh, o = diminished, M7 = major seventh.)"""
17
+
18
+ _TASK_LINE = {
19
+ "symbol_to_rn": (
20
+ "Analyze the chord progression in the given key and provide the "
21
+ "Roman-numeral analysis of every chord, in order."
22
+ ),
23
+ "notes_to_rn": (
24
+ "Each chord is given as spelled notes, bass note first. Analyze the "
25
+ "progression in the given key and provide the Roman-numeral analysis "
26
+ "of every chord, in order."
27
+ ),
28
+ "pcset_to_rn": (
29
+ "Each chord is given as a list of pitch classes (0 = C, 1 = C#/Db, ... "
30
+ "11 = B), bass pitch class first. Analyze the progression in the given "
31
+ "key and provide the Roman-numeral analysis of every chord, in order."
32
+ ),
33
+ }
34
+
35
+ _KEY_ID_PROMPT = """\
36
+ You are analyzing tonal harmony in the common-practice style.
37
+ Each chord is given as spelled notes, bass note first. Identify the key of the phrase.
38
+ Respond with EXACTLY the key and nothing else, in the form: <Tonic> <major|minor>
39
+ Examples: C major / Eb major / F# minor
40
+
41
+ {input}"""
42
+
43
+ _RN_PROMPT = """\
44
+ You are analyzing tonal harmony in the common-practice style.
45
+ {task_line}
46
+ {format_block}
47
+
48
+ {input}"""
49
+
50
+
51
+ def build_prompt(config: str, input_text: str) -> str:
52
+ if config == "key_id":
53
+ return _KEY_ID_PROMPT.format(input=input_text)
54
+ if config in _TASK_LINE:
55
+ return _RN_PROMPT.format(
56
+ task_line=_TASK_LINE[config], format_block=_RN_FORMAT, input=input_text
57
+ )
58
+ raise ValueError(f"unknown config {config!r}")
eval/run_model.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Query a model on a Rameau config and write predictions for score.py.
2
+
3
+ Works against any OpenAI-compatible chat-completions endpoint (ollama, vLLM,
4
+ LM Studio, OpenAI, OpenRouter, ...). Stdlib only.
5
+
6
+ Usage:
7
+ python eval/run_model.py --config notes_to_rn --model qwen2.5:7b \\
8
+ --base-url http://localhost:11434/v1 --out preds.jsonl
9
+ python eval/score.py preds.jsonl --config notes_to_rn --split test
10
+
11
+ Gold records are read from the repo's data/ directory when present, so this
12
+ runs from a fresh `git clone` of the dataset repo with no extra dependencies.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+ import time
21
+ import urllib.error
22
+ import urllib.request
23
+ from concurrent.futures import ThreadPoolExecutor
24
+ from pathlib import Path
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
27
+ from prompts import PROMPT_VERSION, build_prompt # noqa: E402
28
+
29
+ REPO_ROOT = Path(__file__).resolve().parents[1]
30
+ RETRIES = 3
31
+
32
+
33
+ def load_records(config: str, split: str, data_dir: Path) -> list[dict]:
34
+ path = data_dir / config / f"{split}.jsonl"
35
+ if path.exists():
36
+ with open(path, encoding="utf-8") as fh:
37
+ return [json.loads(ln) for ln in fh if ln.strip()]
38
+ try: # fall back to the Hub if datasets is installed
39
+ from datasets import load_dataset
40
+ except ImportError:
41
+ raise SystemExit(f"{path} not found and `datasets` not installed")
42
+ return list(load_dataset("4esv/rameau", config, split=split))
43
+
44
+
45
+ def complete(base_url: str, api_key: str, model: str, prompt: str,
46
+ temperature: float, max_tokens: int) -> str:
47
+ body = json.dumps({
48
+ "model": model,
49
+ "messages": [{"role": "user", "content": prompt}],
50
+ "temperature": temperature,
51
+ "max_tokens": max_tokens,
52
+ }).encode()
53
+ req = urllib.request.Request(
54
+ base_url.rstrip("/") + "/chat/completions",
55
+ data=body,
56
+ headers={"Content-Type": "application/json",
57
+ "Authorization": f"Bearer {api_key}"},
58
+ )
59
+ last_err: Exception | None = None
60
+ for attempt in range(RETRIES):
61
+ try:
62
+ with urllib.request.urlopen(req, timeout=300) as resp:
63
+ data = json.load(resp)
64
+ return data["choices"][0]["message"]["content"]
65
+ except (urllib.error.URLError, KeyError, json.JSONDecodeError) as exc:
66
+ last_err = exc
67
+ time.sleep(2**attempt)
68
+ raise RuntimeError(f"request failed after {RETRIES} attempts: {last_err}")
69
+
70
+
71
+ def main() -> None:
72
+ ap = argparse.ArgumentParser(description=__doc__)
73
+ ap.add_argument("--config", required=True,
74
+ choices=["symbol_to_rn", "notes_to_rn", "pcset_to_rn", "key_id"])
75
+ ap.add_argument("--split", default="test", choices=["train", "validation", "test"])
76
+ ap.add_argument("--model", required=True)
77
+ ap.add_argument("--base-url", default=os.environ.get("OPENAI_BASE_URL",
78
+ "http://localhost:11434/v1"))
79
+ ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "none"))
80
+ ap.add_argument("--out", type=Path, required=True)
81
+ ap.add_argument("--data-dir", type=Path, default=REPO_ROOT / "data")
82
+ ap.add_argument("--limit", type=int, help="evaluate only the first N records")
83
+ ap.add_argument("--temperature", type=float, default=0.0)
84
+ ap.add_argument("--max-tokens", type=int, default=512)
85
+ ap.add_argument("--concurrency", type=int, default=4)
86
+ args = ap.parse_args()
87
+
88
+ records = load_records(args.config, args.split, args.data_dir)
89
+ if args.limit:
90
+ records = records[: args.limit]
91
+
92
+ def run_one(rec: dict) -> dict:
93
+ prompt = build_prompt(args.config, rec["input"])
94
+ try:
95
+ pred = complete(args.base_url, args.api_key, args.model, prompt,
96
+ args.temperature, args.max_tokens)
97
+ err = None
98
+ except RuntimeError as exc:
99
+ pred, err = "", str(exc)
100
+ return {
101
+ "shape_id": rec["shape_id"],
102
+ "key": rec["key"],
103
+ "prediction": pred,
104
+ **({"error": err} if err else {}),
105
+ "model": args.model,
106
+ "prompt_version": PROMPT_VERSION,
107
+ }
108
+
109
+ done = errors = 0
110
+ with ThreadPoolExecutor(max_workers=args.concurrency) as pool, \
111
+ open(args.out, "w", encoding="utf-8") as fh:
112
+ for row in pool.map(run_one, records):
113
+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")
114
+ done += 1
115
+ errors += "error" in row
116
+ if done % 50 == 0:
117
+ print(f"{done}/{len(records)}", file=sys.stderr)
118
+ print(f"wrote {done} predictions to {args.out}"
119
+ + (f" ({errors} request errors)" if errors else ""), file=sys.stderr)
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()
eval/score.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic scorer for Rameau predictions. Stdlib only — no dependencies.
2
+
3
+ Usage:
4
+ python eval/score.py preds.jsonl --config notes_to_rn --split test
5
+ python eval/score.py preds.jsonl --gold data/notes_to_rn/test.jsonl
6
+
7
+ Predictions file: JSONL, one object per record, with a "prediction" field.
8
+ If every object also carries "shape_id" and "key", records are joined on
9
+ (shape_id, key); otherwise predictions are matched to gold by line order.
10
+
11
+ Parsing is deliberately lenient about *wrapping* (markdown fences, prose
12
+ before the answer, unicode music symbols) and deliberately strict about the
13
+ *answer itself* (Roman numeral case and figures must match exactly).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import re
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ REPO_ROOT = Path(__file__).resolve().parents[1]
24
+
25
+ # unicode variants models like to emit -> dataset ASCII conventions
26
+ _UNICODE = {
27
+ "♭": "b", # flat sign
28
+ "♯": "#", # sharp sign
29
+ "°": "o", # degree (diminished)
30
+ "ø": "%", # slashed o (half-diminished)
31
+ "∅": "%", # empty set, occasionally used for half-diminished
32
+ "–": "-", "—": "-", # dashes
33
+ "⁰": "0", "¹": "1", "²": "2", "³": "3", "⁴": "4",
34
+ "⁵": "5", "⁶": "6", "⁷": "7", "⁸": "8", "⁹": "9",
35
+ }
36
+ _SEPARATORS = {"-", "|", ",", ";", "·", "->", "→"}
37
+ _CADENCE_RE = re.compile(r"cadence\s*[:=]\s*([A-Za-z]+)", re.IGNORECASE)
38
+ _KEY_RE = re.compile(r"([A-G](?:b{1,2}|#{1,2})?)[\s-]+(major|minor)", re.IGNORECASE)
39
+ _FENCE_RE = re.compile(r"^```[a-zA-Z]*\s*$")
40
+
41
+
42
+ def normalize(text: str) -> str:
43
+ for k, v in _UNICODE.items():
44
+ text = text.replace(k, v)
45
+ lines = [ln for ln in text.splitlines() if not _FENCE_RE.match(ln.strip())]
46
+ return "\n".join(lines).strip()
47
+
48
+
49
+ def parse_rn(text: str) -> tuple[list[str] | None, str | None]:
50
+ """Extract (labels, cadence) from a model response."""
51
+ text = normalize(text)
52
+ lines = [ln.strip().strip("`") for ln in text.splitlines() if ln.strip()]
53
+ if not lines:
54
+ return None, None
55
+
56
+ cadence = None
57
+ labels_line = None
58
+ cad_idx = None
59
+ for i in range(len(lines) - 1, -1, -1):
60
+ m = _CADENCE_RE.search(lines[i])
61
+ if m:
62
+ cadence = m.group(1).upper().rstrip(".")
63
+ cad_idx = i
64
+ break
65
+
66
+ if cad_idx is not None:
67
+ before = lines[cad_idx][: _CADENCE_RE.search(lines[cad_idx]).start()].strip()
68
+ if before: # single-line answer: "ii7 V7 I cadence: PAC"
69
+ labels_line = before
70
+ else:
71
+ for j in range(cad_idx - 1, -1, -1):
72
+ if lines[j]:
73
+ labels_line = lines[j]
74
+ break
75
+ else:
76
+ labels_line = lines[-1]
77
+
78
+ if not labels_line:
79
+ return None, cadence
80
+
81
+ tokens = []
82
+ for tok in labels_line.split():
83
+ tok = tok.strip("`,.;")
84
+ if not tok or tok in _SEPARATORS:
85
+ continue
86
+ tokens.append(tok)
87
+ return (tokens or None), cadence
88
+
89
+
90
+ def parse_key(text: str) -> str | None:
91
+ """Extract 'Tonic mode' from a model response (last match wins)."""
92
+ text = normalize(text)
93
+ last = None
94
+ for m in _KEY_RE.finditer(text):
95
+ tonic, mode = m.group(1), m.group(2)
96
+ last = f"{tonic[0].upper()}{tonic[1:].lower()} {mode.lower()}"
97
+ return last
98
+
99
+
100
+ def load_jsonl(path: Path) -> list[dict]:
101
+ with open(path, encoding="utf-8") as fh:
102
+ return [json.loads(ln) for ln in fh if ln.strip()]
103
+
104
+
105
+ def join(gold: list[dict], preds: list[dict]) -> list[tuple[dict, dict]]:
106
+ if preds and all("shape_id" in p and "key" in p for p in preds):
107
+ by_id = {(p["shape_id"], p["key"]): p for p in preds}
108
+ pairs = [(g, by_id[(g["shape_id"], g["key"])]) for g in gold
109
+ if (g["shape_id"], g["key"]) in by_id]
110
+ if len(pairs) < len(preds):
111
+ print(f"warning: {len(preds) - len(pairs)} predictions matched no gold record",
112
+ file=sys.stderr)
113
+ return pairs
114
+ if len(preds) != len(gold):
115
+ raise SystemExit(
116
+ f"positional join needs equal counts (gold {len(gold)}, preds {len(preds)}); "
117
+ "or include shape_id+key in each prediction"
118
+ )
119
+ return list(zip(gold, preds))
120
+
121
+
122
+ def score_rn(pairs: list[tuple[dict, dict]]) -> dict:
123
+ n = len(pairs)
124
+ exact = labels_exact = cad_ok = parse_fail = 0
125
+ chord_hits = chord_total = 0
126
+ for g, p in pairs:
127
+ labels, cadence = parse_rn(p.get("prediction") or "")
128
+ if labels is None:
129
+ parse_fail += 1
130
+ gl = g["labels"]
131
+ l_ok = labels == gl
132
+ c_ok = cadence == g["cadence"] # both None counts as correct
133
+ labels_exact += l_ok
134
+ cad_ok += c_ok
135
+ exact += l_ok and c_ok
136
+ chord_total += len(gl)
137
+ if labels:
138
+ chord_hits += sum(a == b for a, b in zip(labels, gl))
139
+ return {
140
+ "n": n,
141
+ "exact": round(exact / n, 4),
142
+ "labels_exact": round(labels_exact / n, 4),
143
+ "chord_acc": round(chord_hits / chord_total, 4),
144
+ "cadence_acc": round(cad_ok / n, 4),
145
+ "parse_failures": parse_fail,
146
+ }
147
+
148
+
149
+ def score_key(pairs: list[tuple[dict, dict]]) -> dict:
150
+ n = len(pairs)
151
+ exact = tonic_ok = mode_ok = parse_fail = 0
152
+ for g, p in pairs:
153
+ pred = parse_key(p.get("prediction") or "")
154
+ if pred is None:
155
+ parse_fail += 1
156
+ continue
157
+ gt, gm = g["target"].rsplit(" ", 1)
158
+ pt, pm = pred.rsplit(" ", 1)
159
+ exact += pred == g["target"]
160
+ tonic_ok += pt == gt
161
+ mode_ok += pm == gm
162
+ return {
163
+ "n": n,
164
+ "exact": round(exact / n, 4),
165
+ "tonic_acc": round(tonic_ok / n, 4),
166
+ "mode_acc": round(mode_ok / n, 4),
167
+ "parse_failures": parse_fail,
168
+ }
169
+
170
+
171
+ def main() -> None:
172
+ ap = argparse.ArgumentParser(description=__doc__)
173
+ ap.add_argument("predictions", type=Path)
174
+ ap.add_argument("--config", choices=["symbol_to_rn", "notes_to_rn", "pcset_to_rn", "key_id"])
175
+ ap.add_argument("--split", default="test", choices=["train", "validation", "test"])
176
+ ap.add_argument("--gold", type=Path, help="explicit gold JSONL (overrides --config/--split)")
177
+ args = ap.parse_args()
178
+
179
+ if args.gold:
180
+ gold_path = args.gold
181
+ config = args.config or gold_path.parent.name
182
+ elif args.config:
183
+ gold_path = REPO_ROOT / "data" / args.config / f"{args.split}.jsonl"
184
+ config = args.config
185
+ else:
186
+ raise SystemExit("need --config or --gold")
187
+
188
+ gold = load_jsonl(gold_path)
189
+ preds = load_jsonl(args.predictions)
190
+ pairs = join(gold, preds)
191
+ metrics = score_key(pairs) if config == "key_id" else score_rn(pairs)
192
+ print(json.dumps({"config": config, "split": args.split, **metrics}, indent=2))
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()
pyproject.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "harmony-dataset"
3
+ version = "0.1.0"
4
+ description = "Synthetic functional-harmony text-to-text dataset: grammar-generated progressions, music21-verified DCML labels"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "4esv", email = "axel@aesv.io" }
8
+ ]
9
+ requires-python = ">=3.14"
10
+ dependencies = [
11
+ "datasets>=5.0.0",
12
+ "music21>=10.5.0",
13
+ "pytest>=9.1.1",
14
+ ]
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.8.22,<0.9.0"]
18
+ build-backend = "uv_build"
scripts/push_to_hub.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Push the dataset repo to the Hub: uv run python scripts/push_to_hub.py
2
+
3
+ Publishes everything needed to load, audit, and reproduce the dataset.
4
+ BRIEF.md (internal seed notes) stays local.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ from huggingface_hub import HfApi
11
+
12
+ REPO_ID = "4esv/rameau"
13
+ REPO_ROOT = Path(__file__).resolve().parents[1]
14
+
15
+ IGNORE = [
16
+ "BRIEF.md",
17
+ ".git*",
18
+ ".venv/**",
19
+ "**/__pycache__/**",
20
+ ".pytest_cache/**",
21
+ ".ruff_cache/**",
22
+ ".DS_Store",
23
+ ]
24
+
25
+
26
+ def main() -> None:
27
+ api = HfApi()
28
+ user = api.whoami()["name"]
29
+ assert user == REPO_ID.split("/")[0], f"logged in as {user!r}, expected {REPO_ID}"
30
+ api.create_repo(REPO_ID, repo_type="dataset", exist_ok=True)
31
+ info = api.upload_folder(
32
+ repo_id=REPO_ID,
33
+ repo_type="dataset",
34
+ folder_path=REPO_ROOT,
35
+ ignore_patterns=IGNORE,
36
+ commit_message="Rameau v1: 21,940 records, 4 configs, verified gold, eval harness",
37
+ )
38
+ print(f"pushed: https://huggingface.co/datasets/{REPO_ID}\ncommit: {info.oid}")
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
src/harmony_dataset/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic functional-harmony dataset generator.
2
+
3
+ Grammar-generated chord progressions with constructive DCML Roman-numeral
4
+ labels, verified by a dual-derivation gold gate (music21), framed as multiple
5
+ text-to-text tasks. See export.main() for the entry point.
6
+ """
7
+ from .vocabulary import Analysis
8
+ from .cadence import classify_cadence
9
+ from .grammar import generate_phrases
10
+ from .generator import build_pool, generate
11
+ from .verify import verify_chord
12
+
13
+ __all__ = ["Analysis", "classify_cadence", "generate_phrases", "build_pool",
14
+ "generate", "verify_chord"]
src/harmony_dataset/cadence.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cadence classification into DCML cadence codes.
2
+
3
+ music21 ships no cadence detector (only building blocks), so this is ours. It
4
+ looks at the last two chords of an Analysis sequence and classifies the terminal
5
+ cadence:
6
+
7
+ PAC perfect authentic V(7) -> I/i, both root position
8
+ IAC imperfect authentic V(7) -> I/i, dominant or tonic inverted
9
+ HC half phrase ends on a root-position diatonic V *triad*
10
+ (a terminal V7 demands resolution and is not an HC)
11
+ PC plagal IV/iv -> I/i
12
+ DC deceptive root-position V(7) -> vi/VI (an inverted dominant's
13
+ bass must resolve to the tonic, so V65 -> vi is a
14
+ voice-leading error, not a deceptive cadence)
15
+ None no terminal cadence
16
+
17
+ Simplification: with synthetic root-position chord symbols we have no soprano
18
+ voice, so PAC vs IAC is decided by inversion rather than by melodic closure.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Optional
23
+
24
+ from .vocabulary import Analysis
25
+
26
+ _TONIC = frozenset({"I", "i"})
27
+ _DOMINANT = frozenset({"V"})
28
+ _SUBDOMINANT = frozenset({"IV", "iv"})
29
+ _SUBMEDIANT = frozenset({"vi", "VI"})
30
+
31
+ # figbass values that denote a root-position chord (triad '' or root seventh '7')
32
+ _ROOT_POSITION = frozenset({"", "7"})
33
+
34
+
35
+ def _is_diatonic(a: Analysis) -> bool:
36
+ return a.relativeroot is None
37
+
38
+
39
+ def _is_root_position(a: Analysis) -> bool:
40
+ return a.figbass in _ROOT_POSITION
41
+
42
+
43
+ def _is(a: Analysis, degrees: frozenset[str]) -> bool:
44
+ return _is_diatonic(a) and a.numeral in degrees
45
+
46
+
47
+ def classify_cadence(seq: list[Analysis]) -> Optional[str]:
48
+ if len(seq) < 2:
49
+ return None
50
+ penult, last = seq[-2], seq[-1]
51
+
52
+ if _is(last, _TONIC):
53
+ if _is(penult, _DOMINANT):
54
+ return "PAC" if _is_root_position(penult) and _is_root_position(last) else "IAC"
55
+ if _is(penult, _SUBDOMINANT):
56
+ return "PC"
57
+ return None
58
+
59
+ if _is(last, _SUBMEDIANT) and _is(penult, _DOMINANT) and _is_root_position(penult):
60
+ return "DC"
61
+
62
+ if _is(last, _DOMINANT) and last.figbass == "":
63
+ return "HC"
64
+
65
+ return None
src/harmony_dataset/export.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble the dataset on disk: one config per task, three splits each, plus a
2
+ draft dataset card and a verification report.
3
+
4
+ Run: ``uv run python -m harmony_dataset.export``. Nothing here pushes to the Hub.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from collections import Counter, defaultdict
10
+ from pathlib import Path
11
+
12
+ from . import tasks
13
+ from .generator import GenResult, generate
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parents[2]
16
+ DATA_DIR = REPO_ROOT / "data"
17
+ SPLITS = ("train", "validation", "test")
18
+ DEFAULT_CONFIG = "notes_to_rn"
19
+
20
+ TASK_BLURB = {
21
+ "symbol_to_rn": "key + chord symbols -> Roman numerals + cadence (easy: chord quality is given)",
22
+ "notes_to_rn": "key + spelled notes -> Roman numerals + cadence (must read each chord)",
23
+ "pcset_to_rn": "key + bass-first pitch-class lists -> Roman numerals + cadence (no spelling)",
24
+ "key_id": "spelled notes, no key -> identify the key (only key-unambiguous phrases)",
25
+ }
26
+ CADENCE_GLOSS = {
27
+ "PAC": "perfect authentic", "IAC": "imperfect authentic", "HC": "half",
28
+ "DC": "deceptive", "PC": "plagal",
29
+ }
30
+
31
+
32
+ def bucket(res: GenResult) -> dict[tuple[str, str], list[dict]]:
33
+ out: dict[tuple[str, str], list[dict]] = defaultdict(list)
34
+ for r in res.records:
35
+ out[(r.data["task"], r.split)].append(r.data)
36
+ # stable order within each file
37
+ for recs in out.values():
38
+ recs.sort(key=lambda d: (d["shape_id"], d["key"]))
39
+ return out
40
+
41
+
42
+ def write_jsonl(records: list[dict], path: Path) -> None:
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ with path.open("w", encoding="utf-8") as fh:
45
+ for d in records:
46
+ fh.write(json.dumps(d, ensure_ascii=False) + "\n")
47
+
48
+
49
+ def _configs_yaml() -> str:
50
+ lines = ["configs:"]
51
+ for task in tasks.TASKS:
52
+ lines.append(f" - config_name: {task}")
53
+ if task == DEFAULT_CONFIG:
54
+ lines.append(" default: true")
55
+ lines.append(" data_files:")
56
+ for split in SPLITS:
57
+ lines.append(f" - split: {split}")
58
+ lines.append(f" path: data/{task}/{split}.jsonl")
59
+ return "\n".join(lines)
60
+
61
+
62
+ def render_card(res: GenResult, buckets: dict) -> str:
63
+ total = len(res.records)
64
+ per_task = Counter(r.data["task"] for r in res.records)
65
+ per_split = Counter(r.split for r in res.records)
66
+ size_cat = "10K<n<100K" if 10_000 <= total < 100_000 else "1K<n<10K" if total >= 1_000 else "n<1K"
67
+ task_rows = "\n".join(
68
+ f"| `{t}` | {TASK_BLURB[t]} | {per_task[t]} |" for t in tasks.TASKS
69
+ )
70
+ return f"""---
71
+ pretty_name: "Rameau: Functional Harmony from Notation (Roman Numerals, Cadence, Key)"
72
+ license: cc-by-4.0
73
+ language:
74
+ - en
75
+ task_categories:
76
+ - text2text-generation
77
+ tags:
78
+ - music
79
+ - music-theory
80
+ - functional-harmony
81
+ - roman-numeral-analysis
82
+ - chord-progression
83
+ - cadence
84
+ - key-detection
85
+ - benchmark
86
+ - synthetic
87
+ size_categories:
88
+ - {size_cat}
89
+ annotations_creators:
90
+ - machine-generated
91
+ source_datasets:
92
+ - original
93
+ {_configs_yaml()}
94
+ ---
95
+
96
+ # Rameau: functional harmony from notation
97
+
98
+ A **text-to-text** dataset and benchmark for functional-harmony understanding in
99
+ music notation: Roman-numeral analysis, cadence classification, and key
100
+ identification. Progressions are generated by a probabilistic common-practice
101
+ grammar and framed as four tasks of increasing difficulty — the harder tasks
102
+ **hide the answer**, so the data tests harmonic reasoning, not chord-symbol lookup.
103
+
104
+ Named for Jean-Philippe Rameau, whose *Traité de l'harmonie* (1722) founded the
105
+ theory of functional harmony this dataset teaches.
106
+
107
+ ```
108
+ symbol_to_rn key: C major / progression: Dm7 G7 Cmaj7 -> ii7 V7 IM7 / cadence: PAC
109
+ notes_to_rn key: C major / notes: D4 F4 A4 C5 | ... -> ii7 V7 IM7 / cadence: PAC
110
+ pcset_to_rn key: C major / pitch classes: [2 5 9 0]|... -> ii7 V7 IM7 / cadence: PAC
111
+ key_id notes: D4 F4 A4 C5 | G3 B3 D4 F4 | ... -> C major
112
+ ```
113
+
114
+ ## Configs (tasks)
115
+
116
+ Load one with `load_dataset("4esv/rameau", "<config>")`. Default: `{DEFAULT_CONFIG}`.
117
+
118
+ | config | task | rows |
119
+ |---|---|---|
120
+ {task_rows}
121
+ | | **total** | **{total}** |
122
+
123
+ ## How the gold labels are generated (and why they are trustworthy)
124
+
125
+ Labels are **not hand-annotated**. A probabilistic functional grammar
126
+ (tonic -> predominant -> dominant -> cadence, with sevenths, inversions,
127
+ cadential 6-4s and secondary dominants) generates each progression *together with*
128
+ its intended Roman-numeral analysis. Every chord is then checked two independent
129
+ ways with [`music21`](https://web.mit.edu/music21/):
130
+
131
+ - the Roman-numeral label rendered to pitch classes by the roman engine;
132
+ - the printed chord symbol parsed to pitch classes by the chord-symbol parser;
133
+
134
+ and the item is kept only if the two agree on pitch content **and** bass. On this
135
+ release: **{res.chord_agreement_rate:.2%}** chord-level agreement
136
+ ({res.attempted_chords - len(res.failures)}/{res.attempted_chords} chords;
137
+ {res.instances - res.dropped_instances}/{res.instances} instances kept). See `VERIFY.md`.
138
+
139
+ Built from **{res.shapes} distinct progression shapes** (key-independent), transposed
140
+ across keys. All content is synthetic; no third-party corpus is redistributed.
141
+
142
+ ## Label convention
143
+
144
+ Roman numerals follow the **DCML harmony standard**'s feature decomposition
145
+ (`numeral` / `form` / `figbass` / `changes` / `relativeroot`), spec at
146
+ <https://github.com/DCMLab/standards> — we conform to the notation, we do not copy
147
+ DCML data. Major-seventh tonic is `IM7`; secondary dominants use `/` (e.g. `V7/vi`).
148
+ Cadence codes: {", ".join(f"`{k}` {v}" for k, v in CADENCE_GLOSS.items())}.
149
+
150
+ ## Fields
151
+
152
+ Common to every config: `input`, `target`, `key`, `mode`, `labels`, `cadence`,
153
+ `analysis` (per-chord DCML features), `source` (`grammar`/`curated`/`single`),
154
+ `category`, `shape_id`. Plus the input representation for the config: `chords`
155
+ (symbols), `notes` (spelled, bass-first), or `pitch_classes` (bass-first).
156
+
157
+ Accidentals are written the standard way (`Bb`, `F#`, `Cb`). Note for music21
158
+ users: its parsers want `-` for flats — convert `b -> -` in note/root names
159
+ before calling `ChordSymbol` or `Pitch`.
160
+
161
+ ## Splits (leakage-free; test doubles as a benchmark)
162
+
163
+ The atomic unit is a **shape** (a key-independent Roman-numeral sequence). Each
164
+ shape is hashed to exactly one split, so a shape — and all of its transpositions
165
+ **and all of its task framings** — never crosses splits. Split sizes (rows):
166
+ train {per_split['train']} / validation {per_split['validation']} / test {per_split['test']}.
167
+
168
+ ## Known limitations
169
+
170
+ - **Synthetic distribution.** Grammar-generated common-practice progressions, not
171
+ sampled from real repertoire; the chord distribution is not naturalistic.
172
+ - **PAC vs IAC** is decided by inversion (no notated soprano voice). Cadence rules
173
+ are strict: an HC must end on a root-position V *triad* (a terminal V7 is not
174
+ labelled), and a DC requires a root-position dominant (`V65 -> vi` is not one).
175
+ - **key_id** includes only cadence-terminated progressions of >= 3 chords whose
176
+ notes contain both key-defining degrees (scale degree 4 and the leading tone),
177
+ so the key is uniquely determined. Without this gate, gold labels can be
178
+ contestable — e.g. `I V7/V V` in C is note-identical to `IV V7 I` in G, and the
179
+ G-major reading (a PAC) is arguably stronger. Such phrases are excluded.
180
+ - Harmony only — no voice-leading, melody, or rhythm. No modal mixture / Neapolitan
181
+ / augmented sixths yet.
182
+
183
+ ## Evaluation
184
+
185
+ The `test` split is a benchmark: gold is deterministic, so scoring is **exact
186
+ match — no LLM judge**. The repo ships a self-contained harness under `eval/`:
187
+
188
+ ```bash
189
+ # query any OpenAI-compatible endpoint (ollama, vLLM, OpenAI, ...):
190
+ python eval/run_model.py --config notes_to_rn --model <model> --out preds.jsonl
191
+ # score predictions (stdlib only):
192
+ python eval/score.py preds.jsonl --config notes_to_rn --split test
193
+ ```
194
+
195
+ Metrics: `exact` (Roman numerals **and** cadence correct — the headline number),
196
+ `labels_exact`, `chord_acc` (positional), `cadence_acc`; for `key_id`: `exact`,
197
+ `tonic_acc`, `mode_acc`. The zero-shot prompts are versioned in
198
+ `eval/prompts.py`; parsing rules are documented in `eval/README.md`.
199
+
200
+ ## Reproduce
201
+
202
+ The full generation pipeline ships in this repo (`src/harmony_dataset/`):
203
+
204
+ ```bash
205
+ uv sync && uv run pytest # full suite, incl. the eval harness
206
+ uv run python -m harmony_dataset.export # regenerates data/, README, VERIFY.md
207
+ ```
208
+
209
+ ## Licensing
210
+
211
+ **CC-BY-4.0.** Content is generated by this repository's pipeline from music theory;
212
+ the underlying facts are not copyrightable and no source corpus is redistributed.
213
+
214
+ ## Citation
215
+
216
+ ```
217
+ @misc{{rameau,
218
+ title = {{Rameau: Functional Harmony from Notation (Roman Numerals, Cadence, Key)}},
219
+ author = {{Stevens, Axel}},
220
+ year = {{2026}},
221
+ url = {{https://huggingface.co/datasets/4esv/rameau}},
222
+ note = {{Synthetic, grammar-generated, music21-verified, DCML-convention labels}}
223
+ }}
224
+ ```
225
+ """
226
+
227
+
228
+ def render_verify(res: GenResult) -> str:
229
+ L: list[str] = ["# Verification report\n", "## Gold gate (dual-derivation agreement)\n",
230
+ "| metric | value |", "|---|---|",
231
+ f"| distinct shapes | {res.shapes} |",
232
+ f"| instances (shape x key) | {res.instances} |",
233
+ f"| instances dropped | {res.dropped_instances} |",
234
+ f"| chords attempted | {res.attempted_chords} |",
235
+ f"| chord disagreements | {len(res.failures)} |",
236
+ f"| **chord agreement rate** | **{res.chord_agreement_rate:.3%}** |",
237
+ f"| total records | {len(res.records)} |\n"]
238
+
239
+ per_source = Counter(r.data["source"] for r in res.records)
240
+ per_cadence = Counter(r.data["cadence"] for r in res.records)
241
+ L += ["## Distribution\n", f"- by source: {dict(per_source)}",
242
+ f"- by cadence: {dict(per_cadence)}\n"]
243
+
244
+ if res.failures:
245
+ L += ["## Dropped chords\n", "| shape | key | figure | symbol | reason |", "|---|---|---|---|---|"]
246
+ for f in res.failures[:50]:
247
+ c = f.check
248
+ L.append(f"| {f.shape_id} | {f.key} | `{c.figure}` | `{c.symbol}` | {c.reason} |")
249
+ L.append("")
250
+
251
+ # the brief example across all four task framings
252
+ L.append("## Same progression, four framings (brief example in C major)\n")
253
+ brief = [r.data for r in res.records
254
+ if r.data["shape_id"] == _shape_id_of(res, ["ii7", "V7", "IM7"])
255
+ and r.data["key"] == "C major"]
256
+ for d in sorted(brief, key=lambda d: tasks.TASKS.index(d["task"])):
257
+ L.append(f"- **{d['task']}**")
258
+ L.append(f" - in: `{d['input'].replace(chr(10), ' // ')}`")
259
+ L.append(f" - out: `{d['target'].replace(chr(10), ' // ')}`")
260
+ L.append("")
261
+
262
+ # a spread of grammar phrases (notes_to_rn framing, reference key)
263
+ L.append("## Grammar phrases (notes_to_rn, in C major / A minor)\n")
264
+ shown = 0
265
+ for r in sorted(res.records, key=lambda r: r.data["shape_id"]):
266
+ d = r.data
267
+ if d["task"] != "notes_to_rn" or d["source"] != "grammar":
268
+ continue
269
+ if d["key"] not in ("C major", "A minor"):
270
+ continue
271
+ cad = d["cadence"] or "-"
272
+ L.append(f"- `{d['key']}` {d['input'].split('notes: ')[1]}")
273
+ L.append(f" -> `{' '.join(d['labels'])}` ({cad})")
274
+ shown += 1
275
+ if shown >= 12:
276
+ break
277
+ L.append("")
278
+ return "\n".join(L)
279
+
280
+
281
+ def _shape_id_of(res: GenResult, labels: list[str]) -> str:
282
+ for r in res.records:
283
+ if r.data["labels"] == labels:
284
+ return r.data["shape_id"]
285
+ return ""
286
+
287
+
288
+ def main(out_dir: Path = REPO_ROOT) -> GenResult:
289
+ res = generate()
290
+ buckets = bucket(res)
291
+ for (task, split), recs in buckets.items():
292
+ write_jsonl(recs, out_dir / "data" / task / f"{split}.jsonl")
293
+ (out_dir / "README.md").write_text(render_card(res, buckets), encoding="utf-8")
294
+ (out_dir / "VERIFY.md").write_text(render_verify(res), encoding="utf-8")
295
+ print(f"wrote {len(res.records)} records across {len(tasks.TASKS)} configs "
296
+ f"from {res.shapes} shapes; chord agreement {res.chord_agreement_rate:.3%}")
297
+ return res
298
+
299
+
300
+ if __name__ == "__main__":
301
+ main()
src/harmony_dataset/generator.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the full dataset: a pool of distinct progression shapes (curated anchors
2
+ + grammar-generated phrases), transposed across keys, gold-gated, and framed as
3
+ multiple tasks.
4
+
5
+ Leakage control: the atomic unit is a **shape** — a key-independent tuple of
6
+ Roman-numeral labels. Each shape is hashed to exactly one split, so no shape (and
7
+ none of its transpositions, and none of its task framings) ever crosses splits.
8
+ The hash is stable (sha1), so splits are reproducible.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ from dataclasses import dataclass, field
14
+ from functools import lru_cache
15
+ from typing import Optional
16
+
17
+ from music21 import key
18
+
19
+ from . import tasks
20
+ from .cadence import classify_cadence
21
+ from .grammar import generate_phrases
22
+ from .vocabulary import (
23
+ Analysis,
24
+ MAJOR_KEYS,
25
+ MINOR_KEYS,
26
+ bass_first_pcs_from_figure,
27
+ chord_symbol_from_figure,
28
+ spelled_notes_from_figure,
29
+ )
30
+ from .verify import ChordCheck, verify_chord
31
+
32
+ # how many grammar phrases to draw per mode, and how many keys to transpose a
33
+ # multi-chord shape into (single chords always go to all 12).
34
+ N_PHRASES_PER_MODE = 400
35
+ KEYS_PER_SHAPE = 6
36
+ SEED = 20260709
37
+
38
+
39
+ def _spec(*s: str) -> tuple[Analysis, ...]:
40
+ return tuple(Analysis.parse(x) for x in s)
41
+
42
+
43
+ # Curated anchors: pedagogically important progressions worth guaranteeing.
44
+ _CURATED: list[tuple[str, str, tuple[Analysis, ...]]] = [
45
+ ("major", "cadence", _spec("ii7", "V7", "IM7")), # the brief's jazz ii-V-I
46
+ ("major", "cadence", _spec("ii7", "V7", "I")),
47
+ ("major", "common", _spec("I", "IV", "V", "I")),
48
+ ("major", "common", _spec("I", "vi", "IV", "V")),
49
+ ("major", "common", _spec("I", "V", "vi", "IV")),
50
+ ("major", "secondary", _spec("I", "V7/vi", "vi", "ii7", "V7", "I")),
51
+ ("minor", "common", _spec("i", "VII", "VI", "V")), # Andalusian
52
+ ("minor", "cadence", _spec("iio6", "V7", "i")),
53
+ ("minor", "common", _spec("i", "iv", "V", "i")),
54
+ ]
55
+
56
+ # Single-chord vocabulary coverage (length-1 shapes).
57
+ _SINGLE_MAJOR = ["I", "ii", "iii", "IV", "V", "vi", "viio",
58
+ "IM7", "ii7", "iii7", "IVM7", "V7", "vi7", "vii%7",
59
+ "I6", "I64", "V6", "V65", "V43", "V2", "ii6"]
60
+ _SINGLE_MINOR = ["i", "iio", "III", "iv", "V", "VI", "viio",
61
+ "i7", "ii%7", "iv7", "V7", "VIM7", "viio7",
62
+ "i6", "i64", "V6", "V65", "V43", "iio6"]
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Shape:
67
+ mode: str
68
+ category: str
69
+ source: str # 'curated' | 'grammar' | 'single'
70
+ analyses: tuple[Analysis, ...]
71
+
72
+ @property
73
+ def labels(self) -> tuple[str, ...]:
74
+ return tuple(a.dcml_label() for a in self.analyses)
75
+
76
+ @property
77
+ def shape_id(self) -> str:
78
+ raw = f"{self.mode}|{','.join(self.labels)}"
79
+ return hashlib.sha1(raw.encode()).hexdigest()[:10]
80
+
81
+ @property
82
+ def split(self) -> str:
83
+ bucket = int(self.shape_id, 16) % 100
84
+ return "train" if bucket < 70 else "validation" if bucket < 85 else "test"
85
+
86
+
87
+ @lru_cache(maxsize=1)
88
+ def build_pool() -> list[Shape]:
89
+ """Distinct shapes: curated anchors, single chords, grammar phrases. Deduped."""
90
+ pool: list[Shape] = []
91
+ seen: set[tuple[str, tuple[str, ...]]] = set()
92
+
93
+ def add(shape: Shape) -> None:
94
+ k = (shape.mode, shape.labels)
95
+ if k not in seen:
96
+ seen.add(k)
97
+ pool.append(shape)
98
+
99
+ for mode, cat, analyses in _CURATED:
100
+ add(Shape(mode, cat, "curated", analyses))
101
+ for spec in _SINGLE_MAJOR:
102
+ add(Shape("major", "single", "single", _spec(spec)))
103
+ for spec in _SINGLE_MINOR:
104
+ add(Shape("minor", "single", "single", _spec(spec)))
105
+ for mode in ("major", "minor"):
106
+ for phrase in generate_phrases(mode, N_PHRASES_PER_MODE, seed=SEED):
107
+ add(Shape(mode, "phrase", "grammar", tuple(phrase)))
108
+ return pool
109
+
110
+
111
+ def _keys_for(shape: Shape) -> list[str]:
112
+ keys = MAJOR_KEYS if shape.mode == "major" else MINOR_KEYS
113
+ if len(shape.analyses) == 1:
114
+ return keys
115
+ # always include the reference key (C major / A minor) so canonical shapes
116
+ # appear in their home key, then a hash-spread sample of others.
117
+ ref = "C" if shape.mode == "major" else "a"
118
+ offset = int(shape.shape_id, 16) % 12
119
+ idxs = sorted({(offset + i * 5) % 12 for i in range(KEYS_PER_SHAPE)})
120
+ ordered = [ref] + [keys[i] for i in idxs if keys[i] != ref]
121
+ return ordered
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class Record:
126
+ data: dict
127
+ split: str
128
+
129
+
130
+ @dataclass
131
+ class Failure:
132
+ shape_id: str
133
+ key: str
134
+ check: ChordCheck
135
+
136
+
137
+ @dataclass
138
+ class GenResult:
139
+ records: list[Record] = field(default_factory=list)
140
+ failures: list[Failure] = field(default_factory=list)
141
+ shapes: int = 0
142
+ instances: int = 0
143
+ dropped_instances: int = 0
144
+ attempted_chords: int = 0
145
+
146
+ @property
147
+ def chord_agreement_rate(self) -> float:
148
+ if self.attempted_chords == 0:
149
+ return 1.0
150
+ return (self.attempted_chords - len(self.failures)) / self.attempted_chords
151
+
152
+
153
+ def _instantiate(shape: Shape, key_name: str) -> Optional[dict]:
154
+ """Render a shape in a key and gold-gate it. Returns representation data or None."""
155
+ K = key.Key(key_name)
156
+ symbols, notes, pcs, checks = [], [], [], []
157
+ for a in shape.analyses:
158
+ fig = a.music21_figure()
159
+ sym = chord_symbol_from_figure(fig, K)
160
+ checks.append(verify_chord(a, sym, K))
161
+ symbols.append(sym.replace("-", "b"))
162
+ notes.append(spelled_notes_from_figure(fig, K))
163
+ pcs.append(bass_first_pcs_from_figure(fig, K))
164
+ if not all(c.ok for c in checks):
165
+ return {"_failed": [c for c in checks if not c.ok]}
166
+ return {
167
+ "key": f"{K.tonic.name.replace('-', 'b')} {K.mode}",
168
+ "symbols": symbols, "notes": notes, "pcs": pcs,
169
+ }
170
+
171
+
172
+ @lru_cache(maxsize=1)
173
+ def generate() -> GenResult:
174
+ res = GenResult()
175
+ pool = build_pool()
176
+ res.shapes = len(pool)
177
+ for shape in pool:
178
+ labels = list(shape.labels)
179
+ cadence = classify_cadence(list(shape.analyses))
180
+ analysis_dicts = [a.to_dict() for a in shape.analyses]
181
+ for key_name in _keys_for(shape):
182
+ res.instances += 1
183
+ res.attempted_chords += len(shape.analyses)
184
+ data = _instantiate(shape, key_name)
185
+ if data is None or "_failed" in data:
186
+ res.dropped_instances += 1
187
+ for c in (data or {}).get("_failed", []):
188
+ res.failures.append(Failure(shape.shape_id, key_name, c))
189
+ continue
190
+ for task in tasks.TASKS:
191
+ r = tasks.render(
192
+ task, key=data["key"], symbols=data["symbols"],
193
+ notes=data["notes"], pcs=data["pcs"], labels=labels, cadence=cadence,
194
+ )
195
+ if r is None:
196
+ continue
197
+ record = {
198
+ "task": r.task,
199
+ "input": r.input,
200
+ "target": r.target,
201
+ "key": data["key"],
202
+ "mode": shape.mode,
203
+ "labels": labels,
204
+ "cadence": cadence,
205
+ "analysis": analysis_dicts,
206
+ "source": shape.source,
207
+ "category": shape.category,
208
+ "shape_id": shape.shape_id,
209
+ **r.extra,
210
+ }
211
+ res.records.append(Record(record, shape.split))
212
+ return res
src/harmony_dataset/grammar.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A probabilistic functional-harmony grammar.
2
+
3
+ Rather than a fixed list of textbook progressions, this assembles phrases from
4
+ functional zones — opening (tonic) -> predominant -> dominant -> cadence — with
5
+ weighted choices at each step, plus sevenths, inversions, cadential 6-4s, and
6
+ secondary dominants. It is a Markov-style generative grammar constrained to
7
+ common-practice syntax, so every phrase is musically shaped, cadence-terminated
8
+ (key-pinning), and — by construction — labelled correctly.
9
+
10
+ All chord specs are drawn from a set pre-verified against the gold gate, so the
11
+ grammar never emits a chord whose Roman-numeral label disagrees with its pitches.
12
+ Deterministic under a seed.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import random
17
+ from typing import Optional
18
+
19
+ from .vocabulary import Analysis
20
+
21
+ # Each option is (list-of-specs, weight). Specs are compact DCML labels parsed by
22
+ # Analysis.parse. An empty predominant list yields direct I-V-I motion.
23
+ _CONFIG = {
24
+ "major": {
25
+ "tonic": "I",
26
+ "submediant": "vi",
27
+ "openings": [
28
+ (["I"], 6), (["I", "I6"], 1), (["I", "vi"], 2),
29
+ (["I", "iii", "vi"], 1), (["I", "V6", "I"], 1), (["I6"], 1),
30
+ ],
31
+ "predominants": [
32
+ ([], 2), (["IV"], 4), (["ii"], 3), (["ii7"], 3), (["ii6"], 2), (["ii65"], 2),
33
+ (["IV", "ii6"], 1), (["vi", "ii7"], 1), (["vi", "IV"], 1), (["I6", "IV"], 1),
34
+ (["V7/V"], 1), (["V7/ii", "ii7"], 1), (["V7/IV", "IV"], 1), (["V7/vi", "vi", "ii7"], 1),
35
+ ],
36
+ "dominants": [
37
+ (["V"], 2), (["V7"], 4), (["V65"], 1), (["I64", "V7"], 2), (["I64", "V"], 1),
38
+ (["viio6", "V7"], 1), (["V7/V", "V7"], 1),
39
+ ],
40
+ # half cadences end on a V *triad*; deceptive resolutions need the
41
+ # dominant in root position (see cadence.py) — hence the separate lists.
42
+ "dominants_half": [(["V"], 4), (["I64", "V"], 2), (["V7/V", "V"], 1)],
43
+ "dominants_deceptive": [(["V7"], 4), (["V"], 2), (["I64", "V7"], 2), (["viio6", "V7"], 1)],
44
+ "plagal_predominants": [(["IV"], 3), (["ii6", "IV"], 1), (["I6", "IV"], 1)],
45
+ "resolutions": [(["I"], 6), (["I6"], 1)],
46
+ },
47
+ "minor": {
48
+ "tonic": "i",
49
+ "submediant": "VI",
50
+ "openings": [
51
+ (["i"], 6), (["i", "i6"], 1), (["i", "VI"], 2), (["i", "III"], 1), (["i6"], 1),
52
+ ],
53
+ "predominants": [
54
+ ([], 2), (["iv"], 4), (["iio6"], 3), (["ii%7"], 2), (["iv6"], 2),
55
+ (["VI", "iv"], 1), (["iv", "iio6"], 1), (["III", "iv"], 1),
56
+ (["V7/V"], 1), (["V7/iv", "iv"], 1), (["V7/VI", "VI", "iio6"], 1),
57
+ ],
58
+ "dominants": [
59
+ (["V"], 2), (["V7"], 4), (["V65"], 1), (["i64", "V7"], 2), (["i64", "V"], 1),
60
+ (["viio6", "V7"], 1), (["V7/V", "V7"], 1),
61
+ ],
62
+ "dominants_half": [(["V"], 4), (["i64", "V"], 2), (["V7/V", "V"], 1)],
63
+ "dominants_deceptive": [(["V7"], 4), (["V"], 2), (["i64", "V7"], 2), (["viio6", "V7"], 1)],
64
+ "plagal_predominants": [(["iv"], 3), (["iio6", "iv"], 1), (["VI", "iv"], 1)],
65
+ "resolutions": [(["i"], 6), (["i6"], 1)],
66
+ },
67
+ }
68
+
69
+ _KINDS = [("authentic", 5), ("half", 2), ("deceptive", 2), ("plagal", 1)]
70
+
71
+
72
+ def _pick(rng: random.Random, options: list[tuple[list, int]]) -> list:
73
+ seqs = [o for o, _ in options]
74
+ weights = [w for _, w in options]
75
+ return list(rng.choices(seqs, weights=weights, k=1)[0])
76
+
77
+
78
+ def _assemble(cfg: dict, rng: random.Random) -> list[str]:
79
+ kind = rng.choices([k for k, _ in _KINDS], weights=[w for _, w in _KINDS], k=1)[0]
80
+ specs = _pick(rng, cfg["openings"])
81
+ if kind == "plagal":
82
+ specs += _pick(rng, cfg["plagal_predominants"])
83
+ specs += [cfg["tonic"]]
84
+ else:
85
+ specs += _pick(rng, cfg["predominants"])
86
+ if kind == "half":
87
+ specs += _pick(rng, cfg["dominants_half"])
88
+ elif kind == "deceptive":
89
+ specs += _pick(rng, cfg["dominants_deceptive"])
90
+ specs += [cfg["submediant"]]
91
+ else:
92
+ specs += _pick(rng, cfg["dominants"])
93
+ specs += _pick(rng, cfg["resolutions"])
94
+ return specs
95
+
96
+
97
+ def generate_phrases(mode: str, n: int, seed: int = 0) -> list[list[Analysis]]:
98
+ """Return up to ``n`` distinct, cadence-terminated phrases for the mode."""
99
+ cfg = _CONFIG[mode]
100
+ rng = random.Random(seed)
101
+ out: list[list[Analysis]] = []
102
+ seen: set[tuple[str, ...]] = set()
103
+ cap = max(500, n * 80)
104
+ for _ in range(cap):
105
+ if len(out) >= n:
106
+ break
107
+ specs = _assemble(cfg, rng)
108
+ phrase = [Analysis.parse(s) for s in specs]
109
+ key_ = tuple(a.dcml_label() for a in phrase)
110
+ if key_ in seen:
111
+ continue
112
+ seen.add(key_)
113
+ out.append(phrase)
114
+ return out
src/harmony_dataset/py.typed ADDED
File without changes
src/harmony_dataset/tasks.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The task tiers — the same verified progression framed several ways.
2
+
3
+ The point is to *hide the answer* to varying degrees so the dataset trains and
4
+ tests real harmonic reasoning, not chord-symbol lookup:
5
+
6
+ symbol_to_rn key + chord symbols -> RN + cadence (easy; quality given)
7
+ notes_to_rn key + spelled notes -> RN + cadence (must read the chord)
8
+ pcset_to_rn key + bass-first pc lists -> RN + cadence (no spelling either)
9
+ key_id spelled notes (no key) -> key (infer the key)
10
+
11
+ Each is exposed as its own dataset config so a consumer can load exactly the tier
12
+ they want.
13
+
14
+ ``key_id`` is determinacy-gated. A cadence and length alone do not pin a key:
15
+ ``I V7/V V`` in C is note-identical to ``IV V7 I`` in G — a *stronger* reading —
16
+ so its gold label would be contestable. We therefore require the phrase's notes
17
+ to contain both key-defining degrees, scale degree 4 and the leading tone: that
18
+ tritone occurs in exactly one major diatonic collection, and the tonic-chord
19
+ third (present via the cadence/opening) settles major vs minor. Phrases failing
20
+ the gate are simply excluded from key_id (they remain in the other tasks, where
21
+ the key is given).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass
26
+ from typing import Optional
27
+
28
+ TASKS = ("symbol_to_rn", "notes_to_rn", "pcset_to_rn", "key_id")
29
+
30
+ # key_id needs enough context to pin a key: a real cadence and >= 3 chords.
31
+ _KEY_ID_MIN_CHORDS = 3
32
+
33
+ _LETTER_PC = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
34
+
35
+
36
+ def _tonic_pc(key_str: str) -> int:
37
+ """Pitch class of the tonic in a key string like 'Ab major' or 'F# minor'."""
38
+ name = key_str.split()[0]
39
+ pc = _LETTER_PC[name[0]]
40
+ for ch in name[1:]:
41
+ pc += 1 if ch == "#" else -1
42
+ return pc % 12
43
+
44
+
45
+ def _key_is_determined(key: str, pcs: list[list[int]]) -> bool:
46
+ """True when the notes contain scale degree 4 AND the leading tone."""
47
+ tonic = _tonic_pc(key)
48
+ present = {p for chord_pcs in pcs for p in chord_pcs}
49
+ return {(tonic + 5) % 12, (tonic + 11) % 12} <= present
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Rendered:
54
+ task: str
55
+ input: str
56
+ target: str
57
+ extra: dict # the input-side representation, for transparency
58
+
59
+
60
+ def _rn_target(labels: list[str], cadence: Optional[str]) -> str:
61
+ body = " ".join(labels)
62
+ return f"{body}\ncadence: {cadence}" if cadence else body
63
+
64
+
65
+ def _notes_str(notes: list[list[str]]) -> str:
66
+ return " | ".join(" ".join(ch) for ch in notes)
67
+
68
+
69
+ def _pcs_str(pcs: list[list[int]]) -> str:
70
+ return " | ".join("[" + " ".join(str(p) for p in ch) + "]" for ch in pcs)
71
+
72
+
73
+ def render(
74
+ task: str,
75
+ *,
76
+ key: str,
77
+ symbols: list[str],
78
+ notes: list[list[str]],
79
+ pcs: list[list[int]],
80
+ labels: list[str],
81
+ cadence: Optional[str],
82
+ ) -> Optional[Rendered]:
83
+ """Render one task, or return None when the task does not apply to this item."""
84
+ if task == "symbol_to_rn":
85
+ return Rendered(task, f"key: {key}\nprogression: {' '.join(symbols)}",
86
+ _rn_target(labels, cadence), {"chords": symbols})
87
+
88
+ if task == "notes_to_rn":
89
+ return Rendered(task, f"key: {key}\nnotes: {_notes_str(notes)}",
90
+ _rn_target(labels, cadence), {"notes": notes})
91
+
92
+ if task == "pcset_to_rn":
93
+ return Rendered(task, f"key: {key}\npitch classes: {_pcs_str(pcs)}",
94
+ _rn_target(labels, cadence), {"pitch_classes": pcs})
95
+
96
+ if task == "key_id":
97
+ if cadence is None or len(labels) < _KEY_ID_MIN_CHORDS:
98
+ return None
99
+ if not _key_is_determined(key, pcs):
100
+ return None
101
+ return Rendered(task, f"notes: {_notes_str(notes)}", key, {"notes": notes})
102
+
103
+ raise ValueError(f"unknown task {task!r}")
src/harmony_dataset/verify.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The gold gate: dual-derivation verification.
2
+
3
+ For each chord we derive pitch content two independent ways and require they
4
+ agree exactly (pitch-class set + bass):
5
+
6
+ figure -> music21 roman engine -> pitches (the label's meaning)
7
+ symbol -> music21 chord-symbol parser -> pitches (what the model sees)
8
+
9
+ If they disagree, the Roman-numeral label and the printed chord symbol denote
10
+ different chords, so the training pair would be wrong. Such items are dropped
11
+ and surfaced in the verification report. This is what makes the synthetic gold
12
+ trustworthy without hand-labelling.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+
18
+ from music21 import key
19
+
20
+ from .vocabulary import (
21
+ Analysis,
22
+ bass_pc_from_figure,
23
+ bass_pc_from_symbol,
24
+ pitch_classes_from_figure,
25
+ pitch_classes_from_symbol,
26
+ )
27
+
28
+ # music21 returns this string when it cannot name a chord.
29
+ _UNIDENTIFIED = "Chord Symbol Cannot Be Identified"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ChordCheck:
34
+ ok: bool
35
+ figure: str
36
+ symbol: str
37
+ figure_pcs: frozenset[int]
38
+ symbol_pcs: frozenset[int]
39
+ reason: str = ""
40
+
41
+
42
+ def verify_chord(analysis: Analysis, symbol: str, key_obj: key.Key) -> ChordCheck:
43
+ figure = analysis.music21_figure()
44
+ fig_pcs = pitch_classes_from_figure(figure, key_obj)
45
+
46
+ if not symbol or symbol == _UNIDENTIFIED:
47
+ return ChordCheck(False, figure, symbol, fig_pcs, frozenset(), "unidentified chord symbol")
48
+
49
+ try:
50
+ sym_pcs = pitch_classes_from_symbol(symbol)
51
+ sym_bass = bass_pc_from_symbol(symbol)
52
+ except Exception as exc: # music21 raises a variety of parse errors
53
+ return ChordCheck(False, figure, symbol, fig_pcs, frozenset(), f"symbol parse error: {exc}")
54
+
55
+ if fig_pcs != sym_pcs:
56
+ return ChordCheck(False, figure, symbol, fig_pcs, sym_pcs, "pitch-class set mismatch")
57
+
58
+ if bass_pc_from_figure(figure, key_obj) != sym_bass:
59
+ return ChordCheck(False, figure, symbol, fig_pcs, sym_pcs, "bass mismatch (inversion)")
60
+
61
+ return ChordCheck(True, figure, symbol, fig_pcs, sym_pcs)
src/harmony_dataset/vocabulary.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DCML label grammar and the music21 bridge.
2
+
3
+ The dataset's canonical harmony convention is the DCML feature decomposition
4
+ (``numeral / form / figbass / changes / relativeroot``) — see the spec at
5
+ github.com/DCMLab/standards. We *conform* to that notation; we do not copy any
6
+ DCML data, which keeps the generated dataset cleanly CC-BY-4.0.
7
+
8
+ music21 is the engine. Its figure strings match DCML almost exactly for the
9
+ vocabulary we generate; the one divergence is the half-diminished glyph
10
+ (DCML ``%`` vs music21 ``ø``). All pitch reasoning goes through music21 so the
11
+ verification gate (``verify.py``) can cross-check labels against chord symbols.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from dataclasses import dataclass
17
+ from functools import lru_cache
18
+ from typing import Optional
19
+
20
+ from music21 import chord, harmony, key, roman
21
+
22
+ # DCML form glyph -> music21 form glyph. Only '%' differs.
23
+ _FORM_DCML_TO_M21 = {"": "", "o": "o", "+": "+", "%": "ø", "M": "M"}
24
+ VALID_FORMS = frozenset(_FORM_DCML_TO_M21)
25
+ VALID_FIGBASS = frozenset({"", "6", "64", "7", "65", "43", "2"})
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Analysis:
30
+ """One chord's functional analysis in the DCML feature decomposition.
31
+
32
+ ``numeral`` carries triad quality in its case (upper = major third, lower =
33
+ minor third) and may carry an accidental prefix (e.g. ``bII``, ``#iv``).
34
+ """
35
+
36
+ numeral: str
37
+ form: str = ""
38
+ figbass: str = ""
39
+ changes: str = ""
40
+ relativeroot: Optional[str] = None
41
+
42
+ def __post_init__(self) -> None:
43
+ if self.form not in VALID_FORMS:
44
+ raise ValueError(f"invalid DCML form {self.form!r}")
45
+ if self.figbass not in VALID_FIGBASS:
46
+ raise ValueError(f"invalid figbass {self.figbass!r}")
47
+
48
+ def dcml_label(self) -> str:
49
+ """The canonical DCML label string, e.g. ``ii7``, ``IM7``, ``ii%65``, ``V7/V``."""
50
+ base = f"{self.numeral}{self.form}{self.figbass}{self.changes}"
51
+ return f"{base}/{self.relativeroot}" if self.relativeroot else base
52
+
53
+ def music21_figure(self) -> str:
54
+ """The equivalent music21 RomanNumeral figure (``%`` -> ``ø``)."""
55
+ base = f"{self.numeral}{_FORM_DCML_TO_M21[self.form]}{self.figbass}{self.changes}"
56
+ return f"{base}/{self.relativeroot}" if self.relativeroot else base
57
+
58
+ def to_dict(self) -> dict:
59
+ return {
60
+ "numeral": self.numeral,
61
+ "form": self.form,
62
+ "figbass": self.figbass,
63
+ "changes": self.changes,
64
+ "relativeroot": self.relativeroot,
65
+ }
66
+
67
+ @classmethod
68
+ def from_dict(cls, d: dict) -> "Analysis":
69
+ return cls(
70
+ numeral=d["numeral"],
71
+ form=d.get("form", ""),
72
+ figbass=d.get("figbass", ""),
73
+ changes=d.get("changes", ""),
74
+ relativeroot=d.get("relativeroot"),
75
+ )
76
+
77
+ @classmethod
78
+ def parse(cls, spec: str) -> "Analysis":
79
+ """Parse a compact DCML spec, e.g. ``ii7``, ``IM7``, ``iio6``, ``ii%65``, ``V7/V``."""
80
+ m = _SPEC_RE.match(spec)
81
+ if not m:
82
+ raise ValueError(f"bad chord spec {spec!r}")
83
+ numeral, form, figbass, rel = m.groups()
84
+ return cls(numeral=numeral, form=form or "", figbass=figbass or "", relativeroot=rel)
85
+
86
+
87
+ # accidentals + roman numeral, optional form glyph, optional figbass, optional /relativeroot
88
+ _SPEC_RE = re.compile(r"^([b#]*[iIvV]+)([o+%M]?)(\d*)(?:/(.+))?$")
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # music21 bridge. Cached because RomanNumeral / ChordSymbol construction is the
93
+ # hot path when transposing hundreds of templates across 24 keys.
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ @lru_cache(maxsize=None)
98
+ def _roman(figure: str, key_name: str) -> roman.RomanNumeral:
99
+ return roman.RomanNumeral(figure, key.Key(key_name))
100
+
101
+
102
+ @lru_cache(maxsize=None)
103
+ def _chord_symbol(symbol: str) -> harmony.ChordSymbol:
104
+ return harmony.ChordSymbol(symbol)
105
+
106
+
107
+ def pitch_classes_from_figure(figure: str, key_obj: key.Key) -> frozenset[int]:
108
+ rn = _roman(figure, key_obj.tonicPitchNameWithCase)
109
+ return frozenset(p.pitchClass for p in rn.pitches)
110
+
111
+
112
+ def bass_pc_from_figure(figure: str, key_obj: key.Key) -> int:
113
+ rn = _roman(figure, key_obj.tonicPitchNameWithCase)
114
+ return rn.bass().pitchClass
115
+
116
+
117
+ def pitch_classes_from_symbol(symbol: str) -> frozenset[int]:
118
+ cs = _chord_symbol(symbol)
119
+ return frozenset(p.pitchClass for p in cs.pitches)
120
+
121
+
122
+ def bass_pc_from_symbol(symbol: str) -> int:
123
+ return _chord_symbol(symbol).bass().pitchClass
124
+
125
+
126
+ def spelled_notes_from_figure(figure: str, key_obj: key.Key) -> list[str]:
127
+ """Voiced, bass-first spelled notes, e.g. ``['D4','F4','A4','C5']`` (flats as 'b').
128
+
129
+ Enharmonic spelling is preserved (``Cb``, ``E#`` in remote keys) — that is part
130
+ of notation reading. The bass is first, so inversion is recoverable.
131
+ """
132
+ rn = _roman(figure, key_obj.tonicPitchNameWithCase)
133
+ return [p.nameWithOctave.replace("-", "b") for p in rn.pitches]
134
+
135
+
136
+ def bass_first_pcs_from_figure(figure: str, key_obj: key.Key) -> list[int]:
137
+ """Pitch classes in bass-first order, de-duplicated (spelling stripped).
138
+
139
+ Order preserves the bass first so inversion stays recoverable, while the
140
+ integers carry no enharmonic hint — the most abstract input tier.
141
+ """
142
+ seen: list[int] = []
143
+ rn = _roman(figure, key_obj.tonicPitchNameWithCase)
144
+ for p in rn.pitches:
145
+ if p.pitchClass not in seen:
146
+ seen.append(p.pitchClass)
147
+ return seen
148
+
149
+
150
+ def chord_symbol_from_figure(figure: str, key_obj: key.Key) -> str:
151
+ """Render a Roman numeral (in a key) to a lead-sheet chord symbol string.
152
+
153
+ Uses music21's ``chordSymbolFigureFromChord``. Returns the string as-is;
154
+ unidentifiable chords come back as a sentinel that the verify gate rejects.
155
+ """
156
+ rn = _roman(figure, key_obj.tonicPitchNameWithCase)
157
+ return harmony.chordSymbolFigureFromChord(chord.Chord(rn.pitches))
158
+
159
+
160
+ # Conventional key spellings: one per pitch class, avoiding needless double
161
+ # accidentals so generated chord symbols stay clean.
162
+ MAJOR_KEYS = ["C", "D-", "D", "E-", "E", "F", "F#", "G", "A-", "A", "B-", "B"]
163
+ MINOR_KEYS = ["c", "c#", "d", "e-", "e", "f", "f#", "g", "g#", "a", "b-", "b"]
tests/test_cadence.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the cadence classifier.
2
+
3
+ music21 has no cadence detector, so this is our own. It emits DCML cadence codes
4
+ (PAC / IAC / HC / DC / PC) from the tail of an Analysis sequence. Because the
5
+ synthetic data is root-position chord symbols with no notated voicing, PAC vs IAC
6
+ is decided by inversion (both chords root position => PAC) rather than by soprano
7
+ position — a documented simplification.
8
+ """
9
+ from harmony_dataset.cadence import classify_cadence
10
+ from harmony_dataset.vocabulary import Analysis
11
+
12
+
13
+ def A(numeral, form="", figbass="", relativeroot=None):
14
+ return Analysis(numeral, form=form, figbass=figbass, relativeroot=relativeroot)
15
+
16
+
17
+ class TestAuthentic:
18
+ def test_pac_major(self):
19
+ assert classify_cadence([A("ii", figbass="7"), A("V", figbass="7"), A("I")]) == "PAC"
20
+
21
+ def test_pac_minor(self):
22
+ assert classify_cadence([A("iv"), A("V"), A("i")]) == "PAC"
23
+
24
+ def test_iac_tonic_inverted(self):
25
+ assert classify_cadence([A("ii", figbass="7"), A("V", figbass="7"), A("I", figbass="6")]) == "IAC"
26
+
27
+ def test_iac_dominant_inverted(self):
28
+ assert classify_cadence([A("ii", figbass="7"), A("V", figbass="65"), A("I")]) == "IAC"
29
+
30
+
31
+ class TestOtherCadences:
32
+ def test_half_cadence(self):
33
+ assert classify_cadence([A("I"), A("IV"), A("V")]) == "HC"
34
+
35
+ def test_half_cadence_after_secondary(self):
36
+ # I - V7/V - V is a tonicized half cadence: ends on diatonic V
37
+ assert classify_cadence([A("I"), A("V", figbass="7", relativeroot="V"), A("V")]) == "HC"
38
+
39
+ def test_plagal(self):
40
+ assert classify_cadence([A("I"), A("IV"), A("I")]) == "PC"
41
+
42
+ def test_plagal_minor(self):
43
+ assert classify_cadence([A("i"), A("iv"), A("i")]) == "PC"
44
+
45
+ def test_deceptive_major(self):
46
+ assert classify_cadence([A("ii", figbass="7"), A("V", figbass="7"), A("vi")]) == "DC"
47
+
48
+ def test_deceptive_minor(self):
49
+ assert classify_cadence([A("iv"), A("V", figbass="7"), A("VI")]) == "DC"
50
+
51
+ def test_inverted_dominant_is_not_deceptive(self):
52
+ # V65 -> vi: the bass (leading tone) must resolve to tonic; not a DC
53
+ assert classify_cadence([A("I"), A("V", figbass="65"), A("vi")]) is None
54
+
55
+
56
+ class TestNoCadence:
57
+ def test_ends_on_predominant(self):
58
+ assert classify_cadence([A("I"), A("IV"), A("ii", figbass="7")]) is None
59
+
60
+ def test_single_chord(self):
61
+ assert classify_cadence([A("I")]) is None
62
+
63
+ def test_empty(self):
64
+ assert classify_cadence([]) is None
65
+
66
+ def test_inverted_dominant_is_not_half_cadence(self):
67
+ # ending on an inverted V is too weak to call a half cadence
68
+ assert classify_cadence([A("I"), A("V", figbass="6")]) is None
69
+
70
+ def test_terminal_v7_is_not_half_cadence(self):
71
+ # a half cadence ends on a V triad; a terminal V7 demands resolution
72
+ assert classify_cadence([A("I"), A("IV"), A("V", figbass="7")]) is None
tests/test_eval.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The eval harness must parse leniently, score strictly, and give the oracle 100%."""
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ REPO = Path(__file__).resolve().parents[1]
7
+ sys.path.insert(0, str(REPO / "eval"))
8
+
9
+ from score import parse_key, parse_rn, score_key, score_rn # noqa: E402
10
+
11
+
12
+ def _pairs(cases):
13
+ return [(g, {"prediction": p}) for g, p in cases]
14
+
15
+
16
+ class TestParseRN:
17
+ def test_clean_two_line(self):
18
+ assert parse_rn("ii7 V7 IM7\ncadence: PAC") == (["ii7", "V7", "IM7"], "PAC")
19
+
20
+ def test_no_cadence(self):
21
+ assert parse_rn("VIM7") == (["VIM7"], None)
22
+
23
+ def test_prose_then_fenced_answer(self):
24
+ text = "Let me analyze this.\n```\nI ii6 I64 V\ncadence: HC\n```"
25
+ assert parse_rn(text) == (["I", "ii6", "I64", "V"], "HC")
26
+
27
+ def test_inline_cadence(self):
28
+ assert parse_rn("ii7 V7 I cadence: PAC") == (["ii7", "V7", "I"], "PAC")
29
+
30
+ def test_unicode_and_separators(self):
31
+ assert parse_rn("iiø7 – V⁷ – vii°6\ncadence: IAC") == (
32
+ ["ii%7", "V7", "viio6"],
33
+ "IAC",
34
+ )
35
+
36
+ def test_case_is_preserved(self):
37
+ labels, _ = parse_rn("i64 V i")
38
+ assert labels == ["i64", "V", "i"] # not I64 / I
39
+
40
+ def test_garbage(self):
41
+ assert parse_rn("") == (None, None)
42
+
43
+
44
+ class TestParseKey:
45
+ def test_plain(self):
46
+ assert parse_key("Eb major") == "Eb major"
47
+
48
+ def test_prose_wrapped(self):
49
+ assert parse_key("The key of this phrase is F# minor.") == "F# minor"
50
+
51
+ def test_lowercase_tonic(self):
52
+ assert parse_key("f# minor") == "F# minor"
53
+
54
+ def test_last_match_wins(self):
55
+ assert parse_key("This has a major sound at first, but it is B minor") == "B minor"
56
+
57
+ def test_no_key(self):
58
+ assert parse_key("I have no idea") is None
59
+
60
+
61
+ class TestScoreRN:
62
+ GOLD = {"labels": ["ii7", "V7", "IM7"], "cadence": "PAC"}
63
+
64
+ def test_mixed_batch(self):
65
+ pairs = _pairs([
66
+ (self.GOLD, "ii7 V7 IM7\ncadence: PAC"), # perfect
67
+ (self.GOLD, "ii7 V7 IM7\ncadence: IAC"), # wrong cadence
68
+ (self.GOLD, "ii7 V7 I\ncadence: PAC"), # one wrong chord
69
+ (self.GOLD, "no idea"), # unparseable-ish
70
+ ])
71
+ m = score_rn(pairs)
72
+ assert m["n"] == 4
73
+ assert m["exact"] == 0.25
74
+ assert m["labels_exact"] == 0.5
75
+ assert m["cadence_acc"] == 0.5 # garbage row has no cadence, misses PAC
76
+ # 3 + 3 + 2 + 0 hits of 12 gold chords ("no" != "ii7", "idea" != "V7")
77
+ assert m["chord_acc"] == round(8 / 12, 4)
78
+
79
+ def test_none_cadence_matches(self):
80
+ m = score_rn(_pairs([({"labels": ["VIM7"], "cadence": None}, "VIM7")]))
81
+ assert m["exact"] == 1.0
82
+
83
+
84
+ class TestScoreKey:
85
+ def test_mixed_batch(self):
86
+ pairs = _pairs([
87
+ ({"target": "C major"}, "C major"),
88
+ ({"target": "Bb major"}, "Bb minor"), # tonic right, mode wrong
89
+ ({"target": "F# minor"}, "???"), # parse failure
90
+ ])
91
+ m = score_key(pairs)
92
+ assert m["exact"] == round(1 / 3, 4)
93
+ assert m["tonic_acc"] == round(2 / 3, 4)
94
+ assert m["mode_acc"] == round(1 / 3, 4)
95
+ assert m["parse_failures"] == 1
96
+
97
+
98
+ class TestOracle:
99
+ """Feeding gold targets back as predictions must score 100% everywhere.
100
+
101
+ This round-trips every real test-split target through the response parser,
102
+ so any formatting the parser can't recover is caught here.
103
+ """
104
+
105
+ def _oracle(self, config):
106
+ path = REPO / "data" / config / "test.jsonl"
107
+ gold = [json.loads(ln) for ln in path.open()]
108
+ return [(g, {"prediction": g["target"]}) for g in gold]
109
+
110
+ def test_rn_configs(self):
111
+ for config in ("symbol_to_rn", "notes_to_rn", "pcset_to_rn"):
112
+ m = score_rn(self._oracle(config))
113
+ assert m["exact"] == 1.0, (config, m)
114
+ assert m["parse_failures"] == 0
115
+
116
+ def test_key_id(self):
117
+ m = score_key(self._oracle("key_id"))
118
+ assert m["exact"] == 1.0, m
119
+ assert m["parse_failures"] == 0
tests/test_generator.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the pool builder and multi-task generator.
2
+
3
+ Locks: every emitted record is gold-verified, splits are leakage-free by shape
4
+ (across keys AND across tasks), the brief's example is present, task framings are
5
+ well-formed, and generation is deterministic.
6
+ """
7
+ from collections import Counter
8
+
9
+ from harmony_dataset.generator import build_pool, generate
10
+ from harmony_dataset.cadence import classify_cadence
11
+ from harmony_dataset.vocabulary import Analysis
12
+
13
+
14
+ class TestPool:
15
+ def test_shapes_distinct(self):
16
+ pool = build_pool()
17
+ keys = [(s.mode, s.labels) for s in pool]
18
+ assert len(keys) == len(set(keys))
19
+
20
+ def test_has_curated_and_grammar_and_single(self):
21
+ sources = {s.source for s in build_pool()}
22
+ assert {"curated", "grammar", "single"} <= sources
23
+
24
+ def test_split_is_stable(self):
25
+ # shape -> split must be deterministic across calls. build_pool is
26
+ # lru_cached, so compare a FRESH build (__wrapped__) against the cached
27
+ # one — comparing two cached calls would be a self-comparison.
28
+ a = {s.shape_id: s.split for s in build_pool.__wrapped__()}
29
+ b = {s.shape_id: s.split for s in build_pool()}
30
+ assert a == b
31
+
32
+
33
+ class TestLeakage:
34
+ def test_no_shape_crosses_splits(self):
35
+ res = generate()
36
+ by_shape: dict[str, set[str]] = {}
37
+ for r in res.records:
38
+ by_shape.setdefault(r.data["shape_id"], set()).add(r.split)
39
+ offenders = {sid: sp for sid, sp in by_shape.items() if len(sp) > 1}
40
+ assert not offenders, f"shapes leaking across splits: {offenders}"
41
+
42
+
43
+ class TestVerifiedAndDeterministic:
44
+ def test_gold_gate_clean(self):
45
+ # the locked vocabulary must verify perfectly; any disagreement is a bug
46
+ res = generate()
47
+ assert res.records
48
+ assert res.chord_agreement_rate == 1.0
49
+ assert res.dropped_instances == 0
50
+ assert res.failures == []
51
+
52
+ # NOTE: full-pipeline determinism follows from build_pool determinism
53
+ # (tested above with a fresh __wrapped__ build — the only RNG lives there)
54
+ # plus _instantiate being pure music21 rendering. A second full generate()
55
+ # here would cost ~30s of suite time for no extra signal.
56
+
57
+
58
+ class TestBriefExample:
59
+ def test_jazz_ii_V_I_symbol_task_present(self):
60
+ res = generate()
61
+ hits = [
62
+ r.data for r in res.records
63
+ if r.data["task"] == "symbol_to_rn"
64
+ and r.data["key"] == "C major"
65
+ and r.data.get("chords") == ["Dm7", "G7", "Cmaj7"]
66
+ ]
67
+ assert len(hits) == 1
68
+ assert hits[0]["target"] == "ii7 V7 IM7\ncadence: PAC"
69
+
70
+
71
+ class TestTaskFraming:
72
+ def test_all_tasks_present(self):
73
+ tasks_seen = Counter(r.data["task"] for r in generate().records)
74
+ assert set(tasks_seen) == {"symbol_to_rn", "notes_to_rn", "pcset_to_rn", "key_id"}
75
+
76
+ def test_key_id_only_for_cadenced_multichord(self):
77
+ for r in generate().records:
78
+ if r.data["task"] == "key_id":
79
+ assert r.data["cadence"] is not None
80
+ assert len(r.data["labels"]) >= 3
81
+ assert "key:" not in r.data["input"] # key is hidden
82
+ assert r.data["target"] == r.data["key"]
83
+
84
+ def test_key_id_records_are_key_determined(self):
85
+ # every key_id record's notes must contain scale degree 4 + leading tone
86
+ # (otherwise a competing key admits the same notes and the gold is moot)
87
+ letter = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
88
+
89
+ def pc(note: str) -> int:
90
+ core = note.rstrip("0123456789")
91
+ v = letter[core[0]]
92
+ for a in core[1:]:
93
+ v += 1 if a == "#" else -1
94
+ return v % 12
95
+
96
+ for r in generate().records:
97
+ if r.data["task"] != "key_id":
98
+ continue
99
+ tonic = pc(r.data["key"].split()[0] + "0")
100
+ present = {pc(n) for ch in r.data["notes"] for n in ch}
101
+ assert {(tonic + 5) % 12, (tonic + 11) % 12} <= present, r.data["input"]
102
+
103
+ def test_notes_task_hides_symbols(self):
104
+ for r in generate().records:
105
+ if r.data["task"] == "notes_to_rn":
106
+ assert "notes:" in r.data["input"]
107
+ assert "progression:" not in r.data["input"]
108
+ # target still matches the classifier
109
+ labels = [Analysis.from_dict(a).dcml_label() for a in r.data["analysis"]]
110
+ assert " ".join(labels) in r.data["target"]
tests/test_grammar.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the probabilistic functional-harmony grammar.
2
+
3
+ The grammar must produce musically-shaped phrases: start on tonic, end on a
4
+ recognised cadence, and (crucially) every chord must survive the gold gate when
5
+ rendered in a key. It must be deterministic under a seed and genuinely diverse.
6
+ """
7
+ from music21 import key
8
+
9
+ from harmony_dataset.grammar import generate_phrases
10
+ from harmony_dataset.cadence import classify_cadence
11
+ from harmony_dataset.verify import verify_chord
12
+ from harmony_dataset.vocabulary import Analysis, chord_symbol_from_figure
13
+
14
+
15
+ class TestParseSpec:
16
+ def test_specs_round_trip_to_labels(self):
17
+ assert Analysis.parse("ii7").dcml_label() == "ii7"
18
+ assert Analysis.parse("IM7").dcml_label() == "IM7"
19
+ assert Analysis.parse("iio6").dcml_label() == "iio6"
20
+ assert Analysis.parse("ii%65").dcml_label() == "ii%65"
21
+ assert Analysis.parse("V7/V").dcml_label() == "V7/V"
22
+ assert Analysis.parse("viio7").dcml_label() == "viio7"
23
+
24
+
25
+ class TestPhraseShape:
26
+ def test_starts_on_tonic(self):
27
+ for mode in ("major", "minor"):
28
+ for phrase in generate_phrases(mode, 40, seed=1):
29
+ assert phrase[0].numeral in {"I", "i"}
30
+ assert phrase[0].relativeroot is None
31
+
32
+ def test_ends_on_cadence(self):
33
+ for mode in ("major", "minor"):
34
+ for phrase in generate_phrases(mode, 40, seed=2):
35
+ assert classify_cadence(phrase) is not None
36
+
37
+ def test_reasonable_length(self):
38
+ for phrase in generate_phrases("major", 40, seed=3):
39
+ assert 2 <= len(phrase) <= 9
40
+
41
+
42
+ class TestGoldGateCompatibility:
43
+ def test_every_chord_verifies_in_reference_key(self):
44
+ # nothing the grammar emits should fail the dual-derivation check
45
+ for mode, k in (("major", "C"), ("minor", "a")):
46
+ K = key.Key(k)
47
+ for phrase in generate_phrases(mode, 60, seed=4):
48
+ for a in phrase:
49
+ sym = chord_symbol_from_figure(a.music21_figure(), K)
50
+ assert verify_chord(a, sym, K).ok, f"{a.dcml_label()} -> {sym} in {k}"
51
+
52
+
53
+ class TestDeterminismAndDiversity:
54
+ def test_deterministic(self):
55
+ a = [tuple(p.dcml_label() for p in ph) for ph in generate_phrases("major", 30, seed=7)]
56
+ b = [tuple(p.dcml_label() for p in ph) for ph in generate_phrases("major", 30, seed=7)]
57
+ assert a == b
58
+
59
+ def test_distinct_shapes(self):
60
+ shapes = {tuple(p.dcml_label() for p in ph) for ph in generate_phrases("major", 120, seed=9)}
61
+ # the grammar should yield real variety, not a handful of templates
62
+ assert len(shapes) >= 40
63
+
64
+ def test_uses_secondary_dominants(self):
65
+ seen = set()
66
+ for mode in ("major", "minor"):
67
+ for ph in generate_phrases(mode, 150, seed=11):
68
+ for a in ph:
69
+ if a.relativeroot is not None:
70
+ seen.add(a.dcml_label())
71
+ assert seen, "grammar never produced a secondary dominant"
tests/test_tasks.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the task framings, especially the key_id determinacy gate."""
2
+ import pytest
3
+
4
+ from harmony_dataset.tasks import render, _key_is_determined
5
+
6
+ # the brief example: ii7 V7 IM7 in C major
7
+ _ARGS = dict(
8
+ key="C major",
9
+ symbols=["Dm7", "G7", "Cmaj7"],
10
+ notes=[["D4", "F4", "A4", "C5"], ["G4", "B4", "D5", "F5"], ["C4", "E4", "G4", "B4"]],
11
+ pcs=[[2, 5, 9, 0], [7, 11, 2, 5], [0, 4, 7, 11]],
12
+ labels=["ii7", "V7", "IM7"],
13
+ cadence="PAC",
14
+ )
15
+
16
+
17
+ class TestFormats:
18
+ def test_symbol(self):
19
+ r = render("symbol_to_rn", **_ARGS)
20
+ assert r.input == "key: C major\nprogression: Dm7 G7 Cmaj7"
21
+ assert r.target == "ii7 V7 IM7\ncadence: PAC"
22
+
23
+ def test_notes(self):
24
+ r = render("notes_to_rn", **_ARGS)
25
+ assert "notes: D4 F4 A4 C5 | G4 B4 D5 F5 | C4 E4 G4 B4" in r.input
26
+
27
+ def test_pcset(self):
28
+ r = render("pcset_to_rn", **_ARGS)
29
+ assert "pitch classes: [2 5 9 0] | [7 11 2 5] | [0 4 7 11]" in r.input
30
+
31
+ def test_unknown_task_raises(self):
32
+ with pytest.raises(ValueError):
33
+ render("nope", **_ARGS)
34
+
35
+
36
+ class TestKeyIdGate:
37
+ def test_determined_case_passes(self):
38
+ r = render("key_id", **_ARGS)
39
+ assert r is not None
40
+ assert r.target == "C major"
41
+ assert "key:" not in r.input
42
+
43
+ def test_smoking_gun_excluded(self):
44
+ # I V7/V V in C == IV V7 I in G (note-identical, stronger reading).
45
+ # No scale degree 4 (F) anywhere -> key not determined -> excluded.
46
+ args = dict(_ARGS)
47
+ args.update(
48
+ symbols=["C", "D7", "G"],
49
+ notes=[["C4", "E4", "G4"], ["D4", "F#4", "A4", "C5"], ["G4", "B4", "D5"]],
50
+ pcs=[[0, 4, 7], [2, 6, 9, 0], [7, 11, 2]],
51
+ labels=["I", "V7/V", "V"],
52
+ cadence="HC",
53
+ )
54
+ assert render("key_id", **args) is None
55
+
56
+ def test_plagal_without_leading_tone_excluded(self):
57
+ # I IV I in C == V I V in F: ambiguous, no B anywhere.
58
+ args = dict(_ARGS)
59
+ args.update(
60
+ symbols=["C", "F", "C"],
61
+ notes=[["C4", "E4", "G4"], ["F4", "A4", "C5"], ["C4", "E4", "G4"]],
62
+ pcs=[[0, 4, 7], [5, 9, 0], [0, 4, 7]],
63
+ labels=["I", "IV", "I"],
64
+ cadence="PC",
65
+ )
66
+ assert render("key_id", **args) is None
67
+
68
+ def test_no_cadence_excluded(self):
69
+ args = dict(_ARGS, cadence=None)
70
+ assert render("key_id", **args) is None
71
+
72
+ def test_too_short_excluded(self):
73
+ args = dict(_ARGS)
74
+ args.update(symbols=["G7", "C"], notes=_ARGS["notes"][1:], pcs=_ARGS["pcs"][1:],
75
+ labels=["V7", "I"], cadence="PAC")
76
+ assert render("key_id", **args) is None
77
+
78
+
79
+ class TestDeterminacyHelper:
80
+ def test_tritone_rule(self):
81
+ # C major needs F (5) and B (11)
82
+ assert _key_is_determined("C major", [[0, 4, 7], [5, 9, 0], [7, 11, 2]])
83
+ assert not _key_is_determined("C major", [[0, 4, 7], [7, 11, 2]]) # no F
84
+ assert not _key_is_determined("C major", [[0, 4, 7], [5, 9, 0]]) # no B
85
+
86
+ def test_accidental_keys(self):
87
+ # Ab major: degree 4 = Db (1), leading tone = G (7)
88
+ assert _key_is_determined("Ab major", [[8, 0, 3], [1, 5, 8], [3, 7, 10]])
89
+ # F# minor: degree 4 = B (11), leading tone = E# (5)
90
+ assert _key_is_determined("F# minor", [[6, 9, 1], [11, 2, 6], [1, 5, 8]])
tests/test_verify.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the dual-derivation gold gate.
2
+
3
+ A chord passes only if the pitch content implied by its Roman-numeral label
4
+ (rendered by music21's roman engine) matches the pitch content implied by its
5
+ printed chord symbol (parsed by music21's independent chord-symbol parser),
6
+ including the bass. Disagreement means the label and the symbol shown to the
7
+ model denote different chords — that item must never reach the dataset.
8
+ """
9
+ from music21 import key
10
+
11
+ from harmony_dataset.vocabulary import Analysis
12
+ from harmony_dataset.verify import verify_chord
13
+
14
+
15
+ K = key.Key("C")
16
+
17
+
18
+ class TestPasses:
19
+ def test_matching_chord(self):
20
+ assert verify_chord(Analysis("ii", figbass="7"), "Dm7", K).ok
21
+
22
+ def test_matching_maj7(self):
23
+ assert verify_chord(Analysis("I", form="M", figbass="7"), "Cmaj7", K).ok
24
+
25
+ def test_matching_inversion_bass(self):
26
+ # V65 = G7/B; bass must line up too
27
+ assert verify_chord(Analysis("V", figbass="65"), "G7/B", K).ok
28
+
29
+
30
+ class TestFails:
31
+ def test_wrong_quality(self):
32
+ # Dm7b5 (half-dim) != ii7 (minor 7)
33
+ res = verify_chord(Analysis("ii", figbass="7"), "Dm7b5", K)
34
+ assert not res.ok
35
+ assert res.figure_pcs != res.symbol_pcs
36
+
37
+ def test_wrong_bass(self):
38
+ # right notes, wrong inversion: V7 (root) vs G7/B (first inversion)
39
+ res = verify_chord(Analysis("V", figbass="7"), "G7/B", K)
40
+ assert not res.ok
41
+ assert "bass" in res.reason.lower()
42
+
43
+ def test_unparseable_symbol(self):
44
+ res = verify_chord(Analysis("V", figbass="7"), "not-a-chord", K)
45
+ assert not res.ok
tests/test_vocabulary.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the DCML label grammar and the music21 bridge.
2
+
3
+ These lock the representation decisions from the plan:
4
+ - DCML feature-decomposed labels (numeral / form / figbass / changes / relativeroot)
5
+ - the single divergence from music21 figures: half-diminished '%' (DCML) vs 'ø' (music21)
6
+ - Cmaj7 -> IM7 (clean maj7, which music21's analytic figure gets wrong as 'I7')
7
+ """
8
+ from music21 import key
9
+
10
+ from harmony_dataset.vocabulary import (
11
+ Analysis,
12
+ pitch_classes_from_figure,
13
+ pitch_classes_from_symbol,
14
+ bass_pc_from_figure,
15
+ bass_first_pcs_from_figure,
16
+ spelled_notes_from_figure,
17
+ chord_symbol_from_figure,
18
+ MAJOR_KEYS,
19
+ MINOR_KEYS,
20
+ )
21
+
22
+
23
+ class TestDCMLLabels:
24
+ def test_plain_seventh(self):
25
+ a = Analysis("ii", figbass="7")
26
+ assert a.dcml_label() == "ii7"
27
+ assert a.music21_figure() == "ii7"
28
+
29
+ def test_major_seventh_is_M(self):
30
+ # the crux: Cmaj7 -> IM7, NOT the music21 analytic 'I7'
31
+ a = Analysis("I", form="M", figbass="7")
32
+ assert a.dcml_label() == "IM7"
33
+ assert a.music21_figure() == "IM7"
34
+
35
+ def test_half_diminished_glyph_diverges(self):
36
+ a = Analysis("ii", form="%", figbass="7")
37
+ assert a.dcml_label() == "ii%7" # DCML uses %
38
+ assert a.music21_figure() == "iiø7" # music21 uses ø
39
+
40
+ def test_diminished_seventh(self):
41
+ a = Analysis("vii", form="o", figbass="7")
42
+ assert a.dcml_label() == "viio7"
43
+ assert a.music21_figure() == "viio7"
44
+
45
+ def test_secondary_dominant(self):
46
+ a = Analysis("V", figbass="7", relativeroot="V")
47
+ assert a.dcml_label() == "V7/V"
48
+ assert a.music21_figure() == "V7/V"
49
+
50
+ def test_inversion_figbass(self):
51
+ a = Analysis("V", figbass="65")
52
+ assert a.dcml_label() == "V65"
53
+
54
+ def test_roundtrip_dict(self):
55
+ a = Analysis("ii", form="%", figbass="65", relativeroot="V")
56
+ assert Analysis.from_dict(a.to_dict()) == a
57
+
58
+
59
+ class TestPitchClasses:
60
+ def test_figure_pitch_classes_c_major(self):
61
+ K = key.Key("C")
62
+ assert pitch_classes_from_figure("ii7", K) == frozenset({0, 2, 5, 9})
63
+ assert pitch_classes_from_figure("V7", K) == frozenset({2, 5, 7, 11})
64
+ assert pitch_classes_from_figure("IM7", K) == frozenset({0, 4, 7, 11})
65
+
66
+ def test_symbol_pitch_classes(self):
67
+ assert pitch_classes_from_symbol("Dm7") == frozenset({0, 2, 5, 9})
68
+ assert pitch_classes_from_symbol("G7") == frozenset({2, 5, 7, 11})
69
+ assert pitch_classes_from_symbol("Cmaj7") == frozenset({0, 4, 7, 11})
70
+
71
+ def test_minor_key_raised_leading_tone(self):
72
+ # V7 in A minor is E7 (G#), not Em7
73
+ K = key.Key("a")
74
+ assert pitch_classes_from_figure("V7", K) == frozenset({2, 4, 8, 11})
75
+
76
+ def test_bass_pc_of_inversion(self):
77
+ K = key.Key("C")
78
+ # V65 = G7 in first inversion, bass = B (pc 11)
79
+ assert bass_pc_from_figure("V65", K) == 11
80
+ # root position V7, bass = G (pc 7)
81
+ assert bass_pc_from_figure("V7", K) == 7
82
+
83
+
84
+ class TestRepresentations:
85
+ def test_spelled_notes_bass_first(self):
86
+ K = key.Key("C")
87
+ assert spelled_notes_from_figure("ii7", K) == ["D4", "F4", "A4", "C5"]
88
+ # first-inversion dominant seventh: bass is the third (B)
89
+ assert spelled_notes_from_figure("V65", K)[0] == "B4"
90
+
91
+ def test_spelled_notes_flats_use_b(self):
92
+ # Eb minor VI = Cb major triad; must render 'Cb', never 'C-'
93
+ notes = spelled_notes_from_figure("VI", key.Key("e-"))
94
+ assert notes[0].startswith("Cb")
95
+ assert all("-" not in n for n in notes)
96
+
97
+ def test_bass_first_pcs_dedup_and_order(self):
98
+ K = key.Key("C")
99
+ assert bass_first_pcs_from_figure("ii7", K) == [2, 5, 9, 0]
100
+ # V65 bass is B (pc 11) — inversion recoverable from first element
101
+ assert bass_first_pcs_from_figure("V65", K)[0] == 11
102
+
103
+
104
+ class TestChordSymbolGeneration:
105
+ def test_symbol_from_figure_major_key(self):
106
+ K = key.Key("C")
107
+ assert chord_symbol_from_figure("ii7", K) == "Dm7"
108
+ assert chord_symbol_from_figure("V7", K) == "G7"
109
+ assert chord_symbol_from_figure("IM7", K) == "Cmaj7"
110
+ assert chord_symbol_from_figure("I", K) == "C"
111
+
112
+ def test_symbol_from_figure_minor_key(self):
113
+ K = key.Key("a")
114
+ assert chord_symbol_from_figure("V7", K) == "E7"
115
+ assert chord_symbol_from_figure("i", K) == "Am"
116
+
117
+
118
+ class TestKeyInventory:
119
+ def test_twelve_of_each(self):
120
+ assert len(MAJOR_KEYS) == 12
121
+ assert len(MINOR_KEYS) == 12
122
+
123
+ def test_all_pitch_classes_covered(self):
124
+ maj_pcs = {key.Key(k).tonic.pitchClass for k in MAJOR_KEYS}
125
+ min_pcs = {key.Key(k).tonic.pitchClass for k in MINOR_KEYS}
126
+ assert maj_pcs == set(range(12))
127
+ assert min_pcs == set(range(12))
uv.lock ADDED
The diff for this file is too large to render. See raw diff