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,76 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Strict original-head bindings for connected straight slides; clocks stay written."""
4
+ import math
5
+ import struct
6
+
7
+ def _f(value):
8
+ return struct.unpack('!f', struct.pack('!f', value))[0]
9
+
10
+ def _part(n):
11
+ return n.get('staffIndex'), n.get('staffCount'), n.get('clefBottomDiatonic')
12
+
13
+ def _previous(notes, target):
14
+ t = notes[target]
15
+ candidates = []
16
+ for i, n in enumerate(notes):
17
+ x = n.get('positionInMeasure')
18
+ if _part(n) != _part(t) or type(x) not in (int, float) or not math.isfinite(x):
19
+ continue
20
+ if (n['measureIndex'] == t['measureIndex'] and _f(x) < _f(_f(t['positionInMeasure'])-_f(.001))
21
+ or t['measureIndex'] > 0 and n['measureIndex'] == t['measureIndex']-1):
22
+ candidates.append(i)
23
+ if not candidates:
24
+ return None
25
+ latest = max(candidates, key=lambda i: (notes[i]['measureIndex'], _f(notes[i]['positionInMeasure'])))
26
+ n = notes[latest]
27
+ if any(i != latest and _part(c) == _part(t) and c['measureIndex'] == n['measureIndex']
28
+ and abs(_f(_f(c['positionInMeasure'])-_f(n['positionInMeasure']))) < _f(.001)
29
+ for i, c in enumerate(notes)):
30
+ return None
31
+ if n['measureIndex'] != t['measureIndex'] and (t.get('leadingRestBeats', 0) > 0 or n.get('followingRestBeats', 0) > 0):
32
+ return None
33
+ return latest
34
+
35
+ def bindings(page):
36
+ """Return source/target/number triples; reject explicit stale or ambiguous relations."""
37
+ events = page['events']
38
+ explicit = [i for i, e in enumerate(events) if 'slide' in e]
39
+ if not explicit:
40
+ return []
41
+ notes = page.get('score', {}).get('notes')
42
+ def require(ok):
43
+ if not ok:
44
+ raise ValueError('Invalid continuous slide original-head relation')
45
+ require(isinstance(notes, list) and len(notes) == len(events))
46
+ for i, (n, e) in enumerate(zip(notes, events)):
47
+ require(isinstance(n, dict) and isinstance(e, dict))
48
+ require(all(type(n.get(k)) is int for k in ('measureIndex', 'staffIndex', 'staffCount', 'clefBottomDiatonic', 'articulations')))
49
+ require(type(n.get('positionInMeasure')) in (int, float) and math.isfinite(n['positionInMeasure']) and 0 <= n['positionInMeasure'] <= 1)
50
+ require(type(e.get('sourceNoteIndex', i)) is int and e.get('sourceNoteIndex', i) == i)
51
+ require(all(type(e.get(k)) is int and e[k] == n.get(k) for k in ('measureIndex', 'staffIndex', 'staffCount')))
52
+ result = []
53
+ for target in explicit:
54
+ e = events[target]; relation = e['slide']
55
+ require(isinstance(relation, dict) and set(relation) == {'style', 'sourceNoteIndex', 'sourceMidi'} and relation['style'] == 'continuous')
56
+ source = relation['sourceNoteIndex']
57
+ require(type(source) is int and 0 <= source < len(notes) and source != target)
58
+ require(type(relation['sourceMidi']) is int and 0 <= relation['sourceMidi'] <= 127)
59
+ flags = notes[target].get('articulations', 0)
60
+ require(flags & 224 == 192 and flags & 16384 and _previous(notes, target) == source)
61
+ require(_part(notes[source]) == _part(notes[target]))
62
+ for i in (source, target):
63
+ n, event = notes[i], events[i]
64
+ require(n.get('kind', 'PITCHED') == 'PITCHED' and event.get('kind', 'PITCHED') == 'PITCHED'
65
+ and not n.get('articulations', 0) & 32768 and n.get('clefBottomDiatonic', -1) != -1
66
+ and not event.get('clefInferred') and event.get('durationFallback') is False
67
+ and 'glissando' not in event and 'guitarEffect' not in event)
68
+ require(type(event.get('midi')) is int and 0 <= event['midi'] <= 127)
69
+ require(all(type(event.get(k)) in (int, float) and math.isfinite(event[k]) for k in ('startBeat', 'durationBeats')))
70
+ require(event['startBeat'] >= 0 and event['durationBeats'] > 0)
71
+ require(events[source]['midi'] == relation['sourceMidi'])
72
+ end = events[source]['startBeat'] + events[source]['durationBeats']; start = e['startBeat']
73
+ require(abs(end-start) <= 8*max(math.ulp(end), math.ulp(start)))
74
+ result.append((source, target, target+1))
75
+ require(len({s for s, _, _ in result}) == len(result))
76
+ return result
@@ -0,0 +1,47 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Complete sudden labels paired through existing exported source ownership."""
4
+ import re
5
+ LEVEL=r'(ppp|pp|p|mp|mf|fff|ff|f)'
6
+ PREFIX=re.compile(r'^(subito\.?|sub\.?)\s*'+LEVEL+r'[.,:;]?$',re.I)
7
+ SUFFIX=re.compile(r'^'+LEVEL+r'\s+(subito\.?|sub\.?)[,:;]?$',re.I)
8
+
9
+ def parse(text):
10
+ if not isinstance(text,str):return None
11
+ text=text.strip();p=PREFIX.fullmatch(text)
12
+ if p:return dict(level=p[2].lower(),qualifier=p[1],before=True)
13
+ p=SUFFIX.fullmatch(text)
14
+ return dict(level=p[1].lower(),qualifier=p[2],before=False)if p else None
15
+
16
+ def combine(marks):
17
+ plans={};blocked=set()
18
+ for d in marks:
19
+ if not d.get('_absoluteDynamic') or not d.get('ownerIds'):continue
20
+ candidates=[]
21
+ for e in marks:
22
+ if (e.get('_absoluteDynamic') or e.get('kind')!='UNRESOLVED_DIRECTION'
23
+ or e.get('scope')not in ('PART','UNRESOLVED')
24
+ or e.get('staffIndex')!=d.get('staffIndex') or e.get('staffCount')!=d.get('staffCount')
25
+ or not(e.get('targetEventId')or'').startswith('expression-column:')
26
+ or set(e.get('ownerIds',[]))!=set(d['ownerIds'])):continue
27
+ texts=[]
28
+ for v in e.get('evidence',[]):
29
+ if (v.get('sourceId')!='printed-expression-word' or v.get('staffIndex')!=e.get('staffIndex')
30
+ or v.get('staffCount')!=e.get('staffCount')):continue
31
+ p=parse(v.get('printedText'))
32
+ if p and p['level']==d['_absoluteDynamic']:texts.append(p)
33
+ if texts and all(p==texts[0]for p in texts):candidates.append((e['identity'],texts[0]))
34
+ if len(candidates)>1:blocked.add(d['_dynamicGroup'])
35
+ if len(candidates)==1:plans.setdefault(d['_dynamicGroup'],[]).append(candidates[0])
36
+ valid={g:values for g,values in plans.items()if g not in blocked and all(v[1]==values[0][1]for v in values)}
37
+ claims={}
38
+ for group,values in valid.items():
39
+ for identity,_ in values:claims.setdefault(identity,set()).add(group)
40
+ valid={g:vs for g,vs in valid.items()if all(len(claims[v[0]])==1 for v in vs)}
41
+ consumed={identity for values in valid.values()for identity,_ in values}
42
+ result=[]
43
+ for mark in marks:
44
+ group=mark.get('_dynamicGroup')
45
+ if group in valid:result.append(dict(mark,_suddenDynamic=valid[group][0][1]))
46
+ elif mark['identity']not in consumed:result.append(mark)
47
+ return result
@@ -0,0 +1,62 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Bind persistent instruction text to its first explicitly owned exported note column."""
4
+ import math
5
+ import struct
6
+
7
+ LABELS=('arco','pizz.','cantabile','sostenuto','marcato','ord.')
8
+
9
+ def position(value):
10
+ if type(value) not in (int,float) or not math.isfinite(value) or not 0<=value<=1:
11
+ return None
12
+ return struct.unpack('>f',struct.pack('>f',value))[0]
13
+
14
+ def plan(page,rendered,bars,page_identity):
15
+ notes=page.get('score',{}).get('notes',[])
16
+ events=page.get('events',[])
17
+ if len(notes)!=len(events) or len(rendered)!=len(notes):return []
18
+ result=[];seen=set()
19
+ for index,change in enumerate(page.get('score',{}).get('techniqueChanges',[])):
20
+ kind=change.get('technique');m=change.get('measureIndex');staff=change.get('staffIndex');count=change.get('staffCount')
21
+ p=position(change.get('positionInMeasure'))
22
+ if (type(kind) is not int or not 0<=kind<len(LABELS) or type(m)is not int or not 0<=m<len(bars)
23
+ or type(staff)is not int or type(count)is not int or not 0<=staff<count<=8 or p is None):continue
24
+ first=None;owners=[];affected=[];malformed=False
25
+ for i,note in enumerate(notes):
26
+ if note.get('measureIndex')!=m or note.get('staffIndex')!=staff:continue
27
+ q=position(note.get('positionInMeasure'))
28
+ if q is None or any(type(note.get(k))is not int for k in ('measureIndex','staffIndex','staffCount')):
29
+ malformed=True;break
30
+ # Match the Java float activation law. This tolerance selects a column, never time.
31
+ following=struct.unpack('>f',struct.pack('>f',q+struct.unpack('>f',struct.pack('>f',.001))[0]))[0]
32
+ if p>following:continue
33
+ affected.append(i)
34
+ if first is None or q<first:first=q;owners=[i]
35
+ elif q==first:owners.append(i)
36
+ if malformed or not owners:continue
37
+ start=None;earliest=None;valid=True
38
+ for i in affected:
39
+ source,event,row=notes[i],events[i],rendered[i]
40
+ if (source.get('staffCount')!=count or type(event.get('sourceNoteIndex'))is not int
41
+ or event['sourceNoteIndex']!=i or event.get('durationFallback')is not False
42
+ or any(type(event.get(k))is not int or event[k]!=source.get(k)
43
+ for k in ('measureIndex','staffIndex','staffCount'))):
44
+ valid=False;break
45
+ at=row['start']
46
+ if (type(at)is not int or not bars[m]['start']<=at<=bars[m]['start']+bars[m]['length']
47
+ or at==bars[m]['start']+bars[m]['length']and not row.get('grace',False)):
48
+ valid=False;break
49
+ earliest=at if earliest is None else min(earliest,at)
50
+ if i in owners:
51
+ if start is not None and start!=at:valid=False;break
52
+ start=at
53
+ if not valid or start!=earliest:continue
54
+ key=(m,staff,count,kind,start)
55
+ if key in seen:continue
56
+ seen.add(key)
57
+ result.append(dict(identity=f'{page_identity}/playing-instruction:{index}',
58
+ kind='UNRESOLVED_DIRECTION',scope='PART',staffIndex=staff,staffCount=count,
59
+ startTick=start,endTick=None,ownerIds=[rendered[i]['sourceIdentity']for i in owners],
60
+ evidence=[dict(sourceId='retained-playing-instruction',printedText=LABELS[kind])],
61
+ _playingInstruction=True, _playingInstructionBarStart=bars[m]['start']))
62
+ return result
@@ -0,0 +1,43 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Unique releasing source owners; an overlapping later attack cannot replace a held note."""
4
+ from bisect import bisect_left, bisect_right
5
+ from collections import Counter, defaultdict
6
+
7
+
8
+ def releasing_links(rows, relations, compatible=lambda earlier, current: True):
9
+ """Return current-index -> prior-index with unique owners at both endpoints.
10
+
11
+ Callers supply their established clock units, lane identities and release tolerances.
12
+ No performed sound alias or input list position is used as a pitch/time heuristic.
13
+ """
14
+ releases = defaultdict(list)
15
+ for index, row in enumerate(rows):
16
+ if row.get('eligible', True) and row['end'] > row['start']:
17
+ releases[row['lane']].append((row['end'], index))
18
+ for values in releases.values():
19
+ values.sort()
20
+ proposed = {}
21
+ for index, row in enumerate(rows):
22
+ if not row.get('eligible', True) or not row.get('tied', False) or row['end'] <= row['start']:
23
+ continue
24
+ candidates = set()
25
+ for lane, tolerance in relations(row):
26
+ values = releases.get(lane, ())
27
+ first = bisect_left(values, (row['start'] - tolerance, -1))
28
+ last = bisect_right(values, (row['start'] + tolerance, len(rows)))
29
+ for _, earlier in values[first:last]:
30
+ if rows[earlier]['start'] < row['start'] and compatible(rows[earlier], row):
31
+ candidates.add(earlier)
32
+ if len(candidates) == 1:
33
+ proposed[index] = candidates.pop()
34
+ uses = Counter(proposed.values())
35
+ return {current: prior for current, prior in proposed.items() if uses[prior] == 1}
36
+
37
+
38
+ def sound_lanes(row, tolerance, hidden_tolerance):
39
+ lane = row['lane']
40
+ yield lane, tolerance
41
+ count, staff, pitch = lane
42
+ if staff == 0 and count in (1, 2):
43
+ yield (3 - count, staff, pitch), hidden_tolerance
@@ -0,0 +1,93 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Written paired tremolos retain source ownership separately from performed pulses."""
4
+ import math
5
+ from .tremolo_wire import clock_policy, performance_pairs
6
+
7
+
8
+ def _anchor(value):
9
+ if not isinstance(value, dict) or any(type(value.get(k)) is not int or value[k] < 0 for k in ('pageIndex', 'noteIndex')):
10
+ raise ValueError('Invalid tremolo source anchor')
11
+ return value['pageIndex'], value['noteIndex']
12
+
13
+
14
+ def retained(page):
15
+ score = page.get('score', {})
16
+ source = score.get('tremoloSource') or {}
17
+ pairs = performance_pairs(source)
18
+ if not pairs:
19
+ return {}
20
+ notes, events, origins = score.get('notes', []), page['events'], source.get('noteOrigins', [])
21
+ if len(notes) != len(events) or len(origins) != len(notes):
22
+ raise ValueError('Tremolo export requires complete source event ownership')
23
+ lookup = {}
24
+ for index, origin in enumerate(origins):
25
+ if origin is None:
26
+ continue
27
+ anchor = _anchor(origin)
28
+ if anchor in lookup:
29
+ raise ValueError('Duplicate tremolo source identity')
30
+ lookup[anchor] = index
31
+ result, ids = {}, set()
32
+ for pair in pairs:
33
+ independent = clock_policy(pair) == 'INDEPENDENT_ENDPOINT_DURATIONS'
34
+ identifier, strokes = pair.get('id'), pair.get('strokes')
35
+ if not isinstance(identifier, str) or not identifier or identifier in ids or type(strokes) is not int or not 1 <= strokes <= 8:
36
+ raise ValueError('Invalid tremolo pair identity or strokes')
37
+ ids.add(identifier)
38
+ sides = []
39
+ for side in ('first', 'second'):
40
+ anchors = pair.get(side, [])
41
+ if not anchors:
42
+ raise ValueError('Missing tremolo chord endpoint')
43
+ members = []
44
+ for anchor in anchors:
45
+ owner = lookup.get(_anchor(anchor))
46
+ if owner is None or owner in result:
47
+ raise ValueError('Missing or ambiguous tremolo endpoint')
48
+ event, note = events[owner], notes[owner]
49
+ if (type(event.get('sourceNoteIndex', owner)) is not int or event.get('sourceNoteIndex', owner) != owner
50
+ or any(event.get(k) != note.get(k) for k in ('measureIndex', 'staffIndex', 'staffCount'))
51
+ or note.get('kind', 'PITCHED') != 'PITCHED'
52
+ or event.get('kind', 'PITCHED') != 'PITCHED'
53
+ or event.get('tiedFromPrevious')
54
+ or note.get('tiedFromPrevious') or note.get('boundaryTies', 0)
55
+ or note.get('articulations', 0) & ((1 << 15) | (7 << 16))):
56
+ raise ValueError('Unproved tremolo source endpoint')
57
+ start, duration = event.get('startBeat'), event.get('durationBeats')
58
+ if any(type(v) not in (int, float) or not math.isfinite(v) or v < 0 for v in (start, duration)) or duration <= 0:
59
+ raise ValueError('Invalid tremolo event clock')
60
+ beams, dots = note.get('beamCount', 0), note.get('augmentationDots', 0)
61
+ actual, normal = note.get('tupletDivisor', 1), note.get('tupletNormalNotes', 1)
62
+ if any(type(v) is not int for v in (beams, dots, actual, normal)) or not 0 <= beams <= 8 or not 0 <= dots <= 3 or min(actual, normal) < 1:
63
+ raise ValueError('Invalid tremolo printed duration')
64
+ base = 2**-beams if beams else note.get('unbeamedDurationBeats', 0)
65
+ if type(base) not in (int, float) or not math.isfinite(base) or base <= 0:
66
+ raise ValueError('Missing tremolo printed base duration')
67
+ if event.get('tupletActualNotes', 1) != actual or event.get('tupletNormalNotes', 1) != normal:
68
+ raise ValueError('Tremolo event ratio disagrees with source')
69
+ written = base * (2 - 2**-dots) * normal / actual
70
+ if not math.isfinite(written) or abs(duration * (1 if independent else 2) - written) > 1e-7:
71
+ raise ValueError('Tremolo clock must be half its written type')
72
+ result[owner] = dict(type='start' if side == 'first' else 'stop', strokes=strokes, pair=identifier)
73
+ if independent:
74
+ if actual != 1 or normal != 1:
75
+ raise ValueError('Independent tremolo tuplet needs a proved outer tuplet group')
76
+ if beams != 0 or abs(base - 1) > 1e-7:
77
+ raise ValueError('Independent tremolo source appearance needs a supported quarter-head representation')
78
+ result[owner].update(printedFilled=True, printedBase=base, printedStem=note.get('stemDirection', 0), canonicalClockPolicy='INDEPENDENT_ENDPOINT_DURATIONS')
79
+
80
+ members.append(owner)
81
+ sides.append(members)
82
+ a, b = (events[side[0]] for side in sides)
83
+ lane = tuple(a.get(k) for k in ('measureIndex', 'staffIndex', 'staffCount'))
84
+ if abs(a['startBeat'] + a['durationBeats'] - b['startBeat']) > 1e-7 or (not independent and abs(a['durationBeats'] - b['durationBeats']) > 1e-7):
85
+ raise ValueError('Tremolo endpoints must share one adjacent duration span')
86
+ for side, reference in zip(sides, (a, b)):
87
+ for owner in side:
88
+ event = events[owner]
89
+ if (tuple(event.get(k) for k in ('measureIndex', 'staffIndex', 'staffCount')) != lane
90
+ or abs(event['startBeat'] - reference['startBeat']) > 1e-7
91
+ or abs(event['durationBeats'] - reference['durationBeats']) > 1e-7):
92
+ raise ValueError('Tremolo chord endpoints disagree')
93
+ return result
@@ -0,0 +1,45 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Source-owned paired spans and phase-preserving alternating chord pulses."""
4
+ import math
5
+ from .tremolo_export import retained
6
+
7
+
8
+ def source_spans(page):
9
+ """Map each printed owner to the full pair span without merging identities."""
10
+ marks = retained(page)
11
+ groups = {}
12
+ for owner, mark in marks.items():
13
+ groups.setdefault(mark['pair'], []).append(owner)
14
+ spans = {}
15
+ for identifier, owners in groups.items():
16
+ start = min(page['events'][i]['startBeat'] for i in owners)
17
+ end = max(page['events'][i]['startBeat'] + page['events'][i]['durationBeats'] for i in owners)
18
+ for owner in owners:
19
+ spans[owner] = dict(pair=identifier, start=start, end=end,
20
+ side=0 if marks[owner]['type'] == 'start' else 1,
21
+ strokes=marks[owner]['strokes'])
22
+ return spans
23
+
24
+
25
+ def pulse_windows(span, start, end, source_start):
26
+ """Clip a projected occurrence while preserving its original pulse phase.
27
+
28
+ start/end are projected beats; source_start is the retained source beat at
29
+ projected start. Holds are applied afterward by the expressive clock.
30
+ """
31
+ values = (span['start'], span['end'], start, end, source_start)
32
+ if any(type(v) not in (int, float) or not math.isfinite(v) for v in values):
33
+ raise ValueError('Nonfinite paired tremolo clock')
34
+ length = span['end'] - span['start']
35
+ if length <= 0 or end <= start or source_start < span['start'] - 1e-7 or source_start + end - start > span['end'] + 1e-7:
36
+ raise ValueError('Projected tremolo lies outside its source span')
37
+ # Match the app's deliberate 75-percent tremolo attack density.
38
+ written_count = min(8192, math.ceil(length * (2 ** span['strokes']) - 1e-7))
39
+ count = max(min(2, written_count), math.floor(written_count * .75 + .5))
40
+ origin = start - (source_start - span['start'])
41
+ step = length / count
42
+ for ordinal in range(span['side'], count, 2):
43
+ a, b = max(start, origin + ordinal * step), min(end, origin + (ordinal + 1) * step)
44
+ if b - a > 1e-8:
45
+ yield ordinal, a, b
@@ -0,0 +1,138 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Private TRS1 source extension. Does not change the guide version."""
4
+ import math
5
+ import struct
6
+
7
+ CLOCK_POLICIES = ('LEGACY_SHARED_DURATION', 'UNRESOLVED', 'SHARED_DURATION', 'INDEPENDENT_ENDPOINT_DURATIONS')
8
+
9
+ def clock_policy(pair):
10
+ if not isinstance(pair, dict): raise ValueError('Invalid tremolo pair')
11
+ value = pair.get('clockPolicy', CLOCK_POLICIES[0])
12
+ if value not in CLOCK_POLICIES: raise ValueError('Unknown tremolo clock policy')
13
+ return value
14
+
15
+ def performance_pairs(source):
16
+ return [pair for pair in (source or {}).get('pairs', []) if clock_policy(pair) != 'UNRESOLVED']
17
+
18
+
19
+
20
+ def decode_source(data, note_count, allow_clock_policies=True):
21
+ """Read one complete TRS1 frame, validating the same ownership as the writer."""
22
+ data = memoryview(data)
23
+ if len(data) < 8:
24
+ raise ValueError('Truncated tremolo frame')
25
+ magic, length = struct.unpack_from('>ii', data)
26
+ if magic not in (0x54525331, 0x54525332) or (magic == 0x54525332 and not allow_clock_policies) or not 0 <= length <= 32*1024*1024 or length != len(data)-8:
27
+ raise ValueError('Invalid tremolo frame')
28
+ offset = 8
29
+
30
+ def take(code):
31
+ nonlocal offset
32
+ size = struct.calcsize('>'+code)
33
+ if size > len(data)-offset:
34
+ raise ValueError('Truncated tremolo record')
35
+ values = struct.unpack_from('>'+code, data, offset)
36
+ offset += size
37
+ return values
38
+
39
+ def count(maximum):
40
+ return integer(take('i')[0], maximum=maximum)
41
+
42
+ notes, stored = count(1_000_000), count(1_000_000)
43
+ if notes != note_count or stored not in (0, notes):
44
+ raise ValueError('Tremolo identity count mismatch')
45
+ origins = []
46
+ for _ in range(stored):
47
+ page, note = take('ii')
48
+ origins.append(None if (page, note) == (-1, -1) else dict(pageIndex=page, noteIndex=note))
49
+ if not stored:
50
+ origins = [None]*notes
51
+ pairs = []
52
+ for _ in range(count(100_000)):
53
+ size = count(1024)
54
+ if size > len(data)-offset:
55
+ raise ValueError('Truncated tremolo identity')
56
+ name = bytes(data[offset:offset+size]).decode('utf-8', errors='strict')
57
+ offset += size
58
+ pair = dict(id=name, strokes=count(8))
59
+ if magic == 0x54525332:
60
+ code = take('B')[0]
61
+ if code >= len(CLOCK_POLICIES): raise ValueError('Unknown tremolo clock policy')
62
+ pair['clockPolicy'] = CLOCK_POLICIES[code]
63
+ for side in ('first', 'second'):
64
+ pair[side] = [dict(zip(('pageIndex','noteIndex'), take('ii'))) for _ in range(count(128))]
65
+ pair['evidence'] = [dict(zip(('pageIndex','left','top','right','bottom'), take('i4f')))
66
+ for _ in range(count(64))]
67
+ pairs.append(pair)
68
+ if offset != len(data):
69
+ raise ValueError('Unexpected tremolo bytes')
70
+ result = dict(pairs=pairs, noteOrigins=origins)
71
+ encode_source(result, note_count)
72
+ return result
73
+
74
+ def integer(value, minimum=0, maximum=2_147_483_647):
75
+ if type(value) is not int or not minimum<=value<=maximum:
76
+ raise ValueError('Invalid tremolo integer')
77
+ return value
78
+
79
+ def anchor(value):
80
+ if not isinstance(value,dict) or set(value)!={'pageIndex','noteIndex'}:
81
+ raise ValueError('Invalid tremolo anchor')
82
+ return integer(value['pageIndex']),integer(value['noteIndex'])
83
+
84
+ def sequence(value,minimum,maximum):
85
+ if not isinstance(value,list) or not minimum<=len(value)<=maximum:
86
+ raise ValueError('Invalid tremolo sequence')
87
+ return value
88
+
89
+ def encode_source(source,note_count,allow_clock_policies=True):
90
+ integer(note_count,maximum=1_000_000)
91
+ if source is None:source={'pairs':[],'noteOrigins':[None]*note_count}
92
+ if not isinstance(source,dict) or set(source)!={'pairs','noteOrigins'}:
93
+ raise ValueError('Invalid tremolo source fields')
94
+ origins=sequence(source['noteOrigins'],note_count,note_count)
95
+ pairs=sequence(source['pairs'],0,100_000)
96
+ v2 = any(clock_policy(pair) != CLOCK_POLICIES[0] for pair in pairs)
97
+ if v2 and not allow_clock_policies: raise ValueError('TRS2 requires Guide298')
98
+ stored=origins if any(o is not None for o in origins) else []
99
+ data=bytearray(struct.pack('>ii',note_count,len(stored)));seen=set()
100
+ for origin in stored:
101
+ point=(-1,-1) if origin is None else anchor(origin)
102
+ if origin is not None:
103
+ if point in seen:raise ValueError('Duplicate tremolo origin')
104
+ seen.add(point)
105
+ data.extend(struct.pack('>ii',*point))
106
+ data.extend(struct.pack('>i',len(pairs)));ids=set();owners=set()
107
+ java_whitespace='\t\n\v\f\r\x1c\x1d\x1e\x1f \u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2008\u2009\u200a\u2028\u2029\u205f\u3000'
108
+ for pair in pairs:
109
+ if not isinstance(pair,dict) or set(pair) not in ({'id','first','second','strokes','evidence'}, {'id','first','second','strokes','evidence','clockPolicy'}):
110
+ raise ValueError('Invalid tremolo pair fields')
111
+ name=pair['id']
112
+ if not isinstance(name,str) or all(c in java_whitespace for c in name) or name in ids:
113
+ raise ValueError('Invalid tremolo identity')
114
+ if len(name.encode('utf-16-be'))//2>256:raise ValueError('Long tremolo identity')
115
+ ids.add(name);encoded=name.encode('utf-8')
116
+ data.extend(struct.pack('>i',len(encoded)));data.extend(encoded)
117
+ data.extend(struct.pack('>i',integer(pair['strokes'],1,8)))
118
+ if v2: data.extend(struct.pack('>B',CLOCK_POLICIES.index(clock_policy(pair))))
119
+ for key in ('first','second'):
120
+ points=[anchor(v) for v in sequence(pair[key],1,128)]
121
+ data.extend(struct.pack('>i',len(points)))
122
+ for point in points:
123
+ if point in owners:raise ValueError('Ambiguous tremolo endpoint')
124
+ owners.add(point);data.extend(struct.pack('>ii',*point))
125
+ evidence=sequence(pair['evidence'],1,64);data.extend(struct.pack('>i',len(evidence)))
126
+ for proof in evidence:
127
+ if not isinstance(proof,dict) or set(proof)!={'pageIndex','left','top','right','bottom'}:
128
+ raise ValueError('Invalid tremolo evidence')
129
+ coordinates=[proof[k] for k in ('left','top','right','bottom')]
130
+ if any(type(v) not in (float,int) or not math.isfinite(v) or not 0<=v<=1 for v in coordinates):
131
+ raise ValueError('Invalid tremolo geometry')
132
+ # Validate float32 geometry as the Java record will see it.
133
+ coordinates=struct.unpack('>4f',struct.pack('>4f',*coordinates))
134
+ if coordinates[0]>=coordinates[2] or coordinates[1]>=coordinates[3]:
135
+ raise ValueError('Empty tremolo evidence')
136
+ data.extend(struct.pack('>i4f',integer(proof['pageIndex']),*coordinates))
137
+ if len(data)>32*1024*1024:raise ValueError('Tremolo source too large')
138
+ return struct.pack('>ii',(0x54525332 if v2 else 0x54525331),len(data))+data
@@ -0,0 +1,57 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Export validation for legacy pitched and explicitly typed unpitched events."""
4
+
5
+
6
+ def event_kind(event):
7
+ kind = event.get('kind', 'PITCHED')
8
+ if kind not in ('PITCHED', 'UNPITCHED'):
9
+ raise ValueError('Unknown decoded note kind')
10
+ return kind
11
+
12
+
13
+ def validate_unpitched(event):
14
+ """Display position describes notation, never a sounding MIDI pitch."""
15
+ if event_kind(event) != 'UNPITCHED':
16
+ return
17
+ if event.get('displayStep') not in ('C', 'D', 'E', 'F', 'G', 'A', 'B'):
18
+ raise ValueError('Unpitched display step must be C..B')
19
+ if type(event.get('displayOctave')) is not int or not 0 <= event['displayOctave'] <= 9:
20
+ raise ValueError('Unpitched display octave must be 0..9')
21
+ if ('clefBottomDiatonic' in event and (type(event['clefBottomDiatonic']) is not int
22
+ or event['clefBottomDiatonic'] not in (18, 22, 24, 25, 30, 32, 37))):
23
+ raise ValueError('Unpitched display clef must be a supported retained clef')
24
+ if any(field in event for field in ('midi', 'boundaryPitch', 'boundaryAccidental', 'upperMidi', 'lowerMidi', 'frequency')):
25
+ raise ValueError('An unpitched event must not carry a tonal pitch identity')
26
+ if event.get('tiedFromPrevious') or event.get('boundaryTies', 0):
27
+ raise ValueError('Unpitched source ties need explicit instrument identity semantics')
28
+ if (event.get('octaveShift', 0) or event.get('tremoloBeats', 0)
29
+ or event.get('glissando') or event.get('ornament') or event.get('ornaments')):
30
+ raise ValueError('Unpitched tonal ornaments or tremolo need an explicit instrument realization')
31
+ effect = event.get('guitarEffect', {})
32
+ if effect and (not isinstance(effect, dict) or effect.get('type') != 'dead'
33
+ or effect.get('semitones', 0) != 0 or effect.get('vibrato', False)
34
+ or effect.get('palmMute', False)):
35
+ raise ValueError('Only neutral DEAD evidence is supported for unpitched preview')
36
+ attack = event.get('performanceAttack')
37
+ if attack is not None:
38
+ import math
39
+ if (not isinstance(attack, dict) or any(type(attack.get(k)) not in (int, float)
40
+ or not math.isfinite(attack[k]) or attack[k] < 0 for k in ('gain', 'settledGain', 'seconds'))):
41
+ raise ValueError('Unpitched expressive gain attack must be finite and nonnegative')
42
+
43
+
44
+
45
+ def notation_order(event):
46
+ """Keep legacy pitched ordering; distinct unpitched heads retain stable source order."""
47
+ if event_kind(event) == 'PITCHED':
48
+ return 0, event['midi']
49
+ return 1, event['displayOctave'] * 7 + 'CDEFGAB'.index(event['displayStep'])
50
+
51
+
52
+ def display_position(event, flats=False):
53
+ if event_kind(event) == 'UNPITCHED':
54
+ return event['displayOctave'] * 7 + 'CDEFGAB'.index(event['displayStep'])
55
+ midi = event['midi']
56
+ letters = (0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6) if flats else (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
57
+ return (midi // 12 - 1) * 7 + letters[midi % 12]
@@ -0,0 +1,44 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Owned unpitched interval grouping without an invented sounding identity."""
4
+ import math
5
+ from .typed_events import event_kind, validate_unpitched
6
+
7
+
8
+ def unpitched_intervals(document):
9
+ result, owners, offset = [], {}, 0.
10
+ for page_index, page in enumerate(document['pages']):
11
+ for index, note in enumerate(page['events']):
12
+ if event_kind(note) != 'UNPITCHED':
13
+ continue
14
+ validate_unpitched(note)
15
+ if any(type(value) not in (int, float) or not math.isfinite(value)
16
+ for value in (offset, note['startBeat'], note['durationBeats'], page['totalBeats'])):
17
+ raise ValueError('Unpitched owned interval needs finite numeric source times')
18
+ start = offset+note['startBeat']
19
+ end = start+note['durationBeats']
20
+ if (not math.isfinite(start) or not math.isfinite(end) or end <= start
21
+ or note['startBeat'] < 0 or end > offset+page['totalBeats']+1e-6):
22
+ raise ValueError('Unpitched owned interval must be finite and inside the performed page')
23
+ owner = note.get('_unpitchedAttackId')
24
+ if owner is not None and (not isinstance(owner, str) or not owner or len(owner) > 4096):
25
+ raise ValueError('Unpitched owned attack identity must be a bounded source ID')
26
+ if type(note.get('_unpitchedContinuation', False)) is not bool:
27
+ raise ValueError('Unpitched continuation flag must be explicit boolean ownership')
28
+ identifier = owner or f'unpitched:{page_index}:{index}'
29
+ if note.get('_unpitchedContinuation', False):
30
+ previous = owners.get(owner)
31
+ if (owner is None or previous is None or not math.isclose(previous['endBeat'], start, abs_tol=1e-8)
32
+ or previous['note'].get('sourceEventId') != note.get('sourceEventId')
33
+ or previous['note'].get('guitarEffect', {}) != note.get('guitarEffect', {})):
34
+ raise ValueError('Unpitched continuation needs the same owned source and contiguous visit')
35
+ previous['endBeat'] = end
36
+ continue
37
+ if owner is not None and owner in owners:
38
+ raise ValueError('Unpitched owned attack identity cannot merge independent visits')
39
+ interval = dict(sourceId=identifier, startBeat=start, endBeat=end, note=note)
40
+ result.append(interval)
41
+ if owner is not None:
42
+ owners[owner] = interval
43
+ offset += page['totalBeats']
44
+ return result
@@ -0,0 +1,18 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Retained glyph size, independent of note kind, duration, and performance."""
4
+ def retained(page, index):
5
+ notes = page.get('score', {}).get('notes', [])
6
+ events = page.get('events', [])
7
+ if len(notes) != len(events) or not 0 <= index < len(notes):
8
+ return 'FULL'
9
+ note, event = notes[index], events[index]
10
+ if (type(event.get('sourceNoteIndex', index)) is not int
11
+ or event.get('sourceNoteIndex', index) != index
12
+ or any(type(note.get(k)) is not int or event.get(k) != note[k]
13
+ for k in ('measureIndex', 'staffIndex', 'staffCount'))):
14
+ return 'FULL'
15
+ size = note.get('visualSize', 'FULL')
16
+ if type(size) is not str or size not in ('FULL', 'CUE'):
17
+ raise ValueError('Invalid retained note visual size')
18
+ return size