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,125 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Exact source-note ownership for printed natural-harmonic notation."""
4
+ import math
5
+ import struct
6
+
7
+ PREFIX = 'natural-harmonic-note-v1:'
8
+ SOURCE = 'printed-natural-harmonic'
9
+
10
+
11
+ def target(note):
12
+ """Canonical raw note identity; never a nearest note or chord-wide attachment."""
13
+ try:
14
+ m, staff, count, step = [note[k] for k in
15
+ ('measureIndex', 'staffIndex', 'staffCount', 'staffStep')]
16
+ x, y = note['positionInMeasure'], note['pageY']
17
+ if (any(type(v) is not int for v in (m, staff, count, step)) or m < 0
18
+ or not 0 <= staff < count or note.get('kind', 'PITCHED') != 'PITCHED'
19
+ or any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 1
20
+ for v in (x, y))):
21
+ return None
22
+ bits = lambda v: struct.pack('>f', v).hex()
23
+ return f'{PREFIX}{m}:{staff}:{count}:{bits(x)}:{step}:{bits(y)}'
24
+ except (KeyError, TypeError, ValueError, OverflowError, struct.error):
25
+ return None
26
+
27
+
28
+ def retained(page):
29
+ notes, events = page.get('score', {}).get('notes', []), page.get('events', [])
30
+ if len(notes) != len(events):
31
+ return frozenset()
32
+ owners = {}
33
+ for i, note in enumerate(notes):
34
+ key = target(note)
35
+ if key is not None:
36
+ owners[key] = i if key not in owners else None
37
+ result = set()
38
+ marks = page.get('score', {}).get('expressiveEvents', [])
39
+ owner_counts = {}
40
+ for mark in marks:
41
+ i = owner_index(mark, notes)
42
+ if i is not None:
43
+ owner_counts[i] = owner_counts.get(i, 0) + 1
44
+ for mark in marks:
45
+ if (mark.get('kind') != 'NATURAL_HARMONIC' or mark.get('scope') not in ('NOTE', 'UNRESOLVED')
46
+ or mark.get('end') is not None or not isinstance(mark.get('targetEventId'), str)):
47
+ continue
48
+ i = owners.get(mark['targetEventId'])
49
+ if i is None or owner_counts.get(i) != 1:
50
+ continue
51
+ note, event, anchor = notes[i], events[i], mark.get('start')
52
+ if (any(mark.get(k) != note[k] for k in ('staffIndex', 'staffCount'))
53
+ or event.get('kind', 'PITCHED') != 'PITCHED'
54
+ or type(event.get('sourceNoteIndex')) is not int or event['sourceNoteIndex'] != i
55
+ or any(event.get(k) != note[k] for k in ('measureIndex', 'staffIndex', 'staffCount'))
56
+ or event.get('durationFallback', False)
57
+ or (mark.get('scope') == 'NOTE' and (not isinstance(anchor, dict)
58
+ or type(anchor.get('measureIndex')) is not int
59
+ or anchor['measureIndex'] != note['measureIndex']))
60
+ or (mark.get('scope') == 'UNRESOLVED' and anchor is not None)
61
+ or not any(e.get('sourceId') == SOURCE
62
+ and all(e.get(k) == note[k] for k in ('staffIndex', 'staffCount'))
63
+ for e in mark.get('evidence', []))):
64
+ continue
65
+ beats, m = page.get('measureBeats', []), note['measureIndex']
66
+ start, duration = event.get('startBeat'), event.get('durationBeats')
67
+ if (m >= len(beats) or any(type(v) not in (int, float) or not math.isfinite(v) or v <= 0 for v in beats[:m+1])
68
+ or any(type(v) not in (int, float) or not math.isfinite(v) for v in (start, duration))
69
+ or duration <= 0):
70
+ continue
71
+ begin = sum(beats[:m])
72
+ if not begin <= start < begin + beats[m]:
73
+ continue
74
+ if mark.get('scope') == 'UNRESOLVED':
75
+ result.add(i)
76
+ continue
77
+ offset = anchor['quarterBeatOffset']
78
+ if not 0 <= offset < beats[m]:
79
+ continue
80
+ # The mark must name the exact final-attack tick used by the Java resolver.
81
+ if round(start * 10080) != round((begin + offset) * 10080):
82
+ continue
83
+ result.add(i)
84
+ return frozenset(result)
85
+
86
+ def owner_index(mark, notes):
87
+ """Mirror Java physical-owner validation before final-clock validation."""
88
+ if (mark.get('kind') != 'NATURAL_HARMONIC'
89
+ or mark.get('scope') not in ('NOTE', 'UNRESOLVED')
90
+ or mark.get('end') is not None
91
+ or not isinstance(mark.get('targetEventId'), str)):
92
+ return None
93
+ anchor = mark.get('start')
94
+ if mark['scope'] == 'NOTE':
95
+ if (not isinstance(anchor, dict) or type(anchor.get('measureIndex')) is not int
96
+ or type(anchor.get('quarterBeatOffset')) not in (int, float)):
97
+ return None
98
+ try:
99
+ if not math.isfinite(anchor['quarterBeatOffset']):
100
+ return None
101
+ except (OverflowError, TypeError, ValueError):
102
+ return None
103
+ elif anchor is not None:
104
+ return None
105
+ evidence = mark.get('evidence', [])
106
+ if not isinstance(evidence, list) or not any(
107
+ isinstance(e, dict) and e.get('sourceId') == SOURCE
108
+ and e.get('staffIndex') == mark.get('staffIndex')
109
+ and e.get('staffCount') == mark.get('staffCount') for e in evidence):
110
+ return None
111
+ matches = [i for i, note in enumerate(notes) if target(note) == mark['targetEventId']]
112
+ if len(matches) != 1:
113
+ return None
114
+ i = matches[0]
115
+ note = notes[i]
116
+ if (note.get('staffIndex') != mark.get('staffIndex')
117
+ or note.get('staffCount') != mark.get('staffCount')
118
+ or (anchor is not None and anchor['measureIndex'] != note.get('measureIndex'))):
119
+ return None
120
+ return i
121
+
122
+
123
+
124
+
125
+
@@ -0,0 +1,186 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Project decoded note events through the production Java route, without re-inference."""
4
+ import copy
5
+ import json
6
+ import math
7
+ import struct
8
+ import subprocess
9
+ import tempfile
10
+ import warnings
11
+ from bisect import bisect_left, bisect_right
12
+ from pathlib import Path
13
+ from .runtime import java_executable
14
+ from .semantic_wire import encode
15
+ from .typed_events import event_kind, validate_unpitched
16
+
17
+
18
+ def _bridge(data):
19
+ jar = Path(__file__).with_name('interpreter.jar')
20
+ if not jar.is_file():
21
+ raise RuntimeError('Build the Java interpreter before exporting navigation')
22
+ if len(data) > 64*1024*1024:
23
+ raise ValueError('Navigation request too large')
24
+ with tempfile.TemporaryDirectory(prefix='sheet-navigation-') as folder:
25
+ request, result = Path(folder)/'request.nav', Path(folder)/'route.json'
26
+ request.write_bytes(data)
27
+ run = subprocess.run([java_executable(), '-Xmx512m', '-cp', str(jar),
28
+ 'io.github.luckolite.interpreter.NavigationBridge', str(request), str(result)],
29
+ capture_output=True, text=True, encoding='utf-8', timeout=60)
30
+ if run.returncode:
31
+ raise ValueError('Navigation engine rejected decoded input: '+run.stderr.strip())
32
+ return json.loads(result.read_text(encoding='utf-8'))
33
+
34
+
35
+ def _route(beats, directions):
36
+ data = struct.pack('>ii', 0x4e415631, len(beats))
37
+ data += b''.join(struct.pack('>f', value) for value in beats)
38
+ return _bridge(data+encode(directions, [], len(beats)))
39
+
40
+
41
+ def project_navigation(document, bpm=120):
42
+ pages=document['pages']
43
+ for page in pages:
44
+ for note in page['events']:
45
+ validate_unpitched(note)
46
+ if not any(page.get('score', {}).get('playbackDirections') for page in pages):
47
+ return document
48
+ if len(pages)<=1:
49
+ return _project_one(document,bpm)
50
+ data=struct.pack('>ii',0x4e415031,len(pages))
51
+ for page in pages:
52
+ data+=struct.pack('>ii',len(page['measureBeats']),page.get('score',{}).get('firstMeasureNumber',0))
53
+ ranges=_bridge(data)
54
+ output,diagnostics,occurrences=[],[],[]
55
+ for index, part in enumerate(ranges):
56
+ first,last=part['firstPage'],part['pageAfterLast']
57
+ played=_project_one(dict(document,pages=pages[first:last]),bpm,first)
58
+ output.extend(played['pages']);diagnostics.extend(played.get('navigationDiagnostics',[]))
59
+ occurrences.extend(dict(occurrence,arrangementIndex=index,sourceFirstPage=first)
60
+ for occurrence in played.get('navigationOccurrences',[]))
61
+ return dict(document,pages=output,navigationDiagnostics=diagnostics,navigationOccurrences=occurrences)
62
+
63
+
64
+ def _project_one(document, bpm=120, source_page_offset=0):
65
+ pages = document['pages']
66
+ if not any(page.get('score', {}).get('playbackDirections') for page in pages):
67
+ return document # Linear MIDI export still needs no Java process or inference imports.
68
+ beats, directions, notes, tempos = [], [], [], []
69
+ offset = 0.0
70
+ for page_index, page in enumerate(pages):
71
+ local = list(page['measureBeats']); starts = [0.0]
72
+ for value in local:
73
+ if not isinstance(value, (int, float)) or not math.isfinite(value) or not .125 <= value <= 128:
74
+ raise ValueError('Invalid decoded measure duration')
75
+ starts.append(starts[-1]+value)
76
+ if not math.isclose(starts[-1], page['totalBeats'], abs_tol=1e-6):
77
+ raise ValueError('Decoded page extent disagrees with its measures')
78
+ for direction in page.get('score', {}).get('playbackDirections', []):
79
+ row = copy.deepcopy(direction); row['measureBoundary'] += len(beats)
80
+ if row.get('details', {}).get('end') is not None:
81
+ row['details']['end']['measureIndex'] += len(beats)
82
+ directions.append(row)
83
+ for index, note in enumerate(page['events']):
84
+ validate_unpitched(note)
85
+ physical_page=page.get('sourcePage',page_index+source_page_offset)
86
+ row = dict(note, startBeat=offset+note['startBeat'], sourceEventId=f'note:{physical_page}:{index}')
87
+ if (not math.isfinite(row['startBeat']) or not math.isfinite(row['durationBeats'])
88
+ or row['durationBeats'] <= 0 or row['startBeat'] < offset
89
+ or row['startBeat'] >= offset+starts[-1]):
90
+ raise ValueError('Invalid decoded note span')
91
+ notes.append(row)
92
+ for change in page.get('score', {}).get('tempoChanges', []):
93
+ m = change['measureIndex']; position = change['positionInMeasure']
94
+ if not 0 <= m < len(local) or not math.isfinite(position) or not 0 <= position <= 1:
95
+ raise ValueError('Invalid decoded tempo anchor')
96
+ if not math.isfinite(change['bpm']) or not 15 <= change['bpm'] <= 1600:
97
+ raise ValueError('Invalid decoded tempo')
98
+ tempos.append((offset+starts[m]+local[m]*position, change['bpm']))
99
+ beats.extend(local); offset += starts[-1]
100
+ starts = [0.0]
101
+ for value in beats: starts.append(starts[-1]+value)
102
+ # Traversal occurrences cover at most one source bar. Index overlapping note
103
+ # spans once instead of scanning an entire document for every repeated bar.
104
+ note_buckets=[[] for _ in beats]
105
+ entries=0
106
+ for note in notes:
107
+ first=max(0,bisect_right(starts,note['startBeat'])-1)
108
+ last=min(len(beats),bisect_left(starts,note['startBeat']+note['durationBeats']))
109
+ entries+=max(0,last-first)
110
+ if entries>1000000:
111
+ raise ValueError('Decoded sustain spans exceed bounded export capacity')
112
+ for measure in range(first,last):note_buckets[measure].append(note)
113
+ route = _route(beats, directions)
114
+ if not route['complete']:
115
+ raise ValueError('Navigation traversal is incomplete: '+str(route['diagnostics']))
116
+ if route['diagnostics']:
117
+ raise ValueError('Navigation performance is unresolved: '+str(route['diagnostics']))
118
+ tempos.sort(key=lambda item: item[0])
119
+ output_notes, output_tempos, spans = [], [], []
120
+ prior_end = None
121
+ run_predecessors = {}
122
+ unpitched_visits = {}
123
+ run_visit = None
124
+ slide_run_visit = None
125
+ for occurrence in route['occurrences']:
126
+ first, last = occurrence['start'], occurrence['end']
127
+ source_start = starts[first['measureIndex']]+first['quarterBeatOffset']
128
+ source_end = starts[last['measureIndex']]+last['quarterBeatOffset']
129
+ performed = occurrence['performanceStartBeat']; span = source_end-source_start
130
+ index = len(spans); spans.append(span)
131
+ if prior_end is None or prior_end != source_start:
132
+ slide_run_visit = occurrence['occurrenceId']
133
+ contiguous = prior_end is not None and math.isclose(prior_end, source_start, abs_tol=1e-8)
134
+ if not contiguous:
135
+ run_predecessors.clear()
136
+ unpitched_visits.clear()
137
+ run_visit = occurrence["occurrenceId"]
138
+ for note in sorted(note_buckets[first['measureIndex']], key=lambda row: row['startBeat']):
139
+ onset, finish = note['startBeat'], note['startBeat']+note['durationBeats']
140
+ a, b = max(onset, source_start), min(finish, source_end)
141
+ if b <= a: continue
142
+ if event_kind(note) == 'UNPITCHED':
143
+ owner = note['sourceEventId'] + '@' + str(run_visit)
144
+ previous_end = unpitched_visits.get(owner)
145
+ continuation = contiguous and previous_end is not None and math.isclose(previous_end, a, abs_tol=1e-8)
146
+ output_notes.append(dict(note, measureIndex=index, startBeat=performed+a-source_start,
147
+ durationBeats=b-a, tiedFromPrevious=False, boundaryTies=0,
148
+ occurrenceId=occurrence['occurrenceId'], _unpitchedAttackId=owner,
149
+ _unpitchedContinuation=continuation, clippedEntry=onset < a))
150
+ unpitched_visits[owner] = b
151
+ continue
152
+ tied = bool(note['tiedFromPrevious'])
153
+ if onset < source_start: tied = contiguous
154
+ elif tied:
155
+ # A jump can land just before a jittered tied onset. Its old
156
+ # predecessor may have been skipped, even when a same-pitch
157
+ # performed note happens to end nearby. Only source notes
158
+ # already visited in this contiguous run can own that tie.
159
+ lanes = [(note['staffCount'], note['staffIndex'], note['midi'])]
160
+ if note['staffIndex'] == 0 and note['staffCount'] in (1, 2):
161
+ lanes.append((3-note['staffCount'], 0, note['midi']))
162
+ tied = any(run_predecessors.get(lane, float('inf')) < onset for lane in lanes)
163
+ output_notes.append(dict(note, measureIndex=index, startBeat=performed+a-source_start,
164
+ durationBeats=b-a, tiedFromPrevious=tied, boundaryTies=0,
165
+ occurrenceId=occurrence['occurrenceId']))
166
+ if note.get('_slideOrigins'):
167
+ output_notes[-1]['_slideContext'] = dict(
168
+ visitId=f'navigation:{source_page_offset}:{slide_run_visit}',
169
+ attack=onset == a and not note.get('tiedFromPrevious', False),
170
+ clippedEntry=onset < a, clippedRelease=b < finish)
171
+ lane = (note['staffCount'], note['staffIndex'], note['midi'])
172
+ run_predecessors[lane] = min(onset, run_predecessors.get(lane, onset))
173
+ current = bpm
174
+ for at, value in tempos:
175
+ if at <= source_start: current = value
176
+ else: break
177
+ if not contiguous or not output_tempos:
178
+ output_tempos.append(dict(measureIndex=index, positionInMeasure=0, bpm=current))
179
+ for at, value in tempos:
180
+ if source_start < at < source_end or contiguous and at == source_start:
181
+ output_tempos.append(dict(measureIndex=index, positionInMeasure=(at-source_start)/span, bpm=value))
182
+ prior_end = source_end
183
+ total = route['occurrences'][-1]['performanceEndBeat'] if spans else 0
184
+ return dict(document, navigationDiagnostics=route['diagnostics'], navigationOccurrences=route['occurrences'],
185
+ pages=[dict(events=output_notes, measureBeats=spans, totalBeats=total,
186
+ score=dict(tempoChanges=output_tempos))])
@@ -0,0 +1,58 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Literal pedal captions own an existing full silent column, never a pedal action."""
4
+ import math
5
+ import re
6
+ import struct
7
+
8
+ from .rest_kinds import rest_kind, full_measure_span
9
+
10
+ PREFIX = 'expression-rest-column:'
11
+ CAPTION = re.compile(r'\s*let\s+(?:the\s+)?pedal\s+ring[.!]?\s*', re.IGNORECASE | re.ASCII)
12
+
13
+
14
+ def is_caption(mark):
15
+ if mark.get('kind') != 'UNRESOLVED_DIRECTION' or not isinstance(mark.get('targetEventId'), str) \
16
+ or not mark['targetEventId'].startswith(PREFIX):
17
+ return False
18
+ evidence = mark.get('evidence', [])
19
+ return bool(evidence) and all(e.get('sourceId') == 'printed-expression-word'
20
+ and isinstance(e.get('printedText'), str)
21
+ and CAPTION.fullmatch(e['printedText']) is not None for e in evidence)
22
+
23
+
24
+ def start(mark, page):
25
+ """Resolve only the original unique full-rest identity in its measured part."""
26
+ if not is_caption(mark):
27
+ return None
28
+ if type(mark.get('staffIndex')) is not int or type(mark.get('staffCount')) is not int:
29
+ return None
30
+ try:
31
+ fields = mark['targetEventId'][len(PREFIX):].split(':')
32
+ if len(fields) != 4 or any(re.fullmatch(r'-?\d+', f, flags=re.ASCII) is None for f in fields):
33
+ return None
34
+ m, staff, count, bits = map(int, fields)
35
+ if any(not -2147483648 <= n <= 2147483647 for n in (m, staff, count, bits)):
36
+ return None
37
+ position = struct.unpack('>f', struct.pack('>i', bits))[0]
38
+ except (ValueError, struct.error):
39
+ return None
40
+ if m < 0 or count < 1 or not 0 <= staff < count or not math.isfinite(position) \
41
+ or not 0 <= position <= 1 or staff != mark.get('staffIndex') or count != mark.get('staffCount'):
42
+ return None
43
+ if any(e.get('staffIndex') != staff or e.get('staffCount') != count
44
+ for e in mark['evidence']):
45
+ return None
46
+ belongs = lambda row: row.get('measureIndex') == m and row.get('staffIndex') == staff \
47
+ and row.get('staffCount') == count
48
+ score = page.get('score', {})
49
+ rows = [r for r in score.get('rests', []) if belongs(r)]
50
+ if len(rows) != 1 or rest_kind(rows[0]) != 'FULL_MEASURE' \
51
+ or not math.isfinite(rows[0].get('positionInMeasure', math.nan)) \
52
+ or abs(rows[0]['positionInMeasure'] - position) > .018:
53
+ return None
54
+ if any(belongs(n) for n in score.get('notes', [])):
55
+ return None
56
+ # The ordinary full-rest resolver retains the real inherited/pickup measure span.
57
+ full_measure_span(page, rows[0])
58
+ return dict(measureIndex=m, quarterBeatOffset=0)
@@ -0,0 +1,103 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Bundled, offline OCR for raster score text and scanned tablature frets."""
4
+
5
+ import numpy as np
6
+ import re
7
+
8
+
9
+ def measure_numbers(words):
10
+ """Offer isolated numbers; the decoder validates system placement and sequence."""
11
+ result = []
12
+ for word in words:
13
+ value = str(word.get("text", "")).strip()
14
+ if not value.isascii() or not value.isdigit() or not 1 <= len(value) <= 4:
15
+ continue
16
+ number = int(value)
17
+ if 1 <= number <= 9999:
18
+ result.append(dict(value=number, left=word["left"], top=word["top"],
19
+ right=word["right"], bottom=word["bottom"]))
20
+ return result
21
+
22
+
23
+ def tempo_numbers(words):
24
+ """Bound BPM digits within an OCR line; the Java decoder verifies the equals glyph."""
25
+ result = []
26
+ for word in words:
27
+ value = str(word.get("text", ""))
28
+ # OCR can join the adjacent chord symbol to the tempo direction.
29
+ # Keep the BPM box separate; arbitrary trailing prose remains rejected.
30
+ match = re.search(r"=\s*(\d{2,3})\s*[)\]]?(?:\s+[A-G][#b♯♭]?(?:(?:maj|min|dim|aug|sus|add|m|M|Δ|∆|ø|°)?[0-9#b♯♭+\-]*)?(?:/[A-G][#b♯♭]?)?)?\s*$", value)
31
+ if not match:
32
+ continue
33
+ bpm = int(match.group(1))
34
+ if bpm < 30 or bpm > 400:
35
+ continue
36
+ width = word["right"] - word["left"]
37
+ if width <= 0 or not value:
38
+ continue
39
+ left = word["left"] + width * match.start(1) / len(value)
40
+ result.append(dict(value=bpm, left=left, top=word["top"],
41
+ right=word["left"] + width * match.end(1) / len(value), bottom=word["bottom"],
42
+ annotationLeft=word["left"]))
43
+ return result
44
+
45
+
46
+ def rest_count_numbers(words):
47
+ """Offer isolated numerals to the decoder's multi-measure-rest geometry check."""
48
+ result = []
49
+ for word in words:
50
+ value = str(word.get("text", "")).strip()
51
+ if not value.isascii() or not value.isdigit():
52
+ continue
53
+ count = int(value)
54
+ if 2 <= count <= 32:
55
+ result.append(dict(value=count, left=word["left"], top=word["top"],
56
+ right=word["right"], bottom=word["bottom"]))
57
+ return result
58
+
59
+
60
+ def page_annotations(words, tab_words):
61
+ """Keep musical OCR separate from native PDF tablature annotations."""
62
+ return {"words": list(words), "tabWords": list(tab_words),
63
+ "measureNumbers": measure_numbers(words), "tempoNumbers": tempo_numbers(words),
64
+ "restCounts": rest_count_numbers(words)}
65
+
66
+
67
+ class LocalOcr:
68
+ def __init__(self):
69
+ try:
70
+ from rapidocr import RapidOCR
71
+ except ImportError as error:
72
+ raise RuntimeError(
73
+ "Install the inference extra for built-in OCR: "
74
+ "pip install 'score-reader[inference]'"
75
+ ) from error
76
+ self.engine = RapidOCR()
77
+
78
+ def words(self, gray):
79
+ """Return decoder words in normalized page coordinates."""
80
+ if not isinstance(gray, np.ndarray) or gray.ndim != 2 or gray.dtype != np.uint8:
81
+ raise ValueError("OCR expects a 2D uint8 grayscale page")
82
+ height, width = gray.shape
83
+ result = self.engine(gray)
84
+ if result.boxes is None or result.txts is None:
85
+ return []
86
+ words = []
87
+ scores = result.scores if result.scores is not None else [1.0] * len(result.txts)
88
+ for box, value, score in zip(result.boxes, result.txts, scores):
89
+ value = value.strip()
90
+ # A tab string crossing a fret can be read as a leading minus sign.
91
+ # Negative frets do not exist, so retain the printed digit evidence.
92
+ numeric = value.strip("-–—")
93
+ if numeric.isdigit():
94
+ value = numeric
95
+ if score < .5 or not value or len(value.encode("utf-8")) > 10000:
96
+ continue
97
+ left = max(0.0, min(1.0, float(np.min(box[:, 0])) / width))
98
+ right = max(0.0, min(1.0, float(np.max(box[:, 0])) / width))
99
+ top = max(0.0, min(1.0, float(np.min(box[:, 1])) / height))
100
+ bottom = max(0.0, min(1.0, float(np.max(box[:, 1])) / height))
101
+ if left < right and top < bottom:
102
+ words.append(dict(text=value, left=left, top=top, right=right, bottom=bottom))
103
+ return words[:10000]
@@ -0,0 +1,94 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Staff-owned octave directions; pitches remain the supplied sounding pitches."""
4
+ from collections import defaultdict
5
+
6
+
7
+ def _lane(notes):
8
+ edges = defaultdict(lambda: [0] * 5)
9
+ for n in notes:
10
+ shift = 0 if n.get('kind', 'PITCHED') == 'UNPITCHED' else n.get('octaveShift', 0)
11
+ if type(shift) is not int or not -2 <= shift <= 2:
12
+ raise ValueError('Invalid retained octave shift')
13
+ if n.get('grace', False):
14
+ continue
15
+ edges[n['start']][shift + 2] += 1
16
+ edges[n['end']][shift + 2] -= 1
17
+ active = [0] * 5
18
+ previous = None
19
+ spans = []
20
+ for at in sorted(edges):
21
+ if previous is not None and at > previous:
22
+ shifts = [i - 2 for i, count in enumerate(active) if count]
23
+ if len(shifts) > 1:
24
+ raise ValueError('Conflicting simultaneous staff octave shifts')
25
+ if shifts and shifts[0]:
26
+ shift = shifts[0]
27
+ if spans and spans[-1][1] == previous and spans[-1][2] == shift:
28
+ spans[-1] = spans[-1][0], at, shift
29
+ else:
30
+ spans.append((previous, at, shift))
31
+ active = [x + y for x, y in zip(active, edges[at])]
32
+ previous = at
33
+ for n in notes:
34
+ if n.get('grace', False):
35
+ shift = 0 if n.get('kind', 'PITCHED') == 'UNPITCHED' else n.get('octaveShift', 0)
36
+ found = {s for a, b, s in spans if a <= n['start'] <= b}
37
+ if (not shift and found) or (shift and found != {shift}):
38
+ raise ValueError('Grace octave direction lacks an unambiguous principal span')
39
+ return spans
40
+
41
+
42
+ def plan(notes):
43
+ spans = [(a, b, shift, voice) for voice in sorted({n['voice'] for n in notes})
44
+ for a, b, shift in _lane([n for n in notes if n['voice'] == voice])]
45
+ active = []
46
+ result = []
47
+ for a, b, shift, voice in sorted(spans):
48
+ active = [(end, number) for end, number in active if end > a]
49
+ number = next((v for v in range(1, 17) if v not in {n for _, n in active}), None)
50
+ if number is None:
51
+ raise ValueError('Too many overlapping octave directions')
52
+ active.append((b, number))
53
+ result.append((a, b, shift, voice, number))
54
+ return result
55
+
56
+
57
+ def apply(root, owned):
58
+ import xml.etree.ElementTree as ET
59
+ for part in root.findall('part'):
60
+ notes = list(part.findall('.//note'))
61
+ parents = {child: parent for parent in part.iter() for child in parent}
62
+ last = {n.findtext('voice', '1'): n for n in notes}
63
+ active, used = {}, set()
64
+ numbers = {}
65
+ for n in notes:
66
+ if owned.get(n, 0):
67
+ numbers.setdefault(n.findtext('voice', '1'), len(numbers) + 1)
68
+ if len(numbers) > 16:
69
+ raise ValueError('Too many octave direction voices')
70
+ def direction(note, entry, stop, after=False):
71
+ shift, staff, number = entry
72
+ d = ET.Element('direction', placement='above' if shift > 0 else 'below')
73
+ t = ET.SubElement(d, 'direction-type')
74
+ ET.SubElement(t, 'octave-shift', type='stop' if stop else 'down' if shift > 0 else 'up', size=str(7*abs(shift)+1), number=str(number))
75
+ ET.SubElement(d, 'voice').text = note.findtext('voice', '1')
76
+ if staff is not None:
77
+ ET.SubElement(d, 'staff').text = staff
78
+ parent = parents[note]
79
+ parent.insert(list(parent).index(note) + int(after), d)
80
+ for note in notes:
81
+ voice, staff = note.findtext('voice', '1'), note.findtext('staff')
82
+ shift = owned.get(note, 0)
83
+ if type(shift) is not int or not -2 <= shift <= 2:
84
+ raise ValueError('Invalid retained octave shift')
85
+ old = active.get(voice)
86
+ if old is not None and (old[0] != shift or old[1] != staff):
87
+ direction(note, old, True); used.remove(old[2]); del active[voice]
88
+ if shift and voice not in active:
89
+ number = numbers[voice]
90
+ active[voice] = shift, staff, number
91
+ direction(note, active[voice], False); used.add(number)
92
+ if last[voice] is note and voice in active:
93
+ old = active.pop(voice)
94
+ direction(note, old, True, after=True); used.remove(old[2])
@@ -0,0 +1,53 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Written ornament glyphs from proved source heads, never performed subdivisions."""
4
+ import xml.etree.ElementTree as ET
5
+ from .articulation_export import source_flags
6
+ from .typed_events import event_kind
7
+
8
+ TYPES = {1: 'trill-mark', 2: 'turn', 3: 'inverted-turn',
9
+ 4: 'inverted-mordent', 5: 'mordent'}
10
+ MASK = (7 << 5) | (1 << 8) | (3 << 9) | (3 << 11) | (1 << 13) | (1 << 14) | (7 << 16)
11
+
12
+
13
+ def retained(page, index):
14
+ flags = source_flags(page, index) & MASK
15
+ kind, beams = (flags >> 5) & 7, (flags >> 16) & 7
16
+ isolated = kind == 6 and not flags & (1 << 14)
17
+ if kind not in TYPES and not isolated and not 1 <= beams <= 4:
18
+ return 0
19
+ if event_kind(page['events'][index]) != 'PITCHED':
20
+ if isolated and not 1 <= beams <= 4:
21
+ return 0
22
+ raise ValueError('Unpitched source ornaments need explicit instrument semantics')
23
+ return flags
24
+
25
+
26
+ def write(notation, flags):
27
+ kind = (flags >> 5) & 7
28
+ glyph = TYPES.get(kind)
29
+ beams = (flags >> 16) & 7
30
+ beams = beams if 1 <= beams <= 4 else 0
31
+ if kind == 6 and not flags & (1 << 14):
32
+ articulations = notation.find('articulations')
33
+ if articulations is None:
34
+ articulations = ET.SubElement(notation, 'articulations')
35
+ approach = ET.SubElement(articulations, 'plop' if flags & (1 << 13) else 'scoop')
36
+ # Bit8 is shape only for an isolated SLIDE; TURN keeps its delayed meaning.
37
+ if flags & (1 << 8):
38
+ approach.set('line-shape', 'straight')
39
+ if glyph is None and not beams:
40
+ return
41
+ ornaments = ET.SubElement(notation, 'ornaments')
42
+ if glyph is not None:
43
+ if flags & (1 << 8) and kind in (2, 3):
44
+ glyph = 'delayed-turn' if kind == 2 else 'delayed-inverted-turn'
45
+ ET.SubElement(ornaments, glyph)
46
+ if glyph is not None:
47
+ for shift, side in ((9, 'above'), (11, 'below')):
48
+ accidental = (flags >> shift) & 3
49
+ if accidental:
50
+ ET.SubElement(ornaments, 'accidental-mark', placement=side).text = (
51
+ 'flat', 'natural', 'sharp')[accidental-1]
52
+ if beams:
53
+ ET.SubElement(ornaments, 'tremolo', type='single').text = str(beams)
@@ -0,0 +1,17 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Bound native decoding time by the accepted analysis raster workload."""
4
+
5
+
6
+ def decoder_timeout_seconds(width, height):
7
+ """Keep ordinary pages at six minutes; allow up to ten for larger rasters.
8
+
9
+ The decoder accepts at most twenty million pixels. Additional time preserves
10
+ the same resolution, model tiles and musical OCR passes on taller pages.
11
+ This remains a hard deadline, rather than extending an unresponsive process.
12
+ """
13
+ if (type(width) is not int or type(height) is not int
14
+ or width < 1 or height < 1 or width * height > 20_000_000):
15
+ raise ValueError("Invalid decoder raster dimensions")
16
+ extra_pixels = max(0, width * height - 8_000_000)
17
+ return 360 + (extra_pixels + 49_999) // 50_000