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,478 @@
|
|
|
1
|
+
# Copyright 2026 Luckolite
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Expressive previews through the shared Java policy, preserving the written document."""
|
|
4
|
+
import copy
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import struct
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from .runtime import java_executable
|
|
12
|
+
from .printed_tempo_spans import preserve_end, resolve_pages, has_open
|
|
13
|
+
from .semantic_wire import encode
|
|
14
|
+
from .typed_events import event_kind, validate_unpitched
|
|
15
|
+
from .rest_kinds import rest_kind, full_measure_span
|
|
16
|
+
from .tremolo_wire import performance_pairs
|
|
17
|
+
from .tremolo_performance import source_spans, pulse_windows
|
|
18
|
+
from .tie_owners import releasing_links, sound_lanes
|
|
19
|
+
|
|
20
|
+
SUPPORTED = {'RITARDANDO', 'RALLENTANDO', 'RITENUTO', 'ACCELERANDO', 'A_TEMPO',
|
|
21
|
+
'TEMPO_PRIMO', 'SAME_TEMPO', 'FERMATA', 'BREATH', 'CAESURA',
|
|
22
|
+
'SFORZANDO', 'SFORZATO', 'SFORZANDO_PIANO', 'METRIC_MODULATION',
|
|
23
|
+
'PEDAL_DOWN', 'PEDAL_UP'}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _bridge(data):
|
|
27
|
+
if len(data) > 64*1024*1024:
|
|
28
|
+
raise ValueError('Expressive performance request too large')
|
|
29
|
+
jar = Path(__file__).with_name('interpreter.jar')
|
|
30
|
+
with tempfile.TemporaryDirectory(prefix='sheet-expression-') as directory:
|
|
31
|
+
request, output = Path(directory)/'request.expr', Path(directory)/'performance.json'
|
|
32
|
+
request.write_bytes(data)
|
|
33
|
+
result = subprocess.run([java_executable(), '-Xmx512m', '-cp', str(jar),
|
|
34
|
+
'io.github.luckolite.interpreter.PerformanceBridge', str(request), str(output)],
|
|
35
|
+
capture_output=True, text=True, encoding='utf-8', timeout=60)
|
|
36
|
+
if result.returncode:
|
|
37
|
+
raise ValueError('Expressive engine rejected decoded input: '+result.stderr.strip())
|
|
38
|
+
return json.loads(output.read_text(encoding='utf-8'))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _text(value):
|
|
42
|
+
raw = value.encode('utf-8')
|
|
43
|
+
if not raw or len(raw) > 4096:
|
|
44
|
+
raise ValueError('Invalid expressive identity')
|
|
45
|
+
return struct.pack('>i', len(raw))+raw
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _anchor(beat, starts):
|
|
49
|
+
for index in range(len(starts)-1):
|
|
50
|
+
if beat < starts[index+1]-1e-8:
|
|
51
|
+
return dict(measureIndex=index, quarterBeatOffset=max(0, beat-starts[index]))
|
|
52
|
+
if not math.isclose(beat, starts[-1], abs_tol=1e-7):
|
|
53
|
+
raise ValueError('Expressive anchor outside page')
|
|
54
|
+
return dict(measureIndex=len(starts)-1, quarterBeatOffset=0)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _column_members(expression, page):
|
|
58
|
+
from . import cue_caption
|
|
59
|
+
if cue_caption.owns(expression):
|
|
60
|
+
return cue_caption.members(expression, page)
|
|
61
|
+
if expression.get('kind') == 'ARPEGGIO':
|
|
62
|
+
from .arpeggio_notation import target_indices
|
|
63
|
+
return target_indices(expression, page)
|
|
64
|
+
target = expression.get('targetEventId') or ''
|
|
65
|
+
sources = {'fermata-raw-ink'} if expression['kind'] == 'FERMATA' else {'printed-expression-word', 'printed-expression-symbol'}
|
|
66
|
+
prefix = 'printed-attack:' if expression['kind'] == 'FERMATA' else 'expression-column:'
|
|
67
|
+
if not target.startswith(prefix) or not any(e['sourceId'] in sources for e in expression['evidence']):
|
|
68
|
+
return []
|
|
69
|
+
try:
|
|
70
|
+
m, staff, count, bits = map(int, target[len(prefix):].split(':'))
|
|
71
|
+
position = struct.unpack('>f', struct.pack('>I', bits & 0xffffffff))[0]
|
|
72
|
+
except (ValueError, struct.error):
|
|
73
|
+
return []
|
|
74
|
+
if not math.isfinite(position) or not 0 <= position <= 1:
|
|
75
|
+
return []
|
|
76
|
+
if expression['kind'] in ('PEDAL_DOWN', 'PEDAL_UP') and (
|
|
77
|
+
staff != expression['staffIndex'] or count != expression['staffCount']
|
|
78
|
+
or any(not -2147483648 <= value <= 2147483647 for value in (m, staff, count, bits))
|
|
79
|
+
or m < 0):
|
|
80
|
+
return []
|
|
81
|
+
notes = page.get('score', {}).get('notes', [])
|
|
82
|
+
# Main exports each decoded head in the same order. Refuse any missing correspondence.
|
|
83
|
+
if len(notes) != len(page['events']):
|
|
84
|
+
return []
|
|
85
|
+
return [index for index, note in enumerate(notes) if note['measureIndex'] == m
|
|
86
|
+
and note['staffIndex'] == staff and note['staffCount'] == count
|
|
87
|
+
and abs(note['positionInMeasure']-position) <= .018]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _rest_owned(expression):
|
|
91
|
+
return expression['kind'] == 'FERMATA' and (expression.get('targetEventId') or '').startswith('printed-rest:') \
|
|
92
|
+
and any(e['sourceId'] == 'fermata-rest-raw-ink' for e in expression['evidence'])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _rest_identity(expression):
|
|
96
|
+
if not _rest_owned(expression):
|
|
97
|
+
return None
|
|
98
|
+
try:
|
|
99
|
+
m, staff, count, bits = map(int, expression['targetEventId'][len('printed-rest:'):].split(':'))
|
|
100
|
+
position = struct.unpack('>f', struct.pack('>I', bits & 0xffffffff))[0]
|
|
101
|
+
except (ValueError, struct.error):
|
|
102
|
+
return None
|
|
103
|
+
if not math.isfinite(position) or not 0 <= position <= 1 \
|
|
104
|
+
or staff != expression['staffIndex'] or count != expression['staffCount']:
|
|
105
|
+
return None
|
|
106
|
+
return m, staff, count, position
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _rest_span(expression, page):
|
|
110
|
+
"""Owned full silent voice, or the same exact literal-slot proof as the Java detector."""
|
|
111
|
+
identity = _rest_identity(expression)
|
|
112
|
+
if identity is None:
|
|
113
|
+
return None
|
|
114
|
+
m, staff, count, position = identity
|
|
115
|
+
beats = page.get('measureBeats')
|
|
116
|
+
if not isinstance(beats, (list, tuple)) or not 0 <= m < len(beats):
|
|
117
|
+
# The typed full-rest resolver diagnoses missing performed spans below.
|
|
118
|
+
if not any(rest_kind(r) == 'FULL_MEASURE' and r.get('measureIndex') == m
|
|
119
|
+
and r.get('staffIndex') == staff and r.get('staffCount') == count
|
|
120
|
+
for r in page.get('score', {}).get('rests', [])):
|
|
121
|
+
return None
|
|
122
|
+
return _rest_column_span(page, m, staff, count, position, .018)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _rest_column_span(page, m, staff, count, position, tolerance):
|
|
126
|
+
belongs = lambda row: row['measureIndex'] == m and row['staffIndex'] == staff and row['staffCount'] == count
|
|
127
|
+
rests = [r for r in page.get('score', {}).get('rests', []) if belongs(r)]
|
|
128
|
+
for row in rests:
|
|
129
|
+
if rest_kind(row) == 'FULL_MEASURE':
|
|
130
|
+
full_measure_span(page, row)
|
|
131
|
+
targets = [r for r in rests if abs(r['positionInMeasure']-position) <= tolerance]
|
|
132
|
+
if len(targets) != 1:
|
|
133
|
+
return None
|
|
134
|
+
target = targets[0]
|
|
135
|
+
if rest_kind(target) == 'FULL_MEASURE':
|
|
136
|
+
beats = full_measure_span(page, target)
|
|
137
|
+
return dict(measureIndex=m, quarterBeatOffset=0), dict(measureIndex=m, quarterBeatOffset=beats)
|
|
138
|
+
raw = page.get('score', {}).get('notes', [])
|
|
139
|
+
if len(raw) != len(page['events']):
|
|
140
|
+
return None
|
|
141
|
+
duration = target['durationBeats']; beats = page['measureBeats'][m]
|
|
142
|
+
if not math.isfinite(duration) or not 0 < duration <= beats:
|
|
143
|
+
return None
|
|
144
|
+
columns = [(r, n) for r, n in zip(raw, page['events']) if belongs(r)]
|
|
145
|
+
if any(abs(r['positionInMeasure']-position) <= tolerance or n.get('durationFallback', False) for r, n in columns):
|
|
146
|
+
return None
|
|
147
|
+
before = max((r['positionInMeasure'] for r, _ in columns if r['positionInMeasure'] < position), default=-1)
|
|
148
|
+
after = min((r['positionInMeasure'] for r, _ in columns if r['positionInMeasure'] > position), default=2)
|
|
149
|
+
bar_start = sum(page['measureBeats'][:m])
|
|
150
|
+
start = max((n['startBeat']+n['durationBeats']-bar_start for r, n in columns if r['positionInMeasure'] == before), default=0)
|
|
151
|
+
end = min((n['startBeat']-bar_start for r, n in columns if r['positionInMeasure'] == after), default=beats)
|
|
152
|
+
slot = [r for r in rests if rest_kind(r) == 'LITERAL' and before < r['positionInMeasure'] < after]
|
|
153
|
+
if any(not math.isfinite(r['durationBeats']) or r['durationBeats'] <= 0 for r in slot) \
|
|
154
|
+
or not math.isclose(end-start, sum(r['durationBeats'] for r in slot), abs_tol=1e-7):
|
|
155
|
+
return None
|
|
156
|
+
if any(n['startBeat']-bar_start < end-1e-7 and n['startBeat']+n['durationBeats']-bar_start > start+1e-7 for _, n in columns):
|
|
157
|
+
return None
|
|
158
|
+
onset = start+sum(r['durationBeats'] for r in slot if r['positionInMeasure'] < position)
|
|
159
|
+
return dict(measureIndex=m, quarterBeatOffset=onset), dict(measureIndex=m, quarterBeatOffset=onset+duration)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _pedal_span(expression, page):
|
|
163
|
+
"""Resolve persisted hook columns using the final exported musical clock, never page spacing."""
|
|
164
|
+
target = expression.get('targetEventId') or ''
|
|
165
|
+
single = target.startswith('pedal-glyph-column-v1:')
|
|
166
|
+
if expression['kind'] not in ('PEDAL_DOWN', 'PEDAL_UP') or not (single or target.startswith('pedal-hooks-v1:')):
|
|
167
|
+
return None
|
|
168
|
+
try:
|
|
169
|
+
prefix = 'pedal-glyph-column-v1:' if single else 'pedal-hooks-v1:'
|
|
170
|
+
fields = list(map(int, target[len(prefix):].split(':')))
|
|
171
|
+
if len(fields) != (6 if single else 10) or any(not -2147483648 <= value <= 2147483647 for value in fields):
|
|
172
|
+
return None
|
|
173
|
+
staff, count = fields[-2:]
|
|
174
|
+
if staff < 0 or count <= staff or staff != expression['staffIndex'] or count != expression['staffCount']:
|
|
175
|
+
return None
|
|
176
|
+
if not any(e['sourceId'] == ('printed-pedal-glyph' if single else 'printed-pedal-bracket') and e['staffIndex'] == staff
|
|
177
|
+
and e['staffCount'] == count for e in expression.get('evidence', [])):
|
|
178
|
+
return None
|
|
179
|
+
anchors = []
|
|
180
|
+
raw = page.get('score', {}).get('notes', [])
|
|
181
|
+
starts = [0.]
|
|
182
|
+
for duration in page['measureBeats']:
|
|
183
|
+
starts.append(starts[-1]+duration)
|
|
184
|
+
for m, kind, bits, tolerance_bits in ((fields[:4], fields[:4]) if single else (fields[:4], fields[4:8])):
|
|
185
|
+
position, tolerance = (struct.unpack('>f', struct.pack('>I', v & 0xffffffff))[0]
|
|
186
|
+
for v in (bits, tolerance_bits))
|
|
187
|
+
if not 0 <= m <= len(page['measureBeats']) or kind not in (0, 1, 2) \
|
|
188
|
+
or not math.isfinite(position) or not 0 <= position <= 1 \
|
|
189
|
+
or not math.isfinite(tolerance) or not 0 <= tolerance <= .100000002:
|
|
190
|
+
return None
|
|
191
|
+
if kind == 0:
|
|
192
|
+
anchors.append(dict(measureIndex=m, quarterBeatOffset=0))
|
|
193
|
+
continue
|
|
194
|
+
if m == len(page['measureBeats']) or len(raw) != len(page['events']):
|
|
195
|
+
return None
|
|
196
|
+
if kind == 2:
|
|
197
|
+
span = _rest_column_span(page, m, staff, count, position, max(tolerance, .018))
|
|
198
|
+
if span is None:
|
|
199
|
+
return None
|
|
200
|
+
anchors.append(span[0])
|
|
201
|
+
continue
|
|
202
|
+
notes = [n for r, n in zip(raw, page['events']) if r['measureIndex'] == m
|
|
203
|
+
and r['staffIndex'] == staff and r['staffCount'] == count
|
|
204
|
+
and not r.get('articulations', 0) & (1 << 15)
|
|
205
|
+
and abs(r['positionInMeasure']-position) <= tolerance]
|
|
206
|
+
if not notes or any(n.get('durationFallback', False) or not math.isfinite(n['startBeat'])
|
|
207
|
+
or not math.isclose(n['startBeat'], notes[0]['startBeat'], abs_tol=.001) for n in notes):
|
|
208
|
+
return None
|
|
209
|
+
beat = notes[0]['startBeat']
|
|
210
|
+
if not starts[m] <= beat <= starts[m+1]:
|
|
211
|
+
return None
|
|
212
|
+
anchors.append(_anchor(beat, starts))
|
|
213
|
+
if not single and (anchors[0]['measureIndex'], anchors[0]['quarterBeatOffset']) >= \
|
|
214
|
+
(anchors[1]['measureIndex'], anchors[1]['quarterBeatOffset']):
|
|
215
|
+
return None
|
|
216
|
+
if single and expression['kind'] == 'PEDAL_DOWN' and anchors[0]['measureIndex'] == len(page['measureBeats']):
|
|
217
|
+
return None
|
|
218
|
+
return tuple(anchors)
|
|
219
|
+
except (ValueError, struct.error, KeyError, TypeError):
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _resolve_pedal(expression, page):
|
|
224
|
+
if expression['kind'] in ('PEDAL_DOWN', 'PEDAL_UP') \
|
|
225
|
+
and (expression.get('targetEventId') or '').startswith('expression-column:') \
|
|
226
|
+
and any(e['sourceId'] == 'printed-expression-word' for e in expression.get('evidence', [])):
|
|
227
|
+
# Literal cues need final written-column proof in both playback and MusicXML.
|
|
228
|
+
expression['start'], expression['end'], expression['scope'] = None, None, 'UNRESOLVED'
|
|
229
|
+
# Revalidate cached columns even when old anchors claim to be resolved.
|
|
230
|
+
if (expression.get('targetEventId') or '').startswith(('pedal-hooks-v1:', 'pedal-glyph-column-v1:')) \
|
|
231
|
+
and expression['kind'] in ('PEDAL_DOWN', 'PEDAL_UP'):
|
|
232
|
+
span = _pedal_span(expression, page)
|
|
233
|
+
down = expression['kind'] == 'PEDAL_DOWN'
|
|
234
|
+
expression['start'] = span[0 if down else 1] if span else None
|
|
235
|
+
expression['end'] = span[1] if span and down and not (expression.get('targetEventId') or '').startswith('pedal-glyph-column-v1:') else None
|
|
236
|
+
expression['scope'] = 'PART' if span else 'UNRESOLVED'
|
|
237
|
+
elif any(e.get('sourceId') == 'printed-pedal-glyph' for e in expression.get('evidence', [])):
|
|
238
|
+
expression['start'], expression['end'], expression['scope'] = None, None, 'UNRESOLVED'
|
|
239
|
+
return expression
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _active_seconds(performance, beat):
|
|
243
|
+
seconds, end, bpm = 0., 0., performance['openingBpm']
|
|
244
|
+
for segment in performance['segments']:
|
|
245
|
+
first, last, a, b = (segment[k] for k in ('startBeat', 'endBeat', 'startBpm', 'endBpm'))
|
|
246
|
+
length = min(beat, last)-first
|
|
247
|
+
if length > 0:
|
|
248
|
+
slope = (b-a)/(last-first)
|
|
249
|
+
seconds += 60*length/a if abs(slope) < 1e-12 else 60/slope*math.log1p(slope*length/a)
|
|
250
|
+
end, bpm = last, b
|
|
251
|
+
if beat <= last:
|
|
252
|
+
return seconds
|
|
253
|
+
return seconds+max(0, beat-end)*60/bpm
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _seconds(performance, beat, after):
|
|
257
|
+
return _active_seconds(performance, beat)+sum(h['seconds'] for h in performance['holds']
|
|
258
|
+
if h['beat'] < beat or after and math.isclose(h['beat'], beat, abs_tol=1e-8))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _perform_one(pages, bpm, slide_group=0):
|
|
262
|
+
pages = resolve_pages(pages)
|
|
263
|
+
beats, numeric, expressions, bindings, sounds, aliases, payloads, directions = [], [], [], {}, [], {}, [], []
|
|
264
|
+
paired_sounds = {}
|
|
265
|
+
source_rows, source_keys, page_pairs, source_offset = [], [], [], 0.
|
|
266
|
+
for page_index, page in enumerate(pages):
|
|
267
|
+
paired = source_spans(page)
|
|
268
|
+
page_pairs.append(paired)
|
|
269
|
+
for index, note in enumerate(page['events']):
|
|
270
|
+
if event_kind(note) == 'UNPITCHED':
|
|
271
|
+
continue
|
|
272
|
+
start, end = source_offset+note['startBeat'], source_offset+note['startBeat']+note['durationBeats']
|
|
273
|
+
if index in paired:
|
|
274
|
+
start, end = source_offset+paired[index]['start'], source_offset+paired[index]['end']
|
|
275
|
+
source_rows.append(dict(start=start, end=end,
|
|
276
|
+
lane=(note['staffCount'], note['staffIndex'], note['midi']),
|
|
277
|
+
tied=note.get('tiedFromPrevious', False), eligible=not note.get('grace', False), note=note))
|
|
278
|
+
source_keys.append((page_index, index))
|
|
279
|
+
source_offset += page['totalBeats']
|
|
280
|
+
source_links = releasing_links(source_rows, lambda row: sound_lanes(row, .125, .04),
|
|
281
|
+
lambda old, row: row['note'].get('guitarEffect', {}) == old['note'].get('guitarEffect', {}))
|
|
282
|
+
prior_keys = {source_keys[current]: source_keys[earlier] for current, earlier in source_links.items()}
|
|
283
|
+
offset = 0.
|
|
284
|
+
for page_index, page in enumerate(pages):
|
|
285
|
+
local = page['measureBeats']; starts = [0.]
|
|
286
|
+
for duration in local:
|
|
287
|
+
if not math.isfinite(duration) or not .125 <= duration <= 128:
|
|
288
|
+
raise ValueError('Invalid expressive measure duration')
|
|
289
|
+
starts.append(starts[-1]+duration)
|
|
290
|
+
if not math.isclose(starts[-1], page['totalBeats'], abs_tol=1e-6):
|
|
291
|
+
raise ValueError('Expressive page extent disagrees with its measures')
|
|
292
|
+
physical = page.get('sourcePage', page_index)
|
|
293
|
+
paired = page_pairs[page_index]
|
|
294
|
+
note_ids = [f'note:{physical}:{index}' for index in range(len(page['events']))]
|
|
295
|
+
for index, note in sorted(enumerate(page['events']), key=lambda entry: (entry[1]['startBeat'], entry[0])):
|
|
296
|
+
identifier = note_ids[index]
|
|
297
|
+
start, end = offset+note['startBeat'], offset+note['startBeat']+note['durationBeats']
|
|
298
|
+
if index in paired:
|
|
299
|
+
start, end = offset+paired[index]['start'], offset+paired[index]['end']
|
|
300
|
+
if not math.isfinite(start) or not math.isfinite(end) or start < offset or end <= start or end > offset+starts[-1]+1e-6:
|
|
301
|
+
raise ValueError('Invalid expressive note span')
|
|
302
|
+
validate_unpitched(note)
|
|
303
|
+
if event_kind(note) == 'UNPITCHED':
|
|
304
|
+
old = len(sounds)
|
|
305
|
+
sounds.append(dict(id=identifier, start=start, end=end,
|
|
306
|
+
staff=note['staffIndex'], count=note['staffCount']))
|
|
307
|
+
payloads.append(dict(note, sourceEventId=identifier))
|
|
308
|
+
aliases[identifier] = old
|
|
309
|
+
continue
|
|
310
|
+
prior = prior_keys.get((page_index, index))
|
|
311
|
+
old = None
|
|
312
|
+
if prior is not None:
|
|
313
|
+
prior_page, prior_index = prior
|
|
314
|
+
prior_physical = pages[prior_page].get('sourcePage', prior_page)
|
|
315
|
+
old = aliases.get(f'note:{prior_physical}:{prior_index}')
|
|
316
|
+
if (old is not None and note.get('_slideRelation')
|
|
317
|
+
and note['_slideRelation'] != payloads[old].get('_slideRelation')):
|
|
318
|
+
old = None
|
|
319
|
+
if old is not None:
|
|
320
|
+
sounds[old]['end'] = max(sounds[old]['end'], end); aliases[identifier] = old
|
|
321
|
+
if note.get('_slideOrigins'):
|
|
322
|
+
merged = list(payloads[old].get('_slideOrigins', []))
|
|
323
|
+
merged.extend(origin for origin in note['_slideOrigins'] if origin not in merged)
|
|
324
|
+
payloads[old]['_slideOrigins'] = merged
|
|
325
|
+
|
|
326
|
+
else:
|
|
327
|
+
old = len(sounds); sounds.append(dict(id=identifier, start=start, end=end,
|
|
328
|
+
staff=note['staffIndex'], count=note['staffCount']))
|
|
329
|
+
payloads.append(dict(note)); aliases[identifier] = old
|
|
330
|
+
if index in paired:
|
|
331
|
+
paired_sounds[old] = dict(paired[index], start=start, end=end)
|
|
332
|
+
for supplied in page.get('score', {}).get('expressiveEvents', []):
|
|
333
|
+
if supplied['kind'] not in SUPPORTED:
|
|
334
|
+
continue
|
|
335
|
+
expression = _resolve_pedal(copy.deepcopy(supplied), page); members = _column_members(expression, page)
|
|
336
|
+
expression['eventId'] = f'page:{page_index}/'+expression['eventId']
|
|
337
|
+
if _rest_owned(expression):
|
|
338
|
+
span = _rest_span(expression, page)
|
|
339
|
+
expression['start'], expression['end'] = span if span else (None, None)
|
|
340
|
+
expression['scope'] = 'REST' if span else 'UNRESOLVED'
|
|
341
|
+
if members:
|
|
342
|
+
if expression['kind'] == 'FERMATA':
|
|
343
|
+
pair_ids = {paired[i]['pair'] for i in members if i in paired}
|
|
344
|
+
members = sorted(set(members) | {i for i, span in paired.items() if span['pair'] in pair_ids})
|
|
345
|
+
owned = [page['events'][i] for i in members]
|
|
346
|
+
spans = [(paired[i]['start'], paired[i]['end']) if i in paired else
|
|
347
|
+
(page['events'][i]['startBeat'], page['events'][i]['startBeat']+page['events'][i]['durationBeats']) for i in members]
|
|
348
|
+
start, release = spans[0]
|
|
349
|
+
if all(not n.get('durationFallback', False) and math.isclose(span[0], start, abs_tol=1e-7)
|
|
350
|
+
and math.isclose(span[1], release, abs_tol=1e-7) for n, span in zip(owned, spans)):
|
|
351
|
+
breath = expression['kind'] in ('BREATH', 'CAESURA')
|
|
352
|
+
resolved_start = _anchor(release if breath else start, starts)
|
|
353
|
+
resolved_end = preserve_end(expression, resolved_start, page)
|
|
354
|
+
expression['start'] = resolved_start
|
|
355
|
+
expression['end'] = _anchor(release, starts) if expression['kind'] == 'FERMATA' else resolved_end
|
|
356
|
+
attack = expression['kind'] in ('SFORZANDO', 'SFORZATO', 'SFORZANDO_PIANO')
|
|
357
|
+
expression['scope'] = 'NOTE' if expression['kind'] == 'FERMATA' or attack else 'PART' if breath or expression['kind'] in ('PEDAL_DOWN', 'PEDAL_UP') else 'SCORE'
|
|
358
|
+
if has_open(expression):
|
|
359
|
+
expression['scope'] = 'UNRESOLVED'
|
|
360
|
+
if expression['kind'] == 'FERMATA':
|
|
361
|
+
bindings[expression['eventId']] = {aliases[note_ids[i]] for i in members}
|
|
362
|
+
for field in ('start', 'end'):
|
|
363
|
+
if expression[field] is not None:
|
|
364
|
+
expression[field]['measureIndex'] += len(beats)
|
|
365
|
+
expressions.append(expression)
|
|
366
|
+
from .source_tempo_clock import rhythmic_changes
|
|
367
|
+
for change in rhythmic_changes(page):
|
|
368
|
+
numeric.append(dict(change, measureIndex=change['measureIndex']+len(beats)))
|
|
369
|
+
for supplied in page.get('score', {}).get('playbackDirections', []):
|
|
370
|
+
direction = copy.deepcopy(supplied); direction['measureBoundary'] += len(beats)
|
|
371
|
+
if direction.get('details', {}).get('end') is not None:
|
|
372
|
+
direction['details']['end']['measureIndex'] += len(beats)
|
|
373
|
+
directions.append(direction)
|
|
374
|
+
beats.extend(local); offset += starts[-1]
|
|
375
|
+
data = struct.pack('>idi', 0x45585031, bpm, len(beats))
|
|
376
|
+
data += b''.join(struct.pack('>d', value) for value in beats)+struct.pack('>i', len(numeric))
|
|
377
|
+
data += b''.join(struct.pack('>ifdd', c['measureIndex'], c['positionInMeasure'], c['bpm'], c.get('beatUnit', 1)) for c in numeric)
|
|
378
|
+
data += struct.pack('>i', len(sounds))
|
|
379
|
+
for sound in sounds:
|
|
380
|
+
data += _text(sound['id'])+struct.pack('>ddii', sound['start'], sound['end'], sound['staff'], sound['count'])
|
|
381
|
+
data += struct.pack('>i', len(bindings))
|
|
382
|
+
for identifier, members in bindings.items():
|
|
383
|
+
data += _text(identifier)+struct.pack('>i', len(members))+b''.join(_text(sounds[i]['id']) for i in sorted(members))
|
|
384
|
+
result = _bridge(data+encode(directions, expressions, len(beats)))
|
|
385
|
+
slide_visits = {}
|
|
386
|
+
if any(payload.get('_slideOrigins') for payload in payloads):
|
|
387
|
+
route = result.get('navigationOccurrences')
|
|
388
|
+
if not isinstance(route, list):
|
|
389
|
+
raise ValueError('Continuous slides require explicit performed navigation occurrences')
|
|
390
|
+
source_starts = [0.]
|
|
391
|
+
for value in beats:
|
|
392
|
+
source_starts.append(source_starts[-1]+value)
|
|
393
|
+
previous_source_end = previous_performed_end = None
|
|
394
|
+
visit = None
|
|
395
|
+
for occurrence in route:
|
|
396
|
+
def absolute(anchor):
|
|
397
|
+
return source_starts[anchor['measureIndex']]+anchor['quarterBeatOffset']
|
|
398
|
+
source_start, source_end = absolute(occurrence['start']), absolute(occurrence['end'])
|
|
399
|
+
contiguous = (previous_source_end is not None
|
|
400
|
+
and previous_source_end == source_start
|
|
401
|
+
and previous_performed_end == occurrence['performanceStartBeat'])
|
|
402
|
+
if not contiguous:
|
|
403
|
+
visit = f"expression:{slide_group}:{occurrence['occurrenceId']}"
|
|
404
|
+
slide_visits[occurrence['occurrenceId']] = visit
|
|
405
|
+
previous_source_end, previous_performed_end = source_end, occurrence['performanceEndBeat']
|
|
406
|
+
events = []
|
|
407
|
+
for interval in result['notes']:
|
|
408
|
+
payload = payloads[interval['sourceIndex']]
|
|
409
|
+
identifier = interval['performanceId']; start, end = interval['startBeat'], interval['endBeat']
|
|
410
|
+
subdivision = payload.get('tremoloBeats', 0)
|
|
411
|
+
if subdivision not in (0, .5, .25, .125, .0625):
|
|
412
|
+
raise ValueError('Unsupported tremolo subdivision')
|
|
413
|
+
# Subdivide the written/performed beat span before integrating tempo. A fixed
|
|
414
|
+
# MIDI subdivision after time conversion adds extra attacks during slowing/holds.
|
|
415
|
+
count = max(1, math.ceil((end-start)/subdivision-1e-8)) if subdivision else 1
|
|
416
|
+
pair = paired_sounds.get(interval['sourceIndex'])
|
|
417
|
+
windows = pulse_windows(pair, start, end, interval['sourceStartBeat']) if pair else (
|
|
418
|
+
(ordinal, start+ordinal*subdivision if subdivision else start,
|
|
419
|
+
min(end,start+(ordinal+1)*subdivision) if subdivision else end) for ordinal in range(count))
|
|
420
|
+
for ordinal, a, b in windows:
|
|
421
|
+
held = any(identifier in hold['sustainedTargets'] and
|
|
422
|
+
(a < hold['beat'] <= b+1e-8 if pair else math.isclose(hold['beat'], b, abs_tol=1e-8)) for hold in result['holds'])
|
|
423
|
+
start_seconds, end_seconds = _seconds(result, a, True), _seconds(result, b, held)
|
|
424
|
+
note = dict(payload)
|
|
425
|
+
note.update(startBeat=start_seconds*2, durationBeats=(end_seconds-start_seconds)*2,
|
|
426
|
+
tiedFromPrevious=False, measureIndex=0,
|
|
427
|
+
performanceId=identifier if not (subdivision or pair) else identifier+f'/tremolo:{ordinal}')
|
|
428
|
+
if note.get('_slideOrigins'):
|
|
429
|
+
occurrences = interval['navigationOccurrences']
|
|
430
|
+
visits = {slide_visits.get(occurrence) for occurrence in occurrences}
|
|
431
|
+
if not occurrences or None in visits or len(visits) != 1:
|
|
432
|
+
raise ValueError('Continuous slide interval lacks a unique performed visit')
|
|
433
|
+
note['_slideContext'] = dict(visitId=next(iter(visits)),
|
|
434
|
+
attack=not interval['clippedEntry'] and ordinal == 0 and not payload.get('tiedFromPrevious', False),
|
|
435
|
+
clippedEntry=interval['clippedEntry'] or ordinal != 0,
|
|
436
|
+
clippedRelease=interval['clippedRelease'] or b != end,
|
|
437
|
+
held=any(identifier in hold['sustainedTargets']
|
|
438
|
+
and interval['startBeat'] < hold['beat'] <= interval['endBeat']
|
|
439
|
+
for hold in result['holds']))
|
|
440
|
+
if event_kind(note) == 'UNPITCHED':
|
|
441
|
+
note['_unpitchedAttackId'] = identifier
|
|
442
|
+
note['_unpitchedContinuation'] = False
|
|
443
|
+
note['clippedEntry'] = interval['clippedEntry']
|
|
444
|
+
if subdivision or pair:
|
|
445
|
+
note['tremoloBeats'] = 0
|
|
446
|
+
attacks = [attack for attack in result['attacks'] if attack['staffIndex'] == note['staffIndex']
|
|
447
|
+
and attack['staffCount'] == note['staffCount'] and math.isclose(attack['beat'], a, abs_tol=1e-7)]
|
|
448
|
+
if attacks and not interval['clippedEntry']:
|
|
449
|
+
note['performanceAttack'] = max(attacks, key=lambda attack: attack['gain'])
|
|
450
|
+
events.append(note)
|
|
451
|
+
duration = result['durationSeconds']*2
|
|
452
|
+
return dict(events=events, measureBeats=[duration] if duration else [], totalBeats=duration,
|
|
453
|
+
score=dict(tempoChanges=[]), pedalControls=[dict(control,
|
|
454
|
+
beat=_seconds(result, control['beat'], True)*2) for control in result['pedalControls']]), result
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def perform_expressions(document, bpm):
|
|
458
|
+
"""Return a fixed-tempo performance document only when supported printed evidence exists."""
|
|
459
|
+
pages = document['pages']
|
|
460
|
+
for page in pages:
|
|
461
|
+
for note in page['events']:
|
|
462
|
+
validate_unpitched(note)
|
|
463
|
+
for row in page.get('score', {}).get('rests', []):
|
|
464
|
+
if rest_kind(row) == 'FULL_MEASURE':
|
|
465
|
+
full_measure_span(page, row)
|
|
466
|
+
if not (any(e['kind'] in SUPPORTED or has_open(e) for page in pages for e in page.get('score', {}).get('expressiveEvents', []))
|
|
467
|
+
or any(performance_pairs(page.get('score', {}).get('tremoloSource')) for page in pages)):
|
|
468
|
+
return None
|
|
469
|
+
# Use the same arrangement boundaries as ordinary navigation export.
|
|
470
|
+
from .navigation import _bridge as navigation_bridge
|
|
471
|
+
data = struct.pack('>ii', 0x4e415031, len(pages))
|
|
472
|
+
data += b''.join(struct.pack('>ii', len(page['measureBeats']), page.get('score', {}).get('firstMeasureNumber', 0)) for page in pages)
|
|
473
|
+
ranges = navigation_bridge(data)
|
|
474
|
+
played, evidence = [], []
|
|
475
|
+
for group in ranges:
|
|
476
|
+
page, result = _perform_one(pages[group['firstPage']:group['pageAfterLast']], bpm, group['firstPage'])
|
|
477
|
+
played.append(page); evidence.append(result)
|
|
478
|
+
return dict(document, pages=played, expressivePerformance=evidence)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Copyright 2026 Luckolite
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Retain optically proved gradual-tempo spans through document resolution."""
|
|
4
|
+
import copy
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import struct
|
|
8
|
+
|
|
9
|
+
SOURCE = 'printed-tempo-dash-span'
|
|
10
|
+
END = 'printed-tempo-dash-end-v1:'
|
|
11
|
+
OPEN = 'printed-tempo-dash-page-edge-v1:'
|
|
12
|
+
GRADUAL = {'ACCELERANDO', 'RITARDANDO', 'RALLENTANDO'}
|
|
13
|
+
TEMPO = GRADUAL | {'RITENUTO', 'A_TEMPO', 'TEMPO_PRIMO', 'METRIC_MODULATION'}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _hint(event, prefix):
|
|
17
|
+
values = [e['sourceId'][len(prefix):] for e in event['evidence']
|
|
18
|
+
if e['sourceId'].startswith(prefix)]
|
|
19
|
+
if not values or any(not re.fullmatch(r'[1-9][0-9]{0,3}', v) for v in values):
|
|
20
|
+
return None
|
|
21
|
+
return int(values[0]) if len(set(values)) == 1 else None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def has_open(event):
|
|
25
|
+
return any(e['sourceId'].startswith(OPEN) for e in event['evidence'])
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _measure(event):
|
|
29
|
+
target = event.get('targetEventId') or ''
|
|
30
|
+
if not target.startswith(('expression-column:', 'expression-rest:')) or not any(
|
|
31
|
+
e['sourceId'] in ('printed-expression-word', 'printed-expression-symbol')
|
|
32
|
+
for e in event['evidence']):
|
|
33
|
+
return None
|
|
34
|
+
try:
|
|
35
|
+
m, staff, count, bits = map(int, target.split(':')[1:])
|
|
36
|
+
position = struct.unpack('>f', struct.pack('>i', bits))[0]
|
|
37
|
+
if m >= 0 and staff == event['staffIndex'] and count == event['staffCount'] and 0 <= position <= 1:
|
|
38
|
+
return m
|
|
39
|
+
except (ValueError, struct.error):
|
|
40
|
+
pass
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def preserve_end(event, start, page):
|
|
45
|
+
"""Preserve a proved endpoint only if resolving ownership did not move its start."""
|
|
46
|
+
if event['kind'] not in GRADUAL or event.get('start') not in (None, start) or not any(
|
|
47
|
+
e['sourceId'] == SOURCE for e in event['evidence']):
|
|
48
|
+
return None
|
|
49
|
+
count = len(page['measureBeats'])
|
|
50
|
+
if event.get('end') is not None:
|
|
51
|
+
end = event['end']
|
|
52
|
+
m, beat = end['measureIndex'], end['quarterBeatOffset']
|
|
53
|
+
if 0 <= m <= count and math.isfinite(beat) and beat >= 0 and (
|
|
54
|
+
m < count and beat < page['measureBeats'][m] or m == count and beat == 0) and (
|
|
55
|
+
m, beat) > (start['measureIndex'], start['quarterBeatOffset']):
|
|
56
|
+
return copy.deepcopy(end)
|
|
57
|
+
return None
|
|
58
|
+
delta = _hint(event, END)
|
|
59
|
+
if delta is None:
|
|
60
|
+
return None
|
|
61
|
+
target = start['measureIndex'] + delta
|
|
62
|
+
marks = [t for t in page.get('score', {}).get('tempoChanges', [])
|
|
63
|
+
if t['measureIndex'] == target and t['positionInMeasure'] == 0]
|
|
64
|
+
if target < count and marks and len({t['bpm'] for t in marks}) == 1:
|
|
65
|
+
return dict(measureIndex=target, quarterBeatOffset=0)
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _latest(marks, fallback):
|
|
70
|
+
if not marks:
|
|
71
|
+
return fallback
|
|
72
|
+
last = marks[-1]
|
|
73
|
+
values = {t['bpm'] for t in marks if (t['measureIndex'], t['positionInMeasure']) ==
|
|
74
|
+
(last['measureIndex'], last['positionInMeasure'])}
|
|
75
|
+
return last['bpm'] if len(values) == 1 else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def resolve_pages(pages):
|
|
79
|
+
"""Resolve only within the supplied continuous movement or playback range."""
|
|
80
|
+
result = copy.deepcopy(pages)
|
|
81
|
+
carried = None
|
|
82
|
+
for i, page in enumerate(result):
|
|
83
|
+
if page is None or not page['measureBeats']:
|
|
84
|
+
carried = None
|
|
85
|
+
continue
|
|
86
|
+
score = page.get('score', {})
|
|
87
|
+
count = len(page['measureBeats'])
|
|
88
|
+
marks = sorted(score.get('tempoChanges', []), key=lambda t: (t['measureIndex'], t['positionInMeasure']))
|
|
89
|
+
next_page = result[i + 1] if i + 1 < len(result) else None
|
|
90
|
+
adjacent = bool(next_page and next_page['measureBeats'])
|
|
91
|
+
first = score.get('firstMeasureNumber', 0)
|
|
92
|
+
following = next_page.get('score', {}).get('firstMeasureNumber', 0) if next_page else 0
|
|
93
|
+
if first > 0 and following > 0 and first + count != following:
|
|
94
|
+
adjacent = False
|
|
95
|
+
openings = [t for t in next_page.get('score', {}).get('tempoChanges', [])
|
|
96
|
+
if t['measureIndex'] == 0 and t['positionInMeasure'] == 0] if adjacent else []
|
|
97
|
+
events = score.get('expressiveEvents', [])
|
|
98
|
+
candidates = [e for e in events if has_open(e)]
|
|
99
|
+
if len(candidates) == 1 and openings and len({t['bpm'] for t in openings}) == 1:
|
|
100
|
+
event = candidates[0]
|
|
101
|
+
measure, delta = _measure(event), _hint(event, OPEN)
|
|
102
|
+
current = carried
|
|
103
|
+
if measure is not None and delta is not None and measure + delta == count:
|
|
104
|
+
current = _latest([t for t in marks if (t['measureIndex'], t['positionInMeasure']) <= (measure, 0)], carried)
|
|
105
|
+
intervening = any((t['measureIndex'], t['positionInMeasure']) > (measure, 0) for t in marks)
|
|
106
|
+
intervening |= any(e is not event and e['kind'] in TEMPO and _measure(e) is not None
|
|
107
|
+
and _measure(e) >= measure for e in events)
|
|
108
|
+
faster = event['kind'] == 'ACCELERANDO' or event['kind'] == 'UNRESOLVED_DIRECTION' and any(
|
|
109
|
+
e['sourceId'] == 'printed-expression-word' and re.fullmatch(r'\s*(?:[mpf]{1,3}\s+)?faster\s*[-.!]*\s*', e['printedText'], re.I)
|
|
110
|
+
for e in event['evidence'])
|
|
111
|
+
slower = event['kind'] in ('RITARDANDO', 'RALLENTANDO')
|
|
112
|
+
target = openings[0]['bpm']
|
|
113
|
+
if current is not None and math.isfinite(current) and not intervening and (
|
|
114
|
+
faster and target > current or slower and target < current):
|
|
115
|
+
evidence = [e for e in event['evidence'] if not e['sourceId'].startswith(OPEN)]
|
|
116
|
+
evidence.extend(dict(event['evidence'][0], sourceId=s) for s in (
|
|
117
|
+
SOURCE, END + str(delta), 'printed-tempo-dash-adjacent-page-v1'))
|
|
118
|
+
event.update(kind='ACCELERANDO' if faster else event['kind'], evidence=evidence,
|
|
119
|
+
end=dict(measureIndex=count, quarterBeatOffset=0) if event.get('start') else None,
|
|
120
|
+
scope='SCORE' if event.get('start') else 'UNRESOLVED')
|
|
121
|
+
carried = _latest(marks, carried)
|
|
122
|
+
if not adjacent:
|
|
123
|
+
carried = None
|
|
124
|
+
return result
|