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
+ """Model inference and a file bridge to the platform-independent Java decoder."""
4
+ import gzip
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import struct
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ from PIL import Image, ImageOps
15
+ from .runtime import java_executable
16
+
17
+ MODEL_SHA256 = "92ab7c34c27cb704d95f0cde247b3611d1563fdf1c114b9f9817abb18a7b6a93"
18
+ MODEL_NAME = "music_sheets_v4_float16.tflite"
19
+
20
+
21
+ def tile_starts(size):
22
+ """Tail tiles retain the app's exact 320/192 ownership order."""
23
+ if size < 1:
24
+ raise ValueError("Image dimensions must be positive")
25
+ last = max(0, size - 320)
26
+ values = []
27
+ for offset in range(0, size, 192):
28
+ value = min(offset, last)
29
+ if not values or values[-1] != value:
30
+ values.append(value)
31
+ if value == last:
32
+ break
33
+ return values
34
+
35
+
36
+ def grayscale(image, width=2048):
37
+ if not 64 <= width <= 4096:
38
+ raise ValueError("Analysis width must be 64..4096")
39
+ image = ImageOps.exif_transpose(image).convert("RGBA")
40
+ white = Image.new("RGBA", image.size, "white")
41
+ white.alpha_composite(image)
42
+ gray = white.convert("L")
43
+ height = max(1, round(gray.height * width / gray.width))
44
+ if width * height > 20_000_000:
45
+ raise ValueError("Analysis image exceeds 20 million pixels")
46
+ return np.asarray(gray.resize((width, height), Image.Resampling.BILINEAR), dtype=np.uint8)
47
+
48
+
49
+ def write_page(path, labels, gray, annotations=None):
50
+ height, width = gray.shape
51
+ if labels.shape != gray.shape or labels.dtype != np.uint8 or gray.dtype != np.uint8:
52
+ raise ValueError("Expected same-size uint8 mask and grayscale arrays")
53
+ if annotations is not None and not isinstance(annotations, dict):
54
+ raise ValueError("Each page's annotations must be an object")
55
+ with gzip.open(path, "wb") as stream:
56
+ stream.write(struct.pack(">III", 0x52535031, width, height))
57
+ stream.write(labels.tobytes())
58
+ stream.write(gray.tobytes())
59
+ if annotations is None:
60
+ return
61
+ stream.write(struct.pack(">I", 0x4F435231))
62
+ for field in ("measureNumbers", "tempoNumbers", "restCounts"):
63
+ rows = annotations.get(field, [])
64
+ if len(rows) > 10000:
65
+ raise ValueError("Too many OCR tokens")
66
+ stream.write(struct.pack(">i", len(rows)))
67
+ for row in rows:
68
+ stream.write(struct.pack(">i5f", row["value"], row["left"], row["top"], row["right"],
69
+ row["bottom"], row.get("annotationLeft", row["left"])))
70
+ def write_words(words):
71
+ if len(words) > 10000:
72
+ raise ValueError("Too many OCR words")
73
+ stream.write(struct.pack(">i", len(words)))
74
+ for word in words:
75
+ text = word["text"].encode("utf-8")
76
+ if len(text) > 10000:
77
+ raise ValueError("OCR word too long")
78
+ stream.write(struct.pack(">i", len(text)) + text)
79
+ stream.write(struct.pack(">4f", word["left"], word["top"], word["right"], word["bottom"]))
80
+ write_words(annotations.get("words", []))
81
+ meters = annotations.get("meters", [])
82
+ if len(meters) > 10000:
83
+ raise ValueError("Too many meter changes")
84
+ stream.write(struct.pack(">i", len(meters)))
85
+ for meter in meters:
86
+ stream.write(struct.pack(">iii", meter["measureIndex"], meter["numerator"], meter["denominator"]))
87
+ write_words(annotations.get("tabWords", []))
88
+
89
+
90
+ class Interpreter:
91
+ """One reusable CPU interpreter. Use one instance per worker; calls are not thread-safe."""
92
+ def __init__(self, model_path=None, threads=2):
93
+ if not 1 <= threads <= 32:
94
+ raise ValueError("threads must be 1..32")
95
+ self.jar = Path(__file__).with_name("interpreter.jar")
96
+ if not self.jar.is_file():
97
+ raise RuntimeError("Core JAR missing: run python scripts/build_java.py before installing from source")
98
+ path = Path(model_path) if model_path else Path(__file__).parent / "data" / MODEL_NAME
99
+ if not path.is_file():
100
+ raise FileNotFoundError("Model missing: run python scripts/build_java.py or use the release wheel")
101
+ self.model_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
102
+ if model_path is None and self.model_sha256 != MODEL_SHA256:
103
+ raise ValueError("Bundled model checksum mismatch")
104
+ try:
105
+ import tensorflow as tf
106
+ except ImportError as error:
107
+ raise RuntimeError("Install the inference extra: pip install 'score-reader[inference]'") from error
108
+ self.runtime = tf.lite.Interpreter(model_path=str(path), num_threads=threads)
109
+ self.runtime.allocate_tensors()
110
+ self.input = self.runtime.get_input_details()[0]
111
+ self.output = self.runtime.get_output_details()[0]
112
+ if self.input["shape"].tolist() != [1, 3, 320, 320] or self.input["dtype"] != np.float32:
113
+ raise ValueError("Expected float32 input [1,3,320,320]")
114
+ if self.output["shape"].tolist() != [1, 320, 320] or self.output["dtype"] != np.int64:
115
+ raise ValueError("Expected int64 class IDs [1,320,320]")
116
+ yy, xx = np.mgrid[:320, :320]
117
+ self.edge = np.minimum.reduce([xx, yy, 319 - xx, 319 - yy]) + 1
118
+ self.ocr = None
119
+
120
+ def predict(self, gray):
121
+ if not isinstance(gray, np.ndarray) or gray.ndim != 2 or gray.dtype != np.uint8:
122
+ raise ValueError("Expected a 2D uint8 grayscale array")
123
+ height, width = gray.shape
124
+ if not width or not height or gray.size > 20_000_000:
125
+ raise ValueError("Invalid image dimensions")
126
+ labels = np.zeros_like(gray)
127
+ confidence = np.zeros_like(gray)
128
+ white_prediction = None
129
+ # Only the reviewed bundled graph has the deterministic-output contract.
130
+ # Custom models keep one inference call per tile, including stateful models.
131
+ reuse_white = getattr(self, "model_sha256", None) == MODEL_SHA256
132
+ for top in tile_starts(height):
133
+ for left in tile_starts(width):
134
+ ch, cw = min(320, height - top), min(320, width - left)
135
+ tile = np.full((320, 320), 255, np.float32)
136
+ tile[:ch, :cw] = gray[top:top + ch, left:left + cw]
137
+ # Every channel is an exact repeat of this padded float plane.
138
+ exact_white = reuse_white and bool(np.all(tile == np.float32(255)))
139
+ if exact_white and white_prediction is not None:
140
+ prediction = white_prediction
141
+ else:
142
+ tensor = np.repeat(tile[None, None], 3, axis=1)
143
+ self.runtime.set_tensor(self.input["index"], tensor)
144
+ self.runtime.invoke()
145
+ prediction = self.runtime.get_tensor(self.output["index"])[0]
146
+ if exact_white:
147
+ # Backends may expose a reused output buffer. Own the cached values.
148
+ white_prediction = prediction.copy()
149
+ if prediction.min() < 0 or prediction.max() > 5:
150
+ raise ValueError("Model returned classes outside 0..5")
151
+ wins = self.edge[:ch, :cw] >= confidence[top:top + ch, left:left + cw]
152
+ labels[top:top + ch, left:left + cw][wins] = prediction[:ch, :cw][wins]
153
+ confidence[top:top + ch, left:left + cw][wins] = self.edge[:ch, :cw][wins]
154
+ return labels
155
+
156
+ def interpret(self, image, *, meter=(4, 4), key_fifths=0, width=2048, annotations=None,
157
+ page_index=None):
158
+ """Recognize an image; optional page_index is its zero-based physical source page."""
159
+ if page_index is not None and (type(page_index) is not int or not 0 <= page_index <= 100000):
160
+ raise ValueError("page_index must be a zero-based physical page in 0..100000")
161
+ if len(meter) != 2 or not all(isinstance(n, int) for n in meter):
162
+ raise ValueError("meter must be a numerator/denominator integer pair")
163
+ numerator, denominator = meter
164
+ if not 1 <= numerator <= 32 or denominator not in (1, 2, 4, 8, 16, 32):
165
+ raise ValueError("Invalid meter")
166
+ if not isinstance(key_fifths, int) or not -7 <= key_fifths <= 7:
167
+ raise ValueError("key_fifths must be -7..7")
168
+ gray = grayscale(image, width)
169
+ labels = self.predict(gray)
170
+ if annotations is None:
171
+ if self.ocr is None:
172
+ from .ocr import LocalOcr
173
+ self.ocr = LocalOcr()
174
+ from .ocr import page_annotations
175
+ words = self.ocr.words(gray)
176
+ annotations = page_annotations(words, [])
177
+ elif "tabWords" in annotations and "words" not in annotations:
178
+ if self.ocr is None:
179
+ from .ocr import LocalOcr
180
+ self.ocr = LocalOcr()
181
+ from .ocr import page_annotations
182
+ words = self.ocr.words(gray)
183
+ annotations = dict(page_annotations(words, annotations["tabWords"]), **annotations)
184
+ with tempfile.TemporaryDirectory(prefix="sheet-interpreter-") as folder:
185
+ page = Path(folder) / "page.page.gz"
186
+ output = Path(folder) / "score.json"
187
+ write_page(page, labels, gray, annotations)
188
+ command = [java_executable(), "-Xmx1g", "-jar", str(self.jar), str(page), str(output),
189
+ str(numerator), str(denominator), str(key_fifths)]
190
+ if page_index is not None:
191
+ command.extend(["--page-index", str(page_index)])
192
+ run = subprocess.run(command, capture_output=True, text=True)
193
+ if run.returncode:
194
+ raise RuntimeError("Decoder failed: " + run.stderr.strip())
195
+ result = json.loads(output.read_text(encoding="utf-8"))
196
+ result["modelSha256"] = self.model_sha256
197
+ result["initialMeter"] = list(meter)
198
+ result["initialKeyFifths"] = key_fifths
199
+ result["warnings"] = ["Experimental recognition: review pitches, accidentals, ties and timing.",
200
+ "OCR can miss small or faint text; the initial meter is an argument, not an automatic reading."]
201
+ result["warnings"].extend(result.get("tablatureWarnings", []))
202
+ if not result["events"]:
203
+ result["warnings"].append("No playable notes detected on this page.")
204
+ return result
@@ -0,0 +1,33 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Retained rest meaning, separate from optical position and whole-glyph base duration."""
4
+ import math
5
+
6
+
7
+ def rest_kind(row):
8
+ kind = row.get('kind', 'LITERAL')
9
+ if type(kind) is not str or kind not in ('LITERAL', 'FULL_MEASURE'):
10
+ raise ValueError('Invalid rest kind')
11
+ if kind == 'FULL_MEASURE':
12
+ duration = row.get('durationBeats')
13
+ if type(duration) not in (int, float) or duration != 4:
14
+ raise ValueError('Full-measure rest must retain its undotted whole-glyph base')
15
+ return kind
16
+
17
+
18
+ def full_measure_span(page, row):
19
+ """Use only the producer's performed measure span; never infer it from geometry."""
20
+ if rest_kind(row) != 'FULL_MEASURE':
21
+ raise ValueError('Expected full-measure rest')
22
+ m, staff, count = (row.get(key) for key in ('measureIndex', 'staffIndex', 'staffCount'))
23
+ beats = page.get('measureBeats')
24
+ if (type(m) is not int or not isinstance(beats, (list, tuple)) or not 0 <= m < len(beats)
25
+ or type(staff) is not int or type(count) is not int or not 0 <= staff < count):
26
+ raise ValueError('Full-measure rest needs a known measure and physical staff')
27
+ position = row.get('positionInMeasure')
28
+ if type(position) not in (int, float) or not math.isfinite(position) or not 0 <= position <= 1:
29
+ raise ValueError('Invalid full-measure rest optical position')
30
+ duration = beats[m]
31
+ if type(duration) not in (int, float) or not math.isfinite(duration) or duration <= 0:
32
+ raise ValueError('Full-measure rest needs a finite positive performed measure span')
33
+ return duration
@@ -0,0 +1,17 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Lightweight Java runtime lookup shared by inference and decoded-data exports."""
4
+ import os
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+
9
+ def java_executable():
10
+ if os.environ.get('JAVA_HOME'):
11
+ path = Path(os.environ['JAVA_HOME']) / 'bin' / ('java.exe' if os.name == 'nt' else 'java')
12
+ if path.is_file():
13
+ return str(path)
14
+ path = shutil.which('java')
15
+ if not path:
16
+ raise RuntimeError('Install Java 17 or newer and put java on PATH or set JAVA_HOME')
17
+ return path
@@ -0,0 +1,321 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Guide263's bounded semantic records; stable IDs match ScoreSemanticWire, not enum order."""
4
+ import io
5
+ import math
6
+ import struct
7
+ from encodings.utf_16_le import encode as utf16_encode
8
+
9
+ KINDS = ('UNRESOLVED_DIRECTION', 'RITARDANDO', 'RALLENTANDO', 'RITENUTO',
10
+ 'ACCELERANDO', 'A_TEMPO', 'TEMPO_PRIMO', 'SAME_TEMPO', 'FERMATA',
11
+ 'BREATH', 'CAESURA', 'SFORZANDO', 'SFORZATO', 'SFORZANDO_PIANO',
12
+ 'PEDAL_DOWN', 'PEDAL_UP', 'ARPEGGIO', 'CRESCENDO', 'DIMINUENDO', 'METRIC_MODULATION', 'NATURAL_HARMONIC', 'FALL_OFF', 'PARENTHESIZED_NOTE_GROUP')
13
+ SCOPES = ('SCORE', 'PART', 'VOICE', 'NOTE', 'REST', 'UNRESOLVED')
14
+ STRENGTHS = ('UNSPECIFIED', 'POCO', 'MOLTO')
15
+ POLICIES = ('DEFAULT', 'SKIP', 'PLAY', 'UNKNOWN')
16
+ JUMPS = (2, 7, 8, 9, 10, 11)
17
+ MAX_RECORD_BYTES = 262144
18
+ DEFAULT_DETAILS = dict(quarterBeatOffset=0, eventId='', targetId='', codaTargetId='',
19
+ repeatGroupId='', totalPlays=2, passes=[], end=None,
20
+ afterJumpRepeats='DEFAULT', printedText='', evidence=[])
21
+
22
+
23
+ def integer(value, minimum, maximum):
24
+ if type(value) is not int or not minimum <= value <= maximum:
25
+ raise ValueError('Invalid semantic integer')
26
+ return value
27
+
28
+
29
+ def number(value, minimum, maximum):
30
+ if type(value) not in (int, float) or not math.isfinite(value) or not minimum <= value <= maximum:
31
+ raise ValueError('Invalid semantic number')
32
+ return value
33
+
34
+
35
+ def text(value, maximum):
36
+ # Explicit codec import keeps frozen desktop packages complete too.
37
+ if not isinstance(value, str) or len(utf16_encode(value)[0]) // 2 > maximum:
38
+ raise ValueError('Invalid semantic text')
39
+ value.encode('utf-8', errors='strict')
40
+ return value
41
+
42
+
43
+ def anchor(value):
44
+ if value is None:
45
+ return None
46
+ return dict(measureIndex=integer(value['measureIndex'], 0, 100000),
47
+ quarterBeatOffset=number(value['quarterBeatOffset'], 0, 128))
48
+
49
+
50
+ def evidence(values, required=False):
51
+ if not isinstance(values, list) or not (1 if required else 0) <= len(values) <= 64:
52
+ raise ValueError('Invalid semantic evidence count')
53
+ for e in values:
54
+ if not text(e['sourceId'], 256).strip():
55
+ raise ValueError('Empty semantic evidence identity')
56
+ integer(e['pageIndex'], 0, 100000)
57
+ number(e['visualX'], 0, 1)
58
+ integer(e['staffCount'], 1, 2147483647)
59
+ integer(e['staffIndex'], 0, e['staffCount'] - 1)
60
+ text(e['printedText'], 4096)
61
+ return values
62
+
63
+
64
+ def owned_start(value, measures):
65
+ if value is not None and (value['measureIndex'] > measures
66
+ or value['measureIndex'] == measures and value['quarterBeatOffset'] != 0):
67
+ raise ValueError('Semantic start outside page')
68
+
69
+
70
+ def direction(row, measures):
71
+ boundary = integer(row['measureBoundary'], 0, measures)
72
+ kind = integer(row['kind'], 0, 13)
73
+ supplied = row.get('details', {})
74
+ if not isinstance(supplied, dict) or set(supplied) - set(DEFAULT_DETAILS):
75
+ raise ValueError('Unknown navigation detail')
76
+ d = dict(DEFAULT_DETAILS, **supplied)
77
+ offset = number(d['quarterBeatOffset'], 0, 128)
78
+ owned_start(dict(measureIndex=boundary, quarterBeatOffset=offset), measures)
79
+ for key in ('eventId', 'targetId', 'codaTargetId', 'repeatGroupId'):
80
+ text(d[key], 256)
81
+ integer(d['totalPlays'], 1, 128)
82
+ passes = d['passes']
83
+ if not isinstance(passes, list) or len(passes) > 128:
84
+ raise ValueError('Invalid navigation passes')
85
+ for value in passes:
86
+ integer(value, 1, 128)
87
+ if len(set(passes)) != len(passes) or passes and kind not in (6, *JUMPS):
88
+ raise ValueError('Invalid navigation pass selector')
89
+ d['end'] = anchor(d['end'])
90
+ if d['end'] is not None and (d['end']['measureIndex'], d['end']['quarterBeatOffset']) <= (boundary, offset):
91
+ raise ValueError('Invalid navigation span')
92
+ if kind == 6 and (d['end'] is None or not passes):
93
+ raise ValueError('Ending needs endpoint and passes')
94
+ if d['afterJumpRepeats'] not in POLICIES:
95
+ raise ValueError('Unknown return policy')
96
+ text(d['printedText'], 4096)
97
+ evidence(d['evidence'])
98
+ if d != DEFAULT_DETAILS and not d['eventId'].strip():
99
+ raise ValueError('Rich navigation needs source identity')
100
+ return dict(measureBoundary=boundary, kind=kind, details=d)
101
+
102
+
103
+ def expression(row, measures):
104
+ if not text(row['eventId'], 256).strip() or row['kind'] not in KINDS or row['scope'] not in SCOPES:
105
+ raise ValueError('Invalid expressive identity or kind')
106
+ start, end = anchor(row['start']), anchor(row['end'])
107
+ owned_start(start, measures)
108
+ if end is not None and (start is None or (end['measureIndex'], end['quarterBeatOffset'])
109
+ < (start['measureIndex'], start['quarterBeatOffset'])):
110
+ raise ValueError('Invalid expressive span')
111
+ if row['scope'] != 'UNRESOLVED' and start is None:
112
+ raise ValueError('Resolved expression needs anchor')
113
+ integer(row['staffCount'], 1, 2147483647)
114
+ integer(row['staffIndex'], 0, row['staffCount'] - 1)
115
+ target = row['targetEventId']
116
+ if target is not None and not text(target, 256).strip():
117
+ raise ValueError('Empty expressive target')
118
+ if row['kind'] == 'FERMATA' and row['scope'] != 'UNRESOLVED' and (end is None or target is None):
119
+ raise ValueError('Resolved fermata needs target and release')
120
+ if row['strength'] not in STRENGTHS:
121
+ raise ValueError('Unknown expressive strength')
122
+ text(row['qualifierText'], 4096)
123
+ if row['kind'] == 'METRIC_MODULATION':
124
+ values = row['qualifierText'].split(':')
125
+ try:
126
+ allowed = {base*factor for base in (.125,.25,.5,1,2,4) for factor in (1,1.5,1.75)}
127
+ valid = len(values) == 3 and values[0] == 'metric-pulse-v1' and all(float(v) in allowed for v in values[1:])
128
+ except ValueError:
129
+ valid = False
130
+ if not valid:
131
+ raise ValueError('Metric modulation needs a validated pulse pair')
132
+ if row['kind'] == 'NATURAL_HARMONIC' and (
133
+ row['scope'] not in ('NOTE', 'UNRESOLVED') or target is None or end is not None
134
+ or row['scope'] == 'UNRESOLVED' and start is not None
135
+ or row['scope'] == 'NOTE' and start is None):
136
+ raise ValueError('Natural harmonic needs one exact note owner')
137
+
138
+ if row['kind'] == 'FALL_OFF':
139
+ try:
140
+ fields = target.split(':')
141
+ nums = [int(fields[i]) for i in (1, 2, 3, 5)]
142
+ floats = [struct.unpack('>f', bytes.fromhex(fields[i]))[0] for i in (4, 6)]
143
+ valid = (len(fields) == 7 and fields[0] == 'fall-off-note-v1'
144
+ and all(-2147483648 <= n <= 2147483647 for n in nums)
145
+ and nums[0] >= 0 and 0 <= nums[1] < nums[2]
146
+ and all(len(fields[i]) == 8 and all(c in '0123456789abcdef' for c in fields[i]) for i in (4, 6))
147
+ and all(math.isfinite(f) and 0 <= f <= 1 for f in floats))
148
+ except (ValueError, TypeError, AttributeError, IndexError, struct.error):
149
+ valid = False
150
+ if (not valid or row['scope'] not in ('NOTE', 'UNRESOLVED') or end is not None
151
+ or row['scope'] == 'UNRESOLVED' and start is not None
152
+ or row['scope'] == 'NOTE' and start is None
153
+ or row['strength'] != 'UNSPECIFIED' or row['qualifierText'] != 'falloff-v1:curved'):
154
+ raise ValueError('Falloff needs one exact note owner and printed shape')
155
+ if row['kind'] == 'PARENTHESIZED_NOTE_GROUP':
156
+ try:
157
+ from .parenthesized_note_group import decode as decode_parentheses
158
+ except ImportError:
159
+ from parenthesized_note_group import decode as decode_parentheses
160
+ pair = decode_parentheses(row['qualifierText'])
161
+ if (pair is None or row['scope'] not in ('NOTE', 'UNRESOLVED') or end is not None
162
+ or row['scope'] == 'UNRESOLVED' and start is not None
163
+ or row['scope'] == 'NOTE' and (start is None or start['measureIndex'] != pair.members[0].measure)
164
+ or row['strength'] != 'UNSPECIFIED' or target != pair.target
165
+ or (row['staffIndex'], row['staffCount']) != (pair.members[0].staff, pair.members[0].count)
166
+ or pair.members[0].measure >= measures):
167
+ raise ValueError('Group needs exact ordered members and one printed pair')
168
+ evidence(row['evidence'], required=True)
169
+ return dict(row, start=start, end=end)
170
+
171
+
172
+ class Writer:
173
+ def __init__(self):
174
+ self.output = io.BytesIO()
175
+
176
+ def put(self, fmt, *values):
177
+ self.output.write(struct.pack('>' + fmt, *values))
178
+
179
+ def text(self, value):
180
+ raw = value.encode('utf-8'); self.put('i', len(raw)); self.output.write(raw)
181
+
182
+ def anchor(self, value):
183
+ self.put('?', value is not None)
184
+ if value is not None:
185
+ self.put('id', value['measureIndex'], value['quarterBeatOffset'])
186
+
187
+ def evidence(self, values):
188
+ self.put('i', len(values))
189
+ for e in values:
190
+ self.text(e['sourceId']); self.put('ifii', e['pageIndex'], e['visualX'], e['staffIndex'], e['staffCount'])
191
+ self.text(e['printedText'])
192
+
193
+ def frame(self, record):
194
+ raw = record.output.getvalue()
195
+ if len(raw) > MAX_RECORD_BYTES:
196
+ raise ValueError('Semantic record too large')
197
+ self.put('i', len(raw)); self.output.write(raw)
198
+
199
+
200
+ def encode(directions, expressions, measures, guide_version=277):
201
+ if not isinstance(directions, list) or len(directions) > min(100000, (measures + 1) * 64):
202
+ raise ValueError('Too many navigation records')
203
+ if not isinstance(expressions, list) or len(expressions) > min(250000, (measures + 1) * 256):
204
+ raise ValueError('Too many expressions')
205
+ if guide_version < 277 and any(row['kind'] == 'METRIC_MODULATION' for row in expressions):
206
+ raise ValueError('Metric modulation requires guide277')
207
+ if guide_version < 294 and any(row['kind'] == 'NATURAL_HARMONIC' for row in expressions):
208
+ raise ValueError('Natural harmonic requires guide294')
209
+ if guide_version < 295 and any(row['kind'] == 'FALL_OFF' for row in expressions):
210
+ raise ValueError('Falloff requires guide295')
211
+ if guide_version < 296 and any(row['kind'] == 'PARENTHESIZED_NOTE_GROUP' for row in expressions):
212
+ raise ValueError('Parenthesized group requires guide296')
213
+ out = Writer(); out.put('i', len(directions))
214
+ for row in directions:
215
+ row = direction(row, measures); d = row['details']; r = Writer()
216
+ r.put('iid', row['measureBoundary'], row['kind'], d['quarterBeatOffset'])
217
+ for key in ('eventId', 'targetId', 'codaTargetId', 'repeatGroupId'):
218
+ r.text(d[key])
219
+ r.put('ii', d['totalPlays'], len(d['passes']))
220
+ for value in d['passes']:
221
+ r.put('i', value)
222
+ r.anchor(d['end']); r.put('i', POLICIES.index(d['afterJumpRepeats']))
223
+ r.text(d['printedText']); r.evidence(d['evidence']); out.frame(r)
224
+ out.put('i', len(expressions)); ids = set()
225
+ for row in expressions:
226
+ row = expression(row, measures)
227
+ if row['eventId'] in ids:
228
+ raise ValueError('Duplicate expression identity')
229
+ ids.add(row['eventId']); r = Writer(); r.text(row['eventId']); r.put('i', KINDS.index(row['kind']))
230
+ r.anchor(row['start']); r.anchor(row['end']); r.put('iii', SCOPES.index(row['scope']), row['staffIndex'], row['staffCount'])
231
+ r.put('?', row['targetEventId'] is not None)
232
+ if row['targetEventId'] is not None:
233
+ r.text(row['targetEventId'])
234
+ r.put('i', STRENGTHS.index(row['strength'])); r.text(row['qualifierText']); r.evidence(row['evidence']); out.frame(r)
235
+ return out.output.getvalue()
236
+
237
+
238
+ class Reader:
239
+ def __init__(self, data):
240
+ self.data, self.offset = memoryview(data), 0
241
+
242
+ def take(self, fmt):
243
+ size = struct.calcsize('>' + fmt)
244
+ if self.offset + size > len(self.data):
245
+ raise ValueError('Truncated semantic record')
246
+ result = struct.unpack_from('>' + fmt, self.data, self.offset); self.offset += size
247
+ return result[0] if len(result) == 1 else result
248
+
249
+ def count(self, maximum):
250
+ return integer(self.take('i'), 0, maximum)
251
+
252
+ def raw(self, size):
253
+ if self.offset + size > len(self.data):
254
+ raise ValueError('Truncated semantic bytes')
255
+ result = self.data[self.offset:self.offset + size]; self.offset += size
256
+ return result
257
+
258
+ def boolean(self):
259
+ return bool(integer(self.take('B'), 0, 1))
260
+
261
+ def text(self, maximum):
262
+ return text(bytes(self.raw(self.count(maximum * 4))).decode('utf-8', errors='strict'), maximum)
263
+
264
+ def anchor(self):
265
+ return anchor(dict(measureIndex=self.take('i'), quarterBeatOffset=self.take('d'))) if self.boolean() else None
266
+
267
+ def evidence(self):
268
+ result = []
269
+ for _ in range(self.count(64)):
270
+ source = self.text(256); page, x, staff, count = self.take('ifii')
271
+ result.append(dict(sourceId=source, pageIndex=page, visualX=x, staffIndex=staff,
272
+ staffCount=count, printedText=self.text(4096)))
273
+ return result
274
+
275
+ def enum(self, values):
276
+ return values[integer(self.take('i'), 0, len(values) - 1)]
277
+
278
+ def frame(self):
279
+ return Reader(self.raw(self.count(MAX_RECORD_BYTES)))
280
+
281
+ def finish(self):
282
+ if self.offset != len(self.data):
283
+ raise ValueError('Unexpected semantic bytes')
284
+
285
+
286
+ def decode_prefix(data, measures, guide_version=277):
287
+ source = Reader(data); directions, expressions = [], []; ids = set()
288
+ for _ in range(source.count(min(100000, (measures + 1) * 64))):
289
+ r = source.frame(); boundary, kind, offset = r.take('iid')
290
+ d = dict(quarterBeatOffset=offset)
291
+ for key in ('eventId', 'targetId', 'codaTargetId', 'repeatGroupId'):
292
+ d[key] = r.text(256)
293
+ d['totalPlays'] = r.take('i'); d['passes'] = [r.take('i') for _ in range(r.count(128))]
294
+ d['end'] = r.anchor(); d['afterJumpRepeats'] = r.enum(POLICIES)
295
+ d['printedText'] = r.text(4096); d['evidence'] = r.evidence(); r.finish()
296
+ directions.append(direction(dict(measureBoundary=boundary, kind=kind, details=d), measures))
297
+ for _ in range(source.count(min(250000, (measures + 1) * 256))):
298
+ r = source.frame(); row = dict(eventId=r.text(256), kind=r.enum(KINDS), start=r.anchor(), end=r.anchor())
299
+ if guide_version < 277 and row['kind'] == 'METRIC_MODULATION':
300
+ raise ValueError('Metric modulation is outside this guide format')
301
+ if guide_version < 294 and row['kind'] == 'NATURAL_HARMONIC':
302
+ raise ValueError('Natural harmonic is outside this guide format')
303
+ if guide_version < 295 and row['kind'] == 'FALL_OFF':
304
+ raise ValueError('Falloff is outside this guide format')
305
+ if guide_version < 296 and row['kind'] == 'PARENTHESIZED_NOTE_GROUP':
306
+ raise ValueError('Parenthesized group is outside this guide format')
307
+ row['scope'] = r.enum(SCOPES); row['staffIndex'], row['staffCount'] = r.take('ii')
308
+ row['targetEventId'] = r.text(256) if r.boolean() else None
309
+ row['strength'] = r.enum(STRENGTHS); row['qualifierText'] = r.text(4096); row['evidence'] = r.evidence(); r.finish()
310
+ row = expression(row, measures)
311
+ if row['eventId'] in ids:
312
+ raise ValueError('Duplicate expressive identity')
313
+ ids.add(row['eventId']); expressions.append(row)
314
+ return directions, expressions, source.offset
315
+
316
+
317
+ def decode(data, measures, guide_version=277):
318
+ directions, expressions, consumed = decode_prefix(data, measures, guide_version)
319
+ if consumed != len(data):
320
+ raise ValueError('Unexpected semantic bytes')
321
+ return directions, expressions
@@ -0,0 +1,43 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Bound straight-slide numbers by their paired endpoints in MusicXML document order."""
4
+
5
+
6
+ def assign(root):
7
+ """Replace internal relation tokens with number-level values 1..16.
8
+
9
+ MusicXML overlap follows document order, including backups and voices. A
10
+ stop may precede its start, so a token is live between its two occurrences,
11
+ irrespective of endpoint type. Split-note placement is already complete.
12
+ Validate and plan every part before mutating any node or writing the file.
13
+ """
14
+ planned = []
15
+ for part in root.findall('part'):
16
+ markers = list(part.iter('slide'))
17
+ pairs = {}
18
+ for marker in markers:
19
+ token = marker.get('number')
20
+ kind = marker.get('type')
21
+ if token is None or kind not in ('start', 'stop'):
22
+ raise ValueError('Straight slide needs an explicit paired endpoint identity')
23
+ pairs.setdefault(token, []).append(kind)
24
+ if any(sorted(kinds) != ['start', 'stop'] for kinds in pairs.values()):
25
+ raise ValueError('Straight slide needs exactly one start and one stop per identity')
26
+ active = {}
27
+ available = set(range(1, 17))
28
+ for marker in markers:
29
+ token = marker.get('number')
30
+ if token in active:
31
+ number = active.pop(token)
32
+ available.add(number)
33
+ else:
34
+ if not available:
35
+ raise ValueError('More than 16 overlapping straight slides in MusicXML document order are unsupported')
36
+ number = min(available)
37
+ available.remove(number)
38
+ active[token] = number
39
+ planned.append((marker, number))
40
+ if active:
41
+ raise ValueError('Straight slide has an unclosed endpoint identity')
42
+ for marker, number in planned:
43
+ marker.set('number', str(number))