cgcardona / muse public
notes.py python
158 lines 5.5 KB
e6786943 feat: upgrade to Python 3.14, drop from __future__ import annotations Gabriel Cardona <cgcardona@gmail.com> 1d ago
1 """muse notes — musical notation view of a MIDI track.
2
3 Shows every note in a MIDI file as structured musical data: pitch name,
4 beat position, bar number, duration, velocity, and MIDI channel.
5
6 Unlike ``git show`` which gives you a binary blob diff, ``muse notes``
7 gives you the actual musical content — readable, sorted, historical.
8
9 Usage::
10
11 muse notes tracks/melody.mid
12 muse notes tracks/bass.mid --commit HEAD~3
13 muse notes tracks/drums.mid --bar 4 # only notes in bar 4
14 muse notes tracks/melody.mid --channel 0 # only channel 0
15 muse notes tracks/melody.mid --json
16
17 Output::
18
19 tracks/melody.mid — 23 notes — commit cb4afaed
20 Key signature (estimated): G major
21
22 Bar Beat Pitch Vel Dur(beats) Channel
23 ─────────────────────────────────────────────────
24 1 1.00 G4 80 1.00 ch 0
25 1 2.00 B4 75 0.50 ch 0
26 1 2.50 D5 72 0.50 ch 0
27 1 3.00 G4 80 1.00 ch 0
28 2 1.00 A4 78 1.00 ch 0
29 ...
30
31 23 note(s) across 8 bar(s)
32 """
33
34 import json
35 import logging
36 import pathlib
37
38 import typer
39
40 from muse.core.errors import ExitCode
41 from muse.core.repo import require_repo
42 from muse.core.store import get_head_commit_id, resolve_commit_ref
43 from muse.plugins.midi._query import (
44 NoteInfo,
45 key_signature_guess,
46 load_track,
47 load_track_from_workdir,
48 )
49
50 logger = logging.getLogger(__name__)
51
52 app = typer.Typer()
53
54
55 def _read_repo_id(root: pathlib.Path) -> str:
56 return str(json.loads((root / ".muse" / "repo.json").read_text())["repo_id"])
57
58
59 def _read_branch(root: pathlib.Path) -> str:
60 head_ref = (root / ".muse" / "HEAD").read_text().strip()
61 return head_ref.removeprefix("refs/heads/").strip()
62
63
64 @app.callback(invoke_without_command=True)
65 def notes(
66 ctx: typer.Context,
67 track: str = typer.Argument(..., metavar="TRACK", help="Workspace-relative path to a .mid file."),
68 ref: str | None = typer.Option(
69 None, "--commit", "-c", metavar="REF",
70 help="Read from a historical commit instead of the working tree.",
71 ),
72 bar_filter: int | None = typer.Option(
73 None, "--bar", "-b", metavar="N",
74 help="Only show notes in bar N (1-indexed, assumes 4/4 time).",
75 ),
76 channel_filter: int | None = typer.Option(
77 None, "--channel", "-C", metavar="N",
78 help="Only show notes on MIDI channel N (0-based).",
79 ),
80 as_json: bool = typer.Option(False, "--json", help="Emit results as JSON."),
81 ) -> None:
82 """Show every note in a MIDI track as structured musical data.
83
84 ``muse notes`` parses the MIDI file and displays all notes with pitch
85 name, beat position, bar number, duration, velocity, and channel.
86
87 Use ``--commit`` to inspect a historical snapshot. Use ``--bar`` to
88 focus on a single bar. Use ``--json`` for pipeline integration.
89
90 Unlike ``git show`` which gives you a raw binary diff, ``muse notes``
91 gives you the actual musical content at any point in history — sorted
92 by time, readable as music notation.
93 """
94 root = require_repo()
95
96 result: tuple[list[NoteInfo], int] | None
97 commit_label = "working tree"
98
99 if ref is not None:
100 repo_id = _read_repo_id(root)
101 branch = _read_branch(root)
102 commit = resolve_commit_ref(root, repo_id, branch, ref)
103 if commit is None:
104 typer.echo(f"❌ Commit '{ref}' not found.", err=True)
105 raise typer.Exit(code=ExitCode.USER_ERROR)
106 result = load_track(root, commit.commit_id, track)
107 commit_label = commit.commit_id[:8]
108 else:
109 result = load_track_from_workdir(root, track)
110
111 if result is None:
112 typer.echo(f"❌ Track '{track}' not found or not a valid MIDI file.", err=True)
113 raise typer.Exit(code=ExitCode.USER_ERROR)
114
115 note_list, tpb = result
116
117 # Apply filters.
118 if bar_filter is not None:
119 note_list = [n for n in note_list if n.bar == bar_filter]
120 if channel_filter is not None:
121 note_list = [n for n in note_list if n.channel == channel_filter]
122
123 if as_json:
124 out: list[dict[str, str | int | float]] = [
125 {
126 "pitch": n.pitch,
127 "pitch_name": n.pitch_name,
128 "velocity": n.velocity,
129 "start_tick": n.start_tick,
130 "duration_ticks": n.duration_ticks,
131 "beat": round(n.beat, 4),
132 "beat_duration": round(n.beat_duration, 4),
133 "bar": n.bar,
134 "beat_in_bar": round(n.beat_in_bar, 2),
135 "channel": n.channel,
136 }
137 for n in note_list
138 ]
139 typer.echo(json.dumps({"track": track, "commit": commit_label, "notes": out}, indent=2))
140 return
141
142 bars_seen: set[int] = {n.bar for n in note_list}
143
144 key = key_signature_guess(note_list) if not bar_filter and not channel_filter else ""
145 key_line = f"\nKey signature (estimated): {key}" if key else ""
146
147 typer.echo(f"\n{track} — {len(note_list)} notes — {commit_label}{key_line}")
148 typer.echo("")
149 typer.echo(f" {'Bar':>4} {'Beat':>5} {'Pitch':<6} {'Vel':>3} {'Dur':>10} Channel")
150 typer.echo(" " + "─" * 50)
151
152 for note in note_list:
153 typer.echo(
154 f" {note.bar:>4} {note.beat_in_bar:>5.2f} {note.pitch_name:<6} "
155 f"{note.velocity:>3} {note.beat_duration:>10.2f} ch {note.channel}"
156 )
157
158 typer.echo(f"\n{len(note_list)} note(s) across {len(bars_seen)} bar(s)")