score-reader 0.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- score_reader-0.1.5.dist-info/METADATA +154 -0
- score_reader-0.1.5.dist-info/RECORD +64 -0
- score_reader-0.1.5.dist-info/WHEEL +5 -0
- score_reader-0.1.5.dist-info/entry_points.txt +2 -0
- score_reader-0.1.5.dist-info/licenses/LICENSE +202 -0
- score_reader-0.1.5.dist-info/licenses/NOTICE +13 -0
- score_reader-0.1.5.dist-info/top_level.txt +1 -0
- sheet_interpreter/__init__.py +9 -0
- sheet_interpreter/arpeggio_notation.py +111 -0
- sheet_interpreter/articulation_export.py +49 -0
- sheet_interpreter/audio.py +260 -0
- sheet_interpreter/beam_source.py +163 -0
- sheet_interpreter/boundary_ties.py +82 -0
- sheet_interpreter/bow_export.py +35 -0
- sheet_interpreter/clef_export.py +76 -0
- sheet_interpreter/cli.py +142 -0
- sheet_interpreter/clock_context.py +261 -0
- sheet_interpreter/continuous_slide_curve.py +89 -0
- sheet_interpreter/cue_caption.py +54 -0
- sheet_interpreter/data/LICENSE +202 -0
- sheet_interpreter/data/NOTICE +13 -0
- sheet_interpreter/data/music_sheets_v4_float16.tflite +0 -0
- sheet_interpreter/dynamic_export.py +76 -0
- sheet_interpreter/fall_off_notation.py +128 -0
- sheet_interpreter/grace_export.py +83 -0
- sheet_interpreter/guide_writer.py +287 -0
- sheet_interpreter/guitar_effect.py +32 -0
- sheet_interpreter/guitar_export.py +36 -0
- sheet_interpreter/hairpin_export.py +102 -0
- sheet_interpreter/interpreter.jar +0 -0
- sheet_interpreter/midi.py +340 -0
- sheet_interpreter/multi_rest_wire.py +62 -0
- sheet_interpreter/musicxml.py +937 -0
- sheet_interpreter/natural_harmonic_notation.py +125 -0
- sheet_interpreter/navigation.py +186 -0
- sheet_interpreter/neutral_rest_caption.py +58 -0
- sheet_interpreter/ocr.py +103 -0
- sheet_interpreter/octave_shift_export.py +94 -0
- sheet_interpreter/ornament_export.py +53 -0
- sheet_interpreter/page_processing_budget.py +17 -0
- sheet_interpreter/parenthesized_note_group.py +198 -0
- sheet_interpreter/pdf_annotations.py +52 -0
- sheet_interpreter/performance.py +478 -0
- sheet_interpreter/printed_tempo_spans.py +124 -0
- sheet_interpreter/reader.py +204 -0
- sheet_interpreter/rest_kinds.py +33 -0
- sheet_interpreter/runtime.py +17 -0
- sheet_interpreter/semantic_wire.py +321 -0
- sheet_interpreter/slide_numbering.py +43 -0
- sheet_interpreter/slide_performance.py +204 -0
- sheet_interpreter/slur_export.py +124 -0
- sheet_interpreter/slur_wire.py +159 -0
- sheet_interpreter/source_tempo_clock.py +93 -0
- sheet_interpreter/spelling_export.py +48 -0
- sheet_interpreter/straight_slide.py +76 -0
- sheet_interpreter/sudden_dynamic.py +47 -0
- sheet_interpreter/technique_export.py +62 -0
- sheet_interpreter/tie_owners.py +43 -0
- sheet_interpreter/tremolo_export.py +93 -0
- sheet_interpreter/tremolo_performance.py +45 -0
- sheet_interpreter/tremolo_wire.py +138 -0
- sheet_interpreter/typed_events.py +57 -0
- sheet_interpreter/typed_performance.py +44 -0
- sheet_interpreter/visual_size.py +18 -0
|
@@ -0,0 +1,937 @@
|
|
|
1
|
+
from . import straight_slide, slide_numbering
|
|
2
|
+
# Copyright 2026 Luckolite
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""MusicXML 4.0 concert-pitch export of the decoded performance (not source engraving)."""
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
from math import gcd
|
|
8
|
+
from fractions import Fraction
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
import math
|
|
11
|
+
import struct
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import xml.etree.ElementTree as ET
|
|
14
|
+
from .typed_events import event_kind, validate_unpitched, notation_order, display_position
|
|
15
|
+
from .rest_kinds import rest_kind, full_measure_span
|
|
16
|
+
from . import visual_size, cue_caption, bow_export, clef_export, articulation_export, ornament_export, grace_export, spelling_export, tremolo_export
|
|
17
|
+
from . import guitar_export
|
|
18
|
+
from .natural_harmonic_notation import owner_index as natural_harmonic_owner_index
|
|
19
|
+
from .fall_off_notation import owner_index as fall_off_owner_index
|
|
20
|
+
from . import parenthesized_note_group
|
|
21
|
+
|
|
22
|
+
DIVISIONS = 10080 # Exact common binary values and triplet/quintuplet/septuplet subdivisions.
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _natural_harmonic_target(note):
|
|
26
|
+
"""Mirror ScoreNaturalHarmonicNotation.target using the wire's float32 values."""
|
|
27
|
+
try:
|
|
28
|
+
measure, staff, count = note['measureIndex'], note['staffIndex'], note['staffCount']
|
|
29
|
+
step = note['staffStep']
|
|
30
|
+
position, page_y = float(note['positionInMeasure']), float(note['pageY'])
|
|
31
|
+
except (KeyError, TypeError, ValueError):
|
|
32
|
+
return None
|
|
33
|
+
if (event_kind(note) != 'PITCHED' or type(measure) is not int or measure < 0
|
|
34
|
+
or type(staff) is not int or type(count) is not int or count < 1 or not 0 <= staff < count
|
|
35
|
+
or type(step) is not int or not math.isfinite(position) or not 0 <= position <= 1
|
|
36
|
+
or not math.isfinite(page_y) or not 0 <= page_y <= 1):
|
|
37
|
+
return None
|
|
38
|
+
try:
|
|
39
|
+
pbits = struct.unpack('>I', struct.pack('>f', position))[0]
|
|
40
|
+
ybits = struct.unpack('>I', struct.pack('>f', page_y))[0]
|
|
41
|
+
except (OverflowError, struct.error):
|
|
42
|
+
return None
|
|
43
|
+
return (f'natural-harmonic-note-v1:{measure}:{staff}:{count}:'
|
|
44
|
+
f'{pbits:08x}:{step}:{ybits:08x}')
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def element(parent, tag, value=None, **attributes):
|
|
48
|
+
node = ET.SubElement(parent, tag, {key: str(value) for key, value in attributes.items()})
|
|
49
|
+
if value is not None:
|
|
50
|
+
node.text = str(value)
|
|
51
|
+
return node
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ticks(value):
|
|
55
|
+
if not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
|
|
56
|
+
raise ValueError("MusicXML needs finite, nonnegative event times")
|
|
57
|
+
return round(value * DIVISIONS)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def note_type(node, duration, event=None):
|
|
61
|
+
actual = event.get('tupletActualNotes', 1) if event else 1
|
|
62
|
+
normal = event.get('tupletNormalNotes', 1) if event else 1
|
|
63
|
+
if (type(actual) is not int or type(normal) is not int or actual not in (1,2,3,4,5,6,7)
|
|
64
|
+
or not 1 <= normal <= 16 or actual == 1 and normal != 1):
|
|
65
|
+
raise ValueError('Unsupported explicit tuplet ratio')
|
|
66
|
+
if actual != 1:
|
|
67
|
+
for denominator, name in ((1,'whole'), (2,'half'), (4,'quarter'), (8,'eighth'),
|
|
68
|
+
(16,'16th'), (32,'32nd'), (64,'64th')):
|
|
69
|
+
base = DIVISIONS * 4 // denominator
|
|
70
|
+
for dots, scale in ((0,1), (1,1.5), (2,1.75)):
|
|
71
|
+
if abs(duration - base*scale*normal/actual) <= 1:
|
|
72
|
+
element(node, 'type', name)
|
|
73
|
+
for _ in range(dots):
|
|
74
|
+
element(node, 'dot')
|
|
75
|
+
modification = element(node, 'time-modification')
|
|
76
|
+
element(modification, 'actual-notes', actual)
|
|
77
|
+
element(modification, 'normal-notes', normal)
|
|
78
|
+
return
|
|
79
|
+
return # An explicit ratio must not silently become ordinary or a different tuplet.
|
|
80
|
+
for denominator, name in ((1, 'whole'), (2, 'half'), (4, 'quarter'), (8, 'eighth'),
|
|
81
|
+
(16, '16th'), (32, '32nd'), (64, '64th')):
|
|
82
|
+
base = DIVISIONS * 4 // denominator
|
|
83
|
+
for dots, scale in ((0, 1), (1, 1.5), (2, 1.75)):
|
|
84
|
+
if abs(duration - base * scale) <= 1:
|
|
85
|
+
element(node, 'type', name)
|
|
86
|
+
for _ in range(dots):
|
|
87
|
+
element(node, 'dot')
|
|
88
|
+
return
|
|
89
|
+
for actual, normal in ((3, 2), (5, 4), (7, 4)):
|
|
90
|
+
if abs(duration - base * normal / actual) <= 1:
|
|
91
|
+
element(node, 'type', name)
|
|
92
|
+
modification = element(node, 'time-modification')
|
|
93
|
+
element(modification, 'actual-notes', actual)
|
|
94
|
+
element(modification, 'normal-notes', normal)
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@lru_cache(maxsize=256)
|
|
99
|
+
def exact_written_parts(duration, values):
|
|
100
|
+
"""Fewest exact glyphs from a proved duration vocabulary; no clock rounding."""
|
|
101
|
+
if not values or duration <= 0:
|
|
102
|
+
return None
|
|
103
|
+
quantum = 0
|
|
104
|
+
for value in values:
|
|
105
|
+
quantum = gcd(quantum, value)
|
|
106
|
+
if duration % quantum:
|
|
107
|
+
return None
|
|
108
|
+
target = duration // quantum
|
|
109
|
+
units = tuple(value // quantum for value in values)
|
|
110
|
+
unreachable = target + 1
|
|
111
|
+
count, choice = [unreachable] * (target + 1), [0] * (target + 1)
|
|
112
|
+
count[0] = 0
|
|
113
|
+
for amount in range(1, target + 1):
|
|
114
|
+
for unit in units:
|
|
115
|
+
if unit <= amount and count[amount-unit] + 1 < count[amount]:
|
|
116
|
+
count[amount], choice[amount] = count[amount-unit] + 1, unit
|
|
117
|
+
if not choice[target]:
|
|
118
|
+
return None
|
|
119
|
+
parts = []
|
|
120
|
+
while target:
|
|
121
|
+
parts.append(choice[target] * quantum)
|
|
122
|
+
target -= choice[target]
|
|
123
|
+
return tuple(sorted(parts, reverse=True))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def duration_parts(duration, events=()):
|
|
127
|
+
"""Split exact composite spans while retaining each head's explicit ratio."""
|
|
128
|
+
heads = tuple(events) or (None,)
|
|
129
|
+
probes = []
|
|
130
|
+
for event in heads:
|
|
131
|
+
probe = ET.Element('note')
|
|
132
|
+
note_type(probe, duration, event)
|
|
133
|
+
probes.append(probe)
|
|
134
|
+
if all(probe.find('type') is not None for probe in probes):
|
|
135
|
+
return (duration,)
|
|
136
|
+
written_values = {Fraction(DIVISIONS * 4, denominator) * Fraction(numerator, 4)
|
|
137
|
+
for denominator in (1, 2, 4, 8, 16, 32, 64)
|
|
138
|
+
for numerator in (4, 6, 7)}
|
|
139
|
+
if any(event and event.get('tupletActualNotes', 1) != 1 for event in heads):
|
|
140
|
+
common = None
|
|
141
|
+
for event in heads:
|
|
142
|
+
actual = event.get('tupletActualNotes', 1) if event else 1
|
|
143
|
+
normal = event.get('tupletNormalNotes', 1) if event else 1
|
|
144
|
+
values = {int(value * normal / actual) for value in written_values
|
|
145
|
+
if (value * normal / actual).denominator == 1}
|
|
146
|
+
common = values if common is None else common & values
|
|
147
|
+
parts = exact_written_parts(duration, tuple(sorted(common, reverse=True)))
|
|
148
|
+
return parts if parts is not None else (duration,)
|
|
149
|
+
# Keep the existing inferred-clock boundary: only ordinary 64th-grid spans split.
|
|
150
|
+
if duration % (DIVISIONS // 16):
|
|
151
|
+
return (duration,)
|
|
152
|
+
values = sorted((int(value) for value in written_values if value.denominator == 1), reverse=True)
|
|
153
|
+
parts, remaining = [], duration
|
|
154
|
+
while remaining:
|
|
155
|
+
value = next(v for v in values if v <= remaining)
|
|
156
|
+
parts.append(value)
|
|
157
|
+
remaining -= value
|
|
158
|
+
return tuple(parts)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def metric_pulse(value):
|
|
162
|
+
for i, name in enumerate(('whole', 'half', 'quarter', 'eighth', '16th', '32nd')):
|
|
163
|
+
for dots, scale in enumerate((1, 1.5, 1.75)):
|
|
164
|
+
if value == math.ldexp(4, -i)*scale:
|
|
165
|
+
return name, dots
|
|
166
|
+
raise ValueError('Unsupported MusicXML metric pulse')
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def tempo_mark(tempo):
|
|
170
|
+
"""Printed pulse and rate; sound tempo remains quarter notes per minute."""
|
|
171
|
+
bpm, pulse = tempo['bpm'], tempo.get('beatUnit', 1)
|
|
172
|
+
if (type(bpm) not in (int, float) or not math.isfinite(bpm) or not 15 <= bpm <= 1600
|
|
173
|
+
or type(pulse) not in (int, float) or not math.isfinite(pulse) or not 0 < pulse <= 4):
|
|
174
|
+
raise ValueError('Invalid printed tempo')
|
|
175
|
+
names = ('whole', 'half', 'quarter', 'eighth', '16th', '32nd', '64th',
|
|
176
|
+
'128th', '256th', '512th', '1024th')
|
|
177
|
+
for i, name in enumerate(names):
|
|
178
|
+
for dots, scale in enumerate((1, 1.5, 1.75)):
|
|
179
|
+
unit = math.ldexp(4, -i) * scale
|
|
180
|
+
if abs(unit - pulse) < 1e-9:
|
|
181
|
+
return name, dots, bpm / unit
|
|
182
|
+
# Match ScoreTempoMark: unsupported pulses use an equivalent quarter mark.
|
|
183
|
+
return 'quarter', 0, bpm
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def expression_direction(measure, mark, offset):
|
|
187
|
+
kind = mark['kind']
|
|
188
|
+
caption = mark.get('_neutralRestCaption', False)
|
|
189
|
+
direction = element(measure, 'direction', placement='below' if caption or kind in ('PEDAL_DOWN', 'PEDAL_UP') else 'above')
|
|
190
|
+
type_node = element(direction, 'direction-type')
|
|
191
|
+
if mark.get('_hairpin'):
|
|
192
|
+
direction.set('placement', 'below')
|
|
193
|
+
element(type_node, 'wedge', type=mark['_hairpin'], number=mark['_hairpinNumber'])
|
|
194
|
+
elif mark.get('_absoluteDynamic'):
|
|
195
|
+
direction.set('placement', 'below')
|
|
196
|
+
caption = mark.get('_suddenDynamic')
|
|
197
|
+
if caption and caption['before']:
|
|
198
|
+
element(type_node, 'words', caption['qualifier']+' ')
|
|
199
|
+
type_node = element(direction, 'direction-type')
|
|
200
|
+
element(element(type_node, 'dynamics'), mark['_absoluteDynamic'])
|
|
201
|
+
if caption and not caption['before']:
|
|
202
|
+
element(element(direction, 'direction-type'), 'words', ' '+caption['qualifier'])
|
|
203
|
+
elif kind in ('PEDAL_DOWN', 'PEDAL_UP'):
|
|
204
|
+
literal = (mark.get('targetEventId') or '').startswith('expression-column:') and any(
|
|
205
|
+
e.get('sourceId') == 'printed-expression-word' for e in mark.get('evidence', []))
|
|
206
|
+
if literal:
|
|
207
|
+
printed = next((e['printedText'] for e in mark.get('evidence', []) if e.get('printedText')), None)
|
|
208
|
+
if not printed:
|
|
209
|
+
measure.remove(direction)
|
|
210
|
+
return
|
|
211
|
+
element(type_node, 'words', printed)
|
|
212
|
+
else:
|
|
213
|
+
element(type_node, 'pedal', type='start' if kind == 'PEDAL_DOWN' else 'stop', line='yes', sign='no')
|
|
214
|
+
elif kind == 'METRIC_MODULATION':
|
|
215
|
+
fields = mark.get('qualifierText', '').split(':')
|
|
216
|
+
if len(fields) != 3 or fields[0] != 'metric-pulse-v1':
|
|
217
|
+
raise ValueError('Metric relationship has no explicit pulse pair')
|
|
218
|
+
metronome = element(type_node, 'metronome')
|
|
219
|
+
for encoded in fields[1:]:
|
|
220
|
+
name, dots = metric_pulse(float(encoded))
|
|
221
|
+
element(metronome, 'beat-unit', name)
|
|
222
|
+
for _ in range(dots):
|
|
223
|
+
element(metronome, 'beat-unit-dot')
|
|
224
|
+
elif kind in ('SFORZANDO', 'SFORZATO', 'SFORZANDO_PIANO'):
|
|
225
|
+
name = {'SFORZANDO': 'sf', 'SFORZATO': 'sfz', 'SFORZANDO_PIANO': 'sfp'}[kind]
|
|
226
|
+
element(element(type_node, 'dynamics'), name)
|
|
227
|
+
else:
|
|
228
|
+
fallback = {'RITARDANDO': 'rit.', 'RALLENTANDO': 'rall.', 'RITENUTO': 'ritenuto',
|
|
229
|
+
'ACCELERANDO': 'accel.', 'A_TEMPO': 'a tempo', 'TEMPO_PRIMO': 'tempo primo',
|
|
230
|
+
'SAME_TEMPO': "l'istesso tempo", 'FERMATA': 'fermata', 'BREATH': 'breath', 'CAESURA': 'caesura'}
|
|
231
|
+
printed = next((e['printedText'] for e in mark.get('evidence', []) if e.get('printedText')), fallback.get(kind))
|
|
232
|
+
if printed is None:
|
|
233
|
+
measure.remove(direction)
|
|
234
|
+
return
|
|
235
|
+
element(type_node, 'words', printed)
|
|
236
|
+
element(direction, 'offset', offset)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def emit_note(measure, duration, voice, event=None, chord=False, stop=False, start=False, flats=False,
|
|
240
|
+
gliss_start=False, gliss_stop=False, slide_start=False, slide_stop=False, fragment_end=None, rest_symbols=(), full_measure=False,
|
|
241
|
+
articulation_flags=0, attack_fragment=True, grace=None, bow_direction=None):
|
|
242
|
+
node = element(measure, 'note')
|
|
243
|
+
if grace is not None:
|
|
244
|
+
element(node, 'grace', **{('steal-time-previous' if grace['afterGrace'] else 'steal-time-following'): grace['stealPercent']})
|
|
245
|
+
if chord:
|
|
246
|
+
element(node, 'chord')
|
|
247
|
+
if event is None:
|
|
248
|
+
element(node, 'rest', **({'measure': 'yes'} if full_measure else {}))
|
|
249
|
+
elif event_kind(event) == 'UNPITCHED':
|
|
250
|
+
identity = element(node, 'unpitched')
|
|
251
|
+
element(identity, 'display-step', event['displayStep'])
|
|
252
|
+
element(identity, 'display-octave', event['displayOctave'])
|
|
253
|
+
else:
|
|
254
|
+
midi = event['midi']
|
|
255
|
+
names = (('C', 0), ('D', -1), ('D', 0), ('E', -1), ('E', 0), ('F', 0),
|
|
256
|
+
('G', -1), ('G', 0), ('A', -1), ('A', 0), ('B', -1), ('B', 0)) if flats else (
|
|
257
|
+
('C', 0), ('C', 1), ('D', 0), ('D', 1), ('E', 0), ('F', 0),
|
|
258
|
+
('F', 1), ('G', 0), ('G', 1), ('A', 0), ('A', 1), ('B', 0))
|
|
259
|
+
step, alter = names[midi % 12]
|
|
260
|
+
step, alter, octave = event.get('retainedSpelling') or (step, alter, midi // 12 - 1)
|
|
261
|
+
pitch = element(node, 'pitch')
|
|
262
|
+
element(pitch, 'step', step)
|
|
263
|
+
if alter:
|
|
264
|
+
element(pitch, 'alter', alter)
|
|
265
|
+
element(pitch, 'octave', octave)
|
|
266
|
+
if grace is None:
|
|
267
|
+
element(node, 'duration', duration)
|
|
268
|
+
for active, kind in ((stop, 'stop'), (start, 'start')):
|
|
269
|
+
if active:
|
|
270
|
+
element(node, 'tie', type=kind)
|
|
271
|
+
if event and event.get('durationFallback'):
|
|
272
|
+
element(node, 'footnote', 'Estimated duration from interpretation')
|
|
273
|
+
element(node, 'voice', voice)
|
|
274
|
+
if full_measure:
|
|
275
|
+
element(node, 'type', 'whole')
|
|
276
|
+
else:
|
|
277
|
+
paired = event.get('retainedTremolo') if event else None
|
|
278
|
+
if paired and (grace is not None or stop or start or duration != event['end'] - event['start']):
|
|
279
|
+
raise ValueError('Paired tremolo requires an unsplit original endpoint')
|
|
280
|
+
note_type(node, duration * 2 if paired else duration, event)
|
|
281
|
+
if paired and paired.get('canonicalClockPolicy'):
|
|
282
|
+
modification = node.find('time-modification')
|
|
283
|
+
if modification is None:
|
|
284
|
+
modification = element(node, 'time-modification')
|
|
285
|
+
element(modification, 'actual-notes', 2)
|
|
286
|
+
element(modification, 'normal-notes', 1)
|
|
287
|
+
else:
|
|
288
|
+
actual_node = modification.find('actual-notes')
|
|
289
|
+
actual_node.text = str(int(actual_node.text) * 2)
|
|
290
|
+
|
|
291
|
+
if event and event.get('retainedVisualSize') == 'CUE' and node.find('type') is not None:
|
|
292
|
+
node.find('type').set('size', 'grace-cue' if grace is not None else 'cue')
|
|
293
|
+
if grace is not None and node.find('type') is None:
|
|
294
|
+
raise ValueError('Grace note has no exact written type')
|
|
295
|
+
if event and (event.get('retainedTremolo') or {}).get('printedFilled'):
|
|
296
|
+
if event['retainedTremolo'].get('printedStem') in (-1, 1):
|
|
297
|
+
element(node, 'stem', 'down' if event['retainedTremolo']['printedStem'] < 0 else 'up')
|
|
298
|
+
element(node, 'notehead', 'normal', filled='yes')
|
|
299
|
+
if event is not None and event_kind(event) == 'UNPITCHED':
|
|
300
|
+
element(node, 'notehead', 'x')
|
|
301
|
+
effect = event.get('guitarEffect') if event and attack_fragment else None
|
|
302
|
+
ornament_flags = event.get('retainedOrnamentFlags', 0) if event and attack_fragment else 0
|
|
303
|
+
symbols = [mark for mark in (event.get('releaseSymbols', []) if event else rest_symbols)
|
|
304
|
+
if mark['release'] == fragment_end]
|
|
305
|
+
paired = event.get('retainedTremolo') if event else None
|
|
306
|
+
arpeggio = bool(event and event.get('retainedArpeggio') and attack_fragment and grace is None)
|
|
307
|
+
natural_harmonic = bool(event and event.get('retainedNaturalHarmonic') and attack_fragment and grace is None)
|
|
308
|
+
fall_off = bool(event and event.get('retainedFallOff') and fragment_end == event['end'] and grace is None)
|
|
309
|
+
parenthesis_left = event.get('retainedParenthesisStart') if event and attack_fragment and grace is None else None
|
|
310
|
+
parenthesis_right = (event.get('retainedParenthesisStop')
|
|
311
|
+
if event and event.get('retainedParenthesisStop') and grace is None
|
|
312
|
+
and fragment_end == event['end'] else None)
|
|
313
|
+
if stop or start or effect or symbols or gliss_start or gliss_stop or slide_start or slide_stop or articulation_flags or ornament_flags or paired or arpeggio or natural_harmonic or fall_off or parenthesis_left or parenthesis_right or bow_direction is not None:
|
|
314
|
+
notation = element(node, 'notations')
|
|
315
|
+
if arpeggio:
|
|
316
|
+
element(notation, 'arpeggiate')
|
|
317
|
+
for endpoint, left in ((parenthesis_left, True), (parenthesis_right, False)):
|
|
318
|
+
if endpoint is not None:
|
|
319
|
+
f32 = parenthesized_note_group.f32
|
|
320
|
+
decimal = lambda value: format(Decimal(str(f32(value))), 'f')
|
|
321
|
+
element(notation, 'other-notation', 'music-sheets-parenthesis-group:' + endpoint['id'],
|
|
322
|
+
type='start' if left else 'stop', number=endpoint['number'],
|
|
323
|
+
id=endpoint['id'] + ('-left' if left else '-right'),
|
|
324
|
+
smufl='noteheadParenthesisLeft' if left else 'noteheadParenthesisRight',
|
|
325
|
+
**{'relative-x': decimal(endpoint['x'] * 10),
|
|
326
|
+
'relative-y': decimal(-endpoint['y'] * 10),
|
|
327
|
+
'font-size': decimal(f32(endpoint['height'] / f32(1.6)) * 100) + '%'})
|
|
328
|
+
if natural_harmonic:
|
|
329
|
+
element(element(notation, 'technical'), 'harmonic')
|
|
330
|
+
element(notation.find('technical/harmonic'), 'natural')
|
|
331
|
+
if fall_off:
|
|
332
|
+
articulations = notation.find('articulations')
|
|
333
|
+
if articulations is None:
|
|
334
|
+
articulations = element(notation, 'articulations')
|
|
335
|
+
element(articulations, 'falloff', **{'line-shape': 'curved', 'line-type': 'solid'})
|
|
336
|
+
if paired and not chord:
|
|
337
|
+
element(element(notation, 'ornaments'), 'tremolo', paired['strokes'], type=paired['type'])
|
|
338
|
+
for active, kind in ((stop, 'stop'), (start, 'start')):
|
|
339
|
+
if active:
|
|
340
|
+
element(notation, 'tied', type=kind)
|
|
341
|
+
for active, kind in ((gliss_stop, 'stop'), (gliss_start, 'start')):
|
|
342
|
+
if active:
|
|
343
|
+
element(notation, 'glissando', type=kind,
|
|
344
|
+
number=event['gliss_'+kind], **{'line-type':'wavy'})
|
|
345
|
+
for active, kind in ((slide_stop, 'stop'), (slide_start, 'start')):
|
|
346
|
+
if active:
|
|
347
|
+
element(notation, 'slide', type=kind, number=event['slide_'+kind], **{'line-type':'solid'})
|
|
348
|
+
if effect:
|
|
349
|
+
guitar_export.write(notation, effect)
|
|
350
|
+
if articulation_flags:
|
|
351
|
+
articulation_export.write(notation, articulation_flags)
|
|
352
|
+
if bow_direction is not None:
|
|
353
|
+
bow_export.write(notation, bow_direction)
|
|
354
|
+
if ornament_flags:
|
|
355
|
+
ornament_export.write(notation, ornament_flags)
|
|
356
|
+
for symbol in symbols:
|
|
357
|
+
kind = symbol['kind']
|
|
358
|
+
if kind == 'FERMATA':
|
|
359
|
+
element(notation, 'fermata', type='inverted' if symbol.get('inverted') else 'upright')
|
|
360
|
+
else:
|
|
361
|
+
articulations = notation.find('articulations')
|
|
362
|
+
if articulations is None:
|
|
363
|
+
articulations = element(notation, 'articulations')
|
|
364
|
+
element(articulations, 'caesura' if kind == 'CAESURA' else 'breath-mark',
|
|
365
|
+
None if kind == 'CAESURA' else symbol.get('value', 'comma'))
|
|
366
|
+
return node
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def emit_rest_gap(measure, start, end, voice, symbols, literal_edges=()):
|
|
370
|
+
boundaries = sorted({start, end}
|
|
371
|
+
| {value for s in symbols for value in (s['start'], s['release']) if start < value < end}
|
|
372
|
+
| {value for value in literal_edges if start < value < end})
|
|
373
|
+
for a, b in zip(boundaries, boundaries[1:]):
|
|
374
|
+
cursor = a
|
|
375
|
+
for duration in duration_parts(b-a):
|
|
376
|
+
cursor += duration
|
|
377
|
+
emit_note(measure, duration, voice, fragment_end=cursor, rest_symbols=symbols)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def write_musicxml(document, path, *, meter=(4, 4), key_fifths=0, bpm=None):
|
|
381
|
+
"""Write uncompressed .musicxml; each decoded staff becomes a concert-pitch part.
|
|
382
|
+
|
|
383
|
+
Derived voices, gap rests and enharmonic spellings are reconstructed. Original
|
|
384
|
+
Engraving and guitar string/fret placement are reconstructed only where supported.
|
|
385
|
+
Expressive symbols preserve written evidence; preview holds never lengthen notation.
|
|
386
|
+
"""
|
|
387
|
+
from .boundary_ties import resolve_boundary_ties
|
|
388
|
+
for page in document['pages']:
|
|
389
|
+
for event in page['events']:
|
|
390
|
+
event_kind(event)
|
|
391
|
+
validate_unpitched(event)
|
|
392
|
+
for row in page.get('score', {}).get('rests', []):
|
|
393
|
+
if rest_kind(row) == 'FULL_MEASURE':
|
|
394
|
+
full_measure_span(page, row)
|
|
395
|
+
document = resolve_boundary_ties(document)
|
|
396
|
+
from .printed_tempo_spans import resolve_pages, preserve_end, SOURCE, GRADUAL
|
|
397
|
+
document = dict(document, pages=resolve_pages(document['pages']))
|
|
398
|
+
from . import slur_export
|
|
399
|
+
retained_slurs = slur_export.retained_spans(document['pages'], include_candidates=True)
|
|
400
|
+
retained_slur_ties = set()
|
|
401
|
+
requested_slur_owners = {owner for _, a, b in retained_slurs for owner in (a, b)}
|
|
402
|
+
slur_attacks = {}
|
|
403
|
+
meter = tuple(document.get('initialMeter', meter))
|
|
404
|
+
key_fifths = document.get('initialKeyFifths', key_fifths)
|
|
405
|
+
bpm = document.get('initialBpm', 120) if bpm is None else bpm
|
|
406
|
+
if len(meter) != 2 or not all(isinstance(n, int) and 1 <= n <= 32 for n in meter) or meter[1] & (meter[1]-1):
|
|
407
|
+
raise ValueError('Invalid MusicXML initial meter')
|
|
408
|
+
if not isinstance(key_fifths, int) or not -7 <= key_fifths <= 7 or not math.isfinite(bpm) or not 15 <= bpm <= 400:
|
|
409
|
+
raise ValueError('Invalid MusicXML key or tempo')
|
|
410
|
+
bars, events, expressions, full_rests, literal_rests = [], [], [], [], []
|
|
411
|
+
first_number = 1
|
|
412
|
+
for page in document['pages']:
|
|
413
|
+
if not page['measureBeats']:
|
|
414
|
+
continue
|
|
415
|
+
score = page['score']
|
|
416
|
+
first = score.get('firstMeasureNumber', 0)
|
|
417
|
+
if type(first) is int:
|
|
418
|
+
first_number = max(1, first)
|
|
419
|
+
if score.get('openingPickup') is True and 0 <= first <= 1:
|
|
420
|
+
first_number = 0
|
|
421
|
+
break
|
|
422
|
+
parenthesis_level_ends = [float("-inf")] * 17
|
|
423
|
+
printed_rest_groups = []
|
|
424
|
+
octave_owned = {}
|
|
425
|
+
offset = 0
|
|
426
|
+
current_meter, current_key = meter, key_fifths
|
|
427
|
+
for page_index, page in enumerate(document['pages']):
|
|
428
|
+
score = page['score']
|
|
429
|
+
local_start = 0
|
|
430
|
+
first_bar = len(bars)
|
|
431
|
+
from . import multi_rest_wire
|
|
432
|
+
for group in multi_rest_wire.checked_score(score):
|
|
433
|
+
printed_rest_groups.append(dict(group, firstBar=first_bar+group['firstMeasureIndex']))
|
|
434
|
+
from . import source_tempo_clock
|
|
435
|
+
for index, beats in enumerate(page['measureBeats']):
|
|
436
|
+
length = ticks(beats)
|
|
437
|
+
if length <= 0:
|
|
438
|
+
raise ValueError('MusicXML measure duration must be positive')
|
|
439
|
+
for change in score.get('keyChanges', []):
|
|
440
|
+
if change['measureIndex'] == index:
|
|
441
|
+
current_key = change['fifths']
|
|
442
|
+
for change in score.get('meterChanges', []):
|
|
443
|
+
if change['measureIndex'] == index:
|
|
444
|
+
current_meter = (change['numerator'], change['denominator'])
|
|
445
|
+
bar = dict(start=offset+local_start, length=length, meter=current_meter, key=current_key,
|
|
446
|
+
tempos=[dict(c, _sourceTempoOnset=source_tempo_clock.onset(page, c))
|
|
447
|
+
for c in score.get('tempoChanges', []) if c['measureIndex'] == index])
|
|
448
|
+
bars.append(bar)
|
|
449
|
+
local_start += length
|
|
450
|
+
for row in score.get('rests', []):
|
|
451
|
+
if rest_kind(row) == 'FULL_MEASURE':
|
|
452
|
+
bar_index = first_bar+row['measureIndex']
|
|
453
|
+
bar = bars[bar_index]
|
|
454
|
+
full_rests.append(dict(row, barIndex=bar_index, sourcePageIndex=page_index,
|
|
455
|
+
start=bar['start'], end=bar['start']+bar['length'],
|
|
456
|
+
restIdentity=len(full_rests), releaseSymbols=[]))
|
|
457
|
+
# Literal rest columns retain their written subdivisions in proved silence slots.
|
|
458
|
+
from .performance import _rest_column_span
|
|
459
|
+
for row in score.get('rests', []):
|
|
460
|
+
if rest_kind(row) != 'LITERAL' or not all(key in row for key in
|
|
461
|
+
('measureIndex', 'staffIndex', 'staffCount', 'positionInMeasure', 'durationBeats')):
|
|
462
|
+
continue
|
|
463
|
+
m = row['measureIndex']
|
|
464
|
+
if not isinstance(m, int) or not 0 <= m < len(page['measureBeats']):
|
|
465
|
+
continue
|
|
466
|
+
span = _rest_column_span(page, m, row['staffIndex'], row['staffCount'],
|
|
467
|
+
row['positionInMeasure'], 0)
|
|
468
|
+
if span is None:
|
|
469
|
+
continue
|
|
470
|
+
bar = bars[first_bar+m]
|
|
471
|
+
start = bar['start']+ticks(span[0]['quarterBeatOffset'])
|
|
472
|
+
end = bar['start']+ticks(span[1]['quarterBeatOffset'])
|
|
473
|
+
if bar['start'] <= start < end <= bar['start']+bar['length']:
|
|
474
|
+
literal_rests.append(dict(row, start=start, end=end))
|
|
475
|
+
first_event = len(events)
|
|
476
|
+
written = grace_export.plan(page, ticks)
|
|
477
|
+
paired_tremolos = tremolo_export.retained(page)
|
|
478
|
+
for note_index, n in enumerate(page['events']):
|
|
479
|
+
if event_kind(n) == 'PITCHED' and (not isinstance(n['midi'], int) or not 0 <= n['midi'] <= 127):
|
|
480
|
+
raise ValueError('MusicXML note pitch must be a MIDI integer in 0..127')
|
|
481
|
+
start, duration = ticks(n['startBeat']), ticks(n['durationBeats'])
|
|
482
|
+
placement = written.get(note_index)
|
|
483
|
+
if placement is not None:
|
|
484
|
+
start, duration = placement['start'], placement['duration']
|
|
485
|
+
is_grace = placement is not None and placement['grace']
|
|
486
|
+
if duration <= 0 or (start if is_grace else start + duration) > local_start + 2:
|
|
487
|
+
raise ValueError('MusicXML note duration lies outside the page timeline')
|
|
488
|
+
measure_index = n.get('measureIndex')
|
|
489
|
+
spelling_key = (bars[first_bar+measure_index]['key']
|
|
490
|
+
if type(measure_index) is int and 0 <= measure_index < len(page['measureBeats'])
|
|
491
|
+
else None)
|
|
492
|
+
events.append(dict(n, start=offset+start, end=offset+(start if is_grace else min(local_start,start+duration)), tie_stop=False, tie_start=False,
|
|
493
|
+
sourceIdentity=len(events), retainedClef=clef_export.retained(page, note_index),
|
|
494
|
+
retainedArticulations=articulation_export.retained(page, note_index),
|
|
495
|
+
retainedBow=bow_export.retained(page, note_index),
|
|
496
|
+
retainedVisualSize=visual_size.retained(page, note_index),
|
|
497
|
+
retainedSpelling=spelling_export.retained(page, note_index, spelling_key),
|
|
498
|
+
retainedOrnamentFlags=ornament_export.retained(page, note_index),
|
|
499
|
+
retainedTremolo=paired_tremolos.get(note_index), retainedArpeggio=False, retainedNaturalHarmonic=False))
|
|
500
|
+
if is_grace:
|
|
501
|
+
events[-1].update(grace=True, graceOrdinal=placement['ordinal'], afterGrace=placement['after'],
|
|
502
|
+
stealPercent=placement['steal'], graceWrittenDuration=duration,
|
|
503
|
+
principalSourceIdentity=first_event+placement['principal'])
|
|
504
|
+
from . import technique_export
|
|
505
|
+
expressions.extend(technique_export.plan(page, events[first_event:], bars[first_bar:], f'page:{page_index}'))
|
|
506
|
+
from . import dynamic_export
|
|
507
|
+
expressions.extend(dynamic_export.plan(page, events[first_event:], bars[first_bar:], f'page:{page_index}'))
|
|
508
|
+
from . import hairpin_export
|
|
509
|
+
expressions.extend(hairpin_export.plan(page, events[first_event:], bars[first_bar:], f'page:{page_index}'))
|
|
510
|
+
for source, target, _ in straight_slide.bindings(page):
|
|
511
|
+
# This global endpoint identity is an internal token, not a MusicXML number.
|
|
512
|
+
token = first_event + target
|
|
513
|
+
events[first_event+source]['slide_start'] = token
|
|
514
|
+
events[first_event+target]['slide_stop'] = token
|
|
515
|
+
from .performance import _column_members, _rest_owned, _rest_span, _rest_identity, _resolve_pedal, _anchor
|
|
516
|
+
def absolute(anchor):
|
|
517
|
+
if anchor is None:
|
|
518
|
+
return None
|
|
519
|
+
m, q = anchor['measureIndex'], anchor['quarterBeatOffset']
|
|
520
|
+
if not isinstance(m, int) or not 0 <= m <= len(page['measureBeats']):
|
|
521
|
+
raise ValueError('Expression anchor outside MusicXML page')
|
|
522
|
+
if not isinstance(q, (int, float)) or not math.isfinite(q) or q < 0 or q > (page['measureBeats'][m] if m < len(page['measureBeats']) else 0):
|
|
523
|
+
raise ValueError('Expression anchor outside MusicXML measure')
|
|
524
|
+
return offset+ticks(sum(page['measureBeats'][:m])+q)
|
|
525
|
+
from .arpeggio_notation import plan as arpeggio_plan
|
|
526
|
+
from .neutral_rest_caption import is_caption, start as caption_start
|
|
527
|
+
harmonic_marks = [m for m in score.get('expressiveEvents', [])
|
|
528
|
+
if m.get('kind') == 'NATURAL_HARMONIC']
|
|
529
|
+
harmonic_owner_counts = defaultdict(int)
|
|
530
|
+
for harmonic_mark in harmonic_marks:
|
|
531
|
+
owner_index = natural_harmonic_owner_index(harmonic_mark, score.get('notes', []))
|
|
532
|
+
if owner_index is not None:
|
|
533
|
+
harmonic_owner_counts[owner_index] += 1
|
|
534
|
+
fall_off_marks = [m for m in score.get('expressiveEvents', [])
|
|
535
|
+
if m.get('kind') == 'FALL_OFF']
|
|
536
|
+
fall_off_owner_counts = defaultdict(int)
|
|
537
|
+
for fall_off_mark in fall_off_marks:
|
|
538
|
+
owner_index = fall_off_owner_index(fall_off_mark, score.get('notes', []))
|
|
539
|
+
if owner_index is not None:
|
|
540
|
+
fall_off_owner_counts[owner_index] += 1
|
|
541
|
+
for group_mark, pair, members in parenthesized_note_group.retained(page):
|
|
542
|
+
first, last = events[first_event + members[0]], events[first_event + members[-1]]
|
|
543
|
+
number = next((n for n in range(1, 17) if parenthesis_level_ends[n] <= first['start']), None)
|
|
544
|
+
if number is None:
|
|
545
|
+
continue
|
|
546
|
+
parenthesis_level_ends[number] = last['end']
|
|
547
|
+
group_id = parenthesized_note_group.group_id(group_mark, pair)
|
|
548
|
+
lx, ly, rx, ry, lh, rh = pair.geometry
|
|
549
|
+
first['retainedParenthesisStart'] = dict(id=group_id, number=number, x=lx, y=ly, height=lh)
|
|
550
|
+
last['retainedParenthesisStop'] = dict(id=group_id, number=number, x=rx, y=ry, height=rh)
|
|
551
|
+
for supplied in score.get('expressiveEvents', []):
|
|
552
|
+
if supplied.get('kind') == 'PARENTHESIZED_NOTE_GROUP':
|
|
553
|
+
continue
|
|
554
|
+
if supplied.get('kind') == 'NATURAL_HARMONIC':
|
|
555
|
+
if (supplied.get('scope') not in ('NOTE', 'UNRESOLVED')
|
|
556
|
+
or supplied.get('end') is not None
|
|
557
|
+
or not isinstance(supplied.get('targetEventId'), str)):
|
|
558
|
+
continue
|
|
559
|
+
owner_index = natural_harmonic_owner_index(supplied, score.get('notes', []))
|
|
560
|
+
if owner_index is None or harmonic_owner_counts.get(owner_index) != 1:
|
|
561
|
+
continue
|
|
562
|
+
matching = [owner_index]
|
|
563
|
+
source = first_event + owner_index
|
|
564
|
+
owner = events[source]
|
|
565
|
+
evidence = supplied.get('evidence', [])
|
|
566
|
+
note_identity = score['notes'][matching[0]]
|
|
567
|
+
if (owner.get('measureIndex') != note_identity.get('measureIndex')
|
|
568
|
+
or owner.get('staffIndex') != supplied.get('staffIndex')
|
|
569
|
+
or owner.get('staffCount') != supplied.get('staffCount')
|
|
570
|
+
or owner.get('sourceNoteIndex') != matching[0]
|
|
571
|
+
or owner.get('durationFallback', False)
|
|
572
|
+
or not any(e.get('sourceId') == 'printed-natural-harmonic'
|
|
573
|
+
and e.get('staffIndex') == owner.get('staffIndex')
|
|
574
|
+
and e.get('staffCount') == owner.get('staffCount')
|
|
575
|
+
for e in evidence)):
|
|
576
|
+
continue
|
|
577
|
+
if supplied.get('scope') == 'NOTE':
|
|
578
|
+
start_anchor = supplied['start']
|
|
579
|
+
measure = owner['measureIndex']
|
|
580
|
+
quarter_beat = start_anchor['quarterBeatOffset']
|
|
581
|
+
if (measure >= len(page['measureBeats'])
|
|
582
|
+
or not 0 <= quarter_beat < page['measureBeats'][measure]):
|
|
583
|
+
continue
|
|
584
|
+
measure_start = sum(page['measureBeats'][:measure])
|
|
585
|
+
expected = offset + ticks(measure_start + quarter_beat)
|
|
586
|
+
if (expected != owner['start']
|
|
587
|
+
or not offset + ticks(measure_start) <= owner['start']
|
|
588
|
+
< offset + ticks(measure_start + page['measureBeats'][measure])):
|
|
589
|
+
continue
|
|
590
|
+
owner['retainedNaturalHarmonic'] = True
|
|
591
|
+
continue
|
|
592
|
+
if supplied.get('kind') == 'FALL_OFF':
|
|
593
|
+
if (supplied.get('scope') not in ('NOTE', 'UNRESOLVED')
|
|
594
|
+
or supplied.get('end') is not None
|
|
595
|
+
or not isinstance(supplied.get('targetEventId'), str)):
|
|
596
|
+
continue
|
|
597
|
+
owner_index = fall_off_owner_index(supplied, score.get('notes', []))
|
|
598
|
+
if owner_index is None or fall_off_owner_counts.get(owner_index) != 1:
|
|
599
|
+
continue
|
|
600
|
+
matching = [owner_index]
|
|
601
|
+
source = first_event + owner_index
|
|
602
|
+
owner = events[source]
|
|
603
|
+
evidence = supplied.get('evidence', [])
|
|
604
|
+
note_identity = score['notes'][matching[0]]
|
|
605
|
+
if (owner.get('measureIndex') != note_identity.get('measureIndex')
|
|
606
|
+
or owner.get('staffIndex') != supplied.get('staffIndex')
|
|
607
|
+
or owner.get('staffCount') != supplied.get('staffCount')
|
|
608
|
+
or owner.get('sourceNoteIndex') != matching[0]
|
|
609
|
+
or owner.get('durationFallback', False)
|
|
610
|
+
or not any(e.get('sourceId') == 'printed-fall-off'
|
|
611
|
+
and e.get('staffIndex') == owner.get('staffIndex')
|
|
612
|
+
and e.get('staffCount') == owner.get('staffCount')
|
|
613
|
+
for e in evidence)):
|
|
614
|
+
continue
|
|
615
|
+
if supplied.get('scope') == 'NOTE':
|
|
616
|
+
start_anchor = supplied['start']
|
|
617
|
+
measure = owner['measureIndex']
|
|
618
|
+
quarter_beat = start_anchor['quarterBeatOffset']
|
|
619
|
+
if (measure >= len(page['measureBeats'])
|
|
620
|
+
or not 0 <= quarter_beat < page['measureBeats'][measure]):
|
|
621
|
+
continue
|
|
622
|
+
measure_start = sum(page['measureBeats'][:measure])
|
|
623
|
+
expected = offset + ticks(measure_start + quarter_beat)
|
|
624
|
+
if (expected != owner['start']
|
|
625
|
+
or not offset + ticks(measure_start) <= owner['start']
|
|
626
|
+
< offset + ticks(measure_start + page['measureBeats'][measure])):
|
|
627
|
+
continue
|
|
628
|
+
owner['retainedFallOff'] = True
|
|
629
|
+
continue
|
|
630
|
+
if supplied.get('kind') == 'ARPEGGIO':
|
|
631
|
+
for source_index in arpeggio_plan(supplied, page):
|
|
632
|
+
events[first_event+source_index]['retainedArpeggio'] = True
|
|
633
|
+
continue # A source-owned note symbol, never a generic words direction.
|
|
634
|
+
mark = _resolve_pedal(dict(supplied), page)
|
|
635
|
+
mark.pop('_neutralRestCaption', None)
|
|
636
|
+
if is_caption(mark):
|
|
637
|
+
mark['start'], mark['end'] = caption_start(mark, page), None
|
|
638
|
+
mark['scope'] = 'PART' if mark['start'] is not None else 'UNRESOLVED'
|
|
639
|
+
mark['_neutralRestCaption'] = mark['start'] is not None
|
|
640
|
+
elif _rest_owned(mark):
|
|
641
|
+
span = _rest_span(mark, page)
|
|
642
|
+
mark['start'], mark['end'] = span if span else (None, None)
|
|
643
|
+
mark['scope'] = 'REST' if span else 'UNRESOLVED'
|
|
644
|
+
if span:
|
|
645
|
+
m, staff, count, position = _rest_identity(mark)
|
|
646
|
+
owned_full = [r for r in full_rests if r['sourcePageIndex'] == page_index
|
|
647
|
+
and r['measureIndex'] == m and r['staffIndex'] == staff
|
|
648
|
+
and r['staffCount'] == count and abs(r['positionInMeasure']-position) <= .018]
|
|
649
|
+
if len(owned_full) == 1:
|
|
650
|
+
mark['fullRestIdentity'] = owned_full[0]['restIdentity']
|
|
651
|
+
if cue_caption.owns(mark):
|
|
652
|
+
mark['start'], mark['end'], mark['scope'] = None, None, 'UNRESOLVED'
|
|
653
|
+
mark['identity'] = f'page:{page_index}/'+mark['eventId']
|
|
654
|
+
mark['startTick'], mark['endTick'] = absolute(mark.get('start')), absolute(mark.get('end'))
|
|
655
|
+
members = _column_members(mark, page)
|
|
656
|
+
mark['ownerIds'] = [first_event+i for i in members]
|
|
657
|
+
owned = [events[first_event+i] for i in members]
|
|
658
|
+
if owned and all(not n.get('durationFallback', False) and n['start'] == owned[0]['start'] and n['end'] == owned[0]['end'] for n in owned):
|
|
659
|
+
mark['startTick'] = owned[0]['end'] if mark['kind'] in ('BREATH', 'CAESURA') else owned[0]['start']
|
|
660
|
+
if cue_caption.owns(mark):
|
|
661
|
+
mark['scope'] = 'PART'
|
|
662
|
+
local_starts = [0]
|
|
663
|
+
for duration in page['measureBeats']:
|
|
664
|
+
local_starts.append(local_starts[-1] + duration)
|
|
665
|
+
resolved_start = _anchor((mark['startTick'] - offset) / DIVISIONS, local_starts)
|
|
666
|
+
if mark['kind'] in GRADUAL:
|
|
667
|
+
mark['endTick'] = absolute(preserve_end(mark, resolved_start, page))
|
|
668
|
+
if mark['kind'] == 'FERMATA':
|
|
669
|
+
mark['endTick'] = owned[0]['end']
|
|
670
|
+
elif mark.get('scope') == 'UNRESOLVED':
|
|
671
|
+
mark['startTick'] = None
|
|
672
|
+
if mark['startTick'] is not None:
|
|
673
|
+
expressions.append(mark)
|
|
674
|
+
offset += local_start
|
|
675
|
+
if not bars:
|
|
676
|
+
raise ValueError('No interpreted measures to export')
|
|
677
|
+
from .sudden_dynamic import combine as combine_sudden_dynamics
|
|
678
|
+
expressions = combine_sudden_dynamics(expressions)
|
|
679
|
+
root = ET.Element('score-partwise', version='4.0')
|
|
680
|
+
element(element(root, 'work'), 'work-title', document.get('inputName', 'Interpreted score'))
|
|
681
|
+
identification = element(root, 'identification')
|
|
682
|
+
element(element(identification, 'encoding'), 'software', 'Music Sheets Interpreter')
|
|
683
|
+
misc = element(identification, 'miscellaneous')
|
|
684
|
+
element(misc, 'miscellaneous-field', 'Concert-pitch reconstruction; recognition and estimated timing require review.', name='interpretation')
|
|
685
|
+
part_list = element(root, 'part-list')
|
|
686
|
+
def physical_staff(row):
|
|
687
|
+
staff = row.get('staffIndex', 0)
|
|
688
|
+
return staff, row.get('staffCount', staff+1)
|
|
689
|
+
if full_rests:
|
|
690
|
+
staffs = sorted({physical_staff(n) for n in events}
|
|
691
|
+
| {physical_staff(r) for r in full_rests}
|
|
692
|
+
| {physical_staff(m) for m in expressions if m.get('scope') == 'REST'})
|
|
693
|
+
else:
|
|
694
|
+
# Preserve the existing literal-only reconstruction and part identities.
|
|
695
|
+
staffs = sorted({n.get('staffIndex', 0) for n in events}
|
|
696
|
+
| {m['staffIndex'] for m in expressions if m.get('scope') == 'REST'}) or [0]
|
|
697
|
+
for identity in staffs:
|
|
698
|
+
staff, count = identity if full_rests else (identity, None)
|
|
699
|
+
same_staff = lambda row: physical_staff(row) == identity if full_rests else row.get('staffIndex', 0) == staff
|
|
700
|
+
ambiguous_index = bool(full_rests) and sum(key[0] == staff for key in staffs) > 1
|
|
701
|
+
part_id = f'P{staff+1}C{count}' if ambiguous_index else f'P{staff+1}'
|
|
702
|
+
name = f'Staff {staff+1} of {count}' if ambiguous_index else f'Staff {staff+1}'
|
|
703
|
+
element(element(part_list, 'score-part', id=part_id), 'part-name', name)
|
|
704
|
+
part = element(root, 'part', id=part_id)
|
|
705
|
+
notes = sorted((n for n in events if same_staff(n)), key=lambda n: (n['start'], notation_order(n)))
|
|
706
|
+
clef_changes = clef_export.plan(notes)
|
|
707
|
+
emitted_clefs = set()
|
|
708
|
+
silent = [r for r in full_rests if same_staff(r)]
|
|
709
|
+
literal_edges = {tick for row in literal_rests if same_staff(row)
|
|
710
|
+
for tick in (row['start'], row['end'])}
|
|
711
|
+
for index, n in enumerate(notes):
|
|
712
|
+
if n.get('grace', False):
|
|
713
|
+
continue
|
|
714
|
+
gliss = n.get('glissando')
|
|
715
|
+
if gliss is None:
|
|
716
|
+
continue
|
|
717
|
+
if (not isinstance(gliss,dict) or gliss.get('style') != 'white_keys'
|
|
718
|
+
or type(gliss.get('targetMidi')) is not int or not 0 <= gliss['targetMidi'] <= 127):
|
|
719
|
+
raise ValueError('Unsupported glissando notation')
|
|
720
|
+
targets = [target for target in notes if not target.get('grace', False) and abs(target['start']-n['end']) <= 2]
|
|
721
|
+
if len(targets) == 1 and event_kind(targets[0]) == 'PITCHED' and targets[0]['midi'] == gliss['targetMidi']:
|
|
722
|
+
n['gliss_start'] = index % 16 + 1
|
|
723
|
+
targets[0]['gliss_stop'] = n['gliss_start']
|
|
724
|
+
marks = sorted((m for m in expressions if m.get('scope') == 'SCORE' or same_staff(m)),
|
|
725
|
+
key=lambda m: (m['startTick'], 0 if m['kind'] == 'PEDAL_UP' else 1))
|
|
726
|
+
dash_numbers = {}
|
|
727
|
+
occupied = []
|
|
728
|
+
for mark in marks:
|
|
729
|
+
if mark['kind'] not in GRADUAL or mark.get('endTick') is None or mark['endTick'] <= mark['startTick'] or not any(e['sourceId'] == SOURCE for e in mark.get('evidence', [])):
|
|
730
|
+
continue
|
|
731
|
+
occupied = [(end, number) for end, number in occupied if end > mark['startTick']]
|
|
732
|
+
number = next((n for n in range(1, 17) if n not in {number for _, number in occupied}), None)
|
|
733
|
+
if number is None:
|
|
734
|
+
raise ValueError('Too many overlapping printed tempo extensions')
|
|
735
|
+
dash_numbers[mark['identity']] = number
|
|
736
|
+
occupied.append((mark['endTick'], number))
|
|
737
|
+
occupied = []
|
|
738
|
+
for mark in marks:
|
|
739
|
+
if not mark.get('_hairpin'):
|
|
740
|
+
continue
|
|
741
|
+
occupied = [(end, number) for end, number in occupied if end > mark['startTick']]
|
|
742
|
+
number = next((n for n in range(1, 17) if n not in {number for _, number in occupied}), None)
|
|
743
|
+
if number is None:
|
|
744
|
+
raise ValueError('Too many overlapping hairpins')
|
|
745
|
+
mark['_hairpinNumber'] = str(number)
|
|
746
|
+
occupied.append((mark['endTick'], number))
|
|
747
|
+
rendered, rest_symbols = set(), []
|
|
748
|
+
for mark in marks:
|
|
749
|
+
if mark['kind'] not in ('FERMATA', 'BREATH', 'CAESURA'):
|
|
750
|
+
continue
|
|
751
|
+
release = mark['endTick'] if mark['kind'] == 'FERMATA' else mark['startTick']
|
|
752
|
+
if release is None:
|
|
753
|
+
continue
|
|
754
|
+
symbol = dict(kind=mark['kind'], start=mark['startTick'], release=release,
|
|
755
|
+
value='tick' if 'tick' in mark.get('qualifierText', '') else 'comma',
|
|
756
|
+
inverted=mark.get('qualifierText') == 'fermata inverted')
|
|
757
|
+
if mark.get('scope') == 'REST' and mark['kind'] == 'FERMATA':
|
|
758
|
+
owned = [r for r in silent if r['restIdentity'] == mark.get('fullRestIdentity')]
|
|
759
|
+
if owned:
|
|
760
|
+
owned[0]['releaseSymbols'].append(symbol)
|
|
761
|
+
rendered.add(mark['identity'])
|
|
762
|
+
elif release > mark['startTick'] and not any(n['start'] < release and n['end'] > mark['startTick'] for n in notes):
|
|
763
|
+
rest_symbols.append(symbol)
|
|
764
|
+
rendered.add(mark['identity'])
|
|
765
|
+
continue
|
|
766
|
+
eligible = [n for n in notes if not n.get('grace', False) and n['end'] == release and not n.get('durationFallback', False)
|
|
767
|
+
and (not mark['ownerIds'] or n['sourceIdentity'] in mark['ownerIds'])]
|
|
768
|
+
if eligible:
|
|
769
|
+
selected = (min if symbol['inverted'] else max)(eligible, key=(
|
|
770
|
+
(lambda n: display_position(n)) if any(event_kind(n) == 'UNPITCHED' for n in eligible)
|
|
771
|
+
else (lambda n: n['midi'])))
|
|
772
|
+
selected.setdefault('releaseSymbols', []).append(symbol)
|
|
773
|
+
rendered.add(mark['identity'])
|
|
774
|
+
from .tie_owners import releasing_links
|
|
775
|
+
tie_rows = [dict(start=n['start'], end=n['end'], lane=(staff, n.get('midi')),
|
|
776
|
+
tied=n.get('tiedFromPrevious', False),
|
|
777
|
+
eligible=not n.get('grace', False) and event_kind(n) == 'PITCHED') for n in notes]
|
|
778
|
+
for current, earlier in releasing_links(tie_rows, lambda row: [(row['lane'], 2)]).items():
|
|
779
|
+
prior, n = notes[earlier], notes[current]
|
|
780
|
+
prior['tie_start'] = True
|
|
781
|
+
n['tie_stop'] = True
|
|
782
|
+
retained_slur_ties.add((prior['sourceIdentity'], n['sourceIdentity']))
|
|
783
|
+
groups = defaultdict(list)
|
|
784
|
+
for n in notes:
|
|
785
|
+
if not n.get('grace', False):
|
|
786
|
+
groups[n['start'], n['end'], 0 if event_kind(n) == 'UNPITCHED' else n.get('octaveShift', 0)].append(n)
|
|
787
|
+
voice_ends = []
|
|
788
|
+
for (start, end, octave_shift), chord in sorted(groups.items()):
|
|
789
|
+
voice = next((i for i, at in enumerate(voice_ends) if at <= start), len(voice_ends))
|
|
790
|
+
if voice == len(voice_ends):
|
|
791
|
+
voice_ends.append(end)
|
|
792
|
+
else:
|
|
793
|
+
voice_ends[voice] = end
|
|
794
|
+
for n in chord:
|
|
795
|
+
n['voice'] = voice + 1
|
|
796
|
+
by_source = {n['sourceIdentity']: n for n in notes}
|
|
797
|
+
grace_groups = defaultdict(list)
|
|
798
|
+
for n in notes:
|
|
799
|
+
if n.get('grace', False):
|
|
800
|
+
owner = by_source.get(n['principalSourceIdentity'])
|
|
801
|
+
if owner is None or owner.get('grace', False):
|
|
802
|
+
raise ValueError('Grace principal is outside exported part')
|
|
803
|
+
n['voice'] = owner['voice']
|
|
804
|
+
grace_groups[n['principalSourceIdentity'], n['afterGrace']].append(n)
|
|
805
|
+
def emit_graces(measure, chord, after, anchor, flats):
|
|
806
|
+
pending = [g for n in chord if anchor == (n['end'] if after else n['start'])
|
|
807
|
+
for g in grace_groups.get((n['sourceIdentity'], after), ())]
|
|
808
|
+
for g in sorted(pending, key=lambda g: (g['graceOrdinal'], g['sourceIdentity'])):
|
|
809
|
+
emitted = emit_note(measure, g['graceWrittenDuration'], g['voice'], g, flats=flats,
|
|
810
|
+
articulation_flags=g['retainedArticulations'], grace=g, bow_direction=g.get('retainedBow'))
|
|
811
|
+
octave_owned[emitted] = 0 if event_kind(g) == 'UNPITCHED' else g.get('octaveShift', 0)
|
|
812
|
+
if g['sourceIdentity'] in requested_slur_owners:
|
|
813
|
+
slur_attacks[g['sourceIdentity']] = emitted
|
|
814
|
+
for index, bar in enumerate(bars):
|
|
815
|
+
measure = element(part, 'measure', number=first_number+index)
|
|
816
|
+
attributes = element(measure, 'attributes')
|
|
817
|
+
element(attributes, 'divisions', DIVISIONS)
|
|
818
|
+
for group in printed_rest_groups:
|
|
819
|
+
if group['firstBar'] == index and same_staff(group):
|
|
820
|
+
element(element(attributes, 'measure-style'), 'multiple-rest', group['measureCount'])
|
|
821
|
+
element(element(attributes, 'key'), 'fifths', bar['key'])
|
|
822
|
+
time = element(attributes, 'time')
|
|
823
|
+
numerator, denominator = bar['meter']
|
|
824
|
+
if ticks(numerator*4/denominator) != bar['length']:
|
|
825
|
+
# Retain actual timeline for pickups or unusual inferred bars.
|
|
826
|
+
measure.set('implicit', 'yes')
|
|
827
|
+
element(time, 'beats', numerator)
|
|
828
|
+
element(time, 'beat-type', denominator)
|
|
829
|
+
if bar['start'] in clef_changes:
|
|
830
|
+
clef_export.write(attributes, clef_changes[bar['start']])
|
|
831
|
+
emitted_clefs.add(bar['start'])
|
|
832
|
+
tempos = list(bar['tempos'])
|
|
833
|
+
if index == 0 and not any(t['positionInMeasure'] == 0 for t in tempos):
|
|
834
|
+
tempos.insert(0, dict(bpm=bpm, positionInMeasure=0))
|
|
835
|
+
for tempo in tempos:
|
|
836
|
+
unit, dots, marked_bpm = tempo_mark(tempo)
|
|
837
|
+
direction = element(measure, 'direction', placement='above')
|
|
838
|
+
metronome = element(element(direction, 'direction-type'), 'metronome')
|
|
839
|
+
element(metronome, 'beat-unit', unit)
|
|
840
|
+
for _ in range(dots):
|
|
841
|
+
element(metronome, 'beat-unit-dot')
|
|
842
|
+
element(metronome, 'per-minute', format(Decimal(str(marked_bpm)).normalize(), 'f'))
|
|
843
|
+
source_onset = tempo.get('_sourceTempoOnset')
|
|
844
|
+
tempo_offset = ticks(source_onset) if source_onset is not None else round(bar['length']*tempo['positionInMeasure'])
|
|
845
|
+
element(direction, 'offset', tempo_offset, sound='yes')
|
|
846
|
+
element(direction, 'sound', tempo=str(tempo['bpm']))
|
|
847
|
+
a, b = bar['start'], bar['start']+bar['length']
|
|
848
|
+
for mark in marks:
|
|
849
|
+
if mark.get('_hairpin'):
|
|
850
|
+
owns = mark['_hairpinStartBarStart'] == a and a <= mark['startTick'] <= b
|
|
851
|
+
elif mark.get('_absoluteDynamic'):
|
|
852
|
+
owns = mark['_absoluteDynamicBarStart'] == a and a <= mark['startTick'] <= b
|
|
853
|
+
elif mark.get('_playingInstruction'):
|
|
854
|
+
# A terminal after-grace still belongs to its original written bar.
|
|
855
|
+
owns = mark['_playingInstructionBarStart'] == a and a <= mark['startTick'] <= b
|
|
856
|
+
else:
|
|
857
|
+
owns = (a <= mark['startTick'] < b
|
|
858
|
+
or index == len(bars)-1 and mark['kind'] == 'PEDAL_UP' and mark['startTick'] == b)
|
|
859
|
+
if mark['identity'] not in rendered and owns:
|
|
860
|
+
expression_direction(measure, mark, mark['startTick']-a)
|
|
861
|
+
if mark['identity'] in dash_numbers:
|
|
862
|
+
dash = element(measure, 'direction', placement='above')
|
|
863
|
+
element(element(dash, 'direction-type'), 'dashes', type='start', number=str(dash_numbers[mark['identity']]))
|
|
864
|
+
element(dash, 'offset', mark['startTick']-a)
|
|
865
|
+
if mark.get('_hairpin') and mark['_hairpinEndBarStart'] == a and a <= mark['endTick'] <= b:
|
|
866
|
+
stop = element(measure, 'direction', placement='below')
|
|
867
|
+
element(element(stop, 'direction-type'), 'wedge', type='stop', number=mark['_hairpinNumber'])
|
|
868
|
+
element(stop, 'offset', mark['endTick']-a)
|
|
869
|
+
if mark['identity'] in dash_numbers and (a <= mark['endTick'] < b or index == len(bars)-1 and mark['endTick'] == b):
|
|
870
|
+
dash = element(measure, 'direction', placement='above')
|
|
871
|
+
element(element(dash, 'direction-type'), 'dashes', type='stop', number=str(dash_numbers[mark['identity']]))
|
|
872
|
+
element(dash, 'offset', mark['endTick']-a)
|
|
873
|
+
present = [n for n in notes if not n.get('grace', False) and n['start'] < b and n['end'] > a]
|
|
874
|
+
bar_rests = [r for r in silent if r['barIndex'] == index]
|
|
875
|
+
voices = sorted({n['voice'] for n in present}) or ([] if bar_rests else [1])
|
|
876
|
+
rest_voices = {max(1000, len(voice_ends))+i+1: row for i, row in enumerate(bar_rests)}
|
|
877
|
+
voices.extend(rest_voices)
|
|
878
|
+
for vi, voice in enumerate(voices):
|
|
879
|
+
if vi:
|
|
880
|
+
element(element(measure, 'backup'), 'duration', bar['length'])
|
|
881
|
+
if voice in rest_voices:
|
|
882
|
+
row = rest_voices[voice]
|
|
883
|
+
emit_note(measure, bar['length'], voice, fragment_end=b,
|
|
884
|
+
rest_symbols=row['releaseSymbols'], full_measure=True)
|
|
885
|
+
continue
|
|
886
|
+
cursor = a
|
|
887
|
+
segments = defaultdict(list)
|
|
888
|
+
for n in present:
|
|
889
|
+
if n['voice'] == voice:
|
|
890
|
+
segments[max(a,n['start']),min(b,n['end'])].append(n)
|
|
891
|
+
for (start, end), chord in sorted(segments.items()):
|
|
892
|
+
if start > cursor:
|
|
893
|
+
emit_rest_gap(measure, cursor, start, voice, rest_symbols, literal_edges)
|
|
894
|
+
fragment_start = start
|
|
895
|
+
for duration in duration_parts(end-start, chord):
|
|
896
|
+
fragment_end = fragment_start + duration
|
|
897
|
+
if any(fragment_start == n['start'] for n in chord) and start in clef_changes and start not in emitted_clefs:
|
|
898
|
+
clef_export.write(element(measure, 'attributes'), clef_changes[start])
|
|
899
|
+
emitted_clefs.add(start)
|
|
900
|
+
emit_graces(measure, chord, False, fragment_start, bar['key']<0)
|
|
901
|
+
articulation_flags = articulation_export.chord_marks(chord, fragment_start)
|
|
902
|
+
bow_directions = bow_export.chord_marks(chord, fragment_start)
|
|
903
|
+
for ci, n in enumerate(chord):
|
|
904
|
+
emitted = emit_note(measure, duration, voice, n, chord=ci>0,
|
|
905
|
+
stop=fragment_start > n['start'] or n['tie_stop'],
|
|
906
|
+
start=fragment_end < n['end'] or n['tie_start'], flats=bar['key']<0,
|
|
907
|
+
gliss_start=fragment_end==n['end'] and 'gliss_start' in n,
|
|
908
|
+
gliss_stop=fragment_start==n['start'] and 'gliss_stop' in n,
|
|
909
|
+
slide_start=fragment_end==n['end'] and 'slide_start' in n,
|
|
910
|
+
slide_stop=fragment_start==n['start'] and 'slide_stop' in n,
|
|
911
|
+
fragment_end=fragment_end, articulation_flags=articulation_flags[ci],
|
|
912
|
+
attack_fragment=fragment_start==n['start'], bow_direction=bow_directions[ci])
|
|
913
|
+
octave_owned[emitted] = 0 if event_kind(n) == 'UNPITCHED' else n.get('octaveShift', 0)
|
|
914
|
+
if fragment_start == n['start'] and n['sourceIdentity'] in requested_slur_owners:
|
|
915
|
+
slur_attacks[n['sourceIdentity']] = emitted
|
|
916
|
+
emit_graces(measure, chord, True, fragment_end, bar['key']<0)
|
|
917
|
+
fragment_start = fragment_end
|
|
918
|
+
cursor = end
|
|
919
|
+
if cursor < b:
|
|
920
|
+
emit_rest_gap(measure, cursor, b, voice, rest_symbols, literal_edges)
|
|
921
|
+
from .octave_shift_export import apply as octave_apply
|
|
922
|
+
octave_apply(root, octave_owned)
|
|
923
|
+
first_score = document['pages'][0].get('score', {})
|
|
924
|
+
known_meter = 'initialMeter' in document or any(
|
|
925
|
+
c.get('measureIndex') == 0 for c in first_score.get('meterChanges', []))
|
|
926
|
+
known_key = 'initialKeyFifths' in document or any(
|
|
927
|
+
c.get('measureIndex') == 0 for c in first_score.get('keyChanges', []))
|
|
928
|
+
part_nodes = {note: part for part in root.findall('part') for note in part.iter('note')}
|
|
929
|
+
exported_slur_parts = {owner: part_nodes.get(note) for owner, note in slur_attacks.items()}
|
|
930
|
+
retained_slurs = slur_export.classify(retained_slurs, document['pages'], events,
|
|
931
|
+
retained_slur_ties, known_meter and known_key,
|
|
932
|
+
exported_slur_parts)
|
|
933
|
+
slur_export.apply(root, retained_slurs, slur_attacks, events)
|
|
934
|
+
slide_numbering.assign(root)
|
|
935
|
+
ET.indent(root)
|
|
936
|
+
ET.ElementTree(root).write(Path(path), encoding='utf-8', xml_declaration=True)
|
|
937
|
+
|