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.
Files changed (64) hide show
  1. score_reader-0.1.5.dist-info/METADATA +154 -0
  2. score_reader-0.1.5.dist-info/RECORD +64 -0
  3. score_reader-0.1.5.dist-info/WHEEL +5 -0
  4. score_reader-0.1.5.dist-info/entry_points.txt +2 -0
  5. score_reader-0.1.5.dist-info/licenses/LICENSE +202 -0
  6. score_reader-0.1.5.dist-info/licenses/NOTICE +13 -0
  7. score_reader-0.1.5.dist-info/top_level.txt +1 -0
  8. sheet_interpreter/__init__.py +9 -0
  9. sheet_interpreter/arpeggio_notation.py +111 -0
  10. sheet_interpreter/articulation_export.py +49 -0
  11. sheet_interpreter/audio.py +260 -0
  12. sheet_interpreter/beam_source.py +163 -0
  13. sheet_interpreter/boundary_ties.py +82 -0
  14. sheet_interpreter/bow_export.py +35 -0
  15. sheet_interpreter/clef_export.py +76 -0
  16. sheet_interpreter/cli.py +142 -0
  17. sheet_interpreter/clock_context.py +261 -0
  18. sheet_interpreter/continuous_slide_curve.py +89 -0
  19. sheet_interpreter/cue_caption.py +54 -0
  20. sheet_interpreter/data/LICENSE +202 -0
  21. sheet_interpreter/data/NOTICE +13 -0
  22. sheet_interpreter/data/music_sheets_v4_float16.tflite +0 -0
  23. sheet_interpreter/dynamic_export.py +76 -0
  24. sheet_interpreter/fall_off_notation.py +128 -0
  25. sheet_interpreter/grace_export.py +83 -0
  26. sheet_interpreter/guide_writer.py +287 -0
  27. sheet_interpreter/guitar_effect.py +32 -0
  28. sheet_interpreter/guitar_export.py +36 -0
  29. sheet_interpreter/hairpin_export.py +102 -0
  30. sheet_interpreter/interpreter.jar +0 -0
  31. sheet_interpreter/midi.py +340 -0
  32. sheet_interpreter/multi_rest_wire.py +62 -0
  33. sheet_interpreter/musicxml.py +937 -0
  34. sheet_interpreter/natural_harmonic_notation.py +125 -0
  35. sheet_interpreter/navigation.py +186 -0
  36. sheet_interpreter/neutral_rest_caption.py +58 -0
  37. sheet_interpreter/ocr.py +103 -0
  38. sheet_interpreter/octave_shift_export.py +94 -0
  39. sheet_interpreter/ornament_export.py +53 -0
  40. sheet_interpreter/page_processing_budget.py +17 -0
  41. sheet_interpreter/parenthesized_note_group.py +198 -0
  42. sheet_interpreter/pdf_annotations.py +52 -0
  43. sheet_interpreter/performance.py +478 -0
  44. sheet_interpreter/printed_tempo_spans.py +124 -0
  45. sheet_interpreter/reader.py +204 -0
  46. sheet_interpreter/rest_kinds.py +33 -0
  47. sheet_interpreter/runtime.py +17 -0
  48. sheet_interpreter/semantic_wire.py +321 -0
  49. sheet_interpreter/slide_numbering.py +43 -0
  50. sheet_interpreter/slide_performance.py +204 -0
  51. sheet_interpreter/slur_export.py +124 -0
  52. sheet_interpreter/slur_wire.py +159 -0
  53. sheet_interpreter/source_tempo_clock.py +93 -0
  54. sheet_interpreter/spelling_export.py +48 -0
  55. sheet_interpreter/straight_slide.py +76 -0
  56. sheet_interpreter/sudden_dynamic.py +47 -0
  57. sheet_interpreter/technique_export.py +62 -0
  58. sheet_interpreter/tie_owners.py +43 -0
  59. sheet_interpreter/tremolo_export.py +93 -0
  60. sheet_interpreter/tremolo_performance.py +45 -0
  61. sheet_interpreter/tremolo_wire.py +138 -0
  62. sheet_interpreter/typed_events.py +57 -0
  63. sheet_interpreter/typed_performance.py +44 -0
  64. sheet_interpreter/visual_size.py +18 -0
@@ -0,0 +1,260 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Stream a synthesized performance preview to an optional local MP3 encoder."""
4
+ import math
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+
11
+ from .midi import performance_events, performed_document, _performance_events_prepared
12
+ from .typed_events import event_kind, validate_unpitched
13
+ from .typed_performance import unpitched_intervals
14
+ from dataclasses import dataclass
15
+
16
+
17
+ SAMPLE_RATE = 44100
18
+ RELEASE_SECONDS = .08
19
+
20
+
21
+ def find_ffmpeg(executable=None):
22
+ """Prefer caller/PATH tools; the audio extra supplies an offline fallback."""
23
+ if executable is not None:
24
+ found = shutil.which(str(executable))
25
+ if not found:
26
+ raise ValueError("FFmpeg executable not found: " + str(executable))
27
+ return found
28
+ found = shutil.which("ffmpeg")
29
+ if found:
30
+ return found
31
+ try:
32
+ import imageio_ffmpeg
33
+ return imageio_ffmpeg.get_ffmpeg_exe()
34
+ except (ImportError, RuntimeError) as error:
35
+ raise RuntimeError(
36
+ "MP3 export needs FFmpeg on PATH, --ffmpeg /path/to/ffmpeg, "
37
+ "or pip install 'score-reader[audio]'"
38
+ ) from error
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class UnpitchedAudioPreview:
43
+ """Explicit caller choice of the finite aperiodic preview; no pitch/timbre mapping."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class UnpitchedNoiseAttack:
48
+ source_id: str
49
+ end_sample: int
50
+ gain: float
51
+ attack: object
52
+
53
+
54
+ def _sample_events(document, bpm, *, unpitched_preview=None):
55
+ has_unpitched = any(event_kind(note) == 'UNPITCHED' for page in document['pages'] for note in page['events'])
56
+ if has_unpitched:
57
+ if not isinstance(unpitched_preview, UnpitchedAudioPreview):
58
+ raise ValueError('Unpitched audio needs an explicit UnpitchedAudioPreview policy')
59
+ for page in document['pages']:
60
+ for note in page['events']:
61
+ validate_unpitched(note)
62
+ document, bpm, expressive_document = performed_document(document, bpm)
63
+ pitched = dict(document, pages=[dict(page, events=[note for note in page['events']
64
+ if event_kind(note) == 'PITCHED']) for page in document['pages']])
65
+ else:
66
+ pitched = document
67
+ if has_unpitched:
68
+ ppq, events, end_tick = _performance_events_prepared(pitched, bpm, expressive_document)
69
+ else:
70
+ ppq, events, end_tick = performance_events(pitched, bpm)
71
+ if len(events) > 1_000_000:
72
+ raise ValueError("Audio preview exceeds one million performance messages")
73
+ seconds, last_tick, micros = 0.0, 0, round(60_000_000 / bpm)
74
+ tempo_points = [(0, micros)]
75
+ result = []
76
+ for tick, _, message in events:
77
+ seconds += (tick-last_tick) * micros / (ppq * 1_000_000)
78
+ last_tick = tick
79
+ if message.startswith(b"\xff\x51\x03"):
80
+ micros = int.from_bytes(message[3:], "big")
81
+ tempo_points.append((tick, micros))
82
+ if micros <= 0:
83
+ raise ValueError("Invalid audio tempo")
84
+ else:
85
+ result.append((round(seconds*SAMPLE_RATE), message))
86
+ seconds += (end_tick-last_tick) * micros / (ppq * 1_000_000)
87
+ if not math.isfinite(seconds) or not 0 <= seconds <= 3600:
88
+ raise ValueError("Audio preview must be at most one hour")
89
+ if has_unpitched:
90
+ def sample_at(beat):
91
+ target = round(beat*ppq)
92
+ elapsed, prior, tempo = 0., 0, round(60_000_000/bpm)
93
+ for tick, value in tempo_points:
94
+ if tick > target:
95
+ break
96
+ elapsed += (tick-prior)*tempo/(ppq*1_000_000)
97
+ prior, tempo = tick, value
98
+ return round((elapsed+(target-prior)*tempo/(ppq*1_000_000))*SAMPLE_RATE)
99
+ for interval in unpitched_intervals(document):
100
+ note = interval['note']
101
+ start = sample_at(interval['startBeat'])
102
+ dead = (note.get('guitarEffect') or {}).get('type') == 'dead'
103
+ end = sample_at(interval['startBeat']+(interval['endBeat']-interval['startBeat'])*(.12 if dead else 1))
104
+ end = min(max(start+1, end), start+round(.020*SAMPLE_RATE))
105
+ result.append((start, UnpitchedNoiseAttack(interval['sourceId'], end,
106
+ .25 if dead else 1., note.get('performanceAttack'))))
107
+ result.sort(key=lambda item: item[0])
108
+ return result, round(seconds*SAMPLE_RATE)
109
+
110
+
111
+ def _pcm_blocks(events, end_sample):
112
+ """Bounded mono blocks; keep phase continuous across bends and tempo changes."""
113
+ import numpy as np
114
+ bends, ranges = [0.0]*16, [2.0]*16
115
+ expression = [1.0]*16
116
+ pedal = [False]*16
117
+ rpn = [[127, 127] for _ in range(16)]
118
+ voices, noise_voices, cursor = [], [], 0
119
+
120
+ def render(stop):
121
+ nonlocal cursor, voices, noise_voices
122
+ while cursor < stop:
123
+ count = min(8192, stop-cursor)
124
+ indices = np.arange(count, dtype=np.float64)
125
+ mix = np.zeros(count, dtype=np.float64)
126
+ for voice in voices:
127
+ channel, pitch, velocity, start, released, phase, release_expression, key_released = voice
128
+ age = (cursor-start+indices)/SAMPLE_RATE
129
+ frequency = 440 * 2**((pitch-69+bends[channel])/12)
130
+ angles = phase + indices*(2*math.pi*frequency/SAMPLE_RATE)
131
+ envelope = np.minimum(1, age/.005) * (.3+.7*np.exp(-age*1.8))
132
+ if released is not None:
133
+ envelope *= np.clip(1-(cursor-released+indices)/(SAMPLE_RATE*RELEASE_SECONDS), 0, 1)
134
+ # Original additive tone, not sampled instruments or a bundled soundfont.
135
+ tone = np.sin(angles)
136
+ for harmonic, level in ((2, .3), (3, .12)):
137
+ if frequency*harmonic < SAMPLE_RATE/2:
138
+ tone += level*np.sin(angles*harmonic)
139
+ mix += tone*envelope*(.16*velocity/127)*(expression[channel] if release_expression is None else release_expression)
140
+ voice[5] = (phase+count*2*math.pi*frequency/SAMPLE_RATE) % (2*math.pi)
141
+ for start, samples in noise_voices:
142
+ a, b = max(0, cursor-start), min(len(samples), cursor-start+count)
143
+ if b > a:
144
+ mix[max(0,start-cursor):max(0,start-cursor)+b-a] += samples[a:b]
145
+ cursor += count
146
+ noise_voices = [(start, samples) for start, samples in noise_voices if cursor < start+len(samples)]
147
+ voices = [v for v in voices if v[4] is None or cursor-v[4] < SAMPLE_RATE*RELEASE_SECONDS]
148
+ yield np.tanh(mix).astype('<f4').tobytes()
149
+
150
+ for at, message in events:
151
+ yield from render(at)
152
+ if isinstance(message, UnpitchedNoiseAttack):
153
+ if (type(message.end_sample) is not int or not 0 < message.end_sample-at <= round(.020*SAMPLE_RATE)
154
+ or not isinstance(message.source_id, str) or not message.source_id
155
+ or not math.isfinite(message.gain) or message.gain < 0):
156
+ raise ValueError('Unpitched noise attack must be finite, owned and at most20ms')
157
+ if len(voices)+len(noise_voices) >= 256:
158
+ raise ValueError('Audio preview exceeds 256 simultaneous voices')
159
+ state, mask = 0x6a09e667f3bcc909, (1<<64)-1
160
+ samples = []
161
+ for frame in range(message.end_sample-at):
162
+ state ^= (state<<13)&mask
163
+ state ^= state>>7
164
+ state ^= (state<<17)&mask
165
+ state &= mask
166
+ age = frame/SAMPLE_RATE
167
+ gain = message.gain
168
+ if message.attack:
169
+ attack = message.attack
170
+ fraction = min(1., age/attack['seconds']) if attack['seconds'] else 1.
171
+ gain *= attack['gain']+(attack['settledGain']-attack['gain'])*fraction
172
+ samples.append(((state>>11)*2**-53*2-1)*.12*math.exp(-450*age)*gain)
173
+ noise_voices.append((at, np.asarray(samples, dtype=np.float64)))
174
+ continue
175
+ status, channel = message[0]&0xf0, message[0]&15
176
+ if status == 0x90 and message[2]:
177
+ if len(voices)+len(noise_voices) >= 256:
178
+ raise ValueError("Audio preview exceeds 256 simultaneous voices")
179
+ voices.append([channel, message[1], message[2], at, None, 0.0, None, False])
180
+ elif status == 0x80 or status == 0x90:
181
+ for voice in voices:
182
+ if voice[0] == channel and voice[1] == message[1] and not voice[7]:
183
+ voice[7] = True
184
+ if not pedal[channel]:
185
+ voice[4] = at
186
+ voice[6] = expression[channel]
187
+ elif status == 0xb0:
188
+ controller, value = message[1:]
189
+ if controller == 64:
190
+ pedal[channel] = value >= 64
191
+ if not pedal[channel]:
192
+ for voice in voices:
193
+ if voice[0] == channel and voice[7] and voice[4] is None:
194
+ voice[4] = at
195
+ elif controller == 11:
196
+ expression[channel] = value/127
197
+ elif controller == 101:
198
+ rpn[channel][0] = value
199
+ elif controller == 100:
200
+ rpn[channel][1] = value
201
+ elif controller == 6 and rpn[channel] == [0, 0]:
202
+ ranges[channel] = value
203
+ elif status == 0xe0:
204
+ bends[channel] = (((message[2]<<7)|message[1])-8192)/8192*ranges[channel]
205
+ yield from render(end_sample+round(RELEASE_SECONDS*SAMPLE_RATE))
206
+
207
+
208
+ def write_mp3(document, path, bpm=120, *, ffmpeg=None, bitrate=192, unpitched_preview=None):
209
+ """Export a basic synthesized MP3 preview, preserving the MIDI performance.
210
+
211
+ Requires local FFmpeg with libmp3lame. No inference, network or soundfont is
212
+ needed for an already decoded document. Existing output survives failures.
213
+ """
214
+ if bitrate not in (64, 96, 128, 160, 192, 256, 320):
215
+ raise ValueError("MP3 bitrate must be 64, 96, 128, 160, 192, 256 or 320 kbps")
216
+ if (any(event_kind(note) == 'UNPITCHED' for page in document['pages'] for note in page['events'])
217
+ and not isinstance(unpitched_preview, UnpitchedAudioPreview)):
218
+ raise ValueError('Unpitched audio needs an explicit UnpitchedAudioPreview policy')
219
+ encoder = find_ffmpeg(ffmpeg)
220
+ events, end_sample = _sample_events(document, bpm, unpitched_preview=unpitched_preview)
221
+ target = Path(path)
222
+ target.parent.mkdir(parents=True, exist_ok=True)
223
+ with tempfile.NamedTemporaryFile(prefix=".mp3-export-", suffix=".mp3", dir=target.parent, delete=False) as output:
224
+ temporary = Path(output.name)
225
+ process = None
226
+ try:
227
+ # File-backed stderr avoids pipe deadlocks and keeps diagnostics off stdout.
228
+ with tempfile.TemporaryFile() as errors:
229
+ process = subprocess.Popen(
230
+ [encoder, '-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
231
+ '-f', 'f32le', '-ar', str(SAMPLE_RATE), '-ac', '1', '-i', 'pipe:0',
232
+ '-c:a', 'libmp3lame', '-b:a', str(bitrate)+'k', '-f', 'mp3', str(temporary)],
233
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors,
234
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0),
235
+ )
236
+ broken = False
237
+ try:
238
+ for block in _pcm_blocks(events, end_sample):
239
+ process.stdin.write(block)
240
+ except BrokenPipeError:
241
+ broken = True
242
+ finally:
243
+ try:
244
+ process.stdin.close()
245
+ except BrokenPipeError:
246
+ broken = True
247
+ code = process.wait(timeout=60)
248
+ if code or broken or temporary.stat().st_size == 0:
249
+ errors.seek(0, os.SEEK_END)
250
+ errors.seek(max(0, errors.tell()-2000))
251
+ detail = errors.read().decode('utf-8', errors='replace').strip()
252
+ raise RuntimeError("MP3 encoder failed" + (": " + detail if detail else ""))
253
+ os.replace(temporary, target)
254
+ except subprocess.TimeoutExpired as error:
255
+ raise RuntimeError("MP3 encoder did not finish within 60 seconds") from error
256
+ finally:
257
+ if process is not None and process.poll() is None:
258
+ process.kill()
259
+ process.wait()
260
+ temporary.unlink(missing_ok=True)
@@ -0,0 +1,163 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Guide297 literal beam topology. No timing or inferred grouping is encoded."""
4
+ import io
5
+ import struct
6
+ MAX = 1_000_000
7
+ MAX_BYTES = 32 * 1024 * 1024
8
+ DIRECTIONS = ('FORWARD', 'BACKWARD')
9
+ _JAVA_SPACES = frozenset(range(9,14)) | frozenset(range(28,33)) | {0x1680,0x2028,0x2029,0x205f,0x3000} | frozenset(range(0x2000,0x2007)) | frozenset(range(0x2008,0x200b))
10
+
11
+
12
+ def empty(note_count):
13
+ _int(note_count, 0, MAX)
14
+ return dict(groups=[], detachedColumns=[], noteOrigins=[None] * note_count)
15
+
16
+
17
+ def _int(n, lo=0, hi=2147483647):
18
+ if type(n) is not int or not lo <= n <= hi:
19
+ raise ValueError('Invalid beam integer')
20
+ return n
21
+
22
+
23
+ def _keys(value, keys):
24
+ if not isinstance(value, dict) or set(value) != set(keys):
25
+ raise ValueError('Invalid beam record fields')
26
+
27
+
28
+ def _list(value, maximum=MAX):
29
+ if not isinstance(value, list) or len(value) > maximum:
30
+ raise ValueError('Invalid beam collection')
31
+ return value
32
+
33
+
34
+ def _anchor(a):
35
+ _keys(a, ('pageIndex', 'noteIndex'))
36
+ return (_int(a['pageIndex']), _int(a['noteIndex'], 0, MAX-1))
37
+
38
+
39
+ def checked(source, note_count):
40
+ """Validate exact source facts; repeated current origins deliberately remain valid."""
41
+ _int(note_count, 0, MAX)
42
+ if source is None:
43
+ return empty(note_count)
44
+ _keys(source, ('groups', 'detachedColumns', 'noteOrigins'))
45
+ groups = _list(source['groups']); detached = _list(source['detachedColumns'])
46
+ origins = _list(source['noteOrigins'])
47
+ if len(origins) != note_count:
48
+ raise ValueError('Beam note ownership mismatch')
49
+ for a in origins:
50
+ if a is not None: _anchor(a)
51
+ used = set(); ids = set(); total = len(detached)
52
+ def column(c):
53
+ _keys(c, ('members',)); members = _list(c['members'],128)
54
+ if not members: raise ValueError('Empty beam column')
55
+ page = None
56
+ for a in members:
57
+ key = _anchor(a)
58
+ if page is not None and key[0] != page:
59
+ raise ValueError('Beam column crosses physical pages')
60
+ page = key[0]
61
+ if key in used: raise ValueError('Duplicate physical beam ownership')
62
+ used.add(key)
63
+ return page
64
+ for g in groups:
65
+ _keys(g, ('id', 'columns', 'bridges', 'hooks'))
66
+ name = g['id']
67
+ if (type(name) is not str or all(ord(ch) in _JAVA_SPACES for ch in name) or len(name.encode('utf-16-be'))//2 > 256
68
+ or len(name.encode('utf-8')) > 1024 or name in ids):
69
+ raise ValueError('Invalid beam group ID')
70
+ ids.add(name); columns = _list(g['columns']); bridges = _list(g['bridges']); hooks = _list(g['hooks'],MAX*8)
71
+ if len(columns) < 2 or len(bridges) != len(columns)-1 or len(hooks) > len(columns)*8:
72
+ raise ValueError('Invalid beam group dimensions')
73
+ total += len(columns)
74
+ if total > MAX: raise ValueError('Too many beam columns')
75
+ if len({column(c) for c in columns}) != 1:
76
+ raise ValueError('Beam group crosses physical pages')
77
+ for mask in bridges:
78
+ _int(mask,1,255)
79
+ if not mask & 1: raise ValueError('Beam bridge lacks primary')
80
+ occupied = set()
81
+ for h in hooks:
82
+ _keys(h, ('columnIndex', 'level', 'direction'))
83
+ c = _int(h['columnIndex'],0,len(columns)-1); level = _int(h['level'],1,8)
84
+ if h['direction'] not in DIRECTIONS: raise ValueError('Invalid beam hook direction')
85
+ bit = 1 << (level-1)
86
+ if ((c,level) in occupied or c and bridges[c-1]&bit
87
+ or c < len(bridges) and bridges[c]&bit):
88
+ raise ValueError('Conflicting beam hook')
89
+ occupied.add((c,level))
90
+ if total > MAX: raise ValueError('Too many beam columns')
91
+ for c in detached: column(c)
92
+ return source
93
+
94
+
95
+ def require_legacy_compatible(source, note_count):
96
+ source = checked(source,note_count)
97
+ if source['groups'] or source['detachedColumns'] or any(a is not None for a in source['noteOrigins']):
98
+ raise ValueError('Legacy guide cannot preserve source beams')
99
+
100
+
101
+ def encode_source(source, note_count):
102
+ source = checked(source,note_count); out=io.BytesIO()
103
+ def put(fmt,*values):
104
+ out.write(struct.pack('>'+fmt,*values))
105
+ if out.tell()>MAX_BYTES: raise ValueError('Beam frame too large')
106
+ def anchor(a): put('ii',a['pageIndex'],a['noteIndex'])
107
+ def column(c):
108
+ put('i',len(c['members']))
109
+ for a in c['members']: anchor(a)
110
+ put('i',len(source['groups']))
111
+ for g in source['groups']:
112
+ raw=g['id'].encode('utf-8');put('i',len(raw));out.write(raw)
113
+ put('i',len(g['columns']))
114
+ for c in g['columns']: column(c)
115
+ put('i',len(g['bridges']))
116
+ for mask in g['bridges']: put('i',mask)
117
+ put('i',len(g['hooks']))
118
+ for h in g['hooks']: put('iii',h['columnIndex'],h['level'],DIRECTIONS.index(h['direction']))
119
+ put('i',len(source['detachedColumns']))
120
+ for c in source['detachedColumns']: column(c)
121
+ put('i',len(source['noteOrigins']))
122
+ for a in source['noteOrigins']:
123
+ put('B',int(a is not None))
124
+ if a is not None: anchor(a)
125
+ payload=out.getvalue();return struct.pack('>i',len(payload))+payload
126
+
127
+
128
+ def decode_source(data, note_count):
129
+ if not 16 <= len(data) <= MAX_BYTES+4: raise ValueError('Invalid beam frame')
130
+ view=memoryview(data); pos=0
131
+ def take(fmt):
132
+ nonlocal pos
133
+ size=struct.calcsize('>'+fmt)
134
+ if pos+size>len(view): raise ValueError('Truncated beam frame')
135
+ result=struct.unpack_from('>'+fmt,view,pos);pos+=size;return result
136
+ def count(maximum=MAX):
137
+ n=_int(take('i')[0],0,maximum)
138
+ if n>len(view)-pos: raise ValueError('Invalid beam count')
139
+ return n
140
+ def anchor():
141
+ p,n=take('ii');return dict(pageIndex=p,noteIndex=n)
142
+ def column(): return dict(members=[anchor() for _ in range(count(128))])
143
+ if take('i')[0] != len(data)-4: raise ValueError('Invalid beam framing')
144
+ groups=[]; total=0
145
+ for _ in range(count()):
146
+ size=count(1024); name=bytes(view[pos:pos+size]).decode('utf-8');pos+=size
147
+ n=count();total+=n
148
+ if total>MAX: raise ValueError('Too many beam columns')
149
+ cs=[column() for _ in range(n)]; nb=count()
150
+ if nb!=n-1: raise ValueError('Wrong beam bridge count')
151
+ bridges=[take('i')[0] for _ in range(nb)]; hooks=[]
152
+ for _ in range(count(n*8)):
153
+ c,level,d=take('iii');_int(d,0,1);hooks.append(dict(columnIndex=c,level=level,direction=DIRECTIONS[d]))
154
+ groups.append(dict(id=name,columns=cs,bridges=bridges,hooks=hooks))
155
+ nd=count()
156
+ if total+nd>MAX: raise ValueError('Too many beam columns')
157
+ detached=[column() for _ in range(nd)]; no=count()
158
+ if no!=note_count: raise ValueError('Beam note ownership mismatch')
159
+ origins=[]
160
+ for _ in range(no):
161
+ present=_int(take('B')[0],0,1); origins.append(anchor() if present else None)
162
+ if pos!=len(view): raise ValueError('Trailing beam bytes')
163
+ return checked(dict(groups=groups,detachedColumns=detached,noteOrigins=origins),note_count)
@@ -0,0 +1,82 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Join two proved page-edge shoulders without guessing ties from equal pitches."""
4
+
5
+ from .typed_events import event_kind, validate_unpitched
6
+
7
+
8
+ def _valid_boundary_ties(value):
9
+ if type(value) is not int or value < 0 or value & ~((1 << 22) - 1):
10
+ return False
11
+ if not value & 16:
12
+ return value <= 15
13
+ string = value >> 5 & 7
14
+ count = 6 + (value >> 8 & 1)
15
+ fret = value >> 9 & 63
16
+ effective_open = value >> 15 & 127
17
+ return bool(value & 15) and string < count and fret <= 36 and effective_open + fret <= 127
18
+
19
+
20
+ def _compatible_boundary_ties(before, after):
21
+ if not _valid_boundary_ties(before) or not _valid_boundary_ties(after):
22
+ return False
23
+ return ((before & ~15) == (after & ~15) if before & 16 and after & 16
24
+ else not (before | after) & 16)
25
+
26
+
27
+ def resolve_boundary_ties(document):
28
+ pages = list(document["pages"])
29
+ for page in pages:
30
+ for event in page['events']:
31
+ validate_unpitched(event)
32
+ if not _valid_boundary_ties(event.get('boundaryTies', 0)):
33
+ raise ValueError('Invalid boundary tie identity')
34
+
35
+ for index in range(1, len(pages)):
36
+ before, after = pages[index - 1], pages[index]
37
+ if ("sourcePage" in before or "sourcePage" in after) and (
38
+ before.get("sourcePage", -2) + 1 != after.get("sourcePage", -2)):
39
+ continue
40
+ events = list(after["events"])
41
+ changed = False
42
+ score_notes = list(after.get("score", {}).get("notes", []))
43
+ for number, current in enumerate(events):
44
+ if event_kind(current) == 'UNPITCHED':
45
+ continue
46
+ incoming = current.get("boundaryTies", 0) & 3
47
+ if not incoming or abs(current["startBeat"]) > .04:
48
+ continue
49
+ for previous in before["events"]:
50
+ if event_kind(previous) == 'UNPITCHED':
51
+ continue
52
+ if not _compatible_boundary_ties(previous.get("boundaryTies", 0), current.get("boundaryTies", 0)):
53
+ continue
54
+ if not (((previous.get("boundaryTies", 0) & 15) >> 2) & incoming):
55
+ continue
56
+ tab_typed = bool(current.get("boundaryTies", 0) & 16)
57
+ if (not tab_typed and (previous.get("boundaryPitch") is None
58
+ or previous["boundaryPitch"] != current.get("boundaryPitch"))
59
+ or previous["staffIndex"] != current["staffIndex"]
60
+ or previous["staffCount"] != current["staffCount"]
61
+ or abs(previous["startBeat"] + previous["durationBeats"] - before["totalBeats"]) > .04):
62
+ continue
63
+ # An unmarked continuation keeps the tied pitch across a bar/key change.
64
+ if (tab_typed or current.get("boundaryAccidental") != 2) and previous["midi"] != current["midi"]:
65
+ continue
66
+ events[number] = dict(current, tiedFromPrevious=True, midi=previous["midi"])
67
+ note_index = current.get("sourceNoteIndex", -1)
68
+ if 0 <= note_index < len(score_notes):
69
+ score_notes[note_index] = dict(score_notes[note_index], tiedFromPrevious=True)
70
+ if not tab_typed:
71
+ pitch = previous["boundaryPitch"]
72
+ natural = (pitch // 7 + 1) * 12 + (0, 2, 4, 5, 7, 9, 11)[pitch % 7]
73
+ accidental = previous["midi"] - natural
74
+ score_notes[note_index]["writtenAccidental"] = 3 if accidental == 2 else accidental
75
+ changed = True
76
+ break
77
+ if changed:
78
+ score = dict(after.get("score", {}))
79
+ if "notes" in score:
80
+ score["notes"] = score_notes
81
+ pages[index] = dict(after, events=events, score=score)
82
+ return dict(document, pages=pages)
@@ -0,0 +1,35 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Attack-local bow directions retained on the existing techniqueChanges records."""
4
+ import xml.etree.ElementTree as ET
5
+ UP_BOW, DOWN_BOW = 6, 7
6
+
7
+ def retained(page, index):
8
+ notes=page.get('score', {}).get('notes', [])
9
+ events=page.get('events', [])
10
+ if len(notes)!=len(events) or not 0<=index<len(notes): return None
11
+ event, note=events[index], notes[index]
12
+ if (type(event.get('sourceNoteIndex', index)) is not int or event.get('sourceNoteIndex', index)!=index or any(event.get(k)!=note.get(k)
13
+ for k in ('measureIndex','staffIndex','staffCount'))): return None
14
+ value=None
15
+ for row in page.get('score', {}).get('techniqueChanges', []):
16
+ kind=row.get('technique')
17
+ if type(kind) is not int or kind not in (UP_BOW, DOWN_BOW): continue
18
+ if any(row.get(k)!=note.get(k) for k in ('measureIndex','positionInMeasure','staffIndex','staffCount')):continue
19
+ if value is not None and value!=kind:return None
20
+ value=kind
21
+ return value
22
+
23
+ def chord_marks(chord, start):
24
+ seen=set(); result=[]
25
+ for row in chord:
26
+ value=row.get('retainedBow') if start==row['start'] else None
27
+ result.append(None if value in seen else value)
28
+ if value is not None:seen.add(value)
29
+ return result
30
+
31
+ def write(notation, value):
32
+ if value not in (UP_BOW, DOWN_BOW):raise ValueError('Invalid retained bow direction')
33
+ technical=notation.find('technical')
34
+ if technical is None:technical=ET.SubElement(notation,'technical')
35
+ ET.SubElement(technical,'up-bow' if value==UP_BOW else 'down-bow')
@@ -0,0 +1,76 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Retained source clefs on the reconstructed staff timeline; pitches are never changed."""
4
+ import xml.etree.ElementTree as ET
5
+ from itertools import groupby
6
+ from .typed_events import event_kind
7
+
8
+ LAYOUT = {18: ('F',4,0), 22: ('C',4,0), 24: ('C',3,0), 25: ('F',4,1), 32: ('F',4,2), 30: ('G',2,0), 37: ('G',2,1)}
9
+
10
+
11
+ def retained(page, index):
12
+ event = page['events'][index]
13
+ if event.get('clefInferred', False):
14
+ return None
15
+ explicit = event.get('clefBottomDiatonic')
16
+ if explicit is not None and (type(explicit) is not int or explicit not in (*LAYOUT, -1)):
17
+ raise ValueError('Unsupported retained display clef')
18
+ explicit = None if explicit == -1 else explicit
19
+ notes = page.get('score', {}).get('notes', [])
20
+ if len(notes) != len(page['events']):
21
+ return explicit
22
+ source = notes[index]
23
+ # Main preserves decoded-head order; refuse to borrow a clef from an unrelated slot.
24
+ fields = ('measureIndex', 'staffIndex', 'staffCount')
25
+ if (type(event.get('sourceNoteIndex', index)) is not int
26
+ or event.get('sourceNoteIndex', index) != index
27
+ or any(key not in event or key not in source or event[key] != source[key] for key in fields)):
28
+ return explicit
29
+ bottom = source.get('clefBottomDiatonic', -1)
30
+ if type(bottom) is not int or bottom not in (*LAYOUT, -1):
31
+ raise ValueError('Unsupported retained source clef')
32
+ bottom = None if bottom == -1 else bottom
33
+ if explicit is not None and bottom is not None and explicit != bottom:
34
+ raise ValueError('Conflicting retained display clefs')
35
+ return explicit if explicit is not None else bottom
36
+
37
+
38
+ def plan(notes):
39
+ total, count = 0, 0
40
+ for note in notes:
41
+ if event_kind(note) == 'PITCHED':
42
+ total += note['midi']
43
+ count += 1
44
+ bass = (total/count < 60 if count
45
+ else bool(notes) and notes[0].get('clefBottomDiatonic') == 18)
46
+ initial = 18 if bass else 30
47
+ first = notes[0]['start'] if notes else 0
48
+ changes, current = {0: initial}, initial
49
+ previous = -1
50
+ # The exporter already orders notes by attack; retain only actual changes, not every onset.
51
+ for tick, group in groupby(notes, key=lambda n: n['start']):
52
+ if tick < previous:
53
+ raise ValueError('Unordered source clef timeline')
54
+ previous = tick
55
+ values = {n['retainedClef'] for n in group if n.get('retainedClef') is not None}
56
+ if len(values) > 1:
57
+ raise ValueError('Conflicting simultaneous clefs need explicit staff mapping')
58
+ if not values:
59
+ continue
60
+ bottom = next(iter(values))
61
+ if tick == first:
62
+ changes[0] = bottom
63
+ current = bottom
64
+ elif bottom != current:
65
+ changes[tick] = bottom
66
+ current = bottom
67
+ return changes
68
+
69
+
70
+ def write(attributes, bottom):
71
+ sign, line, octave = LAYOUT[bottom]
72
+ clef = ET.SubElement(attributes, 'clef')
73
+ ET.SubElement(clef, 'sign').text = sign
74
+ ET.SubElement(clef, 'line').text = str(line)
75
+ if octave:
76
+ ET.SubElement(clef, 'clef-octave-change').text = str(octave)