File size: 17,087 Bytes
2935e65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# /// script
# requires-python = ">=3.12"
# dependencies = ["music21==10.5.2", "verovio==6.4.1", "cairosvg==2.8.2"]
# ///
"""Writes the experiment's test sheets: each sheet's true score as MusicXML, and the page to print as PDF.

Usage: uv run scripts/make_sheets.py

Every sheet is made from a fixed seed, so a second run writes the same notes. Where they are: README.md, "My photos".
"""

from __future__ import annotations

import random
from fractions import Fraction
from pathlib import Path

import cairosvg
import verovio
from music21 import articulations, bar, clef, dynamics, expressions, harmony, key, metadata, meter, note, pitch, repeat, scale, spanner, stream, tempo, tie

SHEETS = Path(__file__).parent / "sheets"

# US Letter at 96 px to the inch. Verovio lays a page out in its own units and draws SCALE percent of a pixel for
# each, so the page is given in units that come to Letter once drawn. SCALE 38 draws a staff 7.2 mm high, the size
# of a printed instrumental part.
SCALE = 38
LETTER_PX = (816, 1056)
MARGIN_PX = 54

# The engraver each printed variant comes from. The number follows the sheet's letter in its label: `a1`.
ENGRAVERS = {1: {"font": "Leipzig"}}

T = Fraction(1, 3)


class Line:
    """One staff of music, built a measure at a time."""

    def __init__(self, seed: str):
        self.rng = random.Random(seed)
        self.part = stream.Part()
        self.notes: list[note.Note] = []
        self.pool: list[pitch.Pitch] = []
        self.at = 0
        self.alter_chance = 0.0
        self.beats = Fraction(4)

    def start(self, *, clef_: clef.Clef | None = None, tonic: str | None = None, time: str | None = None, low: str | None = None, high: str | None = None) -> list:
        """What the next measure opens with: a new clef, key or time signature, and the range notes are drawn from."""
        opening = []
        if clef_:
            opening.append(clef_)
        if tonic:
            self.tonic = tonic
            opening.append(key.Key(tonic))
        if time:
            self.beats = Fraction(meter.TimeSignature(time).barDuration.quarterLength)
            opening.append(meter.TimeSignature(time))
        if low and high:
            self.pool = scale.MajorScale(self.tonic).getPitches(low, high)
            self.at = len(self.pool) // 2
        return opening

    def next_pitch(self) -> pitch.Pitch:
        # Mostly steps, some thirds, a few leaps, as a tune moves; turned back at the ends of the range.
        move = self.rng.choices([1, 2, 3, 4], weights=[60, 25, 10, 5])[0] * self.rng.choice([-1, 1])
        self.at += move if 0 <= self.at + move < len(self.pool) else -move
        self.at = max(0, min(len(self.pool) - 1, self.at))
        chosen = pitch.Pitch(self.pool[self.at].nameWithOctave)
        if self.rng.random() < self.alter_chance:
            alter = int(chosen.alter) + self.rng.choice([-1, 1])
            if -1 <= alter <= 1:
                chosen.accidental = pitch.Accidental(alter)
        return chosen

    def measure(self, pattern: list, opening: list = ()) -> stream.Measure:
        """Adds a measure. A positive length in the pattern is a note, a negative one a rest, in quarter notes."""
        assert sum(abs(Fraction(x)) for x in pattern) == self.beats, (pattern, self.beats)
        m = stream.Measure(number=len(self.part.getElementsByClass(stream.Measure)) + 1)
        for item in opening:
            m.append(item)
        for length in pattern:
            if length < 0:
                m.append(note.Rest(quarterLength=-length))
            else:
                n = note.Note(self.next_pitch(), quarterLength=length)
                m.append(n)
                self.notes.append(n)
        self.part.append(m)
        return m

    def measures(self, patterns: list[list], count: int, opening: list = ()) -> list[stream.Measure]:
        made = []
        for i in range(count):
            made.append(self.measure(self.rng.choice(patterns), opening if i == 0 else ()))
        return made

    def end(self, length=None) -> stream.Measure:
        """A last measure that comes to rest on the key note."""
        home = [i for i, p in enumerate(self.pool) if p.name == key.Key(self.tonic).tonic.name]
        self.at = min(home, key=lambda i: abs(i - self.at))
        chance, self.alter_chance = self.alter_chance, 0
        m = stream.Measure(number=len(self.part.getElementsByClass(stream.Measure)) + 1)
        n = note.Note(pitch.Pitch(self.pool[self.at].nameWithOctave), quarterLength=length or self.beats)
        m.append(n)
        self.notes.append(n)
        m.rightBarline = bar.Barline("final")
        self.part.append(m)
        self.alter_chance = chance
        return m

    def score(self, title: str) -> stream.Score:
        self.part.makeBeams(inPlace=True)
        self.part.makeAccidentals(inPlace=True, overrideStatus=True)
        s = stream.Score()
        s.metadata = metadata.Metadata(title=title)
        s.append(self.part)
        return s


