From 5aab2cc80406933e5b13f8223d6f9a7a733e5630 Mon Sep 17 00:00:00 2001 From: PhysShell <45852143+PhysShell@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:35:58 +0500 Subject: [PATCH 1/4] Studio marks specification Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N3gqehBgzmDPPQ4dCur7DJ --- composer-lab/STUDIO-MARKS-SPEC.md | 54 +++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 composer-lab/STUDIO-MARKS-SPEC.md diff --git a/composer-lab/STUDIO-MARKS-SPEC.md b/composer-lab/STUDIO-MARKS-SPEC.md new file mode 100644 index 0000000..ebe5246 --- /dev/null +++ b/composer-lab/STUDIO-MARKS-SPEC.md @@ -0,0 +1,54 @@ +# Studio: mark "sounds wrong here" on the timeline (specification) + +Base: branch `claude/studio-key` (PR #225). Both front ends (`studio/index.html`, Studio Web) share `studio/engine.py`, `studio/web_api.py` and `composer.py`. + +## Problem (from the owner) + +Some pieces have places where 2–3 notes sound like no guitarist would play them: an odd rest, or a note that falls out of the rhythm. The owner cannot always explain it. Writing down seconds by hand is tedious. The owner wants to mark the place on the timeline while listening. We then read the marks, inspect what the generator did there, and fix the rules. Later the same marks feed a preference model and bar-level editing. + +## Required behaviour + +1. **Making a mark.** While a piece is playing or paused, the owner can add a mark in three ways: + - the button «Тут не так»; + - the key `M`, when focus is not in a text field; + - a click on the timeline with a modifier: Shift+click, or a long press on touch. + + A plain click on the timeline keeps today's meaning: seek. The mark takes the current playback position, or the clicked position. +2. **Mark contents.** Stored with the piece: + - an `id`; + - the time in seconds; + - the 1-based bar number and the sixteenth inside the bar, computed from the piece's tempo and meters; + - the section label; + - the guitar: `lead` / `rhythm` / `both`, default `both`; + - an optional short text, up to 80 characters; + - the `notes` of both guitars sounding or starting within ±1 sixteenth: pitch, start, duration, string, fret, tech; + - the recipe revision it was made on. +3. **Mark editor.** After a mark is added, a small inline editor (not a modal) lets the owner set the guitar and the text, or delete the mark. Enter or "Готово" closes it; Esc deletes a mark that was just added. +4. **Display.** + - Marks appear as small flags on the timeline at their time. + - Clicking a flag seeks to 1 bar before it and opens its editor. + - A list «Отметки (N)» under the timeline shows bar:sixteenth, the guitar and the text. Clicking a row seeks the same way. + - Marks made on an older revision show «(до изменения)» and are greyed. +5. **Auditioning a mark.** "Послушать место" on a flag or row plays from 1 bar before to 1 bar after the mark, then stops. +6. **Persistence.** Marks are stored in the piece state: + - server: `marks.json` in the piece folder, path-checked like the other files; + - Web: the piece record in IndexedDB, included in export and import. + + Adding, editing or deleting a mark does not change the music. It does not push undo or redo and does not clear redo. Each such action is logged to `history.jsonl` as `mark_add` / `mark_edit` / `mark_delete` with the full mark. `studio.summary` lists the mark count per piece. +7. **Export for analysis.** A button «Скачать отметки» downloads `marks.json` for the current piece, or for all pieces from the sidebar. Each file has the seed, the recipe and the marks. +8. **Russian UI text.** The hint under the list reads: «Отметьте место, где звучит не по-человечески: кнопка «Тут не так», клавиша M или Shift+клик по таймлайну. Музыку это не меняет.» + +## Tests (write first) + +- **Bar and sixteenth.** Bar and sixteenth computed from time are correct for 4/4, 7/8, and 7/8 → 5/4 → 7/8, including the intro. +- **Notes snapshot.** The captured notes for a mark equal the composed notes within ±1 sixteenth. +- **Music unchanged.** Adding, editing and deleting marks leaves the MIDI byte-identical, does not change the undo or redo stacks, and logs the three actions. +- **Round trip.** Server save/load and Web export/import round-trip the marks. Legacy pieces without marks load fine. +- **Stale marks.** A mark made before a reroll is flagged stale after it. +- **Path safety.** The server path check covers `marks.json`. +- **Parity.** Server and web behave the same. +- **Page tests.** + - `M` adds a mark at the playback position. + - Shift+click adds a mark; a plain click only seeks. + - Esc removes a new mark. + - "Послушать место" sets the start and stop correctly. From 31b1395cbdf7eb5d0fc10943ca53da35aee9904a Mon Sep 17 00:00:00 2001 From: PhysShell <45852143+PhysShell@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:01:49 +0500 Subject: [PATCH 2/4] Studio marks: mark "sounds wrong here" on the timeline Marks are stored per piece (marks.json on the server, the piece state in Studio Web), carry bar and sixteenth computed from the piece meters, the section, guitar, text, a snapshot of the sounding notes and the recipe revision. They never touch the music, undo or redo, are logged as mark_add, mark_edit and mark_delete, are counted by studio.summary and can be downloaded as marks.json for one piece or for all pieces. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01N3gqehBgzmDPPQ4dCur7DJ --- composer-lab/README.md | 2 + composer-lab/studio/engine.py | 267 +++++++++++- composer-lab/studio/index.html | 315 +++++++++++++- composer-lab/studio/server.py | 27 +- composer-lab/studio/summary.py | 11 + composer-lab/studio/web_api.py | 77 +++- composer-lab/test_studio.py | 615 +++++++++++++++++++++++++++- composer-lab/test_web_api.py | 117 ++++++ composer-lab/web/app.js | 339 ++++++++++++++- composer-lab/web/index.html | 44 ++ composer-lab/web/tests/harness.js | 79 +++- composer-lab/web/tests/test_app.mjs | 316 ++++++++++++++ 12 files changed, 2171 insertions(+), 38 deletions(-) diff --git a/composer-lab/README.md b/composer-lab/README.md index 1e9ad49..f3c847f 100644 --- a/composer-lab/README.md +++ b/composer-lab/README.md @@ -111,6 +111,8 @@ python -m studio.summary out_studio доступен как `POST /api/piece/{id}/redo`; в журнал `history.jsonl` пишется действие `redo`. Оба стека ограничены 50 шагами. +Отметки «Тут не так» (кнопка, клавиша `M`, Shift+клик по таймлайну) хранятся в `marks.json` в папке пьесы (в Studio Web — в состоянии пьесы) и не меняют музыку, `undo.json` и `redo.json`; в журнал пишутся `mark_add`, `mark_edit`, `mark_delete`. «Скачать отметки» отдаёт `marks.json` с seed, рецептом и отметками (`GET /api/piece/{id}/marks.json`, все пьесы — `GET /api/marks.json`). Подробности — `STUDIO-MARKS-SPEC.md`. + ## Studio Web Static browser version of Studio (`composer-lab/web/`): runs the Python generator directly in the browser via Pyodide (`v0.27.7` from `cdn.jsdelivr.net`) inside a Web Worker and plays pieces with a Web Audio multi-velocity MP3 sampler (`web/samples/`, rendered from FreePats EGuitarFSBS clean). Pieces and usage logs are stored in IndexedDB with JSON export/import and `history.jsonl` download (`studio/summary.py` compatible). diff --git a/composer-lab/studio/engine.py b/composer-lab/studio/engine.py index 463febe..5567190 100644 --- a/composer-lab/studio/engine.py +++ b/composer-lab/studio/engine.py @@ -1,7 +1,9 @@ """Pure recipe operations and filesystem-backed store for Studio.""" import argparse +import bisect import copy import datetime +import hashlib import json import math import os @@ -11,6 +13,7 @@ import tempfile import threading import time +import uuid from pathlib import Path import composer @@ -79,6 +82,9 @@ VALID_SQUARE_REPEAT = (1, 2) HISTORY_LIMIT = 50 PIECE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$") +MARK_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,40}$") +MARK_TEXT_MAX = 80 +VALID_MARK_GUITARS = ("lead", "rhythm", "both") def default_options(): @@ -366,7 +372,7 @@ def piece_sections(piece): return spans -def piece_detail(piece_id, recipe, piece, undo_stack=(), redo_stack=()): +def piece_detail(piece_id, recipe, piece, undo_stack=(), redo_stack=(), marks=()): rec = _ensure_studio(recipe) st = rec["studio"] salts = st["salts"] @@ -409,10 +415,195 @@ def layer_info(layer, section): "sections": sections, "whole_layers": whole_layers, "options": dict(st["options"]), + "rev": recipe_rev(rec), + "marks": marks_view(rec, piece, marks), **history_labels(recipe, list(undo_stack), list(redo_stack)), } +def recipe_rev(recipe): + raw = json.dumps(_ensure_studio(recipe), sort_keys=True, separators=(",", ":")) + return hashlib.sha1(raw.encode("ascii")).hexdigest()[:12] + + +def _bar_index(piece, t16): + starts = [c["start"] for c in piece["chords"]] + return max(0, bisect.bisect_right(starts, t16) - 1) + + +def _bar_span(piece, i): + chords = piece["chords"] + end = chords[i + 1]["start"] if i + 1 < len(chords) else piece["total16"] + return chords[i]["start"], end + + +def _clamped_t16(piece, t): + return max(0.0, min(t * piece["tempo"] / 15.0 + 1e-6, piece["total16"] - 1e-6)) + + +def bar_position(piece, t): + t16 = _clamped_t16(piece, t) + i = _bar_index(piece, t16) + start, end = _bar_span(piece, i) + return {"bar": i + 1, "sixteenth": min(int(t16 - start) + 1, end - start)} + + +def mark_notes(piece, t): + t16 = t * piece["tempo"] / 15.0 + lo, hi = t16 - 1, t16 + 1 + out = [] + for guitar, g in ((1, "g1"), (2, "g2")): + for n in piece["parts"][g]: + if n["start"] <= hi and n["start"] + n["dur"] > lo: + out.append({ + "guitar": guitar, + "pitch": int(n["pitch"]), + "start": n["start"], + "dur": n["dur"], + "string": n.get("string"), + "fret": n.get("fret"), + "tech": list(n.get("tech", [])), + }) + out.sort(key=lambda n: (n["start"], n["guitar"], n["pitch"])) + return out + + +def _mark_guitar(value): + if value not in VALID_MARK_GUITARS: + raise ValueError(f"invalid guitar: {value}") + return value + + +def _mark_text(value): + _require_text(value, "text") + if len(value) > MARK_TEXT_MAX: + raise ValueError(f"text is longer than {MARK_TEXT_MAX} characters") + return value + + +def make_mark(recipe, piece, t, guitar="both", text=""): + num = _number(t, "t") + if not 0 <= num <= piece["total16"] * 15.0 / piece["tempo"]: + raise ValueError("t is outside the piece") + pos = bar_position(piece, num) + sec = piece["chords"][_bar_index(piece, _clamped_t16(piece, num))]["sec"] + return { + "id": "m" + uuid.uuid4().hex[:8], + "t": round(float(num), 3), + "bar": pos["bar"], + "sixteenth": pos["sixteenth"], + "section": sec, + "section_label": SECTION_LABELS.get(sec, sec), + "guitar": _mark_guitar(guitar), + "text": _mark_text(text), + "notes": mark_notes(piece, num), + "rev": recipe_rev(recipe), + } + + +def _is_int(value): + return isinstance(value, int) and not isinstance(value, bool) + + +def _parse_mark(raw): + if not isinstance(raw, dict): + raise ValueError("mark must be an object") + mid = raw.get("id") + if not isinstance(mid, str) or not MARK_ID_RE.match(mid): + raise ValueError("invalid mark id") + if not _is_int(raw.get("bar")) or raw["bar"] < 1 or not _is_int(raw.get("sixteenth")) or raw["sixteenth"] < 1: + raise ValueError("invalid mark position") + if _number(raw.get("t"), "mark.t") < 0: + raise ValueError("invalid mark time") + for key in ("section", "section_label", "rev"): + _require_text(raw.get(key), f"mark.{key}") + notes = raw.get("notes") + if not isinstance(notes, list) or any(not isinstance(n, dict) for n in notes): + raise ValueError("invalid mark notes") + return { + "id": mid, + "t": raw["t"], + "bar": raw["bar"], + "sixteenth": raw["sixteenth"], + "section": raw["section"], + "section_label": raw["section_label"], + "guitar": _mark_guitar(raw.get("guitar")), + "text": _mark_text(raw.get("text")), + "notes": copy.deepcopy(notes), + "rev": raw["rev"], + } + + +def parse_marks(raw): + if raw is None: + return [] + if not isinstance(raw, list): + raise ValueError("marks must be a list") + marks = [_parse_mark(m) for m in raw] + if len({m["id"] for m in marks}) != len(marks): + raise ValueError("duplicate mark id") + return marks + + +def apply_mark_add(recipe, piece, marks, t, guitar="both", text=""): + mark = make_mark(recipe, piece, t, guitar, text) + return list(marks) + [mark], mark, True + + +def _mark_index(marks, mark_id): + i = next((k for k, m in enumerate(marks) if m["id"] == mark_id), None) + if i is None: + raise KeyError(f"unknown mark id: {mark_id}") + return i + + +def apply_mark_edit(recipe, piece, marks, mark_id, guitar=None, text=None): + i = _mark_index(marks, mark_id) + mark = dict(marks[i]) + if guitar is not None: + mark["guitar"] = _mark_guitar(guitar) + if text is not None: + mark["text"] = _mark_text(text) + if mark == marks[i]: + return list(marks), marks[i], False + out = list(marks) + out[i] = mark + return out, mark, True + + +def apply_mark_delete(recipe, piece, marks, mark_id): + i = _mark_index(marks, mark_id) + return list(marks[:i]) + list(marks[i + 1:]), marks[i], True + + +def marks_view(recipe, piece, marks): + rev = recipe_rev(recipe) + sec = 15.0 / piece["tempo"] + length = piece["total16"] * sec + out = [] + for m in marks: + start, end = _bar_span(piece, _bar_index(piece, _clamped_t16(piece, m["t"]))) + bar_sec = (end - start) * sec + view = dict(m) + view["stale"] = m["rev"] != rev + view["from_sec"] = round(max(0.0, m["t"] - bar_sec), 2) + view["to_sec"] = round(min(length, m["t"] + bar_sec), 2) + out.append(view) + return out + + +def marks_export(piece_id, recipe, piece, marks): + rev = recipe_rev(recipe) + return { + "version": 1, + "id": piece_id, + "seed": recipe["seed"], + "rev": rev, + "recipe": recipe, + "marks": [{**m, "stale": m["rev"] != rev} for m in marks], + } + + def _now_iso(): return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") @@ -522,6 +713,17 @@ def _log_history(self, pdir, action, layer=None, section=None, salt=None, value= with self._history_lock, path.open("a", encoding="utf-8") as f: f.write(json.dumps(row, ensure_ascii=False) + "\n") + def _read_marks(self, pdir): + path = self._inside(pdir, "marks.json") + if not path.exists(): + return [] + return parse_marks(json.loads(path.read_text(encoding="utf-8"))) + + def _write_marks(self, pdir, marks): + tmp = self._inside(pdir, "marks.json.tmp") + tmp.write_text(json.dumps(marks, ensure_ascii=False), encoding="utf-8") + _replace(tmp, pdir / "marks.json") + def _build(self, pdir, recipe): stage = Path(tempfile.mkdtemp(prefix=".stage-", dir=pdir)) try: @@ -616,22 +818,25 @@ def get_piece(self, piece_id): pdir = self._piece_dir(piece_id) rec = self._read_recipe(pdir) piece = composer.compose(rec) - return piece_detail(piece_id, rec, piece, self._read_undo(pdir), self._read_redo(pdir)) + return piece_detail( + piece_id, rec, piece, self._read_undo(pdir), self._read_redo(pdir), self._read_marks(pdir) + ) def _change(self, piece_id, change, log): pdir = self._piece_dir(piece_id) with self._write_lock(piece_id): old_rec = self._read_recipe(pdir) base_rec = _ensure_studio(old_rec) + marks = self._read_marks(pdir) new_rec = change(old_rec) if new_rec == base_rec: piece = composer.compose(old_rec) - return piece_detail(piece_id, old_rec, piece, self._read_undo(pdir), self._read_redo(pdir)) + return piece_detail(piece_id, old_rec, piece, self._read_undo(pdir), self._read_redo(pdir), marks) stack = self._read_undo(pdir) + [old_rec] piece, stage, reuse = self._build(pdir, new_rec) self._publish(pdir, stage, reuse, stack) log(pdir, new_rec) - return piece_detail(piece_id, new_rec, piece, stack[-HISTORY_LIMIT:]) + return piece_detail(piece_id, new_rec, piece, stack[-HISTORY_LIMIT:], (), marks) def reroll(self, piece_id, layer, section): def log(pdir, rec): @@ -661,14 +866,15 @@ def undo(self, piece_id): stack = self._read_undo(pdir) cur_rec = self._read_recipe(pdir) redo = self._read_redo(pdir) + marks = self._read_marks(pdir) if not stack: - return piece_detail(piece_id, cur_rec, composer.compose(cur_rec), [], redo) + return piece_detail(piece_id, cur_rec, composer.compose(cur_rec), [], redo, marks) prev_rec = stack.pop() redo = redo + [cur_rec] piece, stage, reuse = self._build(pdir, prev_rec) self._publish(pdir, stage, reuse, stack, redo) self._log_history(pdir, "undo") - return piece_detail(piece_id, prev_rec, piece, stack, redo[-HISTORY_LIMIT:]) + return piece_detail(piece_id, prev_rec, piece, stack, redo[-HISTORY_LIMIT:], marks) def redo(self, piece_id): pdir = self._piece_dir(piece_id) @@ -676,14 +882,59 @@ def redo(self, piece_id): redo = self._read_redo(pdir) cur_rec = self._read_recipe(pdir) stack = self._read_undo(pdir) + marks = self._read_marks(pdir) if not redo: - return piece_detail(piece_id, cur_rec, composer.compose(cur_rec), stack, []) + return piece_detail(piece_id, cur_rec, composer.compose(cur_rec), stack, [], marks) next_rec = redo.pop() stack = stack + [cur_rec] piece, stage, reuse = self._build(pdir, next_rec) self._publish(pdir, stage, reuse, stack, redo) self._log_history(pdir, "redo") - return piece_detail(piece_id, next_rec, piece, stack[-HISTORY_LIMIT:], redo) + return piece_detail(piece_id, next_rec, piece, stack[-HISTORY_LIMIT:], redo, marks) + + def _mark_change(self, piece_id, action, change): + pdir = self._piece_dir(piece_id) + with self._write_lock(piece_id): + rec = self._read_recipe(pdir) + piece = composer.compose(rec) + marks, mark, changed = change(rec, piece, self._read_marks(pdir)) + if changed: + self._write_marks(pdir, marks) + self._log_history(pdir, action, value=mark) + det = piece_detail(piece_id, rec, piece, self._read_undo(pdir), self._read_redo(pdir), marks) + return {**det, "mark": mark} + + def add_mark(self, piece_id, t, guitar="both", text=""): + return self._mark_change( + piece_id, "mark_add", lambda rec, piece, marks: apply_mark_add(rec, piece, marks, t, guitar, text) + ) + + def edit_mark(self, piece_id, mark_id, guitar=None, text=None): + return self._mark_change( + piece_id, + "mark_edit", + lambda rec, piece, marks: apply_mark_edit(rec, piece, marks, mark_id, guitar, text), + ) + + def delete_mark(self, piece_id, mark_id): + return self._mark_change( + piece_id, "mark_delete", lambda rec, piece, marks: apply_mark_delete(rec, piece, marks, mark_id) + ) + + def marks_export(self, piece_id): + pdir = self._piece_dir(piece_id) + rec = self._read_recipe(pdir) + return marks_export(piece_id, rec, composer.compose(rec), self._read_marks(pdir)) + + def all_marks_export(self): + pieces = [] + for pdir in sorted(self.out_dir.iterdir(), key=lambda p: p.name): + try: + if pdir.is_dir() and PIECE_ID_RE.match(pdir.name) and (pdir / "recipe.json").exists(): + pieces.append(self.marks_export(pdir.name)) + except (KeyError, OSError, ValueError): + continue + return {"version": 1, "pieces": pieces} def file_path(self, piece_id, filename, log_export=False): pdir = self._piece_dir(piece_id) diff --git a/composer-lab/studio/index.html b/composer-lab/studio/index.html index 55e206e..7ad17d3 100644 --- a/composer-lab/studio/index.html +++ b/composer-lab/studio/index.html @@ -138,6 +138,49 @@ overflow: hidden; transition: transform 0.1s ease, outline 0.1s ease; } + .timeline .sec-block { -webkit-touch-callout: none; user-select: none; } + .mark-bar { margin-top: 10px; } + .mark-track { position: relative; height: 24px; margin-top: 6px; border-top: 1px solid var(--border); } + .mark-flag { + position: absolute; + top: 3px; + width: 14px; + height: 20px; + min-width: 0; + margin-left: -2px; + padding: 0; + border: none; + border-left: 2px solid var(--text); + border-radius: 0 4px 4px 0; + background: var(--warn); + } + .mark-flag.stale { background: var(--muted); opacity: 0.5; } + .marks-box { margin-top: 12px; } + .marks-hint { font-size: 0.78rem; color: var(--muted); margin: 6px 0; } + .marks-title { margin: 0 0 8px 0; font-size: 0.95rem; color: var(--muted); font-weight: 600; } + .mark-list { display: flex; flex-direction: column; gap: 6px; } + .mark-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } + .mark-row .mark-open { flex: 1 1 200px; justify-content: flex-start; text-align: left; } + .mark-row.stale .mark-open { opacity: 0.5; } + .mark-editor { + display: flex; + gap: 8px; + flex-wrap: wrap; + align-items: center; + padding: 8px; + margin-bottom: 8px; + border: 1px solid var(--warn); + border-radius: 6px; + } + .mark-editor input[type="text"] { + flex: 1 1 180px; + min-width: 0; + background: var(--bg); + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + padding: 7px 9px; + } .sec-block:hover { transform: translateY(-1px); outline: 1px solid #fff; } .sec-block.playing { outline: 2px solid #fff; } .sec-block .name { font-size: 0.82rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @@ -259,6 +302,7 @@

Griff Studio

+ Скачать отметки всех пьес