from __future__ import annotations
from typing import List, Tuple, Optional
# Basic note naming (enharmonic: we render as sharps or flats based on preference)
PC_TO_SHARP = {0:"C",1:"C#",2:"D",3:"D#",4:"E",5:"F",6:"F#",7:"G",8:"G#",9:"A",10:"A#",11:"B"}
PC_TO_FLAT = {0:"C",1:"Db",2:"D",3:"Eb",4:"E",5:"F",6:"Gb",7:"G",8:"Ab",9:"A",10:"Bb",11:"B"}
LETTER_INDEX = {"C":0,"D":1,"E":2,"F":3,"G":4,"A":5,"B":6}
def midi_to_name(m: int, prefer_sharps: bool) -> str:
pc = m % 12
octave = (m // 12) - 1
name = (PC_TO_SHARP[pc] if prefer_sharps else PC_TO_FLAT[pc])
return f"{name}{octave}"
def _diatonic_number(letter: str, octave: int) -> int:
return octave * 7 + LETTER_INDEX[letter]
def _parse_name(name: str) -> Tuple[str, str, int]:
# e.g. C#4, Db3, E5
letter = name[0].upper()
acc = ""
rest = name[1:]
if rest and rest[0] in ("#", "b"):
acc = rest[0]
rest = rest[1:]
octave = int(rest)
return letter, acc, octave
def _staff_y_for_midi(m: int, prefer_sharps: bool, clef: str, y_bottom_line: float, space: float) -> Tuple[float, str]:
"""
Returns y coordinate for the notehead centre, and accidental string ('#','b','').
We compute diatonic steps relative to the clef bottom line reference.
"""
name = midi_to_name(m, prefer_sharps)
letter, acc, octave = _parse_name(name)
if clef == "treble":
# bottom line = E4
ref_letter, ref_oct = "E", 4
else:
# bass bottom line = G2
ref_letter, ref_oct = "G", 2
dn = _diatonic_number(letter, octave)
ref = _diatonic_number(ref_letter, ref_oct)
step = dn - ref # each step is a line/space
y = y_bottom_line - step * (space / 2.0)
return y, acc
def _ledger_lines(y: float, y_top: float, y_bottom: float, x: float, w: float, space: float) -> List[str]:
lines = []
# staff lines are at y_top + i*space for i=0..4
# ledger lines occur every other half-step beyond staff
if y < y_top - space/2:
# above top line; add ledger lines at y_top - n*space
n = int(round((y_top - y) / (space/2)))
# ledger lines for even half-steps (line positions)
for k in range(2, n+1, 2):
yy = y_top - (k/2)*space
lines.append(f'')
elif y > y_bottom + space/2:
n = int(round((y - y_bottom) / (space/2)))
for k in range(2, n+1, 2):
yy = y_bottom + (k/2)*space
lines.append(f'')
return lines
def grand_staff_svg(chord_midi: List[int], prefer_sharps: bool = True, width: int = 820, height: int = 260) -> str:
"""
Offline SVG grand staff rendering (no external JS/CDN).
Chord shown as whole notes, split around middle C (C4=60).
"""
mids = sorted(int(m) for m in chord_midi)
treble = [m for m in mids if m >= 60]
bass = [m for m in mids if m < 60]
# layout
pad_x = 20
staff_w = width - 2*pad_x
space = 12.0 # distance between staff lines
treble_top = 40.0
bass_top = 150.0
treble_bottom = treble_top + 4*space
bass_bottom = bass_top + 4*space
# chord x position
x = pad_x + staff_w * 0.25
note_w = 14.0
note_h = 10.0
parts = [f'")
return "\n".join(parts)