def plain_notes() -> stream.Score:
    line = Line("a")
    patterns = [[1, 1, 1, 1], [2, 2], [2, 1, 1], [1, 1, 2], [4], [3, 1], [1, -1, 1, 1], [2, -2], [-1, 1, 2], [1, 2, 1]]
    line.measures(patterns, 31, line.start(clef_=clef.TrebleClef(), tonic="C", time="4/4", low="C4", high="G5"))
    line.measure([-4])
    line.measures(patterns, 31)
    line.end()
    return line.score("a · Plain notes")


def keys_and_accidentals() -> stream.Score:
    line = Line("b")
    line.alter_chance = 0.2
    patterns = [[1, 1, 1, 1], [0.5, 0.5, 1, 1, 1], [1, 0.5, 0.5, 2], [0.5, 0.5, 0.5, 0.5, 2], [1, 1, 0.5, 0.5, 1]]
    line.measures(patterns, 12, line.start(clef_=clef.TrebleClef(), tonic="A", time="4/4", low="C#4", high="A5"))
    line.measures(patterns, 12, line.start(tonic="E-", low="C4", high="A-5"))
    line.measures(patterns, 12, line.start(tonic="B", low="C#4", high="A#5"))
    line.measures(patterns, 11, line.start(tonic="D-", low="C4", high="A-5"))
    line.end()
    return line.score("b · Keys and accidentals")


def rhythms() -> stream.Score:
    line = Line("c")
    four = [
        [1.5, 0.5, 1, 1], [0.5, 0.5, 0.5, 0.5, 1, 1], [0.25, 0.25, 0.25, 0.25, 1, 2], [0.5, 0.25, 0.25, 1, 2],
        [0.75, 0.25, 0.75, 0.25, 2], [0.5, 1, 0.5, 2], [-0.5, 0.5, 1, -1, 1], [T, T, T, 1, 2], [2 * T, 2 * T, 2 * T, 2],
        [-0.25, 0.25, 0.25, 0.25, 1, 2], [1, T, T, T, 1.5, 0.5], [0.25, 0.5, 0.25, 1, -0.5, 0.5, 1],
    ]
    three = [[1, 1, 1], [1.5, 0.5, 1], [3], [0.5] * 6, [2, 1], [1, -1, 1], [0.5, 0.25, 0.25, 1, 1], [-0.5, 0.5, 0.75, 0.25, 1]]
    six = [[1.5, 1.5], [0.5, 0.5, 0.5, 1.5], [1, 0.5, 1, 0.5], [0.5] * 6, [3], [1.5, -1.5], [0.25] * 6 + [1.5], [1, 0.5, -1, 0.5]]
    two = [[1, 1], [0.5, 0.5, 1], [0.25] * 8, [2], [0.5, 0.25, 0.25, 0.5, 0.5], [-0.5, 0.5, 1]]
    made = line.measures(four, 20, line.start(clef_=clef.TrebleClef(), tonic="C", time="4/4", low="D4", high="G5"))
    made += line.measures(three, 14, line.start(time="3/4"))
    made += line.measures(six, 14, line.start(time="6/8"))
    made += line.measures(two, 9, line.start(time="2/4"))
    line.end()
    # A tie joins two notes of one pitch into a single longer note, here across a barline.
    for m in made[::4]:
        last = m.notes[-1] if m.notes else None
        following = m.next(stream.Measure)
        if last and following and isinstance(following[note.GeneralNote].first(), note.Note):
            first = following[note.GeneralNote].first()
            first.pitch = pitch.Pitch(last.pitch.nameWithOctave)
            last.tie, first.tie = tie.Tie("start"), tie.Tie("stop")
    return line.score("c · Rhythms")


def range_and_clefs() -> stream.Score:
    line = Line("d")
    patterns = [[1, 1, 1, 1], [2, 1, 1], [0.5, 0.5, 1, 2], [1, 0.5, 0.5, 1, 1], [2, 2]]
    line.measures(patterns, 8, line.start(clef_=clef.TrebleClef(), tonic="G", time="4/4", low="C5", high="G6"))
    line.measures(patterns, 8, line.start(low="G3", high="E4"))
    line.measures(patterns, 8, line.start(clef_=clef.BassClef(), low="C2", high="B2"))
    line.measures(patterns, 8, line.start(low="A3", high="E4"))
    line.measures(patterns, 8, line.start(clef_=clef.AltoClef(), low="C3", high="D5"))
    for i in range(4):
        line.measures(patterns, 1, line.start(clef_=clef.BassClef(), low="G2", high="C4"))
        line.measures(patterns, 1, line.start(clef_=clef.TrebleClef(), low="C4", high="G5"))
    line.end()
    return line.score("d · Range and clefs")


def dense_runs() -> stream.Score:
    line = Line("e")
    line.alter_chance = 0.12
    s, e, th = 0.25, 0.5, 0.125
    patterns = [[s] * 16, [s] * 8 + [e] * 4, [s] * 4 + [1] + [s] * 8, [th] * 8 + [s] * 4 + [e, e, 1], [e, s, s] * 4, [s] * 12 + [-s, s, e], [s, s, e] * 2 + [s] * 8]
    line.measures(patterns, 27, line.start(clef_=clef.TrebleClef(), tonic="E", time="4/4", low="B3", high="B5"))
    line.end()
    return line.score("e · Dense runs")


def markings() -> stream.Score:
    line = Line("f")
    patterns = [[1, 1, 1, 1], [0.5, 0.5, 1, 1, 1], [1, 0.5, 0.5, 2], [2, 1, 1], [1.5, 0.5, 1, 1], [0.5, 0.5, 0.5, 0.5, 1, 1]]
    rng = line.rng

    # Marks on single notes: short (staccato), stressed (accent, strong accent), held (tenuto), and a pause (fermata).
    line.measures(patterns, 12, line.start(clef_=clef.TrebleClef(), tonic="G", time="4/4", low="D4", high="G5"))
    for n in line.notes:
        if rng.random() < 0.5:
            n.articulations.append(rng.choice([articulations.Staccato, articulations.Accent, articulations.Tenuto, articulations.StrongAccent])())
    line.notes[-1].expressions.append(expressions.Fermata())

    # Slurs: a curve over several notes played joined together.
    first = len(line.notes)
    line.measures(patterns, 12)
    group = line.notes[first:]
    while len(group) > 1:
        length = min(len(group), rng.randint(2, 6))
        line.part.insert(0, spanner.Slur(group[0], group[length - 1]))
        group = group[length + rng.randint(0, 2):]

    # Loudness: letters under the staff, and hairpins for getting louder or quieter.
    for i, m in enumerate(line.measures(patterns, 12)):
        if i % 2 == 0:
            m.insert(0, dynamics.Dynamic(["p", "mf", "f", "pp", "ff", "mp"][i // 2]))
        else:
            hairpin = dynamics.Crescendo if i % 4 == 1 else dynamics.Diminuendo
            line.part.insert(0, hairpin(m.notes[0], m.notes[-1]))

    # Ornaments and fingerings: a trill sign, small grace notes before a note, and finger numbers over notes.
    for m in line.measures(patterns, 11):
        for n in list(m.notes):
            choice = rng.random()
            if choice < 0.35:
                n.articulations.append(articulations.Fingering(rng.randint(1, 5)))
            elif choice < 0.45 and n.quarterLength >= 1:
                n.expressions.append(expressions.Trill())
            elif choice < 0.55:
                at = [p.nameWithOctave for p in line.pool].index(n.pitch.nameWithOctave)
                neighbour = line.pool[at + 1 if at + 1 < len(line.pool) else at - 1]
                grace = note.Note(pitch.Pitch(neighbour.nameWithOctave), quarterLength=0.5).getGrace()
                m.insert(n.offset, grace)
    line.end()
    return line.score("f · Markings")


def structure() -> stream.Score:
    line = Line("g")
    three = [[1, 1, 1], [1.5, 0.5, 1], [2, 1], [0.5, 0.5, 1, 1], [1, 0.5, 0.5, 1], [3]]
    four = [[1, 1, 1, 1], [2, 1, 1], [0.5, 0.5, 1, 2], [1.5, 0.5, 2], [1, 1, 2]]
    six = [[1.5, 1.5], [0.5, 0.5, 0.5, 1.5], [1, 0.5, 1, 0.5], [0.5] * 6, [3]]

    # A pickup: a short measure before the first full one. Over it, a word for the speed.
    opening = line.start(clef_=clef.TrebleClef(), tonic="F", time="3/4", low="C4", high="F5")
    line.beats = Fraction(1)
    pickup = line.measure([0.5, 0.5], opening)
    pickup.padAsAnacrusis()
    pickup.insert(0, tempo.MetronomeMark("Allegretto"))
    line.beats = Fraction(3)

    # A repeated passage with two endings: play to the first ending, go back, then skip to the second.
    repeated = line.measures(three, 8)
    repeated[0].leftBarline = bar.Repeat(direction="start")
    repeated[7].rightBarline = bar.Repeat(direction="end")
    second = line.measures(three, 2)
    line.part.insert(0, spanner.RepeatBracket(repeated[6:8], number=1))
    line.part.insert(0, spanner.RepeatBracket(second, number=2))
    second[1].rightBarline = bar.Barline("double")
    second[1].insert(0, repeat.Fine())

    # A new section, with a letter over it and a new time signature.
    section = line.measures(four, 9, line.start(time="4/4"))
    section[0].insert(0, expressions.RehearsalMark("B"))

    # Empty measures, then a passage that slows down.
    for _ in range(4):
        line.measure([-4])
    slowing = line.measures(four, 7)
    slowing[3].insert(0, expressions.TextExpression("rit."))
    slowing[6].rightBarline = bar.Barline("double")

    # A third section in a new key and time, repeated as a whole, then back to the start as far as "Fine".
    third = line.measures(six, 8, line.start(tonic="B-", time="6/8", low="D4", high="F5"))
    third[0].insert(0, expressions.RehearsalMark("C"))
    third[0].leftBarline = bar.Repeat(direction="start")
    third[7].rightBarline = bar.Repeat(direction="end")
    line.measures(six, 5)
    line.end().insert(0, repeat.DaCapoAlFine())
    for number, m in enumerate(line.part.getElementsByClass(stream.Measure)):
        m.number = number
    return line.score("g · Repeats and structure")


def lead_sheet() -> stream.Score:
    line = Line("h")
    rng = line.rng
    patterns = [[1, 1, 1, 1], [2, 1, 1], [1, 1, 2], [1.5, 0.5, 1, 1], [0.5, 0.5, 1, 2], [1, 0.5, 0.5, 1, 1], [3, 1]]
    words = [["la"], ["sing"], ["the"], ["day"], ["song"], ["mu", "sic"], ["pa", "per"], ["morn", "ing"], ["play", "ing"], ["to", "geth", "er"], ["mel", "o", "dy"], ["light"], ["and"], ["we"]]
    # Chord names without a sharp or flat sign: the PDF writer has no glyph for either (the sheets leave chord symbols plain).
    chords = ["D", "G", "A7", "Bm", "Em", "Gmaj7", "E7", "A", "D/A", "Em7"]

    made = line.measures(patterns, 43, line.start(clef_=clef.TrebleClef(), tonic="D", time="4/4", low="D4", high="E5"))
    made.append(line.end())
    # Words under the notes, a syllable to a note, with hyphens inside a word.
    syllables: list[tuple[str, str]] = []
    while len(syllables) < len(line.notes):
        word = rng.choice([w for w in words if len(w) <= len(line.notes) - len(syllables)])
        places = ["single"] if len(word) == 1 else ["begin"] + ["middle"] * (len(word) - 2) + ["end"]
        syllables += list(zip(word, places))
    for n, (text, place) in zip(line.notes, syllables):
        n.addLyric(text)
        n.lyrics[0].syllabic = place
    s = line.score("h · Lead sheet")
    # Chord names over the staff, as on a lead sheet: one at each measure, sometimes a second halfway. They go in
    # after the accidentals are worked out, because music21 counts a chord name's notes as notes of the measure
    # and would print a natural sign on a G that follows an E7.
    for m in made:
        m.insert(0, harmony.ChordSymbol(rng.choice(chords)))
        if rng.random() < 0.3 and any(n.offset == 2 for n in m.notes):
            m.insert(2, harmony.ChordSymbol(rng.choice(chords)))
    return s


SHEET_MAKERS = {
    "a": plain_notes,
    "b": keys_and_accidentals,
    "c": rhythms,
    "d": range_and_clefs,
    "e": dense_runs,
    "f": markings,
    "g": structure,
    "h": lead_sheet,
}


def engrave(musicxml: Path, label: str, font: str) -> bytes:
    """One Letter page of the score, as SVG, with the sheet's label printed in its title."""
    toolkit = verovio.toolkit()
    toolkit.setOptions({
        "scale": SCALE,
        "pageWidth": round(LETTER_PX[0] * 100 / SCALE),
        "pageHeight": round(LETTER_PX[1] * 100 / SCALE),
        "pageMarginLeft": round(MARGIN_PX * 100 / SCALE),
        "pageMarginRight": round(MARGIN_PX * 100 / SCALE),
        "pageMarginTop": round(MARGIN_PX * 100 / SCALE),
        "pageMarginBottom": round(MARGIN_PX * 100 / SCALE),
        "font": font,
        "header": "auto",
        "footer": "none",
        "breaks": "auto",
        "justifyVertically": True,
    })
    text = musicxml.read_text()
    letter = label[0]
    assert f">{letter} · " in text, label
    if not toolkit.loadData(text.replace(f">{letter} · ", f">{label} · ")):
        raise SystemExit(f"Verovio could not read {musicxml}")
    if toolkit.getPageCount() != 1:
        raise SystemExit(f"{label} takes {toolkit.getPageCount()} pages; a sheet is one page")
    return toolkit.renderToSVG(1).encode()


def main() -> None:
    SHEETS.mkdir(exist_ok=True)
    for letter, make in SHEET_MAKERS.items():
        musicxml = SHEETS / f"{letter}.musicxml"
        make().write("musicxml", musicxml)
        for number, engraver in ENGRAVERS.items():
            label = f"{letter}{number}"
            cairosvg.svg2pdf(bytestring=engrave(musicxml, label, engraver["font"]), write_to=str(SHEETS / f"{label}.pdf"))
            print(label)


if __name__ == "__main__":
    main()