"""vinot: violin audio -> notes / MIDI with pitch bend. python vinot.py my_violin.mp3 # -> my_violin.mid + my_violin.csv python vinot.py my_violin.mp3 --sheet # + sheet music: my_violin.musicxml and my_violin.pdf python vinot.py my_violin.wav -o out.mid --preset bot From Python: from vinot import Vinot model = Vinot.load() # folder with config.json and weights notes = model.transcribe("my_violin.wav") # list of Note(onset, offset, pitch, cents) model.to_midi(notes, "out.mid") model.to_sheet(notes, "my_violin.wav", "out_dir", title="My piece") # MusicXML + PDF """ import argparse import csv import json import os import sys from dataclasses import dataclass import numpy as np import torch HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import features as F # noqa: E402 import transcriber as TR # noqa: E402 from model import VQVAE # noqa: E402 from prep import Prep # noqa: E402 CENT_BINS = np.array([-40, -20, 0, 20, 40], np.float64) # f0 head: 5 sub-bins per semitone @dataclass class Note: onset: float # seconds offset: float # seconds pitch: int # MIDI number (55 = G3 ... 103 = G7) cents: float # mean deviation from the tempered pitch, cents cents_track: np.ndarray # per-10-ms deviation, cents (used for pitch bend) class Vinot: def __init__(self, vq, tr, prep, cfg, device='cpu'): self.vq, self.tr, self.prep, self.cfg, self.device = vq, tr, prep, cfg, device # ------------------------------------------------------------------ loading @classmethod def load(cls, path=HERE, device='cpu'): """path: a local folder or a Hugging Face repo id like 'vfdanil/vinot'.""" if not os.path.isdir(path): from huggingface_hub import snapshot_download path = snapshot_download(path) from safetensors.torch import load_file cfg = json.load(open(os.path.join(path, 'config.json'), encoding='utf-8')) a = cfg['vqvae'] vq = VQVAE(width=a['width'], n_blocks=a['n_blocks'], k=a['k'], c_levels=(a['c_levels'],), onset_probe=a['onset_probe'], p_rate=a['p_rate'], p_levels=a['p_levels'], k2=a['k2']) vq.load_state_dict(load_file(os.path.join(path, 'vqvae.safetensors'))) tr = TR.Transcriber(in_dim=cfg['transcriber']['in_dim']) tr.load_state_dict(load_file(os.path.join(path, 'transcriber.safetensors'))) for m in (vq, tr): m.to(device).eval() for p in m.parameters(): p.requires_grad_(False) return cls(vq, tr, Prep(cfg['input_stats'], device), cfg, device) # ------------------------------------------------------------------ audio def load_audio(self, path): import librosa y, _ = librosa.load(path, sr=F.SR, mono=True) return y.astype(np.float32) def normalize(self, y): """Bring the input to the loudness the model was tuned on (-26 dBFS RMS).""" ms = float(np.mean(y.astype(np.float64) ** 2)) if ms > 1e-12: y = y * 10 ** ((self.cfg['loudness_dbfs'] - 10 * np.log10(ms)) / 20) return y.astype(np.float32) # ------------------------------------------------------------------ model @torch.no_grad() def _codes(self, vqt, mel): h, _, mf, _ = self.prep.inputs(vqt, mel) zp, zr, zc = self.vq.encode_main(h, None) q = self.vq.quantize(zp, zr, zc, self.vq.encode_t(mf)) return TR.codes_to_input(q, h.shape[2]) @torch.no_grad() def probabilities(self, y16, chunk=1000, pad=100): """16 kHz mono audio -> frame-wise probabilities (10 ms frames, 49 pitches G3..G7).""" V = F.vqt(y16).astype(np.float16).astype(np.float32) M = F.logmel(y16)[:len(V)].astype(np.float16).astype(np.float32) n = len(V) outs = {k: [] for k in ('on', 'onfr', 'frame', 'off', 'f0')} for s in range(0, n, chunk): a, e = max(0, s - pad), min(n, s + chunk + pad) L = (e - a + 1) // 2 * 2 v, m = V[a:a + L], M[a:a + L] if len(v) < L: v = np.concatenate([v, np.full((L - len(v), v.shape[1]), F.LOG_FLOOR, np.float32)]) m = np.concatenate([m, np.full((L - len(m), m.shape[1]), np.log(1e-6), np.float32)]) vt = torch.from_numpy(v)[None].to(self.device) mt = torch.from_numpy(m)[None].to(self.device) o = self.tr(self._codes(vt, mt)) lo, hi = s - a, s - a + min(chunk, n - s) for k in outs: x = o[k][0, lo:hi] outs[k].append((torch.sigmoid(x) if k != 'f0' else x).cpu().numpy()) return {k: np.concatenate(v) for k, v in outs.items()} # ------------------------------------------------------------------ decoding @staticmethod def decode(P, th_on=0.5, th_fr=0.5, th_off=0.5, nms=3, t_mode='parabola', frame_edge=False, min_len=3): """Probabilities -> (onset_s, offset_s, midi) by peak-picking onsets and following frames.""" on, fr, off = P['on'], P['frame'], P['off'] T = on.shape[0] notes = [] for p in range(F.N_PITCH): x = on[:, p] peaks = [] for t in np.nonzero(x > th_on)[0]: a, b = max(0, t - nms), min(T, t + nms + 1) if x[t] >= x[a:b].max() and (not peaks or t - peaks[-1] > nms): peaks.append(int(t)) starts = set(peaks) if frame_edge: act = fr[:, p] > th_fr for r in np.nonzero(act & ~np.roll(act, 1))[0]: if not any(abs(r - q) <= nms for q in peaks): starts.add(int(r)) starts = sorted(starts) for i, t in enumerate(starts): nxt = starts[i + 1] if i + 1 < len(starts) else T e = t + 1 while e < nxt and fr[e, p] > th_fr and off[e - 1, p] < th_off: e += 1 if e - t < min_len: continue a0, a1, a2 = x[max(t - 1, 0)], x[t], x[min(t + 1, T - 1)] if t_mode == 'centroid': tc = t + (a2 - a0) / max(a0 + a1 + a2, 1e-6) + 0.5 elif t_mode == 'parabola': den = a0 - 2 * a1 + a2 tc = t + 0.5 + (0.5 * (a0 - a2) / den if abs(den) > 1e-6 else 0.0) else: tc = t + 0.5 notes.append((tc * 0.01, e * 0.01, F.MIDI_LO + p)) return sorted(notes) @staticmethod def drop_octave_ghosts(notes, P, ratio=1.5, tol=0.05, overlap=0.5): """Remove a note when the same note an octave away is clearly stronger and sounds at the same time.""" fr = P['frame'] def strength(n): a, b = int(n[0] * 100), max(int(n[1] * 100), int(n[0] * 100) + 1) return float(fr[a:b, n[2] - F.MIDI_LO].mean()) S = [strength(n) for n in notes] keep = [] for i, n in enumerate(notes): drop = False for j, m in enumerate(notes): if i == j or abs(m[2] - n[2]) != 12: continue ov = min(n[1], m[1]) - max(n[0], m[0]) if (abs(m[0] - n[0]) <= tol or ov >= overlap * (n[1] - n[0])) and S[j] > ratio * S[i]: drop = True break if not drop: keep.append(n) return keep # ------------------------------------------------------------------ main entry def transcribe(self, audio, preset='default', normalize=True): """audio: path or 16 kHz mono float array. preset: 'default' (best on benchmarks) or 'bot'.""" y = self.load_audio(audio) if isinstance(audio, str) else np.asarray(audio, np.float32) if normalize: y = self.normalize(y) P = self.probabilities(y) dec = self.cfg['decode'] if preset == 'default' else self.cfg['decode_bot'] raw = self.drop_octave_ghosts(self.decode(P, **dec), P, **self.cfg['octave']) sm = torch.softmax(torch.from_numpy(P['f0']), -1).numpy() notes = [] for on, off, pitch in raw: p = int(pitch) - F.MIDI_LO a, b = int(on * 100), max(int(on * 100) + 1, int(off * 100)) seg = sm[a:b, p * 5:p * 5 + 5] track = (seg * CENT_BINS).sum(1) / np.maximum(seg.sum(1), 1e-6) if len(seg) else np.zeros(1) notes.append(Note(float(on), float(off), int(pitch), float(track.mean()), track)) return notes @staticmethod def to_midi(notes, path): """Notes -> MIDI file; vibrato and intonation go into pitch bend (range ±2 semitones).""" TR.to_midi([(n.onset, n.offset, n.pitch, n.cents, n.cents_track) for n in notes], path) def to_sheet(self, notes, audio, out_dir, title='vinot', stem='notes'): """Notes -> sheet music: MusicXML + PDF (+ PNG of page 1). Same code as the Telegram bot. Tempo, meter and rhythm are estimated from the recording itself. Needs music21, verovio, pymupdf.""" import librosa import score as SC y = librosa.load(audio, sr=22050, mono=True)[0] if isinstance(audio, str) else librosa.resample(np.asarray(audio, np.float32), orig_sr=F.SR, target_sr=22050) os.makedirs(out_dir, exist_ok=True) return SC.make([(n.onset, n.offset, n.pitch, n.cents, n.cents_track) for n in notes], y, 22050, title, out_dir, stem) @staticmethod def to_csv(notes, path): with open(path, 'w', newline='', encoding='utf-8') as f: w = csv.writer(f) w.writerow(['onset_s', 'offset_s', 'midi', 'cents']) for n in notes: w.writerow([f'{n.onset:.3f}', f'{n.offset:.3f}', n.pitch, f'{n.cents:.1f}']) def main(): ap = argparse.ArgumentParser(description='Violin audio -> MIDI with pitch bend') ap.add_argument('audio') ap.add_argument('-o', '--out', help='output .mid (default: next to the input)') ap.add_argument('--preset', default='default', choices=['default', 'bot']) ap.add_argument('--sheet', action='store_true', help='also write sheet music (MusicXML + PDF)') ap.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu') args = ap.parse_args() model = Vinot.load(HERE, args.device) notes = model.transcribe(args.audio, preset=args.preset) out = args.out or os.path.splitext(args.audio)[0] + '.mid' model.to_midi(notes, out) model.to_csv(notes, os.path.splitext(out)[0] + '.csv') print(f'{len(notes)} notes -> {out}') if args.sheet: d, stem = os.path.split(os.path.splitext(out)[0]) r = model.to_sheet(notes, args.audio, d or '.', title=stem, stem=stem) print(f'sheet music -> {r["xml"]}, {r["pdf"]} ({r["pages"]} pages, tempo ~{r["bpm"]:.0f})') if __name__ == '__main__': main()