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,204 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Bind continuous-slide performance to original endpoints and actual route visits.
4
+
5
+ The source document stays written. Only a private performed copy is annotated
6
+ and coalesced; page-local raw indices are never used after clock projection.
7
+ """
8
+ import copy
9
+ import math
10
+ from .straight_slide import bindings
11
+ from .tremolo_performance import source_spans
12
+
13
+
14
+ def _same(a, b):
15
+ return abs(a-b) <= 8*max(math.ulp(float(a)), math.ulp(float(b)))
16
+
17
+
18
+ def prepare_slides(document):
19
+ internal = ('_slideOrigins', '_slideRelation', '_slideContext', '_continuousSlide', '_slideGate')
20
+ explicit = any('slide' in e for p in document['pages'] for e in p['events'])
21
+ if not explicit and not any(any(k in e for k in internal)
22
+ for p in document['pages'] for e in p['events']):
23
+ return document
24
+ result = copy.deepcopy(document)
25
+ # Caller data cannot supply trusted projection/ownership annotations.
26
+ for page in result['pages']:
27
+ for note in page['events']:
28
+ for key in internal:
29
+ note.pop(key, None)
30
+ if not explicit:
31
+ return result
32
+ verified = [bindings(page) for page in result['pages']]
33
+ for page_number, (page, pairs) in enumerate(zip(result['pages'], verified)):
34
+ paired = source_spans(page) if pairs else {}
35
+ for source, target, _ in pairs:
36
+ for index in (source, target):
37
+ if (page['events'][index].get('tremoloBeats', 0) != 0
38
+ or page['score']['notes'][index].get('articulations', 0) & (7 << 16)
39
+ or index in paired):
40
+ raise ValueError('Continuous slide conflicts with original endpoint tremolo')
41
+ source_id = f'p{page_number}:n{source}'
42
+ target_id = f'p{page_number}:n{target}'
43
+ for index, identity in ((source, source_id), (target, target_id)):
44
+ note = page['events'][index]
45
+ origins = note.setdefault('_slideOrigins', [])
46
+ if identity not in origins:
47
+ origins.append(identity)
48
+ marks = page['score']['notes'][target]['articulations']
49
+ page['events'][target]['_slideGate'] = (.28 if marks & 16 else
50
+ .75 if marks & 4 and marks & 8 else
51
+ .5 if marks & 4 else 1.)
52
+ relation = page['events'][target]['slide']
53
+ page['events'][target]['_slideRelation'] = dict(
54
+ sourceId=source_id, targetId=target_id,
55
+ sourceMidi=relation['sourceMidi'])
56
+ return result
57
+
58
+
59
+ def _context(note, projected):
60
+ value = note.get('_slideContext')
61
+ if value is None:
62
+ if projected:
63
+ raise ValueError('Projected slide endpoint lacks attack and visit context')
64
+ return dict(visitId='linear', attack=not note.get('tiedFromPrevious', False),
65
+ clippedEntry=False, clippedRelease=False)
66
+ if (not isinstance(value, dict) or not isinstance(value.get('visitId'), str)
67
+ or not value['visitId']
68
+ or any(type(value.get(k)) is not bool
69
+ for k in ('attack', 'clippedEntry', 'clippedRelease'))):
70
+ raise ValueError('Invalid projected slide attack and visit context')
71
+ if 'held' in value and type(value['held']) is not bool:
72
+ raise ValueError('Invalid performed slide hold ownership')
73
+ return value
74
+
75
+
76
+ def _pitch(note):
77
+ midi = note.get('midi')
78
+ if (note.get('kind', 'PITCHED') != 'PITCHED' or type(midi) is not int
79
+ or not 0 <= midi <= 127):
80
+ raise ValueError('Continuous slide endpoint has no resolved pitched MIDI')
81
+ return midi
82
+
83
+
84
+ def _compatible(a, b):
85
+ return all(a.get(key) == b.get(key) for key in (
86
+ 'midi', 'staffCount', 'staffIndex', 'guitarEffect', 'glissando',
87
+ 'performanceAttack', 'tremoloBeats', '_slideGate'))
88
+
89
+
90
+ def resolve_slides(document):
91
+ annotated = any(e.get('_slideOrigins') for p in document['pages'] for e in p['events'])
92
+ if not annotated:
93
+ if any('slide' in e for p in document['pages'] for e in p['events']):
94
+ raise ValueError('Continuous slides must be prepared before clock projection')
95
+ return document
96
+ result = copy.deepcopy(document)
97
+ projected = 'navigationOccurrences' in result or 'expressivePerformance' in result
98
+ rows, offset = [], 0.0
99
+ for page_number, page in enumerate(result['pages']):
100
+ for index, note in enumerate(page['events']):
101
+ if not note.get('_slideOrigins'):
102
+ continue
103
+ origins = note['_slideOrigins']
104
+ if (not isinstance(origins, list) or not origins
105
+ or any(not isinstance(x, str) or not x for x in origins)
106
+ or len(set(origins)) != len(origins)):
107
+ raise ValueError('Invalid original slide endpoint identities')
108
+ start, duration = note.get('startBeat'), note.get('durationBeats')
109
+ if (any(type(v) not in (int, float) or not math.isfinite(v)
110
+ for v in (start, duration)) or start < 0 or duration <= 0):
111
+ raise ValueError('Continuous slide endpoint has an invalid performed clock')
112
+ context = _context(note, projected)
113
+ rows.append(dict(page=page_number, index=index, note=note,
114
+ start=offset+start, end=offset+start+duration,
115
+ context=context))
116
+ extent = page['totalBeats']
117
+ if type(extent) not in (int, float) or not math.isfinite(extent) or extent < 0:
118
+ raise ValueError('Invalid performed slide page extent')
119
+ offset += extent
120
+ by_origin = {}
121
+ targets = {}
122
+ for row in rows:
123
+ note, visit = row['note'], row['context']['visitId']
124
+ for origin in note['_slideOrigins']:
125
+ by_origin.setdefault((visit, origin), []).append(row)
126
+ relation = note.get('_slideRelation')
127
+ if relation is not None:
128
+ if (not isinstance(relation, dict)
129
+ or set(relation) != {'sourceId', 'targetId', 'sourceMidi'}
130
+ or any(not isinstance(relation[k], str) or not relation[k]
131
+ for k in ('sourceId', 'targetId'))
132
+ or relation['targetId'] not in note['_slideOrigins']):
133
+ raise ValueError('Invalid projected continuous slide relation')
134
+ targets.setdefault((visit, relation['targetId']), []).append(row)
135
+ remove = set()
136
+ claims = {}
137
+ pending = []
138
+ for (visit, target_id), fragments in targets.items():
139
+ fragments.sort(key=lambda r: (r['start'], r['end']))
140
+ first = fragments[0]
141
+ context = first['context']
142
+ # A jump into a sustain is not a new connected-slide attack.
143
+ if not context['attack'] or context['clippedEntry']:
144
+ continue
145
+ relation = first['note']['_slideRelation']
146
+ target_midi = _pitch(first['note'])
147
+ end = first['end']
148
+ for later in fragments[1:]:
149
+ if (later['context']['attack'] or not _same(end, later['start'])
150
+ or later['note']['_slideRelation'] != relation
151
+ or not _compatible(first['note'], later['note'])):
152
+ raise ValueError('Ambiguous or changing continuous slide target continuation')
153
+ end = later['end']
154
+ source_rows = sorted(by_origin.get((visit, relation['sourceId']), []),
155
+ key=lambda r: (r['start'], r['end']))
156
+ candidates = []
157
+ attack_seen, previous_end = False, None
158
+ for source in source_rows:
159
+ if previous_end is None or not _same(previous_end, source['start']):
160
+ attack_seen = False
161
+ if source['context']['attack'] and not source['context']['clippedEntry']:
162
+ attack_seen = True
163
+ previous_end = source['end']
164
+ if (attack_seen and not source['context']['clippedRelease']
165
+ and _same(source['end'], first['start'])):
166
+ candidates.append(source)
167
+ if not candidates:
168
+ continue # The written predecessor was skipped or clipped by this route.
169
+ if len(candidates) != 1:
170
+ raise ValueError('Ambiguous performed continuous slide source')
171
+ source = candidates[0]
172
+ if any(source['note'].get(k) != first['note'].get(k)
173
+ for k in ('staffCount', 'staffIndex')):
174
+ raise ValueError('Continuous slide changed performed part')
175
+ source_midi = _pitch(source['note'])
176
+ if any(first['note'].get(k) for k in ('glissando', 'guitarEffect', 'tremoloBeats')):
177
+ raise ValueError('Conflicting continuous slide performance')
178
+ claim = (visit, relation['sourceId'], source['end'])
179
+ claims[claim] = claims.get(claim, 0)+1
180
+ pending.append((claim, first, fragments, end, source_midi, target_midi))
181
+ for claim, first, fragments, end, source_midi, target_midi in pending:
182
+ if claims[claim] != 1:
183
+ raise ValueError('Multiple performed slide targets claim one source')
184
+ first['note']['durationBeats'] = end-first['start']
185
+ first['note']['_continuousSlide'] = dict(sourceMidi=source_midi)
186
+ gate = first['note'].get('_slideGate', 1.)
187
+ if type(gate) not in (int, float) or gate not in (.28, .5, .75, 1.):
188
+ raise ValueError('Invalid original slide articulation gate')
189
+ if any(fragment['context'].get('held', False) for fragment in fragments):
190
+ gate = 1.
191
+ if gate != 1:
192
+ first['note']['_continuousSlide']['gate'] = gate
193
+
194
+ for later in fragments[1:]:
195
+ remove.add((later['page'], later['index']))
196
+ for page_number, page in enumerate(result['pages']):
197
+ retained = []
198
+ for index, note in enumerate(page['events']):
199
+ note.pop('slide', None)
200
+ note.pop('_slideRelation', None)
201
+ if (page_number, index) not in remove:
202
+ retained.append(note)
203
+ page['events'] = retained
204
+ return result
@@ -0,0 +1,124 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Retained printed-slur ownership and document-order MusicXML numbering."""
4
+ import xml.etree.ElementTree as ET
5
+ from .slur_wire import anchor, encode_source
6
+ from .grace_export import order as musical_order
7
+
8
+
9
+ def retained_spans(pages, include_candidates=False):
10
+ owners, spans, identities = {}, [], set()
11
+ offset = 0
12
+ for page in pages:
13
+ score = page.get('score', {})
14
+ notes, events = score.get('notes', []), page['events']
15
+ source = score.get('slurSource')
16
+ if source is not None:
17
+ encode_source(source, len(notes)) # Reuse the bounded retained-source contract.
18
+ arcs = source['spans'] + (source.get('candidates', []) if include_candidates else [])
19
+ if any(source['noteOrigins']) and len(notes) != len(events):
20
+ raise ValueError('Slur source needs one event per decoded note')
21
+ for index, origin in enumerate(source['noteOrigins']):
22
+ if origin is None:
23
+ continue
24
+ event, note = events[index], notes[index]
25
+ # Main emits every head in decoded-note order, including distinct equal heads.
26
+ supplied = event.get('sourceNoteIndex', index)
27
+ if type(supplied) is not int or supplied != index or any(
28
+ event.get(key) != note.get(key)
29
+ for key in ('measureIndex', 'staffIndex', 'staffCount')):
30
+ raise ValueError('Slur event and decoded note ownership disagree')
31
+ key = anchor(origin)
32
+ if key in owners:
33
+ raise ValueError('Ambiguous original slur owner across pages')
34
+ owners[key] = offset + index
35
+ for span in arcs:
36
+ if span['id'] in identities:
37
+ raise ValueError('Duplicate retained slur identity across pages')
38
+ identities.add(span['id'])
39
+ spans.append(span)
40
+ offset += len(events)
41
+ # Deleted/unselected original endpoints stay retained in source, without borrowing a note.
42
+ return [(span, owners[anchor(span['start'])], owners[anchor(span['end'])])
43
+ for span in spans if anchor(span['start']) in owners and anchor(span['end']) in owners]
44
+
45
+
46
+ def classify(spans, pages, events, ties, known_context, exported_parts=None):
47
+ """Resolve retained geometry only from the actual assembled sounding owners."""
48
+ candidate_ids = {span['id'] for page in pages
49
+ for span in (page.get('score', {}).get('slurSource') or {}).get('candidates', [])}
50
+ def known(event):
51
+ return (event.get('retainedClef') is not None and not event.get('durationFallback', False)
52
+ and type(event.get('midi')) is int and 0 <= event['midi'] <= 127
53
+ and event.get('kind', 'PITCHED') == 'PITCHED')
54
+ def part(event):
55
+ index, count = event.get('staffIndex'), event.get('staffCount')
56
+ return ((index, count) if type(index) is int and type(count) is int
57
+ and 0 <= index < count else None)
58
+ selected = []
59
+ exported_parts = {} if exported_parts is None else exported_parts
60
+ for span, start, end in spans:
61
+ if span['id'] not in candidate_ids:
62
+ selected.append((span, start, end))
63
+ continue
64
+ a, b = events[start], events[end]
65
+ if not known_context or not known(a) or not known(b) or musical_order(a) >= musical_order(b):
66
+ continue
67
+ actual_part = exported_parts.get(start)
68
+ if (part(a) is None or part(b) is None or actual_part is None
69
+ or actual_part is not exported_parts.get(end)):
70
+ continue
71
+ if (start, end) in ties:
72
+ continue
73
+ phrase = a['midi'] != b['midi']
74
+ if not phrase and part(a) is not None and part(a) == part(b) and a['end'] <= b['start']:
75
+ phrase = any(known(middle) and part(middle) == part(a)
76
+ and middle['midi'] != a['midi']
77
+ and a['start'] < middle['start'] < b['start']
78
+ and middle['end'] > middle['start']
79
+ and a['end'] <= middle['start'] and middle['end'] <= b['start']
80
+ for middle in events)
81
+ if phrase:
82
+ selected.append((span, start, end))
83
+ return selected
84
+
85
+
86
+ def apply(root, spans, attacks, events):
87
+ if not spans:
88
+ return
89
+ requested = set(attacks.values())
90
+ positions = {node: i for i, node in enumerate(root.iter('note')) if node in requested}
91
+ parts = {note: part for part in root.findall('part') for note in part.iter('note') if note in requested}
92
+ bound = []
93
+ for span, start_owner, end_owner in spans:
94
+ start, end = attacks.get(start_owner), attacks.get(end_owner)
95
+ if start is None or end is None:
96
+ raise ValueError('Missing retained slur attack fragment')
97
+ if musical_order(events[start_owner]) >= musical_order(events[end_owner]):
98
+ raise ValueError('Retained slur endpoints are not in musical order')
99
+ if parts[start] is not parts[end]:
100
+ raise ValueError('Cross-part slur needs an explicit part mapping')
101
+ a, b = positions[start], positions[end]
102
+ bound.append((min(a,b), max(a,b), span['id'], span, start, end, a, b))
103
+ live, marks = {}, []
104
+ for first, last, _, span, start, end, a, b in sorted(bound, key=lambda row: row[:3]):
105
+ lane = live.setdefault(parts[start], [])
106
+ lane[:] = [row for row in lane if not (row[1] < first or
107
+ row[1] == first and row[2] is start and a < b)]
108
+ number = next((n for n in range(1,17) if all(row[0] != n for row in lane)), None)
109
+ if number is None:
110
+ raise ValueError('More than sixteen slurs overlap in MusicXML document order')
111
+ lane.append((number,last,end if a < b else None))
112
+ marks.extend([(False,number,end,span),(True,number,start,span)])
113
+ # Validate/allocate every pair before appending either endpoint.
114
+ for is_start, number, note, span in sorted(marks, key=lambda row: row[:2]):
115
+ notation = note.find('notations')
116
+ if notation is None:
117
+ notation = ET.SubElement(note,'notations')
118
+ attributes = dict(type='start' if is_start else 'stop',number=str(number))
119
+ if is_start:
120
+ attributes['line-type'] = span['lineType'].lower()
121
+ if span['placement'] != 'AUTO':
122
+ attributes['placement'] = span['placement'].lower()
123
+ attributes['orientation'] = 'over' if span['placement'] == 'ABOVE' else 'under'
124
+ ET.SubElement(notation,'slur',attributes)
@@ -0,0 +1,159 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """SLT1 source identities and SLP1 printed arcs. No recognition or endpoint inference."""
4
+ import math
5
+ import struct
6
+
7
+ MAX_NOTES = 1_000_000
8
+ MAX_SPANS = 100_000
9
+ MAX_PAGE_BYTES = 16 * 1024 * 1024
10
+ MAX_SOURCE_BYTES = 32 * 1024 * 1024
11
+ PLACEMENTS = {"AUTO": 0, "ABOVE": 1, "BELOW": 2}
12
+ LINES = {"SOLID": 0, "DASHED": 1, "DOTTED": 2}
13
+
14
+
15
+ def integer(value, minimum=0, maximum=2_147_483_647):
16
+ if type(value) is not int or not minimum <= value <= maximum:
17
+ raise ValueError("Invalid slur integer")
18
+ return value
19
+
20
+
21
+ def anchor(value):
22
+ if not isinstance(value, dict) or set(value) != {"pageIndex", "noteIndex"}:
23
+ raise ValueError("Invalid slur source anchor")
24
+ return integer(value["pageIndex"]), integer(value["noteIndex"])
25
+
26
+
27
+ def java_blank(value):
28
+ # Character.isWhitespace used by Java String.isBlank, including its NBSP exclusions.
29
+ return all(c in "\t\n\v\f\r\x1c\x1d\x1e\x1f \u1680\u2000\u2001\u2002\u2003"
30
+ "\u2004\u2005\u2006\u2008\u2009\u200a\u2028\u2029\u205f\u3000" for c in value)
31
+
32
+
33
+ def encode_pages(spans):
34
+ if not isinstance(spans, list) or len(spans) > MAX_SPANS:
35
+ raise ValueError("Invalid page-local slur count")
36
+ output = bytearray(struct.pack(">ii", 0x534C5031, len(spans)))
37
+ identities = set()
38
+ for span in spans:
39
+ if not isinstance(span, dict) or set(span) != {"id", "start", "end", "placement", "lineType", "evidence"}:
40
+ raise ValueError("Invalid page-local slur fields")
41
+ identity = span["id"]
42
+ if not isinstance(identity, str) or java_blank(identity) or identity in identities:
43
+ raise ValueError("Invalid or duplicate slur identity")
44
+ if len(identity.encode("utf-16-be")) // 2 > 256:
45
+ raise ValueError("Slur identity too long")
46
+ identities.add(identity)
47
+ encoded = identity.encode("utf-8")
48
+ start, end = anchor(span["start"]), anchor(span["end"])
49
+ if start == end:
50
+ raise ValueError("Identical printed slur endpoints")
51
+ placement, line = span["placement"], span["lineType"]
52
+ if not isinstance(placement, str) or placement not in PLACEMENTS or not isinstance(line, str) or line not in LINES:
53
+ raise ValueError("Invalid slur style")
54
+ evidence = span["evidence"]
55
+ if not isinstance(evidence, list) or not 1 <= len(evidence) <= 64:
56
+ raise ValueError("Invalid slur evidence count")
57
+ frame = bytearray(struct.pack(">i", len(encoded))) + encoded
58
+ frame.extend(struct.pack(">7i", *start, *end, PLACEMENTS[placement], LINES[line], len(evidence)))
59
+ for arc in evidence:
60
+ if not isinstance(arc, dict) or set(arc) != {"pageIndex", "startX", "startY", "endX", "endY"}:
61
+ raise ValueError("Invalid slur evidence fields")
62
+ geometry = [arc[name] for name in ("startX", "startY", "endX", "endY")]
63
+ if any(type(value) not in (int, float) or not math.isfinite(value) or not 0 <= value <= 1 for value in geometry):
64
+ raise ValueError("Invalid slur evidence geometry")
65
+ frame.extend(struct.pack(">i4f", integer(arc["pageIndex"]), *geometry))
66
+ if len(frame) > 8192 or len(output) + len(frame) + 4 > MAX_PAGE_BYTES:
67
+ raise ValueError("Page-local slur extension too large")
68
+ output.extend(struct.pack(">i", len(frame)))
69
+ output.extend(frame)
70
+ return bytes(output)
71
+
72
+
73
+ def encode_source(source, note_count):
74
+ integer(note_count, maximum=MAX_NOTES)
75
+ if source is None:
76
+ # An omitted extension has no inferred original identities.
77
+ origins, spans, candidates = None, [], []
78
+ else:
79
+ if not isinstance(source, dict) or set(source) not in ({"noteOrigins", "spans"}, {"noteOrigins", "spans", "candidates"}):
80
+ raise ValueError("Invalid retained slur source fields")
81
+ origins, spans = source["noteOrigins"], source["spans"]
82
+ candidates = source.get("candidates", [])
83
+ if not isinstance(origins, list) or len(origins) != note_count:
84
+ raise ValueError("Retained slur identities do not match score notes")
85
+ stored_origins = origins if origins is not None and any(origin is not None for origin in origins) else []
86
+ frame = bytearray(struct.pack(">ii", note_count, len(stored_origins)))
87
+ identities = set()
88
+ for origin in stored_origins:
89
+ pair = (-1, -1) if origin is None else anchor(origin)
90
+ if origin is not None and pair in identities:
91
+ raise ValueError("Duplicate original slur note identity")
92
+ identities.add(pair)
93
+ frame.extend(struct.pack(">ii", *pair))
94
+ confirmed = encode_pages(spans)
95
+ deferred = encode_pages(candidates)
96
+ ids = [arc['id'] for arc in spans] + [arc['id'] for arc in candidates]
97
+ if len(set(ids)) != len(ids):
98
+ raise ValueError("Duplicate source arc identity")
99
+ frame.extend(confirmed)
100
+ if candidates:
101
+ frame.extend(deferred)
102
+ if len(frame) > MAX_SOURCE_BYTES:
103
+ raise ValueError("Retained slur source too large")
104
+ return struct.pack(">ii", 0x534C5432 if candidates else 0x534C5431, len(frame)) + frame
105
+
106
+
107
+ def decode_source(data, note_count):
108
+ # Reuse bounded primitive reads; semantic and slur sections retain distinct framing.
109
+ from .semantic_wire import Reader
110
+ integer(note_count, maximum=MAX_NOTES)
111
+ source = Reader(data)
112
+ magic = source.take('i')
113
+ if magic not in (0x534C5431, 0x534C5432):
114
+ raise ValueError('Unknown retained slur source layout')
115
+ frame = Reader(source.raw(source.count(MAX_SOURCE_BYTES)))
116
+ source.finish()
117
+ count, stored = frame.take('ii')
118
+ if count != note_count or stored not in (0, count):
119
+ raise ValueError('Retained slur identities do not match source notes')
120
+ origins = []
121
+ for _ in range(stored):
122
+ page, note = frame.take('ii')
123
+ origins.append(None if (page, note) == (-1, -1) else {'pageIndex': page, 'noteIndex': note})
124
+ if stored == 0:
125
+ origins = [None] * count
126
+ def pages():
127
+ start = frame.offset
128
+ if frame.take('i') != 0x534C5031:
129
+ raise ValueError('Unknown page-local slur layout')
130
+ spans = []
131
+ for _ in range(frame.count(MAX_SPANS)):
132
+ record = Reader(frame.raw(frame.count(8192)))
133
+ if frame.offset - start > MAX_PAGE_BYTES:
134
+ raise ValueError('Page-local slur section too large')
135
+ identity = bytes(record.raw(record.count(1024))).decode('utf-8', errors='strict')
136
+ a_page, a_note, b_page, b_note, placement, line = record.take('6i')
137
+ evidence = []
138
+ for _ in range(record.count(64)):
139
+ page, a_x, a_y, b_x, b_y = record.take('i4f')
140
+ evidence.append(dict(pageIndex=page, startX=a_x, startY=a_y, endX=b_x, endY=b_y))
141
+ record.finish()
142
+ integer(placement, maximum=2); integer(line, maximum=2)
143
+ spans.append(dict(id=identity, start=dict(pageIndex=a_page, noteIndex=a_note),
144
+ end=dict(pageIndex=b_page, noteIndex=b_note),
145
+ placement=list(PLACEMENTS)[placement], lineType=list(LINES)[line], evidence=evidence))
146
+ return spans
147
+ spans = pages()
148
+ candidates = pages() if magic == 0x534C5432 else []
149
+ frame.finish()
150
+ result = dict(noteOrigins=origins, spans=spans)
151
+ if candidates:
152
+ result["candidates"] = candidates
153
+ encode_source(result, count) # Apply the same identity, geometry and uniqueness validation.
154
+ return result
155
+
156
+
157
+ def is_empty_source(source, note_count):
158
+ """Validate all fields before proving that omitting this extension loses nothing."""
159
+ return encode_source(source, note_count) == encode_source(None, note_count)
@@ -0,0 +1,93 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Numeric tempo clocks from an existing, uniquely owned inline source caption."""
4
+ import math
5
+ import struct
6
+ from .technique_export import position
7
+
8
+
9
+ def _f32(value):
10
+ return struct.unpack('>f', struct.pack('>f', value))[0]
11
+
12
+
13
+ def _visual(region, p):
14
+ left, right = position(region.get('left')), position(region.get('right'))
15
+ if left is None or right is None or right <= left:
16
+ return None
17
+ return _f32(left + _f32(p * _f32(right-left)))
18
+
19
+
20
+ def onset(page, tempo):
21
+ from .performance import _column_members
22
+ score, events = page.get('score', {}), page.get('events', [])
23
+ if tempo not in score.get('tempoChanges', []):
24
+ return None
25
+ notes, regions = score.get('notes', []), score.get('measures', [])
26
+ m, p = tempo.get('measureIndex'), position(tempo.get('positionInMeasure'))
27
+ beats = page.get('measureBeats', [])
28
+ if (type(m) is not int or not 0 <= m < min(len(beats), len(regions)) or p is None
29
+ or len(notes) != len(events) or type(beats[m]) not in (int, float)
30
+ or not math.isfinite(beats[m]) or beats[m] <= 0):
31
+ return None
32
+ x = _visual(regions[m], p)
33
+ if x is None:
34
+ return None
35
+ bits = struct.unpack('>I', struct.pack('>f', x))[0]
36
+ tolerance = (struct.unpack('>f', struct.pack('>I', bits+1))[0]-x)*4
37
+ marks = [c for c in score.get('tempoChanges', []) if c.get('measureIndex') == m
38
+ and (q := position(c.get('positionInMeasure'))) is not None
39
+ and abs(_visual(regions[m], q)-x) <= tolerance]
40
+ if len(marks) != 1:
41
+ return None
42
+ result, bar_start = None, sum(beats[:m])
43
+ for expression in score.get('expressiveEvents', []):
44
+ if (expression.get('kind') != 'UNRESOLVED_DIRECTION'
45
+ or expression.get('scope') not in ('SCORE', 'UNRESOLVED')):
46
+ continue
47
+ words = [e for e in expression.get('evidence', []) if e.get('sourceId') == 'printed-expression-word']
48
+ if len(words) != 1:
49
+ continue
50
+ word = words[0]; visual = position(word.get('visualX'))
51
+ if (word.get('staffIndex') != expression.get('staffIndex')
52
+ or word.get('staffCount') != expression.get('staffCount')
53
+ or visual is None or abs(visual-x) > tolerance or not word.get('printedText', '').strip()):
54
+ continue
55
+ owners = _column_members(expression, page)
56
+ if not owners:
57
+ continue
58
+ at = None
59
+ for i in owners:
60
+ note, event = notes[i], events[i]
61
+ start, duration = event.get('startBeat'), event.get('durationBeats')
62
+ if (type(event.get('sourceNoteIndex')) is not int or event['sourceNoteIndex'] != i
63
+ or event.get('durationFallback') is not False or note.get('measureIndex') != m
64
+ or any(type(event.get(k)) is not int or event[k] != note.get(k)
65
+ for k in ('measureIndex', 'staffIndex', 'staffCount'))
66
+ or note.get('staffIndex') != expression.get('staffIndex')
67
+ or note.get('staffCount') != expression.get('staffCount')
68
+ or note.get('articulations', 0) & 32768
69
+ or type(start) not in (int, float) or type(duration) not in (int, float)
70
+ or not math.isfinite(start) or not math.isfinite(duration) or duration <= 0
71
+ or not bar_start <= start < bar_start + beats[m]
72
+ or at is not None and at != start-bar_start):
73
+ return None
74
+ at = start-bar_start
75
+ anchor = expression.get('start')
76
+ eligibility = at if anchor is None else anchor.get('quarterBeatOffset')
77
+ if (anchor is not None and anchor.get('measureIndex') != m
78
+ or type(eligibility) not in (int, float) or not math.isfinite(eligibility)
79
+ or abs(eligibility-beats[m]*p) > 1/32):
80
+ continue
81
+ if result is not None:
82
+ return None
83
+ result = at
84
+ return result
85
+
86
+
87
+ def rhythmic_changes(page):
88
+ result = []
89
+ for change in page.get('score', {}).get('tempoChanges', []):
90
+ at = onset(page, change)
91
+ result.append(change if at is None else dict(change,
92
+ positionInMeasure=_f32(at/page['measureBeats'][change['measureIndex']])))
93
+ return result
@@ -0,0 +1,48 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Source spelling for concert-pitch XML, only while its sounding identity agrees."""
4
+ from .clef_export import LAYOUT
5
+ from .typed_events import event_kind
6
+
7
+
8
+ def retained(page, index, key):
9
+ event = page['events'][index]
10
+ if event_kind(event) != 'PITCHED' or event.get('clefInferred', False):
11
+ return None
12
+ notes = page.get('score', {}).get('notes', [])
13
+ if len(notes) != len(page['events']):
14
+ return None
15
+ source = notes[index]
16
+ if event_kind(source) != 'PITCHED':
17
+ return None
18
+ fields = ('measureIndex', 'staffIndex', 'staffCount')
19
+ if (type(event.get('sourceNoteIndex', index)) is not int
20
+ or event.get('sourceNoteIndex', index) != index
21
+ or any(k not in event or k not in source or event[k] != source[k] for k in fields)):
22
+ return None
23
+ bottom = source.get('clefBottomDiatonic', -1)
24
+ if bottom == -1:
25
+ return None
26
+ step, accidental = source.get('staffStep'), source.get('writtenAccidental')
27
+ shift = source.get('octaveShift', 0)
28
+ if step is None or accidental is None:
29
+ return None
30
+ if (type(bottom) is not int or bottom not in LAYOUT
31
+ or any(type(v) is not int for v in (step, accidental, shift))
32
+ or accidental not in (-2, -1, 0, 1, 2, 3)):
33
+ raise ValueError('Invalid retained pitch spelling')
34
+ if event.get('clefBottomDiatonic', bottom) != bottom:
35
+ return None
36
+ diatonic = bottom + step + 7 * shift
37
+ octave, letter = divmod(diatonic, 7)
38
+ if accidental == 2: # FROM_KEY is distinct from the double-sharp wire value 3.
39
+ if type(key) is not int or not -7 <= key <= 7:
40
+ raise ValueError('Invalid retained pitch key')
41
+ order = (3, 0, 4, 1, 5, 2, 6) if key >= 0 else (6, 2, 5, 1, 4, 0, 3)
42
+ alter = (1 if key > 0 else -1) if letter in order[:abs(key)] else 0
43
+ else:
44
+ alter = 2 if accidental == 3 else accidental
45
+ midi = (octave + 1) * 12 + (0, 2, 4, 5, 7, 9, 11)[letter] + alter
46
+ if midi != event['midi']:
47
+ return None # Edited or retuned heads must not borrow stale source spelling.
48
+ return 'CDEFGAB'[letter], alter, octave