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,142 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Local image/PDF to JSON, with optional MIDI, MP3 and MusicXML exports."""
4
+ import argparse
5
+ import json
6
+ import hashlib
7
+ import io
8
+ from pathlib import Path
9
+ import sys
10
+ from PIL import Image
11
+ from .reader import Interpreter
12
+ from .midi import write_midi
13
+ from .musicxml import write_musicxml
14
+
15
+
16
+ def main():
17
+ parser = argparse.ArgumentParser(description=__doc__)
18
+ parser.add_argument("input", type=Path)
19
+ parser.add_argument("--output", "-o", required=True, type=Path)
20
+ parser.add_argument("--midi", type=Path)
21
+ parser.add_argument("--mp3", type=Path, help="Optional synthesized audio preview")
22
+ parser.add_argument("--ffmpeg", type=Path, help="FFmpeg executable for MP3 export")
23
+ parser.add_argument("--mp3-bitrate", type=int, default=192, choices=(64, 96, 128, 160, 192, 256, 320))
24
+ parser.add_argument("--musicxml", type=Path, help="Optional concert-pitch MusicXML export")
25
+ parser.add_argument("--meter", default="4/4", help="Initial meter; read by the caller (default: 4/4)")
26
+ parser.add_argument("--bpm", type=float, default=120, help="Initial quarter-note BPM for exports")
27
+ parser.add_argument("--key-fifths", type=int, default=0, help="Fallback key: sharps positive, flats negative")
28
+ parser.add_argument("--width", type=int, default=2048)
29
+ parser.add_argument("--threads", type=int, default=2)
30
+ parser.add_argument("--model", type=Path, help="Custom TFLite model with the documented tensor contract")
31
+ parser.add_argument("--pages", help="One-based comma-separated PDF pages, in reading order")
32
+ parser.add_argument("--annotations", type=Path, help="JSON list of annotation objects, one per selected page")
33
+ args = parser.parse_args()
34
+ try:
35
+ meter = tuple(int(n) for n in args.meter.split("/"))
36
+ if len(meter) != 2:
37
+ raise ValueError("Use --meter numerator/denominator")
38
+ if not 15 <= args.bpm <= 400:
39
+ raise ValueError("BPM must be 15..400")
40
+ annotations = json.loads(args.annotations.read_text(encoding="utf-8")) if args.annotations else None
41
+ if annotations is not None and not isinstance(annotations, list):
42
+ raise ValueError("Annotations must be a JSON list, one object per selected page")
43
+ outputs = [p for p in (args.output, args.midi, args.mp3, args.musicxml) if p]
44
+ if len({p.resolve() for p in outputs}) != len(outputs):
45
+ raise ValueError("JSON, MIDI, MP3 and MusicXML outputs must be different files")
46
+ initial_meter = meter
47
+ for output in outputs:
48
+ if output and output.resolve() == args.input.resolve():
49
+ raise ValueError("Output must not overwrite the input score")
50
+ if args.midi and args.midi.resolve() == args.output.resolve():
51
+ raise ValueError("JSON and MIDI outputs must be different files")
52
+ if args.ffmpeg and not args.mp3:
53
+ raise ValueError("--ffmpeg requires --mp3")
54
+ if args.mp3:
55
+ from .audio import find_ffmpeg
56
+ find_ffmpeg(args.ffmpeg) # Fail before expensive recognition if unavailable.
57
+ engine = Interpreter(args.model, args.threads)
58
+ results = []
59
+ source_bytes = args.input.read_bytes()
60
+ source_sha = hashlib.sha256(source_bytes).hexdigest()
61
+ source_pages = 1
62
+ key = args.key_fifths
63
+
64
+ def process(image, page_number, native_words=None):
65
+ nonlocal key, meter
66
+ index = len(results)
67
+ if annotations is not None and index >= len(annotations):
68
+ raise ValueError("One annotation object is required for every selected page")
69
+ print(f"Reading page {page_number}", file=sys.stderr)
70
+ page = engine.interpret(image, meter=meter, key_fifths=key, width=args.width,
71
+ page_index=page_number - 1,
72
+ annotations=annotations[index] if annotations is not None else ({"tabWords": native_words} if native_words else None))
73
+ from .clock_context import bind_document
74
+ score = page["score"]
75
+ score["clockContextSource"] = bind_document(score.get("clockContextSource"),
76
+ len(score["notes"]),len(score["measures"]),len(score.get("rests",[])),
77
+ source_sha,page_number-1,source_pages)
78
+ page["sourcePage"] = page_number
79
+ results.append(page)
80
+ if page["score"]["keyChanges"]:
81
+ key = page["score"]["keyChanges"][-1]["fifths"]
82
+ if page["score"]["meterChanges"]:
83
+ last = max(page["score"]["meterChanges"], key=lambda x: x["measureIndex"])
84
+ meter = (last["numerator"], last["denominator"])
85
+
86
+ if args.input.suffix.lower() == ".pdf":
87
+ try:
88
+ import pypdfium2 as pdfium
89
+ except ImportError as error:
90
+ raise ValueError("PDF input needs the pdf extra: pip install 'score-reader[pdf]'") from error
91
+ pdf = pdfium.PdfDocument(source_bytes)
92
+ source_pages = len(pdf)
93
+ try:
94
+ pages = [int(n) - 1 for n in args.pages.split(",")] if args.pages else list(range(len(pdf)))
95
+ if not pages or any(n < 0 or n >= len(pdf) for n in pages):
96
+ raise ValueError("PDF page number out of range")
97
+ if pages != sorted(set(pages)):
98
+ raise ValueError("Choose unique PDF pages in increasing reading order")
99
+ from .pdf_annotations import tab_words, tuning_header
100
+ first = pdf[0]
101
+ try:
102
+ header = tuning_header(first)
103
+ finally:
104
+ first.close()
105
+ for number in pages:
106
+ page = pdf[number]
107
+ bitmap = page.render(scale=2400 / page.get_width())
108
+ try:
109
+ process(bitmap.to_pil(), number + 1, tab_words(page, header))
110
+ finally:
111
+ bitmap.close()
112
+ page.close()
113
+ finally:
114
+ pdf.close()
115
+ else:
116
+ if args.pages:
117
+ raise ValueError("--pages is for PDF input")
118
+ with Image.open(io.BytesIO(source_bytes)) as image:
119
+ process(image, 1)
120
+ if annotations is not None and len(annotations) != len(results):
121
+ raise ValueError("Annotation count must match the number of selected pages")
122
+ document = {"schemaVersion": 1, "inputName": args.input.name, "initialBpm": args.bpm, "initialMeter": initial_meter, "initialKeyFifths": args.key_fifths, "pages": results}
123
+ from .boundary_ties import resolve_boundary_ties
124
+ document = resolve_boundary_ties(document)
125
+ args.output.parent.mkdir(parents=True, exist_ok=True)
126
+ args.output.write_text(json.dumps(document, indent=2, allow_nan=False) + "\n", encoding="utf-8")
127
+ if args.midi:
128
+ args.midi.parent.mkdir(parents=True, exist_ok=True)
129
+ write_midi(document, args.midi, args.bpm)
130
+ if args.musicxml:
131
+ args.musicxml.parent.mkdir(parents=True, exist_ok=True)
132
+ write_musicxml(document, args.musicxml)
133
+ if args.mp3:
134
+ from .audio import write_mp3
135
+ write_mp3(document, args.mp3, args.bpm, ffmpeg=args.ffmpeg, bitrate=args.mp3_bitrate)
136
+ print(f"Wrote {len(results)} page(s), {sum(len(p['events']) for p in results)} detected notes to {args.output}", file=sys.stderr)
137
+ except (ValueError, RuntimeError, OSError, KeyError, TypeError) as error:
138
+ parser.exit(1, str(error) + "\n")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
@@ -0,0 +1,261 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Guide299 typed source-clock context, strictly after the complete Guide298 body.
4
+
5
+ An observation or geometric model does not select a timing policy. All unbound,
6
+ contrary and unavailable requirements remain explicit records.
7
+ """
8
+ import io
9
+ import math
10
+ import re
11
+ import struct
12
+ MAGIC = b'CTX1'
13
+ MAX_BYTES = 4 * 1024 * 1024
14
+ _SCHEMA = {'Origin': [['documentSha256', 's'], ['physicalPageIndex', 'i'], ['physicalPageCount', 'i'], ['width', 'i'], ['height', 'i'], ['rasterSha256', 's'], ['labelsSha256', 's']], 'Box': [['left', 'f'], ['top', 'f'], ['right', 'f'], ['bottom', 'f']], 'RasterBox': [['left', 'i'], ['top', 'i'], ['right', 'i'], ['bottom', 'i']], 'PartWord': [['ordinal', 'i'], ['system', 'i'], ['firstMeasure', 'i'], ['measureAfterLast', 'i'], ['text', 's'], ['textSha256', 's'], ['canonicalPart', 's'], ['bounds', 'Box'], ['role', 'EWordRole'], ['sampledMembers', 'i'], ['sampledSha256', 's'], ['status', 'EStatus']], 'NumberRead': [['ordinal', 'i'], ['system', 'i'], ['text', 's'], ['value', 'i'], ['originCandidate', 'i'], ['bounds', 'Box'], ['route', 'ENumberRoute'], ['status', 'EStatus']], 'MeterRead': [['ordinal', 'i'], ['measure', 'i'], ['text', 's'], ['numerator', 'i'], ['denominator', 'i'], ['bounds', 'RasterBox'], ['firstLine', 'f'], ['gap', 'f'], ['votes', 'i'], ['sampledMembers', 'i'], ['sampledSha256', 's'], ['route', 'EMeterRoute'], ['originalProducerAccepted', 'b'], ['status', 'EStatus']], 'PrintedValue': [['noteIndex', 'i'], ['measure', 'i'], ['staff', 'i'], ['staffs', 'i'], ['kind', 'EValueKind'], ['baseBeats', 'f'], ['dots', 'i'], ['beams', 'i'], ['route', 'EValueRoute'], ['originalExit', 's'], ['admissionFlags', 'i'], ['selectedMembers', 'i'], ['parentMembers', 'i'], ['parentLeaves', 'i'], ['residualMembers', 'i'], ['selectedSha256', 's'], ['parentSha256', 's'], ['model', 'EModel'], ['status', 'EStatus']], 'GlyphLedger': [['measure', 'i'], ['semanticLabel', 'i'], ['population', 'l'], ['coveredUnique', 'l'], ['noteMembers', 'l'], ['nonRhythmicMembers', 'l'], ['restMembers', 'l'], ['unknownMembers', 'l'], ['coverageSha256', 's'], ['producerRoute', 's'], ['status', 'EStatus']], 'RestValue': [['restIndex', 'i'], ['measure', 'i'], ['staff', 'i'], ['staffs', 'i'], ['kind', 'ERestKind'], ['baseBeats', 'f'], ['dots', 'i'], ['membersSha256', 's'], ['producerRoute', 's'], ['status', 'EStatus']], 'VoiceGroup': [['measure', 'i'], ['staff', 'i'], ['staffs', 'i'], ['voiceId', 's'], ['ordinal', 'i'], ['kind', 'EGroupKind'], ['noteIndices', 'Li'], ['restIndices', 'Li'], ['membersSha256', 's'], ['sourceRoute', 's'], ['status', 'EStatus']], 'SyncAnchor': [['measure', 'i'], ['firstVoice', 's'], ['firstThroughOrdinal', 'i'], ['secondVoice', 's'], ['secondThroughOrdinal', 'i'], ['kind', 'ESyncKind'], ['bounds', 'Box'], ['membersSha256', 's'], ['sourceRoute', 's'], ['status', 'EStatus']], 'Missing': [['requirement', 'ERequirement'], ['measure', 'i']]}
15
+ _LISTS = [['partWords', 'PartWord', 10000], ['numbers', 'NumberRead', 20000], ['meters', 'MeterRead', 10000], ['printedValues', 'PrintedValue', 100000], ['glyphLedgers', 'GlyphLedger', 100000], ['restValues', 'RestValue', 100000], ['voiceGroups', 'VoiceGroup', 100000], ['syncAnchors', 'SyncAnchor', 100000], ['missing', 'Missing', 100000]]
16
+ _ENUMS = {'Status': ['UNKNOWN', 'OBSERVATION', 'SOURCE_PREMISE', 'CONTRARY', 'UNREAD', 'UNSUPPORTED'], 'WordRole': ['OUTSIDE_PART_SLOT', 'PART_LABEL', 'UNKNOWN_LABEL_RIVAL'], 'NumberRoute': ['OUTSIDE_HEADER', 'TRUSTED_ASSIGNED', 'SINGLE_MEASURE_ONE_RETURN', 'UNASSIGNED_HEADER_OBSERVATION', 'UNREAD_HEADER_WORD'], 'MeterRoute': ['RASTER_UNBOUNDED', 'READER_BOUNDED', 'UNREAD_CANDIDATE', 'UNKNOWN', 'HEADER_MODEL_EXCLUSION'], 'ValueKind': ['UNKNOWN', 'WHOLE', 'HALF', 'QUARTER', 'BEAMED'], 'ValueRoute': ['UNKNOWN', 'OPAQUE_DEFAULT', 'OPEN_WITH_STEM', 'OPEN_WITHOUT_STEM', 'BEAM_INPUT', 'FILLED_PHYSICAL_TREMOLO_ENDPOINT'], 'Model': ['NONE', 'GEOMETRIC_ELLIPSE_SOURCE_CONTACT'], 'RestKind': ['UNKNOWN', 'FULL_BAR', 'WHOLE', 'HALF', 'QUARTER', 'EIGHTH', 'SIXTEENTH', 'THIRTY_SECOND', 'SIXTY_FOURTH'], 'GroupKind': ['ATTACK_CHORD', 'REST', 'GRACE'], 'SyncKind': ['SAME_PRINTED_ATTACK_COLUMN', 'SHARED_BEAM_BOUNDARY'], 'Requirement': ['DOCUMENT_ORIGIN', 'PART_CONTINUITY', 'METER_SCOPE', 'PRINTED_VALUES', 'RHYTHMIC_GLYPH_CLOSURE', 'VOICE_OWNERSHIP', 'REST_OWNERSHIP', 'SYNCHRONIZED_ANCHORS', 'CAPTURE_BUDGET']}
17
+
18
+ _JAVA_SPACES = frozenset(range(9,14)) | frozenset(range(28,33)) | {0x1680,0x2028,0x2029,0x205f,0x3000} | frozenset(range(0x2000,0x2007)) | frozenset(range(0x2008,0x200b))
19
+ def _blank(value):
20
+ return all(ord(c)in _JAVA_SPACES for c in value)
21
+
22
+ def _i(v, lo=-2147483648, hi=2147483647):
23
+ if type(v) is not int or not lo <= v <= hi: raise ValueError('Invalid clock integer')
24
+ return v
25
+
26
+ def _f(v, lo=-3.4028235e38, hi=3.4028235e38):
27
+ if type(v) not in (int,float) or not math.isfinite(v) or not lo <= v <= hi:
28
+ raise ValueError('Invalid clock float')
29
+ try: return struct.unpack('>f',struct.pack('>f',v))[0]
30
+ except (OverflowError,struct.error) as e: raise ValueError('Invalid clock float') from e
31
+
32
+ def _text(v, maximum=1024):
33
+ if not isinstance(v,str) or '\0' in v: raise ValueError('Invalid clock text')
34
+ try:
35
+ if len(v.encode('utf-16-be'))//2 > maximum or len(v.encode('utf-8')) > 4096:
36
+ raise ValueError('Clock text limit')
37
+ except UnicodeError as e: raise ValueError('Invalid clock unicode') from e
38
+ return v
39
+
40
+ def _hash(v):
41
+ if not isinstance(v,str) or (v and not re.fullmatch('[0-9a-f]{64}',v)):
42
+ raise ValueError('Invalid clock source hash')
43
+ return v
44
+
45
+ def _list(v, maximum):
46
+ if not isinstance(v,list) or len(v)>maximum: raise ValueError('Clock collection limit')
47
+ return v
48
+
49
+ def _keys(v, expected):
50
+ if not isinstance(v,dict) or set(v)!=set(expected): raise ValueError('Invalid clock record fields')
51
+
52
+ def _record(kind, value):
53
+ annotation=None
54
+ if kind=='Origin' and isinstance(value,dict):
55
+ value=dict(value);annotation=value.pop('annotationRasterSha256',value.get('rasterSha256',''))
56
+ fields=_SCHEMA[kind];_keys(value,[name for name,t in fields]);v={}
57
+ for name,t in fields:
58
+ x=value[name]
59
+ if t=='i': x=_i(x)
60
+ elif t=='l': x=_i(x,-9223372036854775808,9223372036854775807)
61
+ elif t=='f': x=_f(x)
62
+ elif t=='s':
63
+ x=_text(x,160 if name=='canonicalPart' else 256 if name in ('originalExit','voiceId','firstVoice','secondVoice','producerRoute','sourceRoute') else 1024)
64
+ if name.endswith('Sha256'): _hash(x)
65
+ elif t=='b':
66
+ if type(x) is not bool: raise ValueError('Invalid clock boolean')
67
+ elif t=='Li':
68
+ x=[_i(n,0,999999)for n in _list(x,128)]
69
+ if len(set(x))!=len(x): raise ValueError('Duplicate clock index')
70
+ elif t.startswith('E'):
71
+ if x not in _ENUMS[t[1:]] or not isinstance(x,str): raise ValueError('Invalid clock enum')
72
+ else:x=_record(t,x)
73
+ v[name]=x
74
+ if kind=='Origin':
75
+ _hash(annotation);v['annotationRasterSha256']=annotation
76
+ for n,lo,hi in [('physicalPageIndex',-1,9999),('physicalPageCount',0,10000),('width',0,20000000),('height',0,20000000)]:_i(v[n],lo,hi)
77
+ if (v['width']==0)!=(v['height']==0) or v['width']*v['height']>20000000 or (v['physicalPageCount']>0 and v['physicalPageIndex']>=v['physicalPageCount']):raise ValueError('Clock origin domain')
78
+ elif kind=='Box':
79
+ for n in ('left','top','right','bottom'):_f(v[n],0,1)
80
+ if v['left']>v['right'] or v['top']>v['bottom']:raise ValueError('Clock box order')
81
+ elif kind=='RasterBox':
82
+ if list(v.values())!=[-1,-1,-1,-1]:
83
+ for n in ('left','top','right','bottom'):_i(v[n],0,20000000)
84
+ if v['left']>v['right'] or v['top']>v['bottom']:raise ValueError('Clock raster box')
85
+ elif kind=='PartWord':
86
+ for n,lo,hi in [('ordinal',0,9999),('system',-1,9999),('firstMeasure',-1,10000),('measureAfterLast',-1,10000),('sampledMembers',0,1000000)]:_i(v[n],lo,hi)
87
+ if v['firstMeasure']>=0 and v['measureAfterLast']<=v['firstMeasure']:raise ValueError('Part span')
88
+ if v['status']=='SOURCE_PREMISE' and (v['role']!='PART_LABEL' or _blank(v['canonicalPart']) or not v['sampledMembers'] or not v['sampledSha256'] or v['bounds']['left']==v['bounds']['right'] or v['bounds']['top']==v['bounds']['bottom']):raise ValueError('Unbound part premise')
89
+ elif kind=='NumberRead':
90
+ for n,lo,hi in [('ordinal',0,19999),('system',-1,9999),('value',0,9999),('originCandidate',-10000,10000)]:_i(v[n],lo,hi)
91
+ elif kind=='MeterRead':
92
+ for n,lo,hi in [('ordinal',0,9999),('measure',-1,10000),('numerator',0,128),('denominator',0,128),('votes',0,10000),('sampledMembers',0,1000000)]:_i(v[n],lo,hi)
93
+ _f(v['firstLine'],-1,20000000);_f(v['gap'],0,20000000)
94
+ if v['status']=='SOURCE_PREMISE' and (not v['originalProducerAccepted'] or not v['numerator'] or not v['denominator'] or v['bounds']['left']<0 or not v['sampledMembers'] or not v['sampledSha256']):raise ValueError('Unbound meter premise')
95
+ elif kind in ('PrintedValue','RestValue','VoiceGroup'):
96
+ for n,lo,hi in [('measure',0,9999),('staff',0,127),('staffs',1,128)]:_i(v[n],lo,hi)
97
+ if v['staff']>=v['staffs']:raise ValueError('Clock staff')
98
+ if kind=='PrintedValue':
99
+ for n,lo,hi in [('noteIndex',0,999999),('dots',0,4),('beams',0,8),('admissionFlags',0,65535),('selectedMembers',0,1000000),('parentMembers',v['selectedMembers'],1000000),('parentLeaves',0,10000),('residualMembers',0,v['parentMembers'])]:_i(v[n],lo,hi)
100
+ _f(v['baseBeats'],0,32)
101
+ if v['status']=='SOURCE_PREMISE' and (not v['selectedMembers'] or not v['parentLeaves'] or v['residualMembers'] or not v['selectedSha256'] or not v['parentSha256']):raise ValueError('Unbound printed premise')
102
+ elif kind=='RestValue':_i(v['restIndex'],0,999999);_f(v['baseBeats'],0,64);_i(v['dots'],0,4)
103
+ else:
104
+ _i(v['ordinal'],0,999999)
105
+ bad_members=(bool(v['noteIndices']) or not v['restIndices'])if v['kind']=='REST' else (not v['noteIndices'] or bool(v['restIndices']))
106
+ if v['status']=='SOURCE_PREMISE' and (_blank(v['voiceId']) or not v['membersSha256'] or _blank(v['sourceRoute']) or bad_members):raise ValueError('Unbound voice premise')
107
+ elif kind=='GlyphLedger':
108
+ _i(v['measure'],-1,9999);_i(v['semanticLabel'],0,255)
109
+ for n in ('population','coveredUnique','noteMembers','nonRhythmicMembers','restMembers','unknownMembers'):_i(v[n],0,20000000)
110
+ assigned=v['noteMembers']+v['nonRhythmicMembers']+v['restMembers']
111
+ if v['coveredUnique']>v['population'] or assigned+v['unknownMembers']>v['coveredUnique']:raise ValueError('Clock accounting')
112
+ if v['status']=='SOURCE_PREMISE' and (v['coveredUnique']!=v['population'] or v['unknownMembers'] or assigned!=v['coveredUnique'] or not v['coverageSha256']):raise ValueError('Incomplete glyph premise')
113
+ elif kind=='SyncAnchor':
114
+ _i(v['measure'],0,9999);_i(v['firstThroughOrdinal'],0,999999);_i(v['secondThroughOrdinal'],0,999999)
115
+ if v['status']=='SOURCE_PREMISE' and v['firstVoice']==v['secondVoice']:raise ValueError('Self synchronization')
116
+ elif kind=='Missing':_i(v['measure'],-1,9999)
117
+ return v
118
+
119
+ def unavailable(note_count,measure_count,rest_count):
120
+ return dict(origin=dict(documentSha256='',physicalPageIndex=-1,physicalPageCount=0,width=0,height=0,rasterSha256='',labelsSha256=''),noteCount=note_count,measureCount=measure_count,restCount=rest_count,**{name:[]for name,_,_ in _LISTS if name!='missing'},missing=[dict(requirement=n,measure=-1)for n in _ENUMS['Requirement']if n!='CAPTURE_BUDGET'])
121
+
122
+ def checked(source,note_count,measure_count,rest_count):
123
+ _i(note_count,0,1000000);_i(measure_count,0,10000);_i(rest_count,0,1000000)
124
+ if source is None:source=unavailable(note_count,measure_count,rest_count)
125
+ _keys(source,['origin','noteCount','measureCount','restCount']+[name for name,_,_ in _LISTS])
126
+ if [source['noteCount'],source['measureCount'],source['restCount']]!=[note_count,measure_count,rest_count]:raise ValueError('Clock page counts')
127
+ for key,maximum in [('noteCount',1000000),('measureCount',10000),('restCount',1000000)]:_i(source[key],0,maximum)
128
+ value=dict(origin=_record('Origin',source['origin']),noteCount=note_count,measureCount=measure_count,restCount=rest_count)
129
+ for name,record,maximum in _LISTS:value[name]=[_record(record,row)for row in _list(source[name],maximum)]
130
+ if sum(len(value[name])for name,_,_ in _LISTS)>100000:raise ValueError('Clock fact budget')
131
+ for p in value['partWords']:
132
+ if (p['firstMeasure']>=0 and p['firstMeasure']>=measure_count)or p['measureAfterLast']>measure_count:raise ValueError('Part outside page')
133
+ for m in value['meters']:
134
+ if m['measure']>measure_count or (m['bounds']['left']>=0 and (value['origin']['width']==0 or m['bounds']['right']>=value['origin']['width'] or m['bounds']['bottom']>=value['origin']['height'])):raise ValueError('Meter outside source')
135
+ for name,idx,limit in [('printedValues','noteIndex',note_count),('restValues','restIndex',rest_count)]:
136
+ used=set()
137
+ for v in value[name]:
138
+ if v[idx]>=limit or v['measure']>=measure_count or v[idx]in used:raise ValueError('Clock value owner')
139
+ used.add(v[idx])
140
+ for v in value['glyphLedgers']:
141
+ if v['measure']>=measure_count:raise ValueError('Ledger outside page')
142
+ groups=set()
143
+ for g in value['voiceGroups']:
144
+ key=(g['measure'],g['voiceId'],g['ordinal'])
145
+ if g['measure']>=measure_count or key in groups or any(n>=note_count for n in g['noteIndices'])or any(n>=rest_count for n in g['restIndices']):raise ValueError('Voice group identity')
146
+ groups.add(key)
147
+ for v in value['syncAnchors']:
148
+ if v['measure']>=measure_count:raise ValueError('Sync outside page')
149
+ missing=set()
150
+ for v in value['missing']:
151
+ key=(v['requirement'],v['measure'])
152
+ if v['measure']>=measure_count or key in missing:raise ValueError('Missing source identity')
153
+ missing.add(key)
154
+ return value
155
+
156
+ def require_legacy_compatible(source,note_count,measure_count,rest_count):
157
+ value=checked(source,note_count,measure_count,rest_count)
158
+ if value!=checked(unavailable(note_count,measure_count,rest_count),note_count,measure_count,rest_count):raise ValueError('Legacy guide cannot preserve source clock context')
159
+
160
+ def bind_document(source,note_count,measure_count,rest_count,document_sha,page_index,page_count):
161
+ """Attach the actual held-document envelope without replacing producer raster hashes.
162
+
163
+ A legacy/unavailable page gains an origin observation, never voice or meter authority.
164
+ Conflicting existing provenance fails rather than being relabelled for another document.
165
+ """
166
+ value=checked(source,note_count,measure_count,rest_count)
167
+ _hash(document_sha);_i(page_index,0,9999);_i(page_count,1,10000)
168
+ if not document_sha or page_index>=page_count:raise ValueError('Unbound document origin')
169
+ origin=value['origin']
170
+ if (origin['documentSha256'] and origin['documentSha256']!=document_sha
171
+ or origin['physicalPageIndex']>=0 and origin['physicalPageIndex']!=page_index
172
+ or origin['physicalPageCount']>0 and origin['physicalPageCount']!=page_count):
173
+ raise ValueError('Foreign source document/page')
174
+ result=dict(value,origin=dict(origin,documentSha256=document_sha,
175
+ physicalPageIndex=page_index,physicalPageCount=page_count))
176
+ # DOCUMENT_ORIGIN remains missing without a genuine raster producer frame.
177
+ if origin['rasterSha256'] and origin['width'] and origin['height']:
178
+ result['missing']=[m for m in value['missing']if not(m['requirement']=='DOCUMENT_ORIGIN'and m['measure']==-1)]
179
+ return checked(result,note_count,measure_count,rest_count)
180
+
181
+ class _Writer:
182
+ def __init__(self):self.data=bytearray()
183
+ def put(self,b):
184
+ if len(b)>MAX_BYTES-len(self.data):raise ValueError('Clock frame budget')
185
+ self.data.extend(b)
186
+ def record(self,kind,value):
187
+ for name,t in _SCHEMA[kind]:
188
+ v=value[name]
189
+ if t in ('i','l','f'):self.put(struct.pack('>'+{'i':'i','l':'q','f':'f'}[t],v))
190
+ elif t=='s':
191
+ b=v.encode('utf-8');self.put(struct.pack('>i',len(b)));self.put(b)
192
+ elif t=='b':self.put(bytes([int(v)]))
193
+ elif t=='Li':
194
+ self.put(struct.pack('>i',len(v)))
195
+ for n in v:self.put(struct.pack('>i',n))
196
+ elif t.startswith('E'):self.put(bytes([_ENUMS[t[1:]].index(v)]))
197
+ else:self.record(t,v)
198
+
199
+ class _Reader:
200
+ def __init__(self,data):self.data=memoryview(data);self.at=0
201
+ def take(self,n):
202
+ if n<0 or n>len(self.data)-self.at:raise ValueError('Truncated clock context')
203
+ out=self.data[self.at:self.at+n];self.at+=n;return out
204
+ def scalar(self,t):return struct.unpack('>'+t,self.take(struct.calcsize('>'+t)))[0]
205
+ def count(self,maximum):
206
+ n=self.scalar('i')
207
+ if n<0 or n>maximum or n>len(self.data)-self.at:raise ValueError('Clock collection count')
208
+ return n
209
+ def record(self,kind):
210
+ value={}
211
+ for name,t in _SCHEMA[kind]:
212
+ if t in ('i','l','f'):v=self.scalar({'i':'i','l':'q','f':'f'}[t])
213
+ elif t=='s':
214
+ n=self.scalar('i')
215
+ if not 0<=n<=4096:raise ValueError('Clock text length')
216
+ try:v=bytes(self.take(n)).decode('utf-8','strict')
217
+ except UnicodeError as e:raise ValueError('Invalid clock unicode')from e
218
+ elif t=='b':
219
+ n=self.scalar('B')
220
+ if n>1:raise ValueError('Clock boolean')
221
+ v=bool(n)
222
+ elif t=='Li':v=[self.scalar('i')for _ in range(self.count(128))]
223
+ elif t.startswith('E'):
224
+ n=self.scalar('B');enum=_ENUMS[t[1:]]
225
+ if n>=len(enum):raise ValueError('Clock enum')
226
+ v=enum[n]
227
+ else:v=self.record(t)
228
+ value[name]=v
229
+ return value
230
+
231
+ def encode(source,note_count,measure_count,rest_count):
232
+ value=checked(source,note_count,measure_count,rest_count);out=_Writer();origin=value['origin'];schema=1 if origin['annotationRasterSha256']==origin['rasterSha256'] else 2
233
+ out.put(struct.pack('>iiii',schema,note_count,measure_count,rest_count));out.record('Origin',origin)
234
+ if schema==2:
235
+ annotation=origin['annotationRasterSha256'].encode('utf-8');out.put(struct.pack('>i',len(annotation)));out.put(annotation)
236
+ for name,record,_ in _LISTS:
237
+ rows=value[name];out.put(struct.pack('>i',len(rows)))
238
+ for row in rows:out.record(record,row)
239
+ return MAGIC+struct.pack('>i',len(out.data))+out.data
240
+
241
+ def decode(frame,note_count,measure_count,rest_count):
242
+ if not isinstance(frame,(bytes,bytearray))or not 88<=len(frame)<=MAX_BYTES+8 or frame[:4]!=MAGIC:raise ValueError('Clock frame header')
243
+ n=struct.unpack_from('>i',frame,4)[0]
244
+ if n!=len(frame)-8:raise ValueError('Clock frame length')
245
+ source=_Reader(frame[8:])
246
+ schema=source.scalar('i')
247
+ if schema not in (1,2):raise ValueError('Clock schema')
248
+ counts=[source.scalar('i')for _ in range(3)]
249
+ if counts!=[note_count,measure_count,rest_count]:raise ValueError('Clock page counts')
250
+ origin=source.record('Origin')
251
+ if schema==2:
252
+ n=source.scalar('i')
253
+ if not 0<=n<=4096:raise ValueError('Clock annotation hash length')
254
+ origin['annotationRasterSha256']=bytes(source.take(n)).decode('utf-8','strict')
255
+ value=dict(origin=origin,noteCount=counts[0],measureCount=counts[1],restCount=counts[2]);total=0
256
+ for name,record,maximum in _LISTS:
257
+ n=source.count(maximum);total+=n
258
+ if total>100000:raise ValueError('Clock fact budget')
259
+ value[name]=[source.record(record)for _ in range(n)]
260
+ if source.at!=len(source.data):raise ValueError('Trailing clock context')
261
+ return checked(value,note_count,measure_count,rest_count)
@@ -0,0 +1,89 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Continuous approach bends on the final emitted MIDI tempo clock."""
4
+ import bisect
5
+ import math
6
+
7
+
8
+ def _clock(tempo_events, ppq):
9
+ changes = [(0, 500000)]
10
+ for tick, _, data in sorted(tempo_events, key=lambda item: (item[0], item[1])):
11
+ if data[:3] != b'\xff\x51\x03':
12
+ continue
13
+ if type(tick) is not int or tick < 0 or len(data) != 6:
14
+ raise ValueError('Malformed final MIDI tempo event')
15
+ micros = int.from_bytes(data[3:], 'big')
16
+ if micros <= 0:
17
+ raise ValueError('Nonpositive final MIDI tempo')
18
+ if changes[-1][0] == tick:
19
+ changes[-1] = (tick, micros)
20
+ else:
21
+ changes.append((tick, micros))
22
+ ticks, times = [], []
23
+ seconds = 0.
24
+ for i, (tick, micros) in enumerate(changes):
25
+ if i:
26
+ seconds += (tick-changes[i-1][0])*changes[i-1][1]/(1_000_000*ppq)
27
+ ticks.append(tick)
28
+ times.append(seconds)
29
+
30
+ def seconds_at(tick):
31
+ i = bisect.bisect_right(ticks, tick)-1
32
+ return times[i]+(tick-ticks[i])*changes[i][1]/(1_000_000*ppq)
33
+
34
+ def tick_at(seconds):
35
+ i = bisect.bisect_right(times, seconds)-1
36
+ return ticks[i]+(seconds-times[i])*(1_000_000*ppq)/changes[i][1]
37
+
38
+ return seconds_at, tick_at, ticks
39
+
40
+
41
+ def gated_end(start, end, gate, tempo_events, ppq=480):
42
+ """APP gate scales elapsed frame/time duration, not written beat duration."""
43
+ if (type(start) is not int or type(end) is not int or start < 0 or end <= start
44
+ or type(ppq) is not int or ppq <= 0
45
+ or type(gate) not in (int, float) or gate not in (.28, .5, .75, 1.)):
46
+ raise ValueError('Invalid continuous slide articulation gate')
47
+ if gate == 1:
48
+ return end
49
+ seconds_at, tick_at, _ = _clock(tempo_events, ppq)
50
+ begin = seconds_at(start)
51
+ release = tick_at(begin+(seconds_at(end)-begin)*gate)
52
+ # Positive half-up rounding matches the APP frame gate, to MIDI tick resolution.
53
+ return min(end, max(start+1, math.floor(release+.5)))
54
+
55
+
56
+ def curve(start, end, source_midi, target_midi, tempo_events, ppq=480):
57
+ """Return RPN semitone range and (tick, 14-bit bend) samples, excluding note end.
58
+
59
+ Tempo events use the MIDI writer's exact (tick, priority, bytes) representation.
60
+ Equal-tick tempos retain stable writer order; the last controls following time.
61
+ """
62
+ if (type(start) is not int or type(end) is not int or start < 0 or end <= start
63
+ or type(ppq) is not int or ppq <= 0
64
+ or any(type(p) is not int or not 0 <= p <= 127 for p in (source_midi, target_midi))):
65
+ raise ValueError('Continuous slide requires finite MIDI endpoints and ticks')
66
+ seconds_at, tick_at, ticks = _clock(tempo_events, ppq)
67
+
68
+ begin = seconds_at(start)
69
+ duration = seconds_at(end)-begin
70
+ ramp = max(.001, min(.16, .3*duration))
71
+ delta = source_midi-target_midi
72
+ semitones = max(1, abs(delta))
73
+ finish = min(end-1, math.ceil(tick_at(begin+ramp)))
74
+ sample_ticks = {start, finish}
75
+ sample_ticks.update(min(finish, max(start, round(tick_at(begin+ramp*i/64)))) for i in range(65))
76
+ sample_ticks.update(tick for tick in ticks if start < tick <= finish)
77
+ samples = []
78
+ for tick in sorted(sample_ticks):
79
+ age = seconds_at(tick)-begin
80
+ t = min(1., max(0., age/ramp))
81
+ offset = delta*(1-t*t*(3-2*t))
82
+ scale = 8191 if offset >= 0 else 8192
83
+ bend = round(8192+offset/semitones*scale)
84
+ if not 0 <= bend <= 16383 or not math.isfinite(offset):
85
+ raise ValueError('Continuous slide bend exceeds declared RPN range')
86
+ samples.append((tick, bend))
87
+ if t == 1:
88
+ break
89
+ return semitones, samples
@@ -0,0 +1,54 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Exact source-column ownership for optically proved instrument/Play cue captions."""
4
+ import math
5
+ import struct
6
+ SOURCE = 'printed-cue-instruction'
7
+ INSTRUMENTS = {'guitar', 'piano', 'violin', 'viola', 'cello', 'flute', 'oboe', 'clarinet',
8
+ 'bassoon', 'trumpet', 'trombone', 'horn', 'bass', 'harp', 'organ', 'saxophone'}
9
+
10
+ def owns(mark):
11
+ evidence = mark.get('evidence', [])
12
+ if (mark.get('kind') != 'UNRESOLVED_DIRECTION' or mark.get('qualifierText', '')
13
+ or len(evidence) != 1 or not (mark.get('targetEventId') or '').startswith('expression-column:')):
14
+ return False
15
+ row = evidence[0]
16
+ text = row.get('printedText', '')
17
+ token = text.strip().lower().rstrip('.:') if type(text) is str else ''
18
+ return (row.get('sourceId') == SOURCE and token in INSTRUMENTS | {'play'}
19
+ and all(row.get(k) == mark.get(k) for k in ('staffIndex', 'staffCount')))
20
+
21
+ def members(mark, page):
22
+ if not owns(mark):
23
+ return []
24
+ try:
25
+ m, staff, count, bits = map(int, mark['targetEventId'][len('expression-column:'):].split(':'))
26
+ pos = struct.unpack('>f', struct.pack('>I', bits & 0xffffffff))[0]
27
+ except (ValueError, struct.error):
28
+ return []
29
+ if (m < 0 or not 0 <= staff < count <= 8 or not math.isfinite(pos) or not 0 <= pos <= 1
30
+ or staff != mark.get('staffIndex') or count != mark.get('staffCount')
31
+ or any(not -2147483648 <= v <= 2147483647 for v in (m, staff, count, bits))):
32
+ return []
33
+ notes = page.get('score', {}).get('notes', [])
34
+ events = page.get('events', [])
35
+ if len(notes) != len(events):
36
+ return []
37
+ result = []
38
+ for i, note in enumerate(notes):
39
+ p = note.get('positionInMeasure')
40
+ if (type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1
41
+ or note.get('measureIndex') != m or note.get('staffIndex') != staff):
42
+ continue
43
+ if struct.unpack('>f', struct.pack('>f', p))[0] != pos:
44
+ continue
45
+ event = events[i]
46
+ if (note.get('staffCount') != count or note.get('kind', 'PITCHED') != 'PITCHED'
47
+ or note.get('articulations', 0) & 32768
48
+ or type(event.get('sourceNoteIndex', i)) is not int
49
+ or event.get('sourceNoteIndex', i) != i
50
+ or any(type(note.get(k)) is not int or event.get(k) != note[k]
51
+ for k in ('measureIndex', 'staffIndex', 'staffCount'))):
52
+ return []
53
+ result.append(i)
54
+ return result