File size: 5,761 Bytes
7700c61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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'<line x1="{x-w}" y1="{yy}" x2="{x+w}" y2="{yy}" stroke="#111" stroke-width="1"/>')
    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'<line x1="{x-w}" y1="{yy}" x2="{x+w}" y2="{yy}" stroke="#111" stroke-width="1"/>')
    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'<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">']
    parts.append('<rect x="0" y="0" width="100%" height="100%" fill="white"/>')

    def draw_staff(y_top: float):
        for i in range(5):
            y = y_top + i*space
            parts.append(f'<line x1="{pad_x}" y1="{y}" x2="{pad_x+staff_w}" y2="{y}" stroke="#111" stroke-width="1"/>')

    draw_staff(treble_top)
    draw_staff(bass_top)

    # Clef symbols (simple text glyphs to avoid font dependency)
    parts.append(f'<text x="{pad_x+6}" y="{treble_top+3*space}" font-size="28" fill="#111">𝄞</text>')
    parts.append(f'<text x="{pad_x+6}" y="{bass_top+3*space}" font-size="28" fill="#111">𝄢</text>')

    def draw_chord(notes: List[int], clef: str, y_top: float, y_bottom: float):
        if not notes:
            return
        # Slight x offsets for close seconds to avoid full overlap
        ys = []
        accs = []
        for m in notes:
            y, acc = _staff_y_for_midi(m, prefer_sharps, clef, y_bottom, space)
            ys.append(y); accs.append(acc)

        # sort by y (higher first)
        notes_info = sorted(zip(notes, ys, accs), key=lambda t: t[1])
        x_offsets = []
        last_y = None
        toggle = -1
        for _, y, _ in notes_info:
            if last_y is not None and abs(y - last_y) < (space/2 + 0.5):
                toggle *= -1
                x_offsets.append(toggle * 6.0)
            else:
                toggle = -1
                x_offsets.append(0.0)
            last_y = y

        for (m, y, acc), xo in zip(notes_info, x_offsets):
            # ledger lines
            for ln in _ledger_lines(y, y_top, y_bottom, x+xo, note_w, space):
                parts.append(ln)
            # accidental
            if acc:
                parts.append(f'<text x="{x+xo-18}" y="{y+4}" font-size="14" fill="#111">{acc}</text>')
            # notehead (whole note)
            parts.append(f'<ellipse cx="{x+xo}" cy="{y}" rx="{note_w/2}" ry="{note_h/2}" fill="white" stroke="#111" stroke-width="1.6"/>')

    draw_chord(treble, "treble", treble_top, treble_bottom)
    draw_chord(bass, "bass", bass_top, bass_bottom)

    # Barline
    parts.append(f'<line x1="{pad_x+staff_w}" y1="{treble_top}" x2="{pad_x+staff_w}" y2="{bass_bottom}" stroke="#111" stroke-width="2"/>')

    parts.append("</svg>")
    return "\n".join(parts)