From e3bfed33bbd6d071c5156255f0113db2bc7aa280 Mon Sep 17 00:00:00 2001 From: ChrisBeWithYou Date: Fri, 17 Jul 2026 19:16:03 -0500 Subject: [PATCH 1/2] Detect authored MusicXML guitar tabs --- CHANGELOG.md | 17 +-- mxml2notation.py | 198 ++++++++++++++++++++++++++++---- routes.py | 17 +-- tests/test_parse_arrangement.py | 67 ++++++++++- 4 files changed, 259 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98cc86c..4c9ce96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,19 +13,20 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - **`POST /api/plugins/musicxml_import/parse-arrangement`** — parses a MusicXML file (`.xml` / `.musicxml` / `.mxl`) straight into a ready - editor keys arrangement, the endpoint the editor plugin's + editor arrangement, the endpoint the editor plugin's Add-Keys ▸ MusicXML path has been calling (and 404-ing on) since it shipped. Stateless — nothing is kept server-side. The response carries: - - flat editor-shape notes with **the score's authored hand assignment - per note** (`techniques.hand`, `'rh'`/`'lh'` from the grand-staff - split; staves beyond the grand staff — e.g. organ pedals — stay - unassigned). Ties fold into one held note; grace notes are skipped. + - flat editor-shape notes with authored semantics: grand-staff scores keep + **the score's hand assignment per note** (`techniques.hand`, `'rh'`/`'lh'`), + while guitar/TAB scores keep authored **tuning and string/fret positions**. + Ties fold into one held note; grace notes are skipped. - the full **notation payload** stashed on the arrangement, so the editor can preserve authored notation instead of re-deriving hand splits heuristically. - - an arrangement name guaranteed to satisfy the editor's - prefix-anchored keys router (a non-keys part name gets a - `Keys — ` prefix; placeholder part ids like `P1` are dropped). + - an arrangement name/type the editor routes correctly (`Lead`/`Bass` for + fretted parts; a keys-safe name for grand-staff imports). +- Parallel standard-notation + TAB exports now select the TAB part instead of + blindly parsing the first part, preserving authored fretting and tuning. - `parse_musicxml` result now includes `flat_notes` (`{'t','sus','midi','staff'}`, tie-folded, grace-skipped, staff = hand provenance) and a pure `editor_arrangement(result)` builder for the diff --git a/mxml2notation.py b/mxml2notation.py index 8323b0c..92f3721 100644 --- a/mxml2notation.py +++ b/mxml2notation.py @@ -236,6 +236,127 @@ def _infer_instrument(part_name: str) -> str: # --------------------------------------------------------------------------- +# Instrument and part selection +# --------------------------------------------------------------------------- + +_GUITAR_MIDI_PROGRAMS = set(range(25, 33)) # MusicXML is 1-based: guitars + + +def _score_parts_by_id(root: ET.Element) -> dict[str, ET.Element]: + part_list = root.find('part-list') + if part_list is None: + return {} + return {sp.get('id', ''): sp for sp in part_list.findall('score-part')} + + +def _part_instrument(part: ET.Element, score_part: ET.Element | None) -> str: + """Infer a part's instrument from structural and declared MusicXML data. + + TAB is stronger evidence than a generic/hidden part name. Explicit sound + metadata and MIDI programs cover standard-notation guitar exports. + """ + name = '' + sounds: list[str] = [] + programs: list[int] = [] + if score_part is not None: + name = score_part.findtext('part-name') or '' + sounds = [ + (node.findtext('instrument-sound') or '').strip().lower() + for node in score_part.findall('score-instrument') + ] + for node in score_part.findall('midi-instrument'): + try: + programs.append(int(node.findtext('midi-program') or 0)) + except ValueError: + pass + + declared = ' '.join(sounds) + named = _infer_instrument(name) + if named == 'bass_guitar' or ('bass' in declared and 'guitar' in declared): + return 'bass_guitar' + if named == 'guitar' or 'guitar' in declared: + return 'guitar' + if any((clef.findtext('sign') or '').strip().upper() == 'TAB' + for clef in part.findall('.//clef')): + return 'guitar' + if any(program in _GUITAR_MIDI_PROGRAMS for program in programs): + return 'guitar' + return named + + +def _select_part(root: ET.Element) -> tuple[ET.Element, str, str]: + """Choose the richest playable part and return (part, name, instrument). + + Many notation programs export a standard staff and a parallel TAB staff as + separate parts. The TAB part owns the authored string/fret positions and + must win over document order. Otherwise explicit instrument data wins, + with the historical first-part behavior as the final tie-break. + """ + parts = root.findall('part') + if not parts: + raise ValueError("No elements found in score.") + declared = _score_parts_by_id(root) + ranked = [] + for index, part in enumerate(parts): + score_part = declared.get(part.get('id', '')) + name = ((score_part.findtext('part-name') if score_part is not None else '') + or part.get('id') or 'Part') + instrument = _part_instrument(part, score_part) + tab = any((clef.findtext('sign') or '').strip().upper() == 'TAB' + for clef in part.findall('.//clef')) + positioned = sum( + 1 for note in part.findall('.//note') + if note.find('notations/technical/string') is not None + and note.find('notations/technical/fret') is not None + ) + tuning = bool(part.findall('.//staff-details/staff-tuning')) + score = ((10000 if positioned else 0) + (1000 if tab else 0) + + (100 if tuning else 0) + + (10 if instrument != 'unknown' else 0) - index) + ranked.append((score, part, name, instrument)) + _, part, name, instrument = max(ranked, key=lambda row: row[0]) + return part, name, instrument + + +def _part_fretting(part: ET.Element, instrument: str) -> tuple[list[int], int, int]: + """Return (editor tuning offsets, capo, string count) for a fretted part.""" + details = next(iter(part.findall('.//staff-details')), None) + tunings: dict[int, int] = {} + if details is not None: + for node in details.findall('staff-tuning'): + try: + line = int(node.get('line') or 0) + step = node.findtext('tuning-step') or 'E' + alter = int(float(node.findtext('tuning-alter') or 0)) + octave = int(node.findtext('tuning-octave') or 2) + if line > 0: + tunings[line] = _pitch_to_midi(step, alter, octave) + except (TypeError, ValueError, KeyError): + pass + count = max(tunings, default=0) + if not count and details is not None: + try: + count = int(details.findtext('staff-lines') or 0) + except ValueError: + pass + if not count: + count = 4 if instrument == 'bass_guitar' else 6 + guitar_open = {6: [40, 45, 50, 55, 59, 64], + 7: [35, 40, 45, 50, 55, 59, 64], + 8: [30, 35, 40, 45, 50, 55, 59, 64]} + bass_open = {4: [28, 33, 38, 43], 5: [23, 28, 33, 38, 43], + 6: [23, 28, 33, 38, 43, 48]} + standard = (bass_open if instrument == 'bass_guitar' else guitar_open).get(count) + if standard and len(tunings) == count: + tuning = [tunings[i + 1] - standard[i] for i in range(count)] + else: + tuning = [0] * count + try: + capo = int(details.findtext('capo') or 0) if details is not None else 0 + except ValueError: + capo = 0 + return tuning, capo, count + # Pitch helpers # --------------------------------------------------------------------------- @@ -295,14 +416,16 @@ def _count_dots(note_elem: ET.Element) -> int: # Tempo map (reused logic from the old prototype importer) # --------------------------------------------------------------------------- -def _build_tempo_map(root: ET.Element) -> list[tuple[int, float]]: - """Return (divisions_elapsed, bpm) events from the first part.""" +def _build_tempo_map(root: ET.Element, + part: ET.Element | None = None) -> list[tuple[int, float]]: + """Return (divisions_elapsed, bpm) events from the selected part.""" events: list[tuple[int, float]] = [(0, 120.0)] parts = root.findall('part') if not parts: return events - part = parts[0] + if part is None: + part = parts[0] divisions = 1 abs_div = 0 @@ -361,7 +484,8 @@ def _build_tempo_map(root: ET.Element) -> list[tuple[int, float]]: return events -def _build_divisions_map(root: ET.Element) -> list[tuple[int, int]]: +def _build_divisions_map(root: ET.Element, + part: ET.Element | None = None) -> list[tuple[int, int]]: """Return (abs_div, divisions) at each measure boundary where divisions changes. divisions-per-quarter may change at a measure boundary (a legal change); @@ -379,7 +503,8 @@ def _build_divisions_map(root: ET.Element) -> list[tuple[int, int]]: if not parts: return dmap - part = parts[0] + if part is None: + part = parts[0] divisions = 1 abs_div = 0 @@ -987,20 +1112,14 @@ def parse_musicxml(xml_bytes: bytes) -> dict: name = sp.findtext('part-name') or sp.get('id') or 'Part' part_names.append(name) - instrument = _infer_instrument(part_names[0]) if part_names else 'unknown' + part, selected_part_name, instrument = _select_part(root) + tuning, capo, string_count = _part_fretting(part, instrument) # ── Tempo map ─────────────────────────────────────────────────────────── - tempo_map = _build_tempo_map(root) + tempo_map = _build_tempo_map(root, part) # divisions-per-quarter can change at measure boundaries; _div_to_seconds # needs the value active in each span (issue #5), not a single scalar. - divisions_map = _build_divisions_map(root) - - # ── Parse first part only ─────────────────────────────────────────────── - parts = root.findall('part') - if not parts: - raise ValueError("No elements found in score.") - - part = parts[0] + divisions_map = _build_divisions_map(root, part) # State that persists across measures divisions = 1 @@ -1501,6 +1620,17 @@ def _warn_dropped(feature: str, measure_number: int) -> None: elif sustain > 0: flat = {'t': note_time, 'sus': sustain, 'midi': midi, 'staff': sid} + tech = elem.find('notations/technical') + if tech is not None: + try: + xml_string = int(tech.findtext('string') or 0) + fret = int(tech.findtext('fret') or -1) + if 1 <= xml_string <= string_count and fret >= 0: + # MusicXML string 1 is highest; editor 0 is lowest. + flat['string'] = string_count - xml_string + flat['fret'] = fret + except ValueError: + pass flat_notes.append(flat) if 'start' in tie_types: flat_open[tie_key] = flat @@ -1660,6 +1790,10 @@ def _warn_dropped(feature: str, measure_number: int) -> None: 'song_timeline': song_timeline, 'midi_bytes': midi_bytes, 'part_names': part_names, + 'selected_part_id': part.get('id', ''), + 'selected_part_name': selected_part_name, + 'tuning': tuning, + 'capo': capo, 'measure_count': len(measures_out), 'flat_notes': sorted(flat_notes, key=lambda n: (n['t'], n['midi'])), } @@ -1677,7 +1811,7 @@ def _warn_dropped(feature: str, measure_number: int) -> None: def editor_arrangement(result: dict) -> dict: - """Map a ``parse_musicxml`` result to a ready editor keys arrangement. + """Map a ``parse_musicxml`` result to a ready editor arrangement. Returns the shape the editor plugin's Add-Keys flow appends directly: flat notes in the editor's packed pitch encoding (``midi = string*24 + @@ -1687,22 +1821,44 @@ def editor_arrangement(result: dict) -> dict: stashed under ``notation`` for the editor's authored-notation save rail (which otherwise re-derives hand splits heuristically). """ + instrument = result.get('instrument', 'unknown') + fretted = instrument in ('guitar', 'bass_guitar') notes = [] for n in result.get('flat_notes') or []: midi = n['midi'] + if fretted and 'string' in n and 'fret' in n: + string, fret = n['string'], n['fret'] + techniques = {} + elif fretted: + tuning = result.get('tuning') or [0] * (4 if instrument == 'bass_guitar' else 6) + standard = ([28, 33, 38, 43] if instrument == 'bass_guitar' + else [40, 45, 50, 55, 59, 64]) + opens = [base + (tuning[i] if i < len(tuning) else 0) + for i, base in enumerate(standard[:len(tuning)])] + candidates = [(midi - opened, i) for i, opened in enumerate(opens) + if 0 <= midi - opened <= 24] + fret, string = min(candidates, default=(midi % 24, midi // 24)) + techniques = {} + else: + string, fret = midi // 24, midi % 24 + techniques = ({'hand': n['staff']} + if n.get('staff') in ('rh', 'lh') else {}) note = { 'time': n['t'], - 'string': midi // 24, - 'fret': midi % 24, + 'string': string, + 'fret': fret, 'sustain': n['sus'], - 'techniques': ( - {'hand': n['staff']} if n.get('staff') in ('rh', 'lh') else {} - ), + 'techniques': techniques, } notes.append(note) # A missing falls back to the score-part id ("P1", "P2", …) # upstream — a placeholder, not a name; don't leak it into the label. + if fretted: + name = 'Bass' if instrument == 'bass_guitar' else 'Lead' + return {'name': name, 'tuning': result.get('tuning') or [], + 'capo': result.get('capo', 0), 'notes': notes, 'chords': [], + 'chord_templates': [], 'notation': result.get('notation')} part = next( (p.strip() for p in result.get('part_names') or [] if p and p.strip() and not re.fullmatch(r'P\d+', p.strip())), diff --git a/routes.py b/routes.py index eef8928..0e7d6ce 100644 --- a/routes.py +++ b/routes.py @@ -7,10 +7,10 @@ Saves the raw bytes to a temp file for the build step. POST /api/plugins/musicxml_import/parse-arrangement - Receives a MusicXML file as base64 and returns a ready editor keys - arrangement (the editor plugin's Add-Keys ▸ MusicXML path): flat - notes with authored per-note hand assignments from the grand-staff - split, plus the full notation payload for the editor's + Receives MusicXML as base64 and returns a ready editor arrangement. + Grand-staff scores carry authored hand assignments; guitar/TAB scores + carry their authored tuning and string/fret positions. The full notation + payload is included for the editor's authored-notation save rail. Stateless — nothing is kept server-side. WS /ws/plugins/musicxml_import/build @@ -136,13 +136,14 @@ async def upload_mxml(data: dict): @app.post('/api/plugins/musicxml_import/parse-arrangement') async def parse_arrangement(data: dict): - """Parse a MusicXML file into a ready editor keys arrangement. + """Parse MusicXML into a ready editor arrangement. - Consumed by the editor plugin's Add-Keys ▸ MusicXML path. Returns + Consumed by the editor plugin's MusicXML paths. Returns `{arrangement: {name, notes, chords, chord_templates, notation, …}}` - — flat editor-shape notes carrying the score's authored hand + — flat editor-shape notes carrying authored grand-staff hand assignment (`techniques.hand`, 'rh'/'lh' from grand-staff - provenance) plus the notation payload for the editor's + provenance, or authored TAB string/fret positions and tuning) plus the + notation payload for the editor's authored-notation save rail. Stateless: parses from the request body, keeps nothing on disk. """ diff --git a/tests/test_parse_arrangement.py b/tests/test_parse_arrangement.py index 05e33e6..8e8df84 100644 --- a/tests/test_parse_arrangement.py +++ b/tests/test_parse_arrangement.py @@ -1,6 +1,6 @@ -"""The parse-arrangement surface: flat_notes (tie folding, grace skipping, -staff provenance), editor_arrangement (packed pitch encoding, per-note hand, -keys-recognizable naming, notation passthrough), and the stateless endpoint. +"""The parse-arrangement surface: part/instrument selection, flat notes, +authored piano hands and guitar positions, editor arrangement shaping, +notation passthrough, and the stateless endpoint. The per-note hand vocabulary is 'rh'/'lh' (matching the notation staff ids); staves beyond the grand staff (e.g. an organ pedal staff) stay unassigned — @@ -50,6 +50,67 @@ def _note(step='C', octave='4', staff='1', dur='2', ntype='quarter', {extra} ''' +def _paired_guitar_score() -> bytes: + """Finale-style parallel standard + TAB parts with generic names.""" + return b''' + + + MusicXML Part + + SoftSynth + pluck.guitar + + 26 + + MusicXML Part + + 2 + + G2 + E42 + 1quarter + 4 + + TAB5 + 6 + E2 + A2 + D3 + G3 + B3 + E4 + + + F14 + 41quarter + 12 + +''' + + +def test_parallel_tab_part_wins_and_preserves_guitar_position(): + result = mxml2notation.parse_musicxml(_paired_guitar_score()) + assert result['selected_part_id'] == 'P2' + assert result['instrument'] == 'guitar' + assert result['tuning'] == [0, 0, 0, 0, 0, 0] + assert result['flat_notes'] == [{ + 't': 0.0, 'sus': 0.5, 'midi': 66, 'staff': 'rh', + 'string': 5, 'fret': 2, + }] + arr = mxml2notation.editor_arrangement(result) + assert arr['name'] == 'Lead' + assert arr['tuning'] == [0, 0, 0, 0, 0, 0] + assert arr['notes'][0]['string'] == 5 + assert arr['notes'][0]['fret'] == 2 + assert arr['notes'][0]['techniques'] == {} + + +def test_declared_guitar_program_is_recognized_without_tab(): + root = mxml2notation.ET.fromstring(_paired_guitar_score()) + p1 = root.find("part[@id='P1']") + declared = mxml2notation._score_parts_by_id(root)['P1'] + assert mxml2notation._part_instrument(p1, declared) == 'guitar' + # ── flat_notes semantics ──────────────────────────────────────────────────── From 45fa22a1a4e1855512720c1ee5a3af7e1e332218 Mon Sep 17 00:00:00 2001 From: ChrisBeWithYou Date: Sat, 18 Jul 2026 16:36:18 -0500 Subject: [PATCH 2/2] Handle extended MusicXML instruments --- mxml2notation.py | 31 +++++++++++++++++++------------ tests/test_parse_arrangement.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/mxml2notation.py b/mxml2notation.py index 92f3721..c637a4a 100644 --- a/mxml2notation.py +++ b/mxml2notation.py @@ -240,6 +240,13 @@ def _infer_instrument(part_name: str) -> str: # --------------------------------------------------------------------------- _GUITAR_MIDI_PROGRAMS = set(range(25, 33)) # MusicXML is 1-based: guitars +_FRETTED_OPEN_PITCHES = { + 'guitar': {6: [40, 45, 50, 55, 59, 64], + 7: [35, 40, 45, 50, 55, 59, 64], + 8: [30, 35, 40, 45, 50, 55, 59, 64]}, + 'bass_guitar': {4: [28, 33, 38, 43], 5: [23, 28, 33, 38, 43], + 6: [23, 28, 33, 38, 43, 48]}, +} def _score_parts_by_id(root: ET.Element) -> dict[str, ET.Element]: @@ -341,12 +348,7 @@ def _part_fretting(part: ET.Element, instrument: str) -> tuple[list[int], int, i pass if not count: count = 4 if instrument == 'bass_guitar' else 6 - guitar_open = {6: [40, 45, 50, 55, 59, 64], - 7: [35, 40, 45, 50, 55, 59, 64], - 8: [30, 35, 40, 45, 50, 55, 59, 64]} - bass_open = {4: [28, 33, 38, 43], 5: [23, 28, 33, 38, 43], - 6: [23, 28, 33, 38, 43, 48]} - standard = (bass_open if instrument == 'bass_guitar' else guitar_open).get(count) + standard = _FRETTED_OPEN_PITCHES.get(instrument, {}).get(count) if standard and len(tunings) == count: tuning = [tunings[i + 1] - standard[i] for i in range(count)] else: @@ -1831,8 +1833,8 @@ def editor_arrangement(result: dict) -> dict: techniques = {} elif fretted: tuning = result.get('tuning') or [0] * (4 if instrument == 'bass_guitar' else 6) - standard = ([28, 33, 38, 43] if instrument == 'bass_guitar' - else [40, 45, 50, 55, 59, 64]) + standard = (_FRETTED_OPEN_PITCHES.get(instrument, {}).get(len(tuning)) + or []) opens = [base + (tuning[i] if i < len(tuning) else 0) for i, base in enumerate(standard[:len(tuning)])] candidates = [(midi - opened, i) for i, opened in enumerate(opens) @@ -1860,10 +1862,15 @@ def editor_arrangement(result: dict) -> dict: 'capo': result.get('capo', 0), 'notes': notes, 'chords': [], 'chord_templates': [], 'notation': result.get('notation')} part = next( - (p.strip() for p in result.get('part_names') or [] - if p and p.strip() and not re.fullmatch(r'P\d+', p.strip())), - '', - ) + (p.strip() for p in [result.get('selected_part_name')] + if p and p.strip() and not re.fullmatch(r'P\d+', p.strip())), '') + if not part and 'selected_part_name' not in result: + # Backward-compatible for callers constructing a pre-selection result. + part = next( + (p.strip() for p in result.get('part_names') or [] + if p and p.strip() and not re.fullmatch(r'P\d+', p.strip())), + '', + ) if part and _KEYS_NAME_RE.match(part): name = part elif part: diff --git a/tests/test_parse_arrangement.py b/tests/test_parse_arrangement.py index 8e8df84..2b8ee8c 100644 --- a/tests/test_parse_arrangement.py +++ b/tests/test_parse_arrangement.py @@ -112,6 +112,38 @@ def test_declared_guitar_program_is_recognized_without_tab(): assert mxml2notation._part_instrument(p1, declared) == 'guitar' +def test_extended_fretted_fallback_uses_matching_standard_tuning(): + guitar = mxml2notation.editor_arrangement({ + 'instrument': 'guitar', 'tuning': [0] * 7, + 'flat_notes': [{'t': 0, 'sus': 1, 'midi': 35, 'staff': 'rh'}], + 'selected_part_name': 'Seven String Guitar', + }) + assert guitar['notes'][0]['string'] == 0 + assert guitar['notes'][0]['fret'] == 0 + + bass = mxml2notation.editor_arrangement({ + 'instrument': 'bass_guitar', 'tuning': [0] * 5, + 'flat_notes': [{'t': 0, 'sus': 1, 'midi': 23, 'staff': 'rh'}], + 'selected_part_name': 'Five String Bass', + }) + assert bass['notes'][0]['string'] == 0 + assert bass['notes'][0]['fret'] == 0 + + +def test_arrangement_name_comes_from_selected_part(): + arr = mxml2notation.editor_arrangement({ + 'instrument': 'piano', 'selected_part_name': 'Piano', + 'part_names': ['MusicXML Part', 'Piano'], 'flat_notes': [], + }) + assert arr['name'] == 'Piano' + + unnamed = mxml2notation.editor_arrangement({ + 'instrument': 'piano', 'selected_part_name': 'P2', + 'part_names': ['Unrelated Part', 'P2'], 'flat_notes': [], + }) + assert unnamed['name'] == 'Keys' + + # ── flat_notes semantics ──────────────────────────────────────────────────── def test_flat_notes_carry_staff_provenance():