diff --git a/.github/workflows/cockpit-pages.yml b/.github/workflows/cockpit-pages.yml index 6d2d68bb..43750187 100644 --- a/.github/workflows/cockpit-pages.yml +++ b/.github/workflows/cockpit-pages.yml @@ -12,6 +12,7 @@ on: - 'experiment/**' - 'Cargo.toml' - 'Cargo.lock' + - 'composer-lab/**' - '.github/workflows/cockpit-pages.yml' workflow_dispatch: @@ -54,6 +55,17 @@ jobs: cargo install wasm-bindgen-cli --version "$ver" --locked - name: Build cockpit → cockpit/dist run: ./cockpit/build-web.sh + # Studio Web (composer-lab/web, Pyodide in the browser) is served under /studio/. + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Build Studio Web → cockpit/dist/studio + run: | + python composer-lab/web/build.py + python composer-lab/web/check_site.py + mkdir -p cockpit/dist/studio + cp -r composer-lab/web/index.html composer-lab/web/app.js composer-lab/web/worker.js \ + composer-lab/web/py composer-lab/web/samples cockpit/dist/studio/ - uses: actions/upload-pages-artifact@v3 with: path: cockpit/dist diff --git a/.github/workflows/cockpit-web-test.yml b/.github/workflows/cockpit-web-test.yml index c94711c4..c230a352 100644 --- a/.github/workflows/cockpit-web-test.yml +++ b/.github/workflows/cockpit-web-test.yml @@ -30,7 +30,8 @@ permissions: jobs: smoke: - runs-on: ubuntu-latest + # Playwright 1.56.1 has no browser dependencies for ubuntu-latest (26.04). + runs-on: ubuntu-24.04 steps: # persist-credentials: false — later steps build and run PR-authored code # (build scripts, the wasm, browser JS), so don't leave the token in diff --git a/composer-lab/.gitignore b/composer-lab/.gitignore new file mode 100644 index 00000000..5d74b6ee --- /dev/null +++ b/composer-lab/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +out/ +web/py/ + diff --git a/composer-lab/README.md b/composer-lab/README.md new file mode 100644 index 00000000..e1cab9ba --- /dev/null +++ b/composer-lab/README.md @@ -0,0 +1,127 @@ +# composer-lab + +Isolated prototype of a two-guitar composer (Python 3.12, standard library +only; not a Cargo workspace member). It exists to answer one question with +audio: can a hierarchical motif-development generator write guitar music worth +keeping, where the current S6/Swang path cannot? + +## Generate + +``` +python composer.py --seeds 101-120 --candidates 6 --out OUT --prefix new +python composer.py --seeds 5 --meter 7/8 --mode lydian --key E --tempo 150 --out OUT +python composer.py --recipe OUT/new_005.recipe.json --out OUT2 # rebuild or edit a piece +python composer.py --seeds 101-120 --out OUT --prefix shuf --control shuffle # pitch-randomised control +``` + +Per seed it writes `.mid` (type 1, one track per guitar plus a palm-mute +track), `.musicxml` (tablature with string/fret, tap, hammer-on, pull-off, +slide, palm mute), `.tab.txt` (ASCII tab) and `.recipe.json` (every sampled +decision; editing it and passing `--recipe` rebuilds the piece). The manifest +lists the critic row of every candidate considered. + +## Mechanism + +1. Intent: meter and accent grouping (4/4, 7/8, 6/8, 5/4; e.g. 3+3+2+3+3+2), + mode, key, tempo, which guitar leads. +2. Form: intro | A sentence (statement, sequence, fragment, cadence) | A' + (variation, call and response) | B contrast (palm-mute riff from its own + grouping, lead plays the hook inverted and augmented) | A'' climax (hook + with parallel diatonic thirds) | final chord. +3. Harmony: diatonic Markov progression with phrase-end targets; A must touch + the tonic. +4. Motif: a 2-4 note interval cell sequenced across the meter's groups; one + anchor per phrase so variation comes from harmony and operators, not from + re-planing; accented and phrase-final notes snap to chord tones. +5. Second guitar roles: arpeggio ladder with a common-tone upper shape, + pedal-tone interleave, or a single-string tapping triad; all yield to the + lead's attacks except on accents (interlock). +6. Fretboard: Viterbi over (string, fret, hand position), then techniques are + derived from the chosen positions. +7. Selection: 6 candidates per seed, best by a simple critic (clashes, + fingering cost, climax position). + +## Audition + +`render/audition_midi.py` forces every channel to program 0 and +`render/render.sh` renders with FluidSynth through the CC0 FreePats +"EGuitar FSBS clean" SoundFont plus sox reverb, the same for every arm. + +## Tests + +`python -m unittest test_composer` — byte determinism, string/fret +consistency, legato only on one string, taps above the fretting hand, rare +semitone clashes, every MusicXML measure filling its meter. + +## Studio + +Local web tool for section-level curation over v8 pieces (`127.0.0.1:8765`, +standard library only). + +Windows (PowerShell): + +```powershell +cd composer-lab +python -m studio.server --port 8765 --out out_studio +``` + +WSL (NixOS): + +```bash +cd composer-lab +nix shell --offline nixpkgs#python312 -c python3 -m studio.server --port 8765 --out out_studio +``` + +Open `http://127.0.0.1:8765` in a browser. Usage log summary across all curated +pieces: + +```bash +python -m studio.summary out_studio +``` + +### Как пользоваться (для владельца) + +Нажмите «Новая пьеса» (при желании укажите seed), дождитесь короткого рендера и +слушайте пьесу в плеере; клик по любому цветному блоку на таймлайне под плеером +сразу перематывает на выбранную секцию. Если часть не зашла, перегенерируйте +только нужный слой в этой секции (ритм-гитару, фактуру, вариант середины, +вступление, концовку) или весь риф / темп целиком — всё остальное останется +нетронутым; удачные слои закрепите кнопкой «Откр./Закр.», после чего можно +нажать «Перегенерировать всё незакреплённое». Снизу настраиваются скорость соло в +середине B, пауза в конце риф-такта и дозы v8 для следующих перегенераций ритма; +кнопка «Отменить» возвращает предыдущее состояние, а «Скачать MIDI» и «Скачать +табы (MusicXML)» сохраняют готовый трек для DAW и Guitar Pro. + +## 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). + +Build the self-contained Python bundle (`web/py/`, git-ignored) and verify the site: + +```bash +cd composer-lab +python3 web/build.py +python3 web/check_site.py +``` + +Run locally: + +```bash +cd composer-lab/web +python3 -m http.server 8000 +``` + +Open `http://127.0.0.1:8000` in a browser. Under WSL (NixOS), replace `python3` with `nix shell --offline nixpkgs#python312 -c python3`. + +Rebuild the 98 guitar samples (`web/samples/`, pitches 40–88 at velocities 72 and 100): + +```bash +cd composer-lab/web +nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg -c bash build_samples.sh +``` + +### Как пользоваться в браузере (для владельца) + +Откройте страницу на компьютере или телефоне: при первом запуске браузер загрузит Pyodide и сэмплы гитары (далее они берутся из кеша браузера). Нажмите «Новая пьеса» (при желании задайте `seed`), запускайте воспроизведение кнопкой «Играть» или кликом по блокам секций на таймлайне. Перегенерируйте отдельные слои, закрепляйте удачные кнопкой «Откр./Закр.», меняйте параметры снизу и скачивайте готовый результат в MIDI, MusicXML или ASCII-табах. Все пьесы и журнал действий сохраняются локально в браузере; в боковой панели доступны «Скачать журнал» (`history.jsonl`), «Экспорт пьес» и «Импорт пьес» для переноса между устройствами. + + diff --git a/composer-lab/STUDIO-SPEC.md b/composer-lab/STUDIO-SPEC.md new file mode 100644 index 00000000..7e70477a --- /dev/null +++ b/composer-lab/STUDIO-SPEC.md @@ -0,0 +1,202 @@ +# Studio: section-level curation tool for composer-lab (specification) + +Status: specification for implementation. Owner of the product decision: the +project owner (a guitarist who will use the output as a starting point for his +own tracks and edits MIDI himself). Written 2026-11-24 after a five-model +review concluded that blind rating rounds have stopped producing direction +and that the owner should curate instead of rate. + +## 1. Goal + +A small local web app in which the owner opens a generated piece, listens to +it, and replaces only the parts he dislikes: re-roll one layer of one section +while everything else stays exactly as it was, switch a few named options, +and export the result as MIDI and MusicXML tab for his DAW and Guitar Pro. + +Success is measured by use, not by tests: in one 30-45 minute sitting the +owner curates and exports at least one piece and opens it in his editor. The +tool logs his actions (section 8) so the next development step can be chosen +from what he actually re-rolls and keeps. + +## 2. Context you must read first + +- `composer-lab/README.md`: how pieces are generated, recipe files. +- `composer-lab/composer.py`: `make_recipe` (stacked version flags, each plan + layer has its own `random.Random(seed * K + c)` stream), `compose(recipe)` + (deterministic: same recipe -> same notes), `export` (writes `.mid`, + `.musicxml`, `.tab.txt`), dose tables `V8`, `V9`. +- `composer-lab/test_composer.py`: invariants every piece must keep (string and + fret consistency, legato only on one string, taps above the fretting hand, + no semitone clash on shared accented onsets, MusicXML measures fill their + meter, no minor ninths between the guitars in v7+), and the `NoTail` scope + test as the model for "change one thing, nothing else moves". +- `composer-lab/render/`: `audition_midi.py` (forces program 0), + `render.sh` (fluidsynth + sox), `to_mp3.sh`. Rendering runs inside WSL + (NixOS) under `nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg`; + the guitar SoundFont is `../_griff_out/sf/fsbs_clean.sf2` (next to the repository; override with GRIFF_SOUNDFONT). +- `CHANGE-7.md`, `CHANGE-8.md`, `CHANGE-9.md` (Result sections): the owner's + own words about what he wants to change in pieces. + +Base version for the tool: **v8** (`--v8`), the best-received version. Other +flags stay available as options, never as the default. + +## 3. Constraints + +- Python 3.12 standard library only (as the rest of composer-lab). The web + page is one static HTML file with inline CSS/JS, no build step, no CDN. +- Do not change the output of any existing version flag. Every existing test + in `test_composer.py` must still pass unchanged. New behaviour is opt-in + through new recipe fields that default to the current behaviour. +- Code, comments, commit messages and docs in English. Comments only where a + non-obvious invariant needs them; no history, task numbers or dates in code. +- Test-first: for each behaviour in section 6, write the failing test, then + the code. Run `python -m unittest test_composer` (from `composer-lab/`) and + the new tests; both must be green at the end. +- Work only inside `composer-lab/` of this worktree. Do not push. Commit in + small steps on the current branch. +- Never read or copy the owner's tab library (`D:\tabs`) or anything under + `_griff_out/corpus`; the tool does not need them. + +## 4. Data model: layers and salts + +A recipe gets one new optional field: + +```json +"studio": { + "salts": {"@
": , "...": 0}, + "locks": ["@
", "..."], + "options": {"b_lead": "augmented|same_speed|rest", "...": "..."} +} +``` + +A **layer** is one musical decision that can be re-drawn on its own. A +**section** is one of `intro`, `A`, `A2`, `B`, `A3`, `end` (only those present +in the piece's form). Re-rolling increments the salt of one `layer@section`; +the layer's random stream for that section is then +`random.Random(f"{recipe_seed}:{layer}:{section}:{salt}")` (string seeds are +deterministic in CPython). When a recipe has no `studio` field, every layer +behaves exactly as today. + +Required layers (v8 base): + +| Layer | Scope | What a re-roll changes | Must not change | +|---|---|---|---| +| `comp` | A or A2 | the second guitar's role per bar in that section (chords / chatter / octave chords) and, for chords, its strike rhythm (accents of the grouping bent as in `comp_pattern`, but drawn from the layer stream) | the lead, other sections, harmony | +| `texture` | A or A2 | arpeggio vs tapping for chatter bars, the arpeggio cycle order | lead, roles, other sections | +| `lead_rhythm` | whole piece (section `all`) | the hook's rhythm and contour (new hook drawn as `plan_motifs` would), keeping meter, mode, key, harmony, form | harmony, form, tempo, second-guitar plan (its mask may follow the new lead, as today) | +| `b` | B | the B variant (palm-mute chug / half-time chords / clean arpeggio) and the chug pattern | other sections | +| `intro` | intro | number of intro bars (1, 2 or 4) and the intro texture density | other sections | +| `ending` | end | held chord / short stop / riff-to-hard-end | other sections | +| `tempo` | whole piece | tempo within 0.8-1.1 of the current value | notes (only timing) | + +Required options (switches, not random): + +- `b_lead`: `augmented` (current behaviour: B lead = hook inverted with + doubled durations), `same_speed` (inverted hook at its original note + values), `rest` (no lead in B). The owner heard the augmented B lead as a + "drunk slowdown" in one piece and as fine in another, so this must be a + per-piece choice, not a global change. +- `trailing_rest`: on/off (`--notail` behaviour for this piece only). +- The `V8` doses (`octave_piece`, `octave_sixteenths`, `dead_notes`, + `slide_max`) as per-piece values that apply on the next re-roll of the + layers that use them. + +Locks: a locked `layer@section` is never re-rolled, including by "re-roll the +whole piece except locked parts". + +## 5. Web app + +`composer-lab/studio/server.py`: `python -m studio.server --port 8765 +--out ` (run from `composer-lab/`), `http.server`-based, binds +`127.0.0.1`. All state is files in ``: one folder per piece with +`recipe.json`, `piece.mid`, `piece.musicxml`, `piece.tab.txt`, `piece.mp3`, +and `history.jsonl`. + +JSON API (all POST bodies JSON, all responses JSON unless a file): + +- `POST /api/new {"seed": int|null}`: new v8 piece (random seed if null). +- `GET /api/pieces`: list with seed, meter, mode, key, tempo, length, sections. +- `GET /api/piece/`: recipe summary, section list with start/end seconds, + layers per section with salt and lock state, options. +- `POST /api/piece//reroll {"layer": str, "section": str}`. +- `POST /api/piece//lock {"layer": str, "section": str, "locked": bool}`. +- `POST /api/piece//option {"name": str, "value": ...}`. +- `POST /api/piece//undo`: restore the previous recipe (history stack). +- `GET /api/piece//audio.mp3`, `/piece.mid`, `/piece.musicxml`, + `/piece.tab.txt`. + +Every change writes the new recipe, re-runs `compose` + `export`, renders the +MP3 and appends a line to `history.jsonl` (section 8). Rendering: the server +calls a renderer function with a pluggable backend; the default backend runs +`render/audition_midi.py` then `render/render.sh` and `render/to_mp3.sh` +through `wsl -d NixOS -- nix shell ... -c bash ...` when the server runs on +Windows, or directly when it runs inside WSL. A fake backend for tests writes +a placeholder file. + +`composer-lab/studio/index.html` (served at `/`), one page, Russian UI +labels (the owner's language), works at desktop and phone width: + +- Piece list on the left / top: "Новая пьеса", list of pieces. +- Player for the current piece with a timeline under it: one coloured block + per section, labelled (Вступление, Куплет A, Куплет A2, Середина B, + Кульминация, Концовка) with its seconds. Clicking a block seeks the player. +- Per section, buttons for its layers ("Перегенерировать ритм-гитару", + "Фактура", "Вариант середины", "Вступление", "Концовка") and a lock toggle + per layer. Whole-piece buttons: "Новый риф" (`lead_rhythm`), "Темп", + "Перегенерировать всё незакреплённое". +- Options panel: B lead speed (три кнопки), trailing rest on/off, the V8 + doses as sliders with their current values. +- "Отменить", "Скачать MIDI", "Скачать табы (MusicXML)". +- A busy indicator while a change renders; the page stays usable. + +## 6. Tests (write first) + +In `composer-lab/test_studio.py` (stdlib `unittest`, no network, fake render +backend): + +1. A recipe without `studio` composes byte-identical MIDI to today for v8 + seeds 801, 802, 805, 807, 809, 810. +2. For each layer and each section it applies to, on 20 seeds: re-rolling + changes the target, and every note outside the declared scope (by section + time span and guitar) is identical before and after. For `lead_rhythm` + the declared scope is the lead and the second guitar's notes that are + masked by the lead; harmony, form and tempo are identical. +3. Re-rolling the same `layer@section` with the same salt twice gives the + same recipe and MIDI (determinism); different salts give a different + result in at least 15 of 20 seeds. +4. A locked layer is not changed by "re-roll all unlocked". +5. `b_lead`: `same_speed` B lead notes have the hook's durations; `rest` + leaves no lead notes in B; `augmented` equals today. +6. All invariants of `ComposerInvariants` hold for 20 seeds after 5 random + re-rolls each. +7. Undo restores the previous recipe exactly. +8. Server: start on a free port in a thread, call `new`, `reroll`, `lock`, + `option`, `undo`, download MIDI; check status codes, JSON shape and that + files exist. `history.jsonl` has one line per change. + +A negative control for test 2: break the layer isolation on purpose (draw the +`comp` layer from the piece stream), confirm test 2 turns red, restore. + +## 7. Out of scope + +New musical idioms (fast single-note line, "шмель", rhythm skeletons from +tabs), band renders, blind listening packs, any change to versions v1-v9. + +## 8. Usage log + +`history.jsonl` per piece, one JSON object per change: +`{"t": ISO time, "action": "new|reroll|lock|option|undo|export", +"layer": ..., "section": ..., "salt": ..., "value": ...}`. Exports are logged +too. A small script `studio/summary.py ` prints, over all pieces: number +of re-rolls per layer, re-rolls before the first export per piece, options +used, pieces exported. This is the data for the next decision. + +## 9. Deliverables and acceptance + +- `studio/` package (server, page, renderer backends, summary), `test_studio.py`. +- README section "Studio" with the start command for Windows (PowerShell) and + for WSL, and a one-paragraph Russian how-to for the owner. +- All tests green; the negative control recorded in the final report. +- A final report (in the reply, not a file) listing: what was built, test + results with the command used, anything not done, and any place where the + spec could not be followed and why. diff --git a/composer-lab/STUDIO-WEB-SPEC.md b/composer-lab/STUDIO-WEB-SPEC.md new file mode 100644 index 00000000..04d20271 --- /dev/null +++ b/composer-lab/STUDIO-WEB-SPEC.md @@ -0,0 +1,163 @@ +# Studio Web: the Studio tool running fully in the browser (specification) + +Status: specification for implementation. Base: branch `claude/griff-studio` +(Studio with a local Python server, commits e84a719 and 31f0448, reviewed). +Goal: the same Studio, served as static files (GitHub Pages), with the +generator running in the browser through Pyodide, so the owner can use it from +a phone without a computer running a server. + +## 1. Scope + +In scope: a static web app in `composer-lab/web/` that offers everything the +current Studio page offers (new piece, section timeline, per-layer re-roll and +lock, whole-piece re-roll, options, undo, MIDI and MusicXML download, usage +log), with no server code at run time. + +Out of scope: changing the generator's music, the Rust Griff code, the +existing `cockpit` Pages site, and deploying. Deployment is a separate, +owner-approved step (section 9). + +## 2. Read first + +- `composer-lab/STUDIO-SPEC.md` (behaviour that must be preserved). +- `composer-lab/studio/engine.py` (pure recipe functions: `new_recipe`, + `reroll`, `set_lock`, `set_option`, `available_layers`, `piece_sections`, + `piece_detail`, plus the file-backed `StudioStore`), `studio/index.html` + (current UI), `studio/server.py` (API shapes the page uses). +- `composer-lab/composer.py`, `fretboard.py`, `midiio.py`, `musicxml.py` + (the generator; standard library only). +- `composer-lab/render/render.sh` (current sound: FluidSynth with the + FreePats "EGuitarFSBS clean" SoundFont, CC0, then sox reverb). + +## 3. Architecture + +1. **Python in the browser.** Load Pyodide from + `https://cdn.jsdelivr.net/pyodide//full/` (pin an exact + version released at least two weeks ago; no other CDN). Fetch the Python + sources from the site (`py/composer.py`, `py/fretboard.py`, `py/midiio.py`, + `py/musicxml.py`, `py/studio/engine.py`, `py/web_api.py`), write them into + Pyodide's virtual file system and import them. No Python package installs. +2. **`composer-lab/studio/web_api.py`** (new, pure Python, also runs under + CPython): an in-memory API over the engine's pure functions, JSON in, JSON + out, no file system or subprocess use: + - `new_piece(seed|None) -> state` + - `reroll(state, layer, section) -> state`, `lock(state, layer, section, + locked) -> state`, `option(state, name, value) -> state`, `undo(state) -> + state` + - `detail(state) -> dict` (what the page shows: sections with start/end + seconds and labels, layers with salt and lock, options, can_undo) + - `events(state) -> list` of notes for playback: `{"t": seconds, "dur": + seconds, "pitch": int, "vel": int, "guitar": 1|2, "dead": bool}`, with + ring durations as realized, sorted by time. + - `export_midi(state) -> base64 str`, `export_musicxml(state) -> str`, + `export_tab(state) -> str`. + - `state` is a JSON-serializable dict holding the recipe and the undo stack + (bounded to 50 entries). The JS side stores it; Python keeps no globals + between calls. + It must reuse the engine's functions; do not duplicate their logic. If the + engine's pure functions need a small refactor to be importable without + `StudioStore`'s dependencies, do it without changing behaviour (existing + tests stay green). +3. **Sound: a sampler, not a SoundFont player.** The SoundFont is 446 MB and + cannot be shipped. Add `composer-lab/web/build_samples.sh` (runs in WSL + under `nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg`) that + renders, with the same SoundFont path the renderer uses + (`../_griff_out/sf/fsbs_clean.sf2` (next to the repository; override with GRIFF_SOUNDFONT)), + one sample per MIDI pitch 40-88 at two velocities (72 and 100), 2.5 s + each, mono, 44.1 kHz, encoded as `.mp3` at 96 kbit/s into + `composer-lab/web/samples/` with a `manifest.json`. Target total size under + 8 MB. Commit the samples and the SoundFont's licence text + (`_griff_out/sf/fsbs_LICENSE.txt`) next to them. + In the page, a small Web Audio sampler plays `events(state)`: pick the + nearer velocity layer, scale gain by velocity, stop each note at its + duration with a 30 ms release, dead notes as 40 ms clicks at low gain, + guitar 1 panned left and guitar 2 right (as in the MIDI export), a single + convolution-free reverb is optional. Transport: play/pause, seek by + clicking a section block or a progress bar, current-time display. +4. **Persistence.** Pieces (their `state`) and the usage log live in + IndexedDB (fall back to memory if unavailable, wrapped in try/catch). A + "Скачать журнал" button downloads the log as JSONL in the same format as + `history.jsonl` (STUDIO-SPEC section 8), so `studio/summary.py` can read + it. A "Экспорт/импорт пьес" option saves and loads all pieces as one JSON + file. +5. **Files.** `composer-lab/web/index.html` (page, Russian UI labels as in + the current Studio page, inline CSS/JS, no build step), `web/app.js` (may + be inline instead), `web/samples/`, `web/build.py` (copies the Python + sources listed in 3.1 into `web/py/` so the site is self-contained; the + copies are generated and git-ignored, or the page fetches them from a + path configured in one constant — choose one and document it). +6. **Paths.** Every URL in the page is relative, so the site works under a + sub-path such as `/griff/studio/`. + +## 4. Behaviour to preserve + +Everything in STUDIO-SPEC sections 4 and 5 as implemented and reviewed on +`claude/griff-studio`: layer scopes, locks (including the ending riff and +frozen comp decisions), options, undo, dose snapshots. Same seed and same +action sequence must give the same notes in the browser as `engine` under +CPython (Pyodide runs the same CPython code). + +## 5. Performance and UX + +- First load: show a progress message while Pyodide and samples load; the + page must say clearly what is happening. Later loads use the browser cache. +- A re-roll must update the timeline and be playable within 2 s on a desktop + after Pyodide is loaded (compose is about 20-100 ms under CPython; measure + under Pyodide and report it). +- Run Python in a Web Worker so the UI does not freeze; the page stays usable + while a change is computed. +- Works at 360 px phone width; touch targets at least 40 px; no horizontal + scroll. + +## 6. Constraints + +- Python changes: standard library only; existing tests + (`python -m unittest test_composer test_studio` from `composer-lab`) stay + green; `test_composer.py` is not edited; outputs of all existing version + flags stay byte-identical. +- No secrets, no tracking, no network calls other than the pinned Pyodide CDN + and the site's own files. +- English for code, comments, docs; Russian for UI labels. Minimal comments. +- Work only inside `composer-lab/` of the worktree. Do not commit or push. +- Do not read `D:\tabs` or `_griff_out/corpus`. + +## 7. Tests (write first) + +- `composer-lab/test_web_api.py` (CPython, stdlib `unittest`): + 1. `new_piece(801000)` then `events` equals the notes of the engine piece + for the same seed (start, pitch, duration, velocity, guitar). + 2. For a fixed action sequence (re-roll comp@A, lock b@B, option b_lead + same_speed, re-roll all, undo), `web_api` and `StudioStore` (fake + render) end in identical recipes and identical MIDI bytes. + 3. `state` survives `json.dumps`/`json.loads` between every call. + 4. Undo stack bound: after 60 changes, 50 undos are possible and the 51st + reports no undo. + 5. `export_midi` decodes to the same bytes as `composer.export`. +- `composer-lab/web/check_site.py`: verifies the site is self-contained + (every relative URL referenced by `index.html`/`app.js` exists after + `build.py`; samples manifest lists existing files; total size of `web/` + under 12 MB excluding Pyodide). +- Browser check (report, not a unit test): if a headless Chromium or Edge is + available (`msedge --headless`), load the page from a local static server + (`python -m http.server` in `web/`), wait for Pyodide, create a piece, + re-roll a layer, and capture a screenshot and the console log; report + timings and any console errors. + +## 8. Deliverables + +- `studio/web_api.py`, `test_web_api.py`, `web/` (page, sampler, samples, + build and check scripts), README section "Studio Web" with: how to rebuild + samples, how to run locally (`python -m http.server` in `web/`), and a + short Russian how-to for the owner. +- A final report: what was built, test commands and results, Pyodide version + and load time, re-roll time under Pyodide, total site size, anything not + done, and any deviation from this spec with the reason. + +## 9. Deployment (not part of this task) + +The repository already deploys `cockpit/dist` to GitHub Pages +(`.github/workflows/cockpit-pages.yml`). The proposed deployment, to be done +only after the owner approves publishing, is one step in that workflow that +copies `composer-lab/web/` (after `build.py`) to `cockpit/dist/studio/`, so +Studio appears at `/studio/` without replacing the cockpit. Do not +edit the workflow in this task. diff --git a/composer-lab/composer.py b/composer-lab/composer.py new file mode 100644 index 00000000..41fa7d94 --- /dev/null +++ b/composer-lab/composer.py @@ -0,0 +1,2001 @@ +"""Griff composer-lab: hierarchical motif-development composer for two guitars. + +Layers: intent -> form -> harmony -> motif family -> phrase programs +(development operators) -> guitar roles -> fretboard realization. +Every sampled decision is stored in a recipe so a piece can be rebuilt. +""" +import argparse +import copy +import functools +import itertools +import json +import math +import random +import sys +from pathlib import Path + +import fretboard +import musicxml +from midiio import write_midi + +SCALES = { + "ionian": [0, 2, 4, 5, 7, 9, 11], + "lydian": [0, 2, 4, 6, 7, 9, 11], + "mixolydian": [0, 2, 4, 5, 7, 9, 10], + "dorian": [0, 2, 3, 5, 7, 9, 10], + "aeolian": [0, 2, 3, 5, 7, 8, 10], +} +TONICS = {"E": 4, "F#": 6, "A": 9, "B": 11, "D": 2, "G": 7, "C#": 1} +METERS = { # name: (sixteenths per bar, numerator, denominator, groupings) + "4/4": (16, 4, 4, [[3, 3, 3, 3, 4], [3, 3, 2, 3, 3, 2], [4, 4, 4, 4], [3, 3, 4, 3, 3]]), + "7/8": (14, 7, 8, [[4, 4, 3, 3], [3, 4, 3, 4], [4, 4, 6], [2, 2, 3, 2, 2, 3]]), + "6/8": (12, 6, 8, [[3, 3, 3, 3], [2, 2, 2, 3, 3], [6, 6]]), + "5/4": (20, 5, 4, [[4, 4, 4, 4, 4], [3, 3, 4, 3, 3, 4], [6, 6, 4, 4]]), +} +G1_RANGE = (55, 86) +G2_RANGE = (40, 72) + + +class Theory: + def __init__(self, tonic_pc, mode): + self.tonic_pc = tonic_pc + self.scale = SCALES[mode] + self.base = 48 + tonic_pc + + def midi(self, deg): + o, i = divmod(deg, 7) + return self.base + 12 * o + self.scale[i] + + def deg_near(self, midi): + best = None + for d in range(-21, 35): + dist = abs(self.midi(d) - midi) + if best is None or dist < best[0]: + best = (dist, d) + return best[1] + + def triad_ok(self, root): + r, t, f = (self.midi(root + k) for k in (0, 2, 4)) + return f - r == 7 + + def color_ok(self, root, k): + """A 9th (k=1) colours the chord only when it is a major 9th.""" + return k != 1 or (self.midi(root + 1) - self.midi(root)) % 12 == 2 + + def chord_pcs(self, root, ext=(0, 2, 4)): + return {self.midi(root + k) % 12 for k in ext if self.color_ok(root, k)} + + +def stable(deg, root): + return (deg - root) % 7 in (0, 2, 4) + + +# ---------------------------------------------------------------- planning + +def plan_intent(rng, args): + meter = args.meter or rng.choice(["4/4", "4/4", "7/8", "7/8", "6/8", "5/4"]) + L, num, den, groupings = METERS[meter] + grouping = rng.choice(groupings) + mode = args.mode or rng.choice(["ionian", "lydian", "lydian", "mixolydian", "dorian", "aeolian"]) + tonic = args.key or rng.choice(list(TONICS)) + base_tempo = {"4/4": (128, 160), "7/8": (140, 176), "6/8": (120, 150), "5/4": (130, 160)}[meter] + tempo = args.tempo or rng.randrange(*base_tempo) + b_meter = meter + if rng.random() < 0.3: + b_meter = rng.choice([m for m in METERS if m != meter]) + return { + "meter": meter, "grouping": grouping, "mode": mode, "tonic": tonic, + "tempo": tempo, "b_meter": b_meter, + "b_grouping": rng.choice(METERS[b_meter][3]), + "lead": rng.choice(["g1", "g1", "g2"]), + "intro_bars": rng.choice([1, 2, 2]), + } + + +def sample_prog(rng, th, n, start_choices, end_choices): + moves = [(3, 3.0), (5, 2.5), (1, 2.0), (6, 1.2), (4, 1.5), (2, 1.0)] + for _ in range(200): + prog = [rng.choice(start_choices)] + while len(prog) < n - 1: + r = prog[-1] + opts = [((r + m) % 7, w) for m, w in moves if th.triad_ok((r + m) % 7)] + tot = sum(w for _, w in opts) + x = rng.random() * tot + for c, w in opts: + x -= w + if x <= 0: + prog.append(c) + break + prog.append(rng.choice(end_choices)) + if all(a != b for a, b in zip(prog, prog[1:])) and len(set(prog)) >= min(3, n): + return prog + return prog + + +def plan_harmony(rng, th, intent): + ok = [r for r in range(7) if th.triad_ok(r)] + starts = [r for r in (0, 3, 5) if r in ok] or [0] + a = sample_prog(rng, th, 4, starts, [r for r in (4, 3, 1) if r in ok] or [0]) + if 0 not in a: + a[0 if a[1] != 0 else 2] = 0 + a2 = list(a) + alt = [r for r in ok if r not in (a[2], a[1])] + a2[2] = rng.choice(alt) + a2[3] = rng.choice([r for r in (5, 4, 3) if r in ok and r != a2[2]] or [a[3]]) + b = sample_prog(rng, th, 2, [r for r in (5, 3, 1) if r in ok and r != a[0]] or [3], + [r for r in (4, 1, 6) if r in ok] or [4]) + final = list(a[:2]) + [rng.choice([r for r in (3, 1) if r in ok and r != a[1]] or [a[2]]), + rng.choice([r for r in (4, 6) if r in ok] or [4])] + return {"A": a, "A2": a2, "B": b, "A3": final, "end": 0} + + +def gen_rhythm(rng, L, grouping, density, tail_rest=True): + starts = [] + p = 0 + for g in grouping: + starts.append(p) + p += g + on = {0} + for s in starts[1:]: + if rng.random() < 0.7: + on.add(s) + for s in starts[1:]: + if rng.random() < 0.35 * density: + on.add(s - 1) + if rng.random() < 0.5: + on.add(s - 2) + for _ in range(int(L * 0.12 * density)): + on.add(rng.randrange(1, L)) + if rng.random() < 0.6: + tail = rng.choice([3, 4]) + if tail_rest: + on = {o for o in on if o < L - tail} or {0} + on = sorted(on) + while len(on) < 4: + cand = rng.randrange(1, L - 2) + if cand not in on: + on.append(cand) + on.sort() + return on + + +def gen_contour(rng, n, arch): + offs = [0] + for i in range(1, n): + phase = i / max(1, n - 1) + up_bias = (0.65 if phase < 0.55 else 0.35) if arch == "up" else (0.35 if phase < 0.55 else 0.65) + last_leap = len(offs) > 1 and abs(offs[-1] - offs[-2]) >= 3 + if last_leap: + step = -1 if offs[-1] > offs[-2] else 1 + else: + x = rng.random() + mag = 1 if x < 0.55 else (0 if x < 0.62 else (2 if x < 0.84 else rng.choice([3, 4]))) + step = mag if rng.random() < up_bias else -mag + nxt = max(-6, min(8, offs[-1] + step)) + offs.append(nxt) + return offs + + +def gen_cell_hook(rng, L, grouping, tail_rest=True): + """Hook = a 2-4 note interval cell sequenced across the meter's groups.""" + cell_len = rng.choice([2, 3, 3, 4]) + cell = [0] + for _ in range(cell_len - 1): + cell.append(cell[-1] + rng.choice([1, 1, 2, -1, -2, 3, -3, 4])) + seq_step = rng.choice([-1, -1, 1, 2, -2, 3]) + rhythm, contour = [], [] + pos, k = 0, 0 + rests = rng.random() < 0.5 and tail_rest + for gi, g in enumerate(grouping): + base = k * seq_step + n = min(g, cell_len) + spacing = 1 if g <= cell_len + 1 or rng.random() < 0.6 else 2 + for i in range(n): + on = pos + i * spacing + if on < pos + g: + rhythm.append(on) + contour.append(base + cell[i]) + if rests and gi == len(grouping) - 1 and len(rhythm) > 3: + keep = [j for j, o in enumerate(rhythm) if o < pos + 1] + rhythm, contour = [rhythm[j] for j in keep], [contour[j] for j in keep] + pos += g + k += 1 + shift = contour[0] + contour = [c - shift for c in contour] + lo = min(contour) + if lo < -6: + contour = [c - lo - 6 for c in contour] + return rhythm, contour, {"cell": cell, "seq_step": seq_step, "rest_tail": rests} + + +def plan_motifs(rng, intent, tail_rest=True, _inner=False): + if not tail_rest and not _inner: + # The hook without its trailing rest is drawn from a copy of the RNG, so + # every draw after it (and the rest of the recipe) stays as with the rest. + alt = random.Random() + alt.setstate(rng.getstate()) + out = plan_motifs(rng, intent) + full = plan_motifs(alt, intent, False, _inner=True)["hook"] + out["hook"].update({k: full[k] for k in ("rhythm", "contour", "slides", "cellinfo")}) + return out + L, _, _, _ = METERS[intent["meter"]] + arch = rng.choice(["up", "down"]) + if rng.random() < 0.7: + rhythm, contour, cellinfo = gen_cell_hook(rng, L, intent["grouping"], tail_rest) + else: + rhythm = gen_rhythm(rng, L, intent["grouping"], rng.uniform(1.0, 1.6), tail_rest) + contour = gen_contour(rng, len(rhythm), arch) + cellinfo = {"cell": None} + slides = [i for i in range(1, len(rhythm)) if rng.random() < 0.15] + cycle = rng.choice([3, 4, 5, 5, 6, 7]) + for _ in range(50): + ladder_pick = [0] + [rng.randrange(0, 7) for _ in range(cycle - 1)] + colorful = any(i in (3, 4) for i in ladder_pick) + no_rep = all(a != b for a, b in zip(ladder_pick, ladder_pick[1:] + ladder_pick[:1])) + if colorful and no_rep and len(set(ladder_pick)) >= 3: + break + texture = rng.choice(["arp", "arp", "pedal", "tap", "tap"]) + bL = METERS[intent["b_meter"]][0] + b_acc = accents_of(intent["b_grouping"]) + chug = sorted({a + 1 for a in b_acc if rng.random() < 0.5 and a + 1 < bL} | + {x for x in range(bL) if x % 2 == 0 and rng.random() < 0.25}) + return { + "hook": {"rhythm": rhythm, "contour": contour, "slides": slides, + "anchor": rng.choice([0, 2, 2, 4, 1]), "arch": arch, "cellinfo": cellinfo, + "push": rng.random() < 0.4, "run_first": rng.random() < 0.5}, + "texture": texture, + "chug": chug, + "arp": {"cycle": ladder_pick, "ladder": rng.choice( + [[0, 4, 7, 8, 9, 11, 14], [0, 2, 4, 7, 8, 9, 11], [0, 4, 8, 9, 11, 13, 14], + [0, 4, 7, 9, 11, 12, 14]])}, + } + + +def plan_form(rng, intent, harmony): + L = METERS[intent["meter"]][0] + form = [] + for i in range(intent["intro_bars"]): + form.append({"sec": "intro", "chord": harmony["A"][i], "prog": "intro"}) + prog_a = rng.choice([["stmt", "seq", "frag", "cad_open"], ["stmt", "seq_orn", "frag", "cad_open"]]) + prog_a2 = rng.choice([["stmt_orn", "invert", "call", "cad_open"], ["stmt", "retro", "call", "cad_open"], + ["displace", "seq", "call", "cad_open"]]) + prog_a3 = ["oct_harm", "seq_harm", "frag_harm", "cad_final"] + for chords, progs, sec in ((harmony["A"], prog_a, "A"), (harmony["A2"], prog_a2, "A2")): + for c, p in zip(chords, progs): + form.append({"sec": sec, "chord": c, "prog": p}) + for c in harmony["B"]: + form.append({"sec": "B", "chord": c, "prog": "b1"}) + form.append({"sec": "B", "chord": c, "prog": "b2"}) + for c, p in zip(harmony["A3"], prog_a3): + form.append({"sec": "A3", "chord": c, "prog": p}) + form.append({"sec": "end", "chord": harmony["end"], "prog": "end"}) + return form + + +# ---------------------------------------------------------------- operators + +def motif_events(hook, L): + r = hook["rhythm"] + out = [] + for i, on in enumerate(r): + nxt = r[i + 1] if i + 1 < len(r) else L + out.append({"on": on, "dur": min(nxt - on, 6), "off": hook["contour"][i], + "art": "slide" if i in hook["slides"] else None}) + return out + + +def op(name, ev, L, rng_local): + ev = [dict(e) for e in ev] + if name == "invert": + for e in ev: + e["off"] = -e["off"] + elif name == "retro": + offs = [e["off"] for e in ev][::-1] + base = offs[0] + for e, o in zip(ev, offs): + e["off"] = o - base + elif name == "frag": + head = [e for e in ev if e["on"] < L // 2] + half = L // 2 + second = [dict(e, on=e["on"] + half, off=e["off"] + rng_local.choice([1, 2, -1])) for e in head] + ev = head + [e for e in second if e["on"] < L] + for i, e in enumerate(ev): + nxt = ev[i + 1]["on"] if i + 1 < len(ev) else L + e["dur"] = min(e["dur"], nxt - e["on"]) + elif name == "call": + ev = [e for e in ev if e["on"] < L // 2] + elif name == "orn": + extra = [] + for e in ev: + if e["dur"] >= 3 and rng_local.random() < 0.6: + extra.append({"on": e["on"] + e["dur"] - 1, "dur": 1, "off": e["off"] + 1, "art": None}) + e["dur"] -= 1 + ev = sorted(ev + extra, key=lambda e: e["on"]) + elif name == "displace": + k = rng_local.choice([1, 2, 3]) + ev = [dict(e, on=(e["on"] + k)) for e in ev if e["on"] + k < L] + elif name == "seq": + cut = L // 2 + shift = rng_local.choice([2, -2, 3, -1]) + ev = [dict(e, off=e["off"] + shift) if e["on"] >= cut else e for e in ev] + elif name == "cad_run": + head = [e for e in ev if e["on"] < L // 3] + start = (head[-1]["on"] + 1) if head else 0 + tgt_on = max(start + 3, L - max(3, L // 4)) + run_len = tgt_on - start + base = head[-1]["off"] if head else 0 + direction = rng_local.choice([1, -1]) + if head: + head[-1]["dur"] = 1 + run = [{"on": start + i, "dur": 1, "off": base + direction * (i + 1), "art": None} for i in range(run_len)] + ev = head + run + [{"on": tgt_on, "dur": L - tgt_on, "off": None, "art": None, "cad": True}] + elif name == "cad": + head = [e for e in ev if e["on"] < L // 2][:3] + last_on = (head[-1]["on"] + head[-1]["dur"]) if head else 0 + if head: + head[-1]["dur"] = max(1, min(head[-1]["dur"], L // 2 - head[-1]["on"])) + tgt = {"on": max(last_on, L // 2), "dur": L - max(last_on, L // 2), "off": None, "art": "slide", "cad": True} + ev = head + [tgt] + return ev + + +# ---------------------------------------------------------------- realization + +def place_line(th, ev, root, anchor_fn, bar_start, accents, lo, hi, vel, harm=0, strict=True, colors=False): + """colors: accented notes keep 9ths, 11ths, 13ths and 7ths and move only + when they sit a semitone above a chord tone (a minor ninth); otherwise they + are pulled onto the triad.""" + anchor = anchor_fn(root) + prev = None + degs = [] + triad = {th.midi(root + k) % 12 for k in (0, 2, 4)} + harsh = lambda d: any((th.midi(d) - c) % 12 == 1 for c in triad) + for e in ev: + if e.get("off") is None: + cands = [d for d in range(anchor - 7, anchor + 8) if (d - root) % 7 in (0, 2)] + deg = min(cands, key=lambda d: abs(d - (prev if prev is not None else anchor))) + elif colors: + deg = anchor + e["off"] + if (e["on"] in accents or e is ev[-1]) and harsh(deg): + up = prev is None or deg >= prev + step = 1 if up else -1 + deg = deg + step if not harsh(deg + step) else deg - step + else: + deg = anchor + e["off"] + if strict and (e["on"] in accents or e is ev[0] or e is ev[-1]) and not stable(deg, root): + up = prev is None or deg >= prev + deg = deg + (1 if up else -1) if stable(deg + (1 if up else -1), root) else deg + (-1 if up else 1) + deg += harm + if harm and not stable(deg, root) and e["on"] in accents: + deg -= 1 + degs.append(deg) + prev = deg - harm + pitches = [th.midi(d) for d in degs] + if pitches: + shift = 0 + while max(pitches) + shift > hi and min(pitches) + shift - 12 >= lo - 5: + shift -= 12 + while min(pitches) + shift < lo and max(pitches) + shift + 12 <= hi + 5: + shift += 12 + pitches = [p + shift for p in pitches] + pitches = [p - 12 if p > 86 else (p + 12 if p < 40 else p) for p in pitches] + notes = [] + for e, p in zip(ev, pitches): + notes.append({"start": bar_start + e["on"], "dur": e["dur"], "pitch": p, + "vel": vel + (14 if e["on"] in accents else 0) + (8 if e["on"] == 0 else 0), + "art": e.get("art")}) + return notes + + +def arp_bar(th, motif, root, bar_start, L, lo, hi, phase, step, vel, accents, mask=None, shape=None, onsets=None): + """Arpeggio/pedal texture. Ladder slots >= 3 form an upper shape held as + common tones across chord changes (moved only on a semitone clash). + `mask` = lead onsets in this bar; the texture yields to them except on + accents so the two guitars interlock.""" + ladder = motif["ladder"] + cyc = motif["cycle"] + base = root + while th.midi(base) < lo: + base += 7 + while th.midi(base + ladder[-1]) > hi and th.midi(base) - 12 >= lo: + base -= 7 + chord_pcs = th.chord_pcs(root) + upper = {} + for idx in range(3, len(ladder)): + d = base + ladder[idx] + if shape is not None and idx in shape: + d = shape[idx] + pc = th.midi(d) % 12 + if any((pc - c) % 12 in (1, 11) for c in chord_pcs): + d = min((x for x in range(d - 2, d + 3) if stable(x, root)), key=lambda x: abs(x - d)) + upper[idx] = d + if shape is not None and not shape: + shape.update(upper) + notes = [] + t = 0 + pedal = motif.get("texture") == "pedal" + grid = sorted(onsets) if onsets is not None else range(0, L, step) + for t in grid: + idx = cyc[phase % len(cyc)] + if pedal: + idx = (len(ladder) - 1) if (t // step) % 2 else min(idx, len(ladder) - 3) + d = upper.get(idx, base + ladder[idx]) + if (d - root) % 7 == 1 and not th.color_ok(root, 1): + d += 1 + p = th.midi(d) + while p > hi: + p -= 12 + phase += 1 + if mask is not None and t in mask and t not in accents: + continue + notes.append({"start": bar_start + t, "dur": 8, "pitch": p, "ring": True, + "tappable": p >= 64 and idx >= 3, + "vel": vel + (12 if t in accents else 0) + (8 if t == 0 else 0)}) + return notes, phase + + +def tap_bar(th, root, bar_start, L, phase, vel, accents, mask, state, reset_on_hits=False): + """Single-string tapping triad: tap (right hand) -> pull-off -> hammer-on, + all three chord tones, the string chosen to keep the fretting hand still.""" + pcs = th.chord_pcs(root, (0, 2, 4, 1)) + best = None + for s in (3, 4, 5): + for a in range(2, 13): + if (fretboard.OPEN[s] + a) % 12 not in pcs: + continue + for b in range(a + 2, a + 5): + if (fretboard.OPEN[s] + b) % 12 not in pcs: + continue + for c in range(a + 6, min(a + 13, 22)): + if (fretboard.OPEN[s] + c) % 12 not in pcs: + continue + cost = (abs(a - state.get("a", a)) + 0.5 * abs(s - state.get("s", s)) + 0.1 * (c - a) + + 0.15 * abs(a - 6)) + if best is None or cost < best[0]: + best = (cost, s, a, b, c) + if best is None: + return [], phase + _, s, a, b, c = best + state.update(s=s, a=a) + cyc = [(c, "tap"), (a, "pull"), (b, "hammer")] + notes = [] + last_reset = -99 + for x in range(L): + if reset_on_hits and x in accents and x - last_reset >= 3: + phase = 0 + last_reset = x + f, tech = cyc[phase % 3] + phase += 1 + if mask is not None and x in mask and x not in accents: + continue + if tech != "tap" and (not notes or notes[-1]["start"] != bar_start + x - 1 or notes[-1]["fixed"][0] != s): + tech = "pick" + elif tech != "tap": + tech = "hammer" if f > notes[-1]["fixed"][1] else "pull" + notes.append({"start": bar_start + x, "dur": 3, "pitch": fretboard.OPEN[s] + f, "fixed": (s, f), + "preset_tech": [] if tech == "pick" else [tech], "ring": False, + "vel": vel + (12 if x in accents else 0)}) + return notes, phase + + +V8 = { # doses of the v8 rhythm-guitar idioms; meant to become user controls + "octave_piece": 0.5, # share of pieces with one A or A2 section of octave shapes in the rhythm guitar + "octave_sixteenths": 0.3, # of those, share in sixteenths instead of eighths + "dead_notes": 0.35, # of those, share with dead notes before the accents + "slide_max": 5, # largest position change (frets) bridged by a slide +} + + +def octave_bar(th, root, bar_start, L, accents, grid, dead, state, slide_max=None): + """Octave shape on the A and G strings (G two frets higher, D string + muted), struck on `grid`; slides into a new position when it is close; + optional dead notes on the sixteenth before each accent.""" + x = (th.midi(root) - fretboard.OPEN[1]) % 12 + if x < 2: + x += 12 + prev = state.get("x") + smax = V8["slide_max"] if slide_max is None else slide_max + slide = prev is not None and prev != x and abs(prev - x) <= smax + state["x"] = x + ons = sorted(eighths(accents, L)) if grid == 8 else list(range(L)) + notes = [] + for k, o in enumerate(ons): + nxt = ons[k + 1] if k + 1 < len(ons) else L + tech = ["slide"] if slide and k == 0 else [] + for s, f in ((1, x), (3, x + 2)): + notes.append({"start": bar_start + o, "dur": max(1, nxt - o), "pitch": fretboard.OPEN[s] + f, + "fixed": (s, f), "preset_tech": tech, "dyad": True, "ring": False, + "vel": 86 if o in accents else 72}) + if dead: + for a in sorted(accents): + if a > 0 and a - 1 not in ons: + for s, f in ((1, x), (3, x + 2)): + notes.append({"start": bar_start + a - 1, "dur": 1, "pitch": fretboard.OPEN[s] + f, + "fixed": (s, f), "preset_tech": ["dead"], "dyad": True, "ring": False, "vel": 44}) + return notes + + +def plan_v8(rng, form): + plan = {} + secs = [s for s in ("A", "A2") if any(b["sec"] == s and b.get("role") for b in form)] + if secs and rng.random() < V8["octave_piece"]: + plan[rng.choice(secs)] = {"grid": 16 if rng.random() < V8["octave_sixteenths"] else 8, + "dead": rng.random() < V8["dead_notes"]} + out = [] + for b in form: + b = dict(b) + if b["sec"] in plan and b.get("role") in ("chords", "chatter"): + b["role"] = "octave" + b["oct"] = plan[b["sec"]] + out.append(b) + return {"octave": plan}, out + + +V9 = { # doses of the v9 comping vocabulary; meant to become user controls + "push": 0.5, # pattern has one accent anticipated by a sixteenth + "offbeat": 0.5, # pattern has one extra hit on a free eighth + "drop": 0.3, # pattern leaves one accent out (a breath) + "dead_strum": 0.25, # pattern has a muted strum before an accent + "vary_bar4": 0.45, # a square varies its pattern in bar 4 + "vary_next_bar1": 0.1, # ...or, instead, in bar 1 of the next square + "half_square": 0.15, # bar 2 varies too (phrasing in half-squares) + "variants": {"shift": 0.5, "fill": 0.3, "stop": 0.2}, + "intro": {"pause": 0.35, "build": 0.3, "short": 0.35}, +} + + +def comp_pattern(rng, grouping, L): + """A comping rhythm built from the meter's grouping and then bent, so that + pieces in the same meter do not share one strumming pattern.""" + acc = sorted(accents_of(grouping)) + hits = {a: "hit" for a in acc} + if rng.random() < V9["push"] and len(acc) > 1: + a = rng.choice(acc[1:]) + if a - 1 not in hits: + del hits[a] + hits[a - 1] = "hit" + if rng.random() < V9["offbeat"]: + free = [x for x in range(2, L, 2) if not {x - 1, x, x + 1} & set(hits)] + if free: + hits[rng.choice(free)] = "hit" + if rng.random() < V9["drop"] and len(hits) > 3: + del hits[rng.choice([x for x in hits if x != 0])] + if rng.random() < V9["dead_strum"]: + free = [x - 1 for x in hits if x > 0 and x - 1 not in hits] + if free: + hits[rng.choice(free)] = "dead" + return sorted(hits.items()) + + +def vary_pattern(pat, kind, L): + pat = [tuple(x) for x in pat] + if kind == "stop": + return pat[:1] + out = dict(pat) + if kind == "shift": + for p in [p for p, _ in pat][-2:]: + k = out.pop(p) + out[p - 1 if p > 0 and p - 1 not in out else p] = k + elif kind == "fill": + for x in range(pat[-1][0], L, 2): + out.setdefault(x, "hit") + return sorted(out.items()) + + +def plan_v9(rng, intent, form): + """Comping patterns per section, where they vary (bar 4, bar 2, or bar 1 + of the next square), and how the intro hands over to A.""" + L = METERS[intent["meter"]][0] + secs = [s for s in ("intro", "A", "A2") if any(b["sec"] == s for b in form)] + pats = {s: comp_pattern(rng, intent["grouping"], L) for s in secs} + events = {} + for s in ("A", "A2"): + if s not in secs: + continue + r = rng.random() + kind = pick(rng, V9["variants"]) + if r < V9["vary_next_bar1"] and s == "A" and "A2" in secs: + events[("A2", 0)] = kind + elif r < V9["vary_next_bar1"] + V9["vary_bar4"]: + events[(s, 3)] = kind + if rng.random() < V9["half_square"]: + events[(s, 1)] = "shift" + intro = pick(rng, V9["intro"]) + out, pos = [], {} + n_intro = sum(b["sec"] == "intro" for b in form) + for b in form: + b = dict(b) + i = pos.get(b["sec"], 0) + pos[b["sec"]] = i + 1 + if b["sec"] == "intro" and intro == "short" and i < n_intro - 1: + continue + if b["sec"] in pats: + b["comp"] = pats[b["sec"]] + if (b["sec"], i) in events: + b["comp_var"] = events[(b["sec"], i)] + if b["sec"] == "intro" and i == n_intro - 1 and intro in ("pause", "build"): + b["handover"] = intro + out.append(b) + return {"patterns": {s: pats[s] for s in secs}, "events": {f"{s}:{i}": k for (s, i), k in events.items()}, + "intro": intro}, out + + +def comp_strike(th, root, bar_start, L, g, pattern, vel, avoid_cluster): + lo, hi = (40, 64) if g == "g2" else (52, 76) + v = fretboard.voice_chord(th.chord_pcs(root, (0, 2, 4, 1)), th.midi(root) % 12, lo, hi, None, 4, + avoid_cluster=avoid_cluster) + notes = [] + for k, (p, kind) in enumerate(pattern): + nxt = pattern[k + 1][0] if k + 1 < len(pattern) else L + for s, f, pitch in v or []: + if kind == "dead": + notes.append({"start": bar_start + p, "dur": 1, "pitch": pitch, "vel": 40, "fixed": (s, f), + "preset_tech": ["dead"], "ring": False}) + else: + notes.append({"start": bar_start + p, "dur": max(1, nxt - p), "pitch": pitch, + "vel": vel + (8 if p == 0 else 0), "fixed": (s, f), "ring": True}) + return notes + + +def leap_cycle(cycle): + """Reorder an arpeggio cycle so consecutive notes skip at least one ladder + step where possible (string skips instead of a stepwise ladder).""" + def steps(cyc): + return sum(abs(a - b) <= 1 for a, b in zip(cyc, cyc[1:] + cyc[:1])) + + best = list(cycle) + for first in range(len(cycle)): + rest = list(cycle) + cur = rest.pop(first) + out = [cur] + while rest: + far = [c for c in rest if abs(c - cur) >= 2] + cur = max(far or rest, key=lambda c: (abs(c - cur) >= 2, -abs(abs(c - cur) - 3))) + rest.remove(cur) + out.append(cur) + if steps(out) < steps(best): + best = out + return best + + +def chord_hits(th, root, bar_start, L, g, accents, vel, low=False, avoid_cluster=False): + """Sparse texture: one ringing voicing struck on each accent.""" + lo, hi = ((40, 64) if low or g == "g2" else (52, 76)) + v = fretboard.voice_chord(th.chord_pcs(root, (0, 2, 4, 1)), th.midi(root) % 12, lo, hi, None, 4, + avoid_cluster=avoid_cluster) + hits = sorted(accents) + notes = [] + for i, a in enumerate(hits): + end = hits[i + 1] if i + 1 < len(hits) else L + for s, f, p in v or []: + notes.append({"start": bar_start + a, "dur": end - a, "pitch": p, "vel": vel + (8 if a == 0 else 0), + "fixed": (s, f), "ring": True}) + return notes + + +def doubled(th, notes, root, kind, bar_start, accents): + """The second guitar plays the lead's rhythm: unison, an octave below, a + diatonic third below, or a low root-fifth dyad.""" + out = [] + for n in notes: + base = {"start": n["start"], "dur": n["dur"], "vel": n["vel"] - 8} + if kind == "unison": + out.append(dict(base, pitch=n["pitch"])) + elif kind == "octave": + out.append(dict(base, pitch=n["pitch"] - 12 if n["pitch"] - 12 >= 40 else n["pitch"])) + elif kind == "harm3": + d = th.deg_near(n["pitch"]) - 2 + if not stable(d, root) and int(n["start"] - bar_start) in accents: + d -= 1 + p = th.midi(d) + while p - n["pitch"] > -3: + p -= 12 + out.append(dict(base, pitch=p if p >= 40 else p + 12)) + else: + low = th.midi(root) + while low > 52: + low -= 12 + while low < 40: + low += 12 + out.append(dict(base, pitch=low)) + out.append(dict(base, pitch=low + 7, chordtone=True)) + return out + + +def minor_ninth(a, b): + return abs(a - b) % 12 == 1 and a != b + + +def resolve_minor_ninths(parts, lead, other): + """The corpus has many major sevenths between the guitars but almost no + minor ninths. An accompaniment note sounding a minor ninth or semitone + against a lead note is cut short before it, or dropped when struck together + with it or under it. The lead is never changed, so a riff stays verbatim.""" + resolved = [] + keep = [] + for m in sorted(parts[other], key=lambda n: n["start"]): + end = m["start"] + m["dur"] + hits = [n for n in parts[lead] if m["start"] <= n["start"] < end and minor_ninth(n["pitch"], m["pitch"])] + under = [n for n in parts[lead] if n["start"] < m["start"] < n["start"] + n["dur"] + and minor_ninth(n["pitch"], m["pitch"])] + if under or any(n["start"] == m["start"] for n in hits): + resolved.append(m["start"]) + continue + if hits: + m["dur"] = min(n["start"] for n in hits) - m["start"] + resolved.append(m["start"]) + keep.append(m) + gone = {n["start"] for n in parts[other] if n.get("dyad") and n not in keep} + keep = [n for n in keep if not (n.get("dyad") and n["start"] in gone)] + for start in {n["start"] for n in keep if n.get("dyad")}: + pair = [n for n in keep if n.get("dyad") and n["start"] == start] + for n in pair: + n["dur"] = min(x["dur"] for x in pair) + prev, by_string = None, {} + for n in keep: + if n.get("chordtone") or (n.get("fixed") and "preset_tech" not in n): + continue + p = by_string.get(n["string"]) if n.get("dyad") else prev + legato = {"hammer", "pull", "slide"} & set(n["tech"]) + if legato and (p is None or p["string"] != n["string"] or p["fret"] == n["fret"] + or ("hammer" in legato and n["fret"] < p["fret"]) + or ("pull" in legato and n["fret"] > p["fret"])): + n["tech"] = [x for x in n["tech"] if x not in legato] + prev = n + by_string[n["string"]] = n + parts[other] = keep + return resolved + + +def apply_rests_and_pushes(parts, lead, other, form, spans, plan): + """Rests at square boundaries and rhythm-guitar anticipations (the last + hits of a bar an eighth early), as listed in plan.""" + def bars_of(sec): + return [i for i, b in enumerate(form) if b["sec"] == sec] + mute = [] + for kind in plan["rests"]: + if kind == "rhythm_out_A2" and bars_of("A2"): + mute += [(i, other, 0) for i in bars_of("A2")[:2]] + elif kind == "lead_late_B" and bars_of("B"): + mute.append((bars_of("B")[0], lead, 0)) + elif kind == "drop_before_A3" and bars_of("A3"): + i = bars_of("A3")[0] - 1 + if i >= 0 and form[i]["sec"] != "intro": + mute += [(i, lead, 1), (i, other, 1)] + for i, g, after in mute: + s, e = spans[i] + parts[g] = [n for n in parts[g] if not (s + after <= n["start"] < e)] + for i in plan["pushes"]: + s, e = spans[i] + ons = sorted({n["start"] for n in parts[other] if s <= n["start"] < e}) + tail = [o for k, o in enumerate(ons) if k >= len(ons) - 3 and o - 2 > (ons[k - 1] if k else s - 1)] + for n in parts[other]: + if n["start"] in tail: + n["start"] -= 2 + n["dur"] = max(1, min(n["dur"], 2)) + + +def plan_v6(rng, form): + kinds = ["rhythm_out_A2", "lead_late_B", "drop_before_A3"] + rests = [k for k in kinds if rng.random() < 0.4] or [rng.choice(kinds)] + pushes = [] + for sec in ("A", "A2"): + bars = [i for i, b in enumerate(form) if b["sec"] == sec] + if len(bars) >= 4 and rng.random() < 0.45: + i = bars[rng.choice([1, 3])] + if form[i]["prog"] != "shift" and form[i].get("role") == "chords": + pushes.append(i) + return {"rests": rests, "pushes": pushes, "end": pick(rng, ENDINGS_V6)} + + +def eighths(accents, L): + """Eighth-note grid re-anchored on every accent, so odd groupings keep their downbeats.""" + out, last = set(), -2 + for x in range(L): + if x in accents or x - last >= 2: + out.add(x) + last = x + return out + + +def accents_of(grouping): + out, p = set(), 0 + for g in grouping: + out.add(p) + p += g + return out + + +def _studio_rng(seed, layer, section, salt): + return random.Random(f"{seed}:{layer}:{section}:{salt}") + + +def _studio_cycle(rng, v8): + cycle = rng.choice([3, 4, 5, 5, 6, 7]) + ladder_pick = list(range(cycle)) + for _ in range(50): + cand = [0] + [rng.randrange(0, 7) for _ in range(cycle - 1)] + colorful = any(i in (3, 4) for i in cand) + no_rep = all(a != b for a, b in zip(cand, cand[1:] + cand[:1])) + if colorful and no_rep and len(set(cand)) >= 3: + ladder_pick = cand + break + return leap_cycle(ladder_pick) if v8 else ladder_pick + + +def _studio_tempo(seed, base_tempo, salt): + tempo = base_tempo + for k in range(1, salt + 1): + rng = _studio_rng(seed, "tempo", "all", k) + lo = max(60, int(round(tempo * 0.8))) + hi = min(220, int(round(tempo * 1.1))) + val = max(lo, min(hi, int(round(tempo * rng.uniform(0.8, 1.1))))) + if val == tempo and hi > lo: + step = rng.choice([-1, 1]) + val = val + step if lo <= val + step <= hi else val - step + tempo = val + return tempo + + +def _studio_hook_variants(recipe): + """Replay the recipe's motif stream: ({True: hook with trailing rest, False: hook without}, + whether the recipe's own hook keeps the rest), or None when the stream cannot be matched.""" + it = recipe["intent"] + seed = recipe["seed"] + want_intent = json.dumps(it, sort_keys=True) + want_hook = json.dumps(recipe["motifs"]["hook"], sort_keys=True) + for flags in itertools.product((False, True), repeat=4): + given = {k: (it[f] if on else None) for (k, f), on in zip( + (("meter", "meter"), ("mode", "mode"), ("key", "tonic"), ("tempo", "tempo")), flags)} + args = argparse.Namespace(**given) + rng = random.Random(seed) + intent = plan_intent(rng, args) + if "lead" in recipe and not args.mode: + intent["mode"] = pick(random.Random(seed * 86028121 + 13), MODES_V7) + if json.dumps(intent, sort_keys=True) != want_intent: + continue + plan_harmony(rng, Theory(TONICS[intent["tonic"]], intent["mode"]), intent) + state = rng.getstate() + hooks = {} + for tail in (True, False): + r = random.Random() + r.setstate(state) + hooks[tail] = plan_motifs(r, intent, tail_rest=tail)["hook"] + for tail in (True, False): + if json.dumps(hooks[tail], sort_keys=True) == want_hook: + return hooks, tail + return None + + +def studio_base_trailing_rest(recipe): + variants = _studio_hook_variants(recipe) + if variants is not None: + return variants[1] + return not str(recipe.get("generator", "")).endswith("-notail") + + +def _studio_lead_rhythm(seed, intent, salt, tail_rest): + rng = _studio_rng(seed, "lead_rhythm", "all", salt) + m = plan_motifs(rng, intent, tail_rest=tail_rest) + lp = plan_lead(rng, m["hook"], intent) + return m["hook"], lp + + +def _studio_intro(seed, base_bars, base_dens, salt): + rng = _studio_rng(seed, "intro", "intro", salt) + for _ in range(8): + n_bars = rng.choice([1, 2, 4]) + dens = rng.choice([1, 2, 3]) + tex = rng.choice(["arp", "tap"]) if dens == 3 else "arp" + if salt != 1 or n_bars != base_bars or dens != base_dens: + return n_bars, dens, tex + return n_bars, dens, tex + + +def _studio_comp(seed, sec, salt, grouping, L, doses, base_sec_bars): + rng = _studio_rng(seed, "comp", sec, salt) + pool = [ + ["chords", "chords", "chatter"], + ["chatter", "chords", "chatter"], + ["chords", "chatter", "chords"], + ["chords", "chords", "chords"], + ["chatter", "chatter", "chords"], + ] + base_roles = [b.get("role") for b in base_sec_bars if b.get("role")] + base_oct = base_sec_bars[0].get("oct") if base_roles and base_roles[0] == "octave" else None + base_acc_pat = [(a, "hit") for a in sorted(accents_of(grouping))] + + def draw(): + if rng.random() < doses["octave_piece"]: + return { + "kind": "octave", + "oct": { + "grid": 16 if rng.random() < doses["octave_sixteenths"] else 8, + "dead": rng.random() < doses["dead_notes"], + "slide_max": int(doses["slide_max"]), + }, + } + return {"kind": "roles", "roles": rng.choice(pool), "comp": comp_pattern(rng, grouping, L)} + + plan = draw() + for _ in range(8): + if salt != 1: + break + if plan["kind"] == "octave": + same = base_oct is not None and ( + plan["oct"]["grid"] == base_oct.get("grid") and plan["oct"]["dead"] == base_oct.get("dead") + ) + else: + same = plan["comp"] == base_acc_pat + if not same: + break + plan = draw() + return plan + + +def _studio_texture(seed, sec, salt, base_arp, v8): + rng = _studio_rng(seed, "texture", sec, salt) + base_tex = base_arp.get("texture") + base_key = (base_tex, list(base_arp.get("cycle", []))) + for _ in range(8): + tex = rng.choice(["arp", "arp", "pedal", "tap"]) + cyc = _studio_cycle(rng, v8) + same_tap = (tex == "tap" and base_tex == "tap") + if salt != 1 or (not same_tap and (tex, cyc) != base_key): + return dict(base_arp, texture=tex, cycle=cyc) + return dict(base_arp, texture=tex, cycle=cyc) + + +def _studio_b(seed, salt, b_meter, b_grouping, base_chug, base_arp, v8, base_vars): + rng = _studio_rng(seed, "b", "B", salt) + bL = METERS[b_meter][0] + b_acc = sorted(accents_of(b_grouping)) + mid = max(a for a in b_acc if a <= bL // 2) + last_a = b_acc[-1] + half_opts = sorted({ + tuple(sorted(s)) + for s in ({0, mid}, {0}, {0, max(1, mid - 1)}, {0, last_a}, {0, mid, last_a}) + }) + b_vars = ["chug", "half", "clean"] + + def draw(): + v1 = rng.choice(b_vars) + v2 = rng.choice([v for v in b_vars if v != v1]) + chug = sorted( + {a + 1 for a in b_acc if rng.random() < 0.5 and a + 1 < bL} + | {x for x in range(bL) if x % 2 == 0 and rng.random() < 0.25} + ) or [0] + half_hits = set(rng.choice(half_opts)) + clean_arp = dict(base_arp, texture="arp", cycle=_studio_cycle(rng, v8)) + return {"vars": [v1, v2], "chug": chug, "half_hits": half_hits, "arp": clean_arp} + + plan = draw() + for _ in range(8): + if salt != 1: + break + v1 = plan["vars"][0] + same_v = v1 == (base_vars[0] if base_vars else "chug") + if not same_v: + break + if v1 == "chug" and plan["chug"] != (base_chug or [0]): + break + if v1 == "half" and plan["half_hits"] != {0, mid}: + break + if v1 == "clean" and plan["arp"]["cycle"] != base_arp["cycle"]: + break + plan = draw() + return plan + + +def _studio_ending(seed, salt, base_end): + base = base_end or "held" + _studio_rng(seed, "ending", "end", salt) + others = [e for e in ("held", "stop", "busy") if e != base] + if random.Random(f"{seed}:ending:end:order").random() < 0.5: + others.reverse() + order = others + [base] + return order[(salt - 1) % 3] + + +_STUDIO_BASELINES = {} + + +def _studio_baseline(recipe): + plain = {k: v for k, v in recipe.items() if k != "studio"} + key = json.dumps(plain, sort_keys=True, default=list) + trace = _STUDIO_BASELINES.get(key) + if trace is None: + trace = {} + compose(copy.deepcopy(plain), _trace=trace) + if len(_STUDIO_BASELINES) >= 64: + _STUDIO_BASELINES.clear() + _STUDIO_BASELINES[key] = trace + return trace + + +def _studio_canon(notes, s0, s1): + return sorted( + (n["start"] - s0, json.dumps({k: v for k, v in n.items() if k != "start"}, sort_keys=True, default=list)) + for n in notes + if s0 <= n["start"] < s1 + ) + + +def _prepare_studio(recipe, arp, v8): + studio = recipe["studio"] + salts = studio.get("salts") or {} + opts = studio.get("options") or {} + comp_doses_map = studio.get("comp_doses") or {} + it = recipe["intent"] + seed = recipe["seed"] + + base = _studio_baseline(recipe) + variants = _studio_hook_variants(recipe) + base_tail = variants[1] if variants else not str(recipe.get("generator", "")).endswith("-notail") + tail_rest = bool(opts.get("trailing_rest", base_tail)) + lead_salt = int(salts.get("lead_rhythm@all", 0)) + hook, lead_plan = recipe["motifs"]["hook"], recipe.get("lead") + if lead_salt > 0: + hook, lead_plan = _studio_lead_rhythm(seed, it, lead_salt, tail_rest) + elif tail_rest != base_tail and variants: + hook = variants[0][tail_rest] + if "lead" in recipe: + lead_plan = plan_lead(random.Random(seed * 49979693 + 21), hook, it) + + form = [dict(b, _orig_bar_i=idx) for idx, b in enumerate(recipe["form"])] + + intro_salt = int(salts.get("intro@intro", 0)) + if intro_salt > 0: + orig_intro = [b for b in form if b["sec"] == "intro"] + base_bars = len(orig_intro) + base_dens = orig_intro[0].get("dens", 3) if orig_intro else 3 + n_bars, dens, intro_tex = _studio_intro(seed, base_bars, base_dens, intro_salt) + non_intro = [b for b in form if b["sec"] != "intro"] + harmony_a = recipe["harmony"]["A"] + new_intro = [ + { + "sec": "intro", + "chord": harmony_a[i % len(harmony_a)], + "prog": "intro", + "dens": dens, + "_intro_tex": intro_tex, + "_orig_bar_i": i, + } + for i in range(n_bars) + ] + form = new_intro + non_intro + + L = METERS[it["meter"]][0] + for sec in ("A", "A2"): + csalt = int(salts.get(f"comp@{sec}", 0)) + if csalt > 0: + sec_bars = [b for b in form if b["sec"] == sec] + if sec_bars: + doses = { + "octave_piece": float(comp_doses_map.get(sec, {}).get("octave_piece", opts.get("octave_piece", V8["octave_piece"]))), + "octave_sixteenths": float(comp_doses_map.get(sec, {}).get("octave_sixteenths", opts.get("octave_sixteenths", V8["octave_sixteenths"]))), + "dead_notes": float(comp_doses_map.get(sec, {}).get("dead_notes", opts.get("dead_notes", V8["dead_notes"]))), + "slide_max": int(comp_doses_map.get(sec, {}).get("slide_max", opts.get("slide_max", V8["slide_max"]))), + } + cplan = _studio_comp(seed, sec, csalt, it["grouping"], L, doses, sec_bars) + ri = 0 + for b in form: + if b["sec"] == sec and b.get("role") in ("chords", "chatter", "octave"): + if cplan["kind"] == "octave": + b["role"] = "octave" + b["oct"] = dict(cplan["oct"]) + b.pop("comp", None) + b.pop("_fallback_comp", None) + else: + b.pop("oct", None) + b["role"] = cplan["roles"][ri % len(cplan["roles"])] + b["comp"] = list(cplan["comp"]) + b["_fallback_comp"] = list(cplan["comp"]) + ri += 1 + + sec_arp = {} + for sec in ("A", "A2"): + tsalt = int(salts.get(f"texture@{sec}", 0)) + if tsalt > 0: + sec_arp[sec] = _studio_texture(seed, sec, tsalt, arp, v8) + + b_plan = None + b_salt = int(salts.get("b@B", 0)) + if b_salt > 0: + b_bars = [b for b in form if b["sec"] == "B"] + base_vars = [] + for b in b_bars: + v = b.get("var", "chug") + if not base_vars or base_vars[-1] != v: + base_vars.append(v) + b_plan = _studio_b( + seed, b_salt, it["b_meter"], it["b_grouping"], + recipe["motifs"].get("chug"), arp, v8, base_vars, + ) + n_b = len(b_bars) + split = recipe.get("arrange", {}).get("template") == "double_b" + for bi, b in enumerate(b_bars): + b["var"] = b_plan["vars"][0] if (not split or bi < n_b // 2) else b_plan["vars"][1] + + end_salt = int(salts.get("ending@end", 0)) + if end_salt > 0: + base_end = next((b.get("end") for b in form if b["sec"] == "end"), None) + end_kind = _studio_ending(seed, end_salt, base_end) + for b in form: + if b["sec"] == "end": + b["end"] = end_kind + + end_riff = None + if "ending@end" in (studio.get("locks") or []): + end_riff = (studio.get("locked_riffs") or {}).get("ending@end") + if end_riff is None: + end_riff = base["riff"].get("A3") or base["riff"].get("A") or [] + + base_tempo = recipe.get("arrange", {}).get("tempo", it["tempo"]) + tempo_salt = int(salts.get("tempo@all", 0)) + tempo = _studio_tempo(seed, base_tempo, tempo_salt) if tempo_salt > 0 else base_tempo + + return { + "hook": hook, + "lead_plan": lead_plan, + "form": form, + "sec_arp": sec_arp, + "b_plan": b_plan, + "b_lead": opts.get("b_lead", "augmented"), + "base_tempo": base_tempo, + "tempo": tempo, + "base": base, + "end_riff": end_riff, + } + + +def compose(recipe, _trace=None): + rng = random.Random(recipe["seed"] * 7919 + 17) + it = recipe["intent"] + th = Theory(TONICS[it["tonic"]], it["mode"]) + hook = recipe["motifs"]["hook"] + arp = dict(recipe["motifs"]["arp"], texture=recipe["motifs"].get("texture")) + if recipe.get("v8"): + arp["cycle"] = leap_cycle(arp["cycle"]) + oct_state, entered = {}, set() + lead, other = (("g1", "g2") if it["lead"] == "g1" else ("g2", "g1")) + lead_plan = recipe.get("lead") + v8 = bool(recipe.get("v8")) + studio = recipe.get("studio") + if _trace is not None: + _trace["dense"] = {} + _trace["riff"] = {} + _trace["states"] = {} + st_cfg = _prepare_studio(recipe, arp, v8) if studio is not None else None + rec_hook, rec_lead_plan = hook, lead_plan + if st_cfg is not None: + hook = st_cfg["hook"] + lead_plan = st_cfg["lead_plan"] + strike = functools.partial(chord_hits, avoid_cluster=v8) + rng_lead = dict(LEAD_RANGE_V7) if lead_plan else {"g1": (64, 86), "g2": (52, 74)} + col = bool(lead_plan) + rng_arp = {"g1": (59, 86), "g2": (40, 71)} + parts = {"g1": [], "g2": []} + chords = [] + meters = [] + t = 0 + phase = 0 + anchor_tone = hook["anchor"] + sec_anchor = {} + shape = {} + tap_state = {} + riff_cache = {} + lead_center = (rng_lead[lead][0] + rng_lead[lead][1]) // 2 - 3 + + def phrase_anchor(sec, root, lift, tone=None): + if sec not in sec_anchor: + cands = [root + (anchor_tone if tone is None else tone) + 7 * k for k in range(-3, 6)] + target = th.deg_near(lead_center) + lift + sec_anchor[sec] = min(cands, key=lambda d: abs(d - target)) + return lambda _root: sec_anchor[sec] + + base_ev = None + last_meter = None + form = st_cfg["form"] if st_cfg is not None else recipe["form"] + sec_spans = [] + prev_sec = None + for bar_i, bar in enumerate(form): + if bar["sec"] != prev_sec and (st_cfg is not None or _trace is not None): + prev_sec = bar["sec"] + if st_cfg is not None: + snap = st_cfg["base"]["states"].get(len(sec_spans)) + shape, tap_state, oct_state, phase = copy.deepcopy(snap) if snap else ({}, {}, {}, phase) + sec_spans.append([bar["sec"], t, t]) + else: + _trace.setdefault("states", {})[len(sec_spans)] = copy.deepcopy((shape, tap_state, oct_state, phase)) + sec_spans.append(None) + meter = it["b_meter"] if bar["sec"] == "B" else it["meter"] + grouping = it["b_grouping"] if bar["sec"] == "B" else it["grouping"] + L, num, den, _ = METERS[meter] + if meter != last_meter: + meters.append((t * 120, num, den)) + last_meter = meter + acc = accents_of(grouping) + skel = recipe["motifs"].get("skeleton") + if skel: + acc = set(skel["B" if bar["sec"] == "B" else "A"]) + root = bar["chord"] + chords.append({"bar": bar_i, "start": t, "root_deg": root, "sec": bar["sec"]}) + hook_L = METERS[it["meter"]][0] + if base_ev is None: + base_ev = motif_events(hook, hook_L) + if lead_plan: + base_ev = shape_lead(base_ev, lead_plan) + call_ev = base_ev + if hook is not rec_hook or lead_plan is not rec_lead_plan: + call_ev = motif_events(rec_hook, hook_L) + if rec_lead_plan: + call_ev = shape_lead(call_ev, rec_lead_plan) + lr = rng_lead[lead] + pr = bar["prog"] + orig_i = bar.get("_orig_bar_i", bar_i) + brng = random.Random(recipe["seed"] * 31 + orig_i) + dens = bar.get("dens", 3) + if "repeat" in recipe: + phase = 0 + comp = bar.get("comp") + if comp is not None and bar.get("comp_var"): + comp = vary_pattern(comp, bar["comp_var"], L) + bar_arp = st_cfg["sec_arp"].get(bar["sec"], arp) if st_cfg is not None else arp + if pr == "intro" and comp is not None: + if bar.get("handover") == "build": + ramp = [(x, "hit") for x in range(0, L, 2)] + notes = comp_strike(th, root, t, L, other, ramp, 56, v8) + for n in notes: + n["vel"] += int(30 * (n["start"] - t) / L) + parts[other] += notes + else: + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, 1, 66, acc, None, shape, + {p for p, k in comp if k == "hit"}) + if bar.get("handover") == "pause": + n = [x for x in n if x["start"] < t + L // 2] + for x in n: + x["dur"] = min(x["dur"], t + L // 2 - x["start"]) + parts[other] += n + elif pr == "intro" and dens < 3: + if dens == 1: + parts[other] += strike(th, root, t, L, other, acc, 70) + else: + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, 2, 64, acc, None, shape, + eighths(acc, L)) + parts[other] += n + elif pr == "intro": + intro_tap = bar.get("_intro_tex") == "tap" if bar.get("_intro_tex") else (bar_arp.get("texture") == "tap") + if intro_tap: + n, phase = tap_bar(th, root, t, L, phase, 66, acc, None, tap_state, bool(skel)) + else: + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, 1, 66, acc, None, shape) + parts[other] += n + elif bar["sec"] in ("A", "A2", "A3"): + name = pr.replace("_harm", "").replace("_open", "").replace("_final", "") + ev = base_ev + if name == "riff_var": + ev = op("seq", ev, L, brng) + elif name == "shift": + ev = op("displace", ev, L, brng) + elif name == "stop": + ev = [e for e in ev if e["on"] < L // 2] + elif name in ("stmt_orn", "seq_orn"): + ev = op("orn", ev, L, brng) + if name == "seq_orn": + ev = op("seq", ev, L, brng) + elif name in ("invert", "retro", "frag", "call", "displace", "seq"): + ev = op("seq" if skel and name == "displace" else name, ev, L, brng) + elif name == "cad": + ev = op("cad_run" if (bar["sec"] == "A2") != hook.get("run_first", False) else "cad", ev, L, brng) + lift = 7 if bar["sec"] == "A3" else 0 + fn = phrase_anchor(bar["sec"], root, lift) + if skel and name not in ("call",): + ev = conform(ev, sorted(acc), L) + if hook.get("push") and not skel and name in ("stmt", "seq", "stmt_orn", "seq_orn") and ev and ev[0]["on"] == 0: + ev = [dict(ev[0], on=-1, dur=ev[0]["dur"] + 1)] + ev[1:] + parts[lead] = [n for n in parts[lead] if n["start"] != t - 1] + if name == "riff": + if bar["sec"] not in riff_cache: + riff_cache[bar["sec"]] = place_line(th, ev, root, fn, 0, acc, lr[0] + (5 if bar["sec"] == "A3" else 0), + lr[1], 90, colors=col) + notes = [dict(n, start=n["start"] + t) for n in riff_cache[bar["sec"]]] + if v8 and bar["sec"] == "A" and "A" not in entered and len(notes) >= 0.6 * L: + notes = [n for n in notes if n["start"] - t < L // 2] + entered.add(bar["sec"]) + else: + notes = place_line(th, ev, root, fn, t, acc, lr[0] + (5 if bar["sec"] == "A3" else 0), lr[1], 90, + colors=col) + if pr == "cad_final": + for nn in notes[-1:]: + nn["dur"] = L - (nn["start"] - t) + parts[lead] += notes + mask = {int(n["start"] - t) for n in notes} + dense = len(mask) >= L / 2 + if _trace is not None: + _trace.setdefault("dense", {})[orig_i] = dense + if st_cfg is not None: + dense = st_cfg["base"]["dense"].get(orig_i, dense) + tex = bar.get("tex") + if tex == "alone": + pass + elif tex: + parts[other] += doubled(th, notes, root, tex, t, acc) + elif pr == "stop": + parts[other] += [dict(n, dur=2) for n in strike(th, root, t, L, other, {0}, 96)] + elif pr.endswith("_harm"): + hn = [] + for nn in notes: + d = th.deg_near(nn["pitch"]) - 2 + if not stable(d, root) and int(nn["start"] - t) in acc: + d -= 1 + hn.append(dict(nn, pitch=th.midi(d), vel=nn["vel"] - 6)) + lo2, hi2 = rng_lead[other][0] - 6, rng_lead[other][1] + 6 + if hn: + sh = 0 + while max(x["pitch"] for x in hn) + sh > hi2: + sh -= 12 + while min(x["pitch"] for x in hn) + sh < lo2: + sh += 12 + for x in hn: + x["pitch"] += sh + parts[other] += hn + elif pr == "call": + resp = op("invert", op("call", call_ev, L, brng), L, brng) + resp = [dict(e, on=e["on"] + L // 2) for e in resp if e["on"] + L // 2 < L] + fn2 = phrase_anchor("call", root, -5, rec_hook["anchor"]) + parts[other] += place_line(th, resp, root, fn2, t, acc, *rng_lead[other], 86) + elif comp is not None and (pr == "cad_open" or bar.get("role") == "chords"): + parts[other] += comp_strike(th, root, t, L, other, comp, 84 if pr == "cad_open" else 74, v8) + elif pr == "cad_open": + lo, hi = (52, 76) if other == "g1" else (40, 64) + v = fretboard.voice_chord(th.chord_pcs(root, (0, 2, 4, 1)), th.midi(root) % 12, lo, hi, None, 4, + avoid_cluster=v8) + for a in sorted(acc): + for s, f, p in v or []: + parts[other].append({"start": t + a, "dur": 2, "pitch": p, "vel": 92 if a == 0 else 84, + "fixed": (s, f)}) + elif bar.get("role") == "octave": + parts[other] += octave_bar(th, root, t, L, acc, bar["oct"]["grid"], bar["oct"]["dead"], oct_state, + slide_max=bar["oct"].get("slide_max")) + elif bar.get("role") == "chords" or (bar.get("role") and dense): + if bar.get("_fallback_comp") is not None: + parts[other] += comp_strike(th, root, t, L, other, bar["_fallback_comp"], 74, v8) + else: + parts[other] += strike(th, root, t, L, other, acc, 74) + elif bar.get("role") == "chatter" and bar_arp.get("texture") == "tap": + n, phase = tap_bar(th, root, t, L, phase, 66, acc, mask, tap_state) + parts[other] += n + elif bar.get("role") == "chatter": + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, 1, 64, acc, mask, shape) + parts[other] += n + elif dens == 1: + parts[other] += strike(th, root, t, L, other, acc, 72) + elif dens == 2 and "dens" in bar: + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, 2, 64, acc, mask, shape, + eighths(acc, L)) + parts[other] += n + elif bar_arp.get("texture") == "tap" and bar["sec"] != "A2": + n, phase = tap_bar(th, root, t, L, phase, 66, acc, mask, tap_state, bool(skel)) + parts[other] += n + else: + step = 1 if bar["sec"] != "A2" else 2 + n, phase = arp_bar(th, bar_arp, root, t, L, *rng_arp[other], phase, step, 64, acc, mask, shape) + parts[other] += n + elif bar["sec"] == "B": + b_index = [i for i, x in enumerate(form) if x["sec"] == "B"].index(bar_i) + n_b = sum(1 for x in form if x["sec"] == "B") + low = th.midi(root) + while low > 52: + low -= 12 + while low < 40: + low += 12 + b_plan = st_cfg["b_plan"] if st_cfg is not None else None + chug = (b_plan["chug"] if b_plan else recipe["motifs"].get("chug")) or [0] + turnaround = b_index == n_b - 1 + var = bar.get("var", "chug") + if var == "half": + hits = b_plan["half_hits"] if b_plan else {0, max(a for a in acc if a <= L // 2)} + parts[other] += strike(th, root, t, L, other, hits, 90, low=True) + elif var == "clean": + b_arp = b_plan["arp"] if b_plan else bar_arp + n, phase = arp_bar(th, b_arp, root, t, L, *rng_arp[other], phase, 2, 62, acc, None, shape, + eighths(acc, L)) + parts[other] += n + for x in range(L if var == "chug" else 0): + last_group = turnaround and x >= max(acc) + if x in acc or x in chug or last_group: + pitch = low + if last_group: + k = x - max(acc) + pitch = th.midi(th.deg_near(low) + [0, 2, 4, 7, 9, 11][k % 6]) + parts[other].append({"start": t + x, "dur": 1, "pitch": pitch, "vel": 88 if x in acc else 72, + "art": None if last_group else "pm"}) + if x in acc and not last_group: + parts[other].append({"start": t + x, "dur": 1, "pitch": low + 7, "vel": 82, "art": "pm", + "chordtone": True}) + b_lead = st_cfg["b_lead"] if st_cfg is not None else "augmented" + if b_lead == "rest": + pass + elif b_lead == "same_speed": + inv = op("invert", base_ev, hook_L, brng) + seg2 = [ + dict(e, dur=min(e["dur"], L - e["on"])) + for e in inv + if e["on"] < L + ] + fn = phrase_anchor("B", root, 4) + parts[lead] += place_line(th, seg2, root, fn, t, acc, *rng_lead[lead], 84, colors=col) + else: + inv = op("invert", base_ev, hook_L, brng) + span = 2 * hook_L + inv_aug = [dict(e, on=e["on"] * 2, dur=min(e["dur"] * 2, 8), art="slide" if e["dur"] >= 2 else None) + for e in inv] + off0 = (b_index % 2) * L + seg2 = [dict(e, on=(e["on"] - off0) % span) for e in inv_aug] + seg2 = sorted((e for e in seg2 if e["on"] < L), key=lambda e: e["on"]) + if not seg2: + seg2 = [dict(e, on=e["on"] % L) for e in inv_aug[:3]] + fn = phrase_anchor("B", root, 4) + parts[lead] += place_line(th, seg2, root, fn, t, acc, *rng_lead[lead], 84, colors=col) + elif bar["sec"] == "end" and bar.get("end") == "busy": + riff = riff_cache.get("A3") or riff_cache.get("A") or [] + if st_cfg is not None and st_cfg["end_riff"] is not None: + riff = st_cfg["end_riff"] + notes = [dict(n, start=n["start"] + t) for n in riff if n["start"] < L] + if notes: + notes[-1]["dur"] = 1 + parts[lead] += notes + parts[other] += [dict(n, dur=min(n["dur"], 2)) for n in strike(th, root, t, L, other, acc, 84)] + elif bar["sec"] == "end": + for g, (lo, hi) in (("g1", (55, 84)), ("g2", (40, 67))): + pcs = th.chord_pcs(root, (0, 2, 4, 1)) + v = fretboard.voice_chord(pcs, th.midi(root) % 12, lo, hi, None, 4, avoid_cluster=v8) + if v: + for s, f, p in v: + stop = bar.get("end") == "stop" + parts[g].append({"start": t, "dur": 2 if stop else L, "pitch": p, "vel": 104 if stop else 96, + "fixed": (s, f), "ring": not stop}) + t += L + if st_cfg is not None: + sec_spans[-1][2] = t + + if recipe.get("control") == "shuffle": + crng = random.Random(recipe["seed"] + 99991) + for g in ("g1", "g2"): + for n in parts[g]: + if n.get("fixed") or n.get("chordtone"): + continue + opts = [p for p in range(n["pitch"] - 9, n["pitch"] + 10) + if (p - th.tonic_pc) % 12 in th.scale and 40 <= p <= 86] + n["pitch"] = crng.choice(opts) + for g in ("g1", "g2"): + for n in parts[g]: + while n["pitch"] > 86: + n["pitch"] -= 12 + while n["pitch"] < 40: + n["pitch"] += 12 + report = {"cost": {}} + v6 = recipe.get("v6") + fix = bool(v6 or recipe.get("fix")) + tempo = st_cfg["tempo"] if st_cfg is not None else recipe.get("arrange", {}).get("tempo", it["tempo"]) + realize_tempo = st_cfg["base_tempo"] if st_cfg is not None else tempo + if v6: + spans = [(c["start"], chords[i + 1]["start"] if i + 1 < len(chords) else t) for i, c in enumerate(chords)] + v6_plan = v6 + if st_cfg is not None: + moved = [] + for i in v6["pushes"]: + j = next((k for k, b in enumerate(form) + if b.get("_orig_bar_i") == i and b["sec"] == recipe["form"][i]["sec"]), None) + if j is not None: + moved.append(j) + v6_plan = dict(v6, pushes=moved) + apply_rests_and_pushes(parts, lead, other, form, spans, v6_plan) + if _trace is not None: + _trace["pre"] = copy.deepcopy(parts) + _trace["hook"] = hook + _trace["form"] = form + _trace["riff"] = {k: copy.deepcopy(v) for k, v in riff_cache.items()} + if st_cfg is not None: + bt = st_cfg["base"] + canon = bt.setdefault("canon", {}) + out_parts = {"g1": [], "g2": []} + report["cost"] = {"g1": 0.0, "g2": 0.0} + for idx, (_sec, s0, s1) in enumerate(sec_spans): + bsp = bt["spans"][idx] if idx < len(bt["spans"]) and bt["spans"][idx][0] == _sec else None + sec_parts, kept = {}, {} + for g in ("g1", "g2"): + ns = sorted((n for n in parts[g] if s0 <= n["start"] < s1), key=lambda n: (n["start"], n["pitch"])) + if bsp is not None: + if (g, idx) not in canon: + canon[(g, idx)] = _studio_canon(bt["pre"][g], bsp[1], bsp[2]) + kept[g] = _studio_canon(ns, s0, s1) == canon[(g, idx)] + else: + kept[g] = False + if kept[g]: + delta = s0 - bsp[1] + sec_parts[g] = [dict(copy.deepcopy(n), start=n["start"] + delta) + for n in bt["real"][g] if bsp[1] <= n["start"] < bsp[2]] + continue + fixed = [n for n in ns if n.get("fixed") or n.get("chordtone")] + line = [n for n in ns if not n.get("fixed") and not n.get("chordtone")] + report["cost"][g] += fretboard.realize_line( + line, allow_tap=(g == "g1"), sec16=15 / realize_tempo if fix else None + ) + for n in fixed: + if n.get("fixed"): + n["string"], n["fret"] = n["fixed"] + else: + base = next((m for m in line if m["start"] == n["start"]), None) + s = base["string"] + 1 if base and base["string"] < 5 else 1 + n["string"], n["fret"] = s, n["pitch"] - fretboard.OPEN[s] + if n["fret"] < 0: + n["string"], n["fret"] = base["string"], base["fret"] + 7 if base else (0, 0) + n["tech"] = n.get("preset_tech") or (["pm"] if n.get("art") == "pm" else []) + fretboard.apply_ring(ns, 6) + for n in ns: + n["dur"] = min(n["dur"], max(1, s1 - n["start"])) + sec_parts[g] = ns + for g in ("g1", "g2"): + out_parts[g].extend(sec_parts[g]) + parts = out_parts + if fix: + report["m9_resolved"] = resolve_minor_ninths(parts, lead, other) + else: + for g in ("g1", "g2"): + ns = sorted(parts[g], key=lambda n: (n["start"], n["pitch"])) + fixed = [n for n in ns if n.get("fixed") or n.get("chordtone")] + line = [n for n in ns if not n.get("fixed") and not n.get("chordtone")] + report["cost"][g] = fretboard.realize_line(line, allow_tap=(g == "g1"), + sec16=15 / tempo if fix else None) + for n in fixed: + if n.get("fixed"): + n["string"], n["fret"] = n["fixed"] + else: + base = next((m for m in line if m["start"] == n["start"]), None) + s = base["string"] + 1 if base and base["string"] < 5 else 1 + n["string"], n["fret"] = s, n["pitch"] - fretboard.OPEN[s] + if n["fret"] < 0: + n["string"], n["fret"] = base["string"], base["fret"] + 7 if base else (0, 0) + n["tech"] = n.get("preset_tech") or (["pm"] if n.get("art") == "pm" else []) + fretboard.apply_ring(ns, 6) + parts[g] = ns + if _trace is not None: + _trace["real"] = copy.deepcopy(parts) + if fix: + report["m9_resolved"] = resolve_minor_ninths(parts, lead, other) + if _trace is not None: + starts = [(c["sec"], c["start"]) for i, c in enumerate(chords) if i == 0 or chords[i - 1]["sec"] != c["sec"]] + _trace["spans"] = [ + [sec, st0, starts[k + 1][1] if k + 1 < len(starts) else t] for k, (sec, st0) in enumerate(starts) + ] + return {"tempo": tempo, "meters": meters, "parts": parts, + "chords": chords, + "total16": t, "report": report, "theory": th} + + +def plan_skeleton(rng, intent): + """Shared rhythm skeleton: per section, the sixteenth positions both + guitars hit together (group accents plus 1-2 eighth-grid syncopations).""" + out = {} + for sec, meter, grouping in (("A", intent["meter"], intent["grouping"]), + ("B", intent["b_meter"], intent["b_grouping"])): + L = METERS[meter][0] + acc = accents_of(grouping) + off = [x for x in range(2, L, 2) if x not in acc and x - 1 not in acc] + extra = rng.sample(off, min(len(off), rng.choice([1, 2]))) + out[sec] = sorted(acc | set(extra)) + return out + + +def conform(ev, hits, L): + """Make the lead attack every skeleton hit: snap the nearest event within + one sixteenth onto the hit, otherwise repeat the previous pitch there.""" + ev = sorted((dict(e) for e in ev), key=lambda e: e["on"]) + ons = {e["on"] for e in ev} + for h in hits: + if h in ons or h >= L: + continue + near = [e for e in ev if abs(e["on"] - h) == 1 and e["on"] not in hits] + if near: + e = near[0] + ons.discard(e["on"]) + e["on"] = h + ons.add(h) + else: + prev = [e for e in ev if e["on"] < h] + ev.append({"on": h, "dur": 1, "off": prev[-1]["off"] if prev and prev[-1]["off"] is not None else 0, + "art": None}) + ons.add(h) + ev.sort(key=lambda e: e["on"]) + for i, e in enumerate(ev): + nxt = ev[i + 1]["on"] if i + 1 < len(ev) else L + e["dur"] = max(1, min(e["dur"], nxt - e["on"])) + return ev + + +def make_recipe(seed, args): + rng = random.Random(seed) + intent = plan_intent(rng, args) + v9 = getattr(args, "v9", False) + v8 = getattr(args, "v8", False) or v9 + if v8: + args = argparse.Namespace(**{**vars(args), "v7": True}) + v7 = getattr(args, "v7", False) + if v7 and not args.mode: + intent["mode"] = pick(random.Random(seed * 86028121 + 13), MODES_V7) + th = Theory(TONICS[intent["tonic"]], intent["mode"]) + harmony = plan_harmony(rng, th, intent) + motifs = plan_motifs(rng, intent, tail_rest=not getattr(args, "notail", False)) + form = plan_form(rng, intent, harmony) + version = "v1" + rec = {"seed": seed, "intent": intent, "harmony": harmony, "motifs": motifs, "form": form} + if getattr(args, "skeleton", False): + motifs["skeleton"] = plan_skeleton(random.Random(seed * 104729 + 7), intent) + version = "v2-skeleton" + if any(getattr(args, f, False) for f in ("arrange", "repeat", "texture", "v6", "v7")): + arr = plan_arrangement(random.Random(seed * 15485863 + 11), intent) + base = form_seconds(form, intent, intent["tempo"]) + cap = args.tempo or intent["tempo"] + for template in [arr["template"]] + [x for x in ARR_TEMPLATES if x != arr["template"]]: + cand = dict(arr, template=template) + f3 = arrange_form(form, harmony, cand) + beats = form_seconds(f3, intent, 1) + lo, hi = math.ceil(beats / (1.25 * base)), min(cap, math.floor(beats / (0.8 * base))) + if lo <= hi: + break + cand["tempo"] = args.tempo or max(lo, min(hi, arr["tempo"])) + rec["form"], rec["arrange"] = f3, cand + version = "v3-arrange" + if any(getattr(args, f, False) for f in ("repeat", "texture", "v6", "v7")): + rec["repeat"] = {"roles": random.Random(seed * 32452843 + 5).choice(ROLE_PATTERNS)} + rec["form"] = repeat_form(rec["form"], rec["repeat"]) + version = "v4-repeat" + if getattr(args, "texture", False) or getattr(args, "v6", False): + rec["texture"], rec["form"] = texture_form(random.Random(seed * 49979687 + 3), rec["form"]) + version = "v5-texture" + if getattr(args, "v6", False): + rec["v6"] = plan_v6(random.Random(seed * 67867967 + 9), rec["form"]) + rec["form"] = [dict(b, end=rec["v6"]["end"]) if b["sec"] == "end" else b for b in rec["form"]] + version = "v6" + if v7: + rec["fix"] = True + rec["lead"] = plan_lead(random.Random(seed * 49979693 + 21), motifs["hook"], intent) + version = "v7" + if v8: + rec["v8"], rec["form"] = plan_v8(random.Random(seed * 32452867 + 17), rec["form"]) + version = "v8" + if getattr(args, "notail", False): + version += "-notail" + if v9: + rec["v9"], rec["form"] = plan_v9(random.Random(seed * 15485867 + 23), intent, rec["form"]) + version = "v9" + return {"generator": f"composer-lab/motif-dev {version}", **rec} + + +MODES_V7 = {"aeolian": 0.3, "dorian": 0.3, "lydian": 0.15, "mixolydian": 0.15, "ionian": 0.1} +LEAD_RANGE_V7 = {"g1": (60, 82), "g2": (50, 72)} + + +def plan_lead(rng, hook, intent): + """Phrase shape for the lead: start after a short rest instead of on the + downbeat, tie one note across an accent, colour tones allowed on accents.""" + L = METERS[intent["meter"]][0] + acc = sorted(accents_of(intent["grouping"])) + r = hook["rhythm"] + ties = [a for a in acc[1:] if a in r and r.index(a) > 0] + return {"pickup": rng.choice([1, 2]) if r and r[0] == 0 and rng.random() < 0.7 else 0, + "tie": rng.choice(ties) if ties and rng.random() < 0.6 else None, + "colors": True, "L": L} + + +def shape_lead(ev, plan): + """Apply plan_lead to the motif events (all bars use the same shaped riff).""" + ev = [dict(e) for e in ev] + if plan["pickup"] and ev and ev[0]["on"] == 0 and ev[0]["dur"] > plan["pickup"]: + ev[0]["on"] = plan["pickup"] + ev[0]["dur"] -= plan["pickup"] + if plan["tie"] is not None: + at = [i for i, e in enumerate(ev) if e["on"] == plan["tie"]] + if at and at[0] > 0: + i = at[0] + ev[i - 1]["dur"] += ev[i]["dur"] + del ev[i] + return ev + + +ARR_SHAPES = { # density of the accompanying guitar per section: 1 sparse hits, 2 eighths, 3 sixteenths + "build": {"intro": 1, "A": 1, "A2": 2, "A3": 3}, + "hot_start": {"intro": 2, "A": 3, "A2": 1, "A3": 3}, + "breathe": {"intro": 1, "A": 2, "A2": 1, "A3": 3}, + "arch": {"intro": 2, "A": 2, "A2": 3, "A3": 3}, +} + + +ARR_TEMPLATES = ["classic", "double_b", "no_a2"] + + +def plan_arrangement(rng, intent): + """Arrangement plan; the template may later be swapped so that the piece + keeps the length of its v1 twin without getting faster.""" + template = rng.choice(ARR_TEMPLATES) + shape = rng.choice(sorted(ARR_SHAPES)) + b_vars = ["chug", "half", "clean"] + b1 = rng.choice(b_vars) + b2 = rng.choice([v for v in b_vars if v != b1]) + lo, hi = {"4/4": (96, 160), "7/8": (104, 176), "6/8": (92, 150), "5/4": (100, 160)}[intent["meter"]] + third = (hi - lo) // 3 + lo = rng.choice([lo, lo + third, lo + 2 * third]) + return {"template": template, "shape": shape, "b": [b1, b2], "tempo": rng.randrange(lo, lo + third), + "intro_bars": rng.choice([1, 2, 2, 4])} + + +ROLE_PATTERNS = [["chords", "chords", "chatter"], ["chatter", "chords", "chatter"], ["chords", "chatter", "chords"]] +REPEAT_PROGS = {"A": ["riff", "riff", "riff_var", "cad_open"], "A2": ["riff", "riff", "call", "cad_open"], + "A3": ["riff", "riff_harm", "riff_var", "cad_final"]} + + +def repeat_form(form, plan): + """Four-bar squares: the riff twice verbatim, a varied third bar, a cadence. + The second guitar alternates between chord hits and chatter, and plays + chords whenever the riff itself is busy; in A3 it joins the riff in + harmony only in the second bar.""" + out, pos = [], {} + for b in form: + b = dict(b) + if b["sec"] in REPEAT_PROGS: + i = pos.get(b["sec"], 0) + pos[b["sec"]] = i + 1 + b["prog"] = REPEAT_PROGS[b["sec"]][i % 4] + if b["sec"] == "A3" and b["prog"] in ("riff", "riff_var"): + b["role"] = "chords" + elif b["sec"] != "A3" and i % 4 < 3 and b["prog"] != "call": + b["role"] = plan["roles"][i % 4] + out.append(b) + return out + + +TEX_DOSE = {"alone": 0.25, "unison": 0.12, "harm3": 0.12, "rhythm": 0.11, "none": 0.40} # corpus: CORPUS-STUDY.md +SQUARE_END = {"riff_var": 0.80, "shift": 0.15, "stop": 0.05} +ENDINGS = {"held": 0.35, "stop": 0.2, "busy": 0.45} +ENDINGS_V6 = {"held": 0.5, "stop": 0.3, "busy": 0.2} + + +def pick(rng, weights): + x = rng.random() * sum(weights.values()) + for k, w in weights.items(): + x -= w + if x <= 0: + return k + return k + + +def texture_form(rng, form): + """Doses from the corpus study. A square keeps one texture throughout, as + the corpus repeats whole bars: in about a fifth of the squares one guitar + plays alone, in another fifth the second guitar doubles the lead's rhythm, + otherwise it comps or chatters for the whole square. The 4th bar mostly + keeps the riff's rhythm, sometimes shifts it or stops. An octave doubling + appears in some pieces only, for one bar.""" + out = [dict(b) for b in form] + plan = {"ends": {}, "tex": {}, "role": {}, "end": pick(rng, ENDINGS), "octave": rng.random() < 0.3} + for sec in ("A", "A2"): + plan["ends"][sec] = pick(rng, SQUARE_END) + plan["tex"][sec] = pick(rng, TEX_DOSE) + plan["role"][sec] = rng.choice(["chords", "chatter"]) + pos = {} + for b in out: + if b["sec"] in ("A", "A2"): + i = pos.get(b["sec"], 0) + pos[b["sec"]] = i + 1 + if i % 4 == 3: + b["prog"] = plan["ends"][b["sec"]] + if b["prog"] in ("riff", "riff_var", "shift"): + b["role"] = plan["role"][b["sec"]] + if plan["tex"][b["sec"]] != "none": + b["tex"] = plan["tex"][b["sec"]] + else: + b.pop("role", None) + if plan["octave"]: + cands = [b for b in out if b["sec"] in ("A2", "A3") and b["prog"] in ("riff", "riff_var") and "tex" not in b] + if cands: + rng.choice(cands)["tex"] = "octave" + for b in out: + if b["sec"] == "end": + b["end"] = plan["end"] + return plan, out + + +def form_seconds(form, intent, tempo): + six = sum(METERS[intent["b_meter"] if b["sec"] == "B" else intent["meter"]][0] for b in form) + return six * 15 / tempo + + +def arrange_form(form, harmony, arr): + dens = ARR_SHAPES[arr["shape"]] + body = [dict(b) for b in form if b["sec"] != "intro"] + if arr["template"] == "no_a2": + body = [b for b in body if b["sec"] != "A2"] + n_intro = 4 if arr["template"] == "no_a2" else arr["intro_bars"] + intro = [{"sec": "intro", "chord": harmony["A"][i % 4], "prog": "intro"} for i in range(n_intro)] + out = [] + for b in intro + body: + out.append(b) + if b["sec"] == "B": + b["var"] = arr["b"][0] + if arr["template"] == "double_b": + last_b = max(i for i, b in enumerate(out) if b["sec"] == "B") + extra = [dict(b, var=arr["b"][1]) for b in out if b["sec"] == "B"] + out[last_b + 1:last_b + 1] = extra + for b in out: + if b["sec"] in dens: + b["dens"] = dens[b["sec"]] + return out + + +# ---------------------------------------------------------------- critic + +def critique(piece): + th = piece["theory"] + score = 0.0 + notes = {g: piece["parts"][g] for g in ("g1", "g2")} + chord_at = [] + for c in piece["chords"]: + chord_at.append((c["start"], c["root_deg"])) + + def root_at(t): + r = chord_at[0][1] + for s, rr in chord_at: + if s <= t: + r = rr + return r + + clashes = 0 + pairs = 0 + for a in notes["g1"]: + for b in notes["g2"]: + if b["start"] == a["start"]: + pairs += 1 + ic = abs(a["pitch"] - b["pitch"]) % 12 + if ic in (1, 11) or (ic == 6 and not stable(th.deg_near(a["pitch"]), root_at(a["start"]))): + clashes += 1 + score -= 3.0 * clashes / max(1, pairs) + leaps = 0 + for g in notes: + line = [n for n in notes[g] if not n.get("fixed") and not n.get("ring")] + for x, y in zip(line, line[1:]): + if abs(x["pitch"] - y["pitch"]) > 12: + leaps += 1 + score -= 0.05 * leaps + cost = sum(piece["report"]["cost"].values()) / max(1, sum(len(v) for v in notes.values())) + score -= cost + peak = max(notes["g1"] + notes["g2"], key=lambda n: n["pitch"]) + pos = peak["start"] / piece["total16"] + score -= 0.8 * abs(pos - 0.72) + return {"score": round(score, 4), "clash_ratio": round(clashes / max(1, pairs), 3), + "big_leaps": leaps, "fret_cost_per_note": round(cost, 3), "peak_pos": round(pos, 3)} + + +# ---------------------------------------------------------------- output + +def tab_text(piece): + lines_out = [] + names = ["E", "A", "D", "G", "B", "e"] + sym = {"tap": "t", "hammer": "h", "pull": "p", "slide": "/"} + for g in ("g1", "g2"): + lines_out.append(f"== {g} ==") + ns = piece["parts"][g] + for c_i, c in enumerate(piece["chords"]): + start = c["start"] + end = piece["chords"][c_i + 1]["start"] if c_i + 1 < len(piece["chords"]) else piece["total16"] + width = end - start + rows = [["---"] * width for _ in range(6)] + pm = [" "] * width + for n in ns: + if start <= n["start"] < end and float(n["start"]).is_integer(): + i = int(n["start"] - start) + mark = "".join(sym[x] for x in n.get("tech", []) if x in sym) + cell = (mark + str(n["fret"])).ljust(3, "-")[:3] + rows[n["string"]][i] = cell + if "pm" in n.get("tech", []): + pm[i] = "M" + lines_out.append(f"bar {c_i + 1} [{c['sec']}] chord deg {c['root_deg'] + 1}") + if any(x != " " for x in pm): + lines_out.append("PM " + "".join(x.ljust(3) for x in pm)) + for s in range(5, -1, -1): + lines_out.append(names[s] + "|" + "".join(rows[s]) + "|") + lines_out.append("") + lines_out.append("legend: t=tap h=hammer-on p=pull-off /=slide M=palm mute") + return "\n".join(lines_out) + + +def midi_tracks(piece, programs=(27, 27)): + tracks = [] + for i, g in enumerate(("g1", "g2")): + norm = [(n["start"], n["dur"], n["pitch"], max(30, min(127, n["vel"]))) for n in piece["parts"][g] + if "pm" not in n.get("tech", [])] + pm = [(n["start"], n["dur"], n["pitch"], max(30, min(127, n["vel"]))) for n in piece["parts"][g] + if "pm" in n.get("tech", [])] + tracks.append({"name": f"Guitar {i + 1}", "channel": i * 2, "program": programs[i], + "pan": 34 if i == 0 else 94, "notes": norm}) + if pm: + tracks.append({"name": f"Guitar {i + 1} (palm mute)", "channel": i * 2 + 1, "program": 28, + "pan": 34 if i == 0 else 94, "notes": pm}) + return tracks + + +def export(piece, out_base, programs=(27, 27)): + write_midi(out_base.with_suffix(".mid"), piece["tempo"], piece["meters"], midi_tracks(piece, programs)) + out_base.with_suffix(".tab.txt").write_text(tab_text(piece), encoding="utf-8") + musicxml.write_musicxml(piece, out_base.with_suffix(".musicxml"), out_base.name) + + +def generate(seed, args, k): + best = None + tried = [] + for j in range(k): + rec = make_recipe(seed * 1000 + j, args) + if args.control: + rec["control"] = args.control + piece = compose(rec) + crit = critique(piece) + tried.append({"subseed": rec["seed"], **crit}) + if best is None or crit["score"] > best[2]["score"]: + best = (rec, piece, crit) + return best, tried + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--seeds", default="1") + ap.add_argument("--candidates", type=int, default=6) + ap.add_argument("--out", default="out") + ap.add_argument("--meter") + ap.add_argument("--mode") + ap.add_argument("--key") + ap.add_argument("--tempo", type=int) + ap.add_argument("--recipe") + ap.add_argument("--prefix", default="new") + ap.add_argument("--control", choices=["shuffle"]) + ap.add_argument("--skeleton", action="store_true", help="v2: shared rhythm skeleton for both guitars") + ap.add_argument("--arrange", action="store_true", help="v3: tempo, density, B variant and form plan") + ap.add_argument("--repeat", action="store_true", help="v4: v3 plus repeated riffs and alternating guitar roles") + ap.add_argument("--texture", action="store_true", help="v5: v4 plus corpus-dosed square ends, doubling and endings") + ap.add_argument("--notail", action="store_true", + help="no trailing rest of 3-4 sixteenths at the end of the riff bar (combine with a version flag)") + ap.add_argument("--v9", action="store_true", + help="v9: v8 plus a comping vocabulary with square variations and intro hand-over") + ap.add_argument("--v8", action="store_true", + help="v8: v7 plus octave-shape rhythm guitar, leaping arpeggios, no low clusters, soft riff entry") + ap.add_argument("--v7", action="store_true", + help="v7: v4 plus minor-ninth resolution, tempo-aware fingering and the lead plan") + ap.add_argument("--v6", action="store_true", + help="v6: v5 plus minor-ninth resolution, rests, pushes, tempo-aware fingering") + args = ap.parse_args(argv) + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + manifest = [] + if args.recipe: + rec = json.loads(Path(args.recipe).read_text(encoding="utf-8")) + piece = compose(rec) + export(piece, out / f"{args.prefix}_recipe") + print(json.dumps(critique(piece))) + return + a, b = (args.seeds.split("-") + [None])[:2] + seeds = range(int(a), int(b) + 1) if b else [int(a)] + for seed in seeds: + (rec, piece, crit), tried = generate(seed, args, args.candidates) + base = out / f"{args.prefix}_{seed:03d}" + export(piece, base) + base.with_suffix(".recipe.json").write_text(json.dumps(rec, indent=1), encoding="utf-8") + manifest.append({"file": base.name, "seed": seed, "chosen_subseed": rec["seed"], + "candidates_considered": len(tried), "critic": crit, "all_candidates": tried, + "intent": rec["intent"], "bars": len(rec["form"])}) + (out / f"{args.prefix}_manifest.json").write_text( + json.dumps({"python": sys.version, "generator": rec["generator"], "pieces": manifest}, + indent=1), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/composer-lab/corpus/novelty.py b/composer-lab/corpus/novelty.py new file mode 100644 index 00000000..d5a7825d --- /dev/null +++ b/composer-lab/corpus/novelty.py @@ -0,0 +1,72 @@ +"""Copy check: share of generated 8-note windows (pitch intervals plus onset +gaps, transposition-invariant) that also occur in the tab corpus. + +python corpus/novelty.py ... (flags: arrange repeat texture) +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import study + +N = 7 + + +def grams(line): + """line: (absolute onset16, pitch) sorted; the top pitch per onset.""" + top = {} + for o, p in line: + top[o] = max(p, top.get(o, p)) + seq = sorted(top.items()) + tok = [(b[1] - a[1], b[0] - a[0]) for a, b in zip(seq, seq[1:]) if b[0] - a[0] <= 16] + return {tuple(tok[i:i + N]) for i in range(len(tok) - N + 1)} + + +def corpus_grams(tabs): + out, songs = set(), 0 + for p in sorted(Path(tabs).iterdir()): + if p.suffix.lower() not in (".gp3", ".gp4", ".gp5"): + continue + try: + song, _ = study.load_song(p) + except Exception: + continue + if song is None: + continue + songs += 1 + t = 0 + lines = ([], []) + for b in song["bars"]: + for k in (0, 1): + lines[k].extend((t + o, pitch) for o, pitch in b["parts"][k]) + t += b["L"] + for line in lines: + out |= grams(line) + return out, songs + + +def piece_lines(piece): + return [[(n["start"], n["pitch"]) for n in piece["parts"][g]] for g in ("g1", "g2")] + + +def main(): + import composer + tabs, a, b = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) + flags = {f: True for f in sys.argv[4:]} + ref, songs = corpus_grams(tabs) + hit = tot = 0 + worst = (0, None) + for seed in range(a, b + 1): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **flags) + piece = composer.compose(composer.make_recipe(seed * 1000, args)) + g = set().union(*(grams(x) for x in piece_lines(piece))) + h = len(g & ref) + hit, tot = hit + h, tot + len(g) + worst = max(worst, (h / max(1, len(g)), seed)) + print(f"corpus: {songs} songs, {len(ref)} distinct windows; generated {sorted(flags)} seeds {a}-{b}: " + f"{hit}/{tot} windows found in corpus ({hit / max(1, tot):.3f}); worst piece seed {worst[1]} {worst[0]:.3f}") + + +if __name__ == "__main__": + main() diff --git a/composer-lab/corpus/study.py b/composer-lab/corpus/study.py new file mode 100644 index 00000000..4d14a281 --- /dev/null +++ b/composer-lab/corpus/study.py @@ -0,0 +1,305 @@ +"""Corpus dosing study (see CORPUS-STUDY.md). + +python corpus/study.py + +Writes per-song statistics, the sample log and an audit sheet to +(keep it local: it names copyrighted songs and prints bars from them) and +prints only aggregates. +""" +import hashlib +import json +import random +import re +import statistics +import sys +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +BANDS = {"Dance Gavin Dance": 7, "Hail The Sun": 4, "A Lot Like Birds": 4} +SKIP_NAME = re.compile(r"bass|vocal|vox|voice|drum|synth|key|piano|lyric|organ|omnichord|string|choir|pad", re.I) +HARMONY = {3, 4, 8, 9, 15, 16} +Q = 960 + + +# ---------------------------------------------------------------- corpus reading + +def play_order(headers): + """Measure indices in playing order with repeats and alternate endings expanded.""" + order, i, start, done = [], 0, 0, {} + while i < len(headers) and len(order) < 5000: + h = headers[i] + if h.isRepeatOpen: + start = i + p = done.get(start, 0) + 1 + if h.repeatAlternative and not (h.repeatAlternative >> (p - 1)) & 1: + i += 1 + continue + order.append(i) + if h.repeatClose > 0: + if done.get(start, 0) < h.repeatClose: + done[start] = done.get(start, 0) + 1 + i = start + continue + done[start] = 0 + i += 1 + return order + + +def guitar_tracks(song): + tracks = [t for t in song.tracks if not t.isPercussionTrack and len(t.strings) >= 6 + and not SKIP_NAME.search(t.name)] + count = lambda t: sum(len(b.notes) for m in t.measures for v in m.voices for b in v.beats) + tracks = sorted(tracks, key=count, reverse=True) + return [t for t in tracks if count(t) > 0][:2], [t.name for t in tracks] + + +def bar_notes(measure): + """(onset16, pitch) of struck notes, or None when voice 1 has notes but does not + fill the bar. Guitar Pro stores an empty bar as a single quarter rest.""" + v0 = measure.voices[0].beats + if sum(b.duration.time for b in v0) != measure.length and any(b.notes for b in v0): + return None + out = [] + for v in measure.voices: + for b in v.beats: + for n in b.notes: + if n.type.name in ("tie", "dead"): + continue + out.append((round((b.start - measure.start) / (Q / 4)), n.realValue)) + return out + + +def load_song(path): + import guitarpro + song = guitarpro.parse(str(path)) + tracks, names = guitar_tracks(song) + if len(tracks) < 2: + return None, names + bars, dropped = [], 0 + for i in play_order(song.measureHeaders): + h = song.measureHeaders[i] + L = h.timeSignature.numerator * 16 // h.timeSignature.denominator.value + parts = [bar_notes(t.measures[i]) for t in tracks] + if any(p is None for p in parts): + dropped += 1 + continue + bars.append({"L": L, "parts": parts, "src": i + 1}) + return {"bars": bars, "dropped": dropped, "tracks": [t.name for t in tracks]}, names + + +def sample(tabs): + files = sorted(p for p in Path(tabs).iterdir() if p.suffix.lower() in (".gp3", ".gp4", ".gp5")) + rng = random.Random(20261124) + chosen, log = [], [] + for band, n in BANDS.items(): + pool = [p for p in files if p.name.startswith(band + " - ") and "(ver" not in p.name.lower()] + rng.shuffle(pool) + got = 0 + for p in pool: + if got == n: + break + try: + song, names = load_song(p) + except Exception as e: + log.append({"file": p.name, "replaced": f"load error: {e}"}) + continue + if song is None: + log.append({"file": p.name, "replaced": f"fewer than two guitar tracks: {names}"}) + continue + got += 1 + chosen.append((p, song)) + log.append({"file": p.name, "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), + "tracks": song["tracks"], "bars": len(song["bars"]), "dropped_bars": song["dropped"]}) + return chosen, log + + +# ---------------------------------------------------------------- statistics + +def onsets(notes): + return {o for o, _ in notes} + + +def relation(bar): + a, b = bar["parts"] + oa, ob = onsets(a), onsets(b) + half = bar["L"] / 2 + if not oa or not ob: + return "one_silent" if (oa or ob) else "both_silent" + shared = oa & ob + if len(shared) >= 0.8 * max(len(oa), len(ob)): + iv = Counter() + for o in shared: + pa = max(p for t, p in a if t == o) + pb = max(p for t, p in b if t == o) + iv[abs(pa - pb)] += 1 + top = iv.most_common(1)[0][0] + if top == 0: + return "unison" + if top in (12, 24): + return "octave" + if top in HARMONY: + return "harmony" + return "same_rhythm" + busy = (len(oa) >= half, len(ob) >= half) + if all(busy): + return "both_busy" + if any(busy): + return "one_busy" + return "neither_busy" + + +def pattern(bar): + return tuple(sorted(onsets(bar["parts"][0]) | onsets(bar["parts"][1]))) + + +def squares(bars): + out, i = [], 0 + while i + 3 < len(bars): + w = bars[i:i + 4] + if len({b["L"] for b in w}) == 1 and pattern(w[0]) and pattern(w[0]) == pattern(w[1]) == pattern(w[2]): + p3, p4 = len(pattern(w[0])), pattern(w[3]) + if p4 == pattern(w[0]): + kind = "repeat" + elif len(p4) <= 2: + kind = "stop" + elif len(p4) >= 1.3 * p3: + kind = "denser" + elif len(p4) <= 0.7 * p3: + kind = "thinner" + else: + kind = "shifted" + out.append((i, kind)) + i += 4 + else: + i += 1 + return out + + +def runs(bars): + key = lambda b: (b["L"], tuple(sorted(b["parts"][0])), tuple(sorted(b["parts"][1]))) + out, cur = [], 1 + for x, y in zip(bars, bars[1:]): + if key(x) == key(y) and pattern(x): + cur += 1 + else: + out.append(cur) + cur = 1 + out.append(cur) + return [r for r in out if r > 1] or [1] + + +def last_bar(bars): + live = [b for b in bars if pattern(b)] + if not live: + return "none" + b = live[-1] + n = len(pattern(b)) + if n >= b["L"] / 2: + return "busy" + return "held" if n <= 2 else "stop" + + +def song_stats(bars): + two = [b for b in bars if pattern(b)] + rel = Counter(relation(b) for b in two) + sq = squares(bars) + kinds = Counter(k for _, k in sq) + return { + "bars": len(bars), + "relation": {k: rel[k] / max(1, len(two)) for k in + ("one_busy", "both_busy", "unison", "octave", "harmony", "same_rhythm", "neither_busy", + "one_silent")}, + "squares": len(sq), + "square_varied": (1 - kinds["repeat"] / len(sq)) if sq else None, + "square_kind": {k: kinds[k] / len(sq) for k in ("repeat", "stop", "denser", "thinner", "shifted")} if sq else None, + "median_run": statistics.median(runs(bars)), + "last_bar": last_bar(bars), + } + + +# ---------------------------------------------------------------- generator side + +def piece_bars(piece): + ch = piece["chords"] + out = [] + for i, c in enumerate(ch): + s = c["start"] + e = ch[i + 1]["start"] if i + 1 < len(ch) else piece["total16"] + parts = [[(int(n["start"] - s), n["pitch"]) for n in piece["parts"][g] if s <= n["start"] < e] + for g in ("g1", "g2")] + out.append({"L": e - s, "parts": parts, "src": i + 1}) + return out + + +def generator_stats(seeds, **flags): + import composer + res = [] + for seed in seeds: + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **flags) + res.append(song_stats(piece_bars(composer.compose(composer.make_recipe(seed * 1000, args))))) + return res + + +def summary(stats): + def q(vals): + vals = sorted(v for v in vals if v is not None) + if not vals: + return None + qs = statistics.quantiles(vals, n=4) if len(vals) > 1 else [vals[0]] * 3 + return {"median": round(statistics.median(vals), 3), "q1": round(qs[0], 3), "q3": round(qs[2], 3), "n": len(vals)} + out = {"square_varied": q([s["square_varied"] for s in stats]), + "median_run": q([s["median_run"] for s in stats]), + "squares_per_song": q([s["squares"] for s in stats])} + for k in stats[0]["relation"]: + out["rel_" + k] = q([s["relation"][k] for s in stats]) + for k in ("repeat", "stop", "denser", "thinner", "shifted"): + out["sq_" + k] = q([s["square_kind"][k] for s in stats if s["square_kind"]]) + lb = Counter(s["last_bar"] for s in stats) + out["last_bar"] = {k: round(v / len(stats), 3) for k, v in lb.items()} + return out + + +def tab_lines(bar): + rows = [] + for name, notes in zip(("g1", "g2"), bar["parts"]): + cells = ["."] * bar["L"] + for o, p in notes: + if 0 <= o < bar["L"]: + cells[o] = str(p) + rows.append(f"{name}: " + " ".join(c.rjust(2) for c in cells)) + return rows + + +def main(): + tabs, out = Path(sys.argv[1]), Path(sys.argv[2]) + out.mkdir(parents=True, exist_ok=True) + chosen, log = sample(tabs) + (out / "sample_log.json").write_text(json.dumps(log, indent=1, ensure_ascii=False), encoding="utf-8") + per = [dict(song_stats(s["bars"]), file=p.name) for p, s in chosen] + (out / "per_song.json").write_text(json.dumps(per, indent=1, ensure_ascii=False), encoding="utf-8") + rng = random.Random(20261124) + order = list(range(len(per))) + rng.shuffle(order) + halves = [[per[i] for i in order[: len(order) // 2]], [per[i] for i in order[len(order) // 2:]]] + audit, pool = [], [(p.name, b) for p, s in chosen for b in s["bars"] if pattern(b)] + for name, b in rng.sample(pool, 20): + audit.append(f"{name} bar {b['src']} (L={b['L']}): {relation(b)}\n" + "\n".join(tab_lines(b))) + (out / "audit.txt").write_text("\n\n".join(audit), encoding="utf-8") + result = { + "songs": len(per), + "replacements": sum("replaced" in x for x in log), + "dropped_bars": sum(x.get("dropped_bars", 0) for x in log), + "corpus": summary(per), + "half_a": summary(halves[0]), + "half_b": summary(halves[1]), + "v1": summary(generator_stats(range(401, 441))), + "v4": summary(generator_stats(range(401, 441), arrange=True, repeat=True)), + } + (out / "summary.json").write_text(json.dumps(result, indent=1), encoding="utf-8") + print(json.dumps(result, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/composer-lab/fretboard.py b/composer-lab/fretboard.py new file mode 100644 index 00000000..4acbc3e2 --- /dev/null +++ b/composer-lab/fretboard.py @@ -0,0 +1,173 @@ +"""Fretboard realization: string/fret assignment with technique derivation. + +Single lines are realised by a Viterbi pass over (string, fret, hand position, +tapped) states; chords by a voicing search inside one hand window. +""" + +OPEN = [40, 45, 50, 55, 59, 64] # string index 0 = low E ... 5 = high E +MAX_FRET = 22 +SPAN = 4 + + +def _candidates(pitch): + out = [] + for s, o in enumerate(OPEN): + f = pitch - o + if 0 <= f <= MAX_FRET: + out.append((s, f)) + return out + + +FAST = 0.12 # seconds + + +def realize_line(notes, allow_tap, sec16=None): + """notes: time-ordered dicts with start, dur, pitch. Adds string, fret, + tech. Returns total cost. With sec16 (seconds per sixteenth), a hand jump + over 4 frets or a skip over 2 strings within FAST seconds is priced as + unplayable, so it is taken only when the pitches leave no other path.""" + if not notes: + return 0.0 + layers = [] + prev = None + for i, n in enumerate(notes): + layer = {} + cands = _candidates(n["pitch"]) + if not cands: + raise ValueError(f"pitch {n['pitch']} not on fretboard") + gap = n["start"] - notes[i - 1]["start"] if i else 99 + for s, f in cands: + if prev is None: + hs = [1] if f == 0 else list(range(max(1, f - SPAN + 1), f + 1)) + for h in hs: + layer[(s, f, h, False)] = (f * 0.05, None) + continue + for key, (pc, _) in prev.items(): + ps, pf, ph, ptap = key + opts = [] + if f == 0: + opts.append((ph, False, 0.0)) + elif ph <= f <= ph + SPAN - 1: + opts.append((ph, False, 0.0)) + elif f == ph + SPAN: + opts.append((ph, False, 0.6)) + if f > 0 and not (ph <= f <= ph + SPAN - 1): + for h in range(max(1, f - SPAN + 1), f + 1): + shift = abs(h - ph) + speed = 1.0 if gap >= 2 else 2.2 + opts.append((h, False, 0.8 + shift * 0.35 * speed)) + if allow_tap and n.get("tappable") and f >= ph + SPAN + 2 and s == ps and not ptap: + opts.append((ph, True, 0.5)) + if allow_tap and ptap and f > 0 and s == ps and ph <= f <= ph + SPAN - 1: + opts.append((ph, False, -0.3)) + fast = sec16 is not None and 0 < gap * sec16 < FAST + for h, tap, c in opts: + if fast and (abs(h - ph) > 4 or abs(s - ps) > 2 or (f and pf and abs(f - pf) >= 7)): + c += 25.0 + c += 0.12 * abs(s - ps) + if gap < 2 and s == ps and pf == f and f > 0: + c += 0.4 + if ptap and s != ps: + c += 1.0 + c += 0.02 * f + 0.06 * max(0, f - 12) * (1 + 0.4 * (5 - s)) + k = (s, f, h, tap) + tot = pc + c + if k not in layer or tot < layer[k][0]: + layer[k] = (tot, key) + if not layer: + raise ValueError("no fretboard path") + layers.append(layer) + prev = layer + key = min(prev, key=lambda k: prev[k][0]) + total = prev[key][0] + path = [] + for layer in reversed(layers): + path.append(key) + key = layer[key][1] + path.reverse() + for i, (n, (s, f, h, tap)) in enumerate(zip(notes, path)): + n["string"], n["fret"] = s, f + tech = [] + if tap: + tech.append("tap") + elif i: + p = notes[i - 1] + ps, pf = p["string"], p["fret"] + sounding = p["start"] + p["dur"] >= n["start"] - 0.01 + close = n["start"] - p["start"] <= 2 + if s == ps and pf != f and sounding and close: + if n.get("art") == "slide" or (abs(f - pf) <= 2 and n["start"] - p["start"] >= 2): + tech.append("slide") + elif f > pf: + tech.append("hammer") + else: + tech.append("pull") + elif s == ps and pf != f and n.get("art") == "slide" and abs(f - pf) <= 5: + tech.append("slide") + if n.get("art") == "pm": + tech.append("pm") + n["tech"] = tech + return total + + +def apply_ring(notes, max_ring): + """Let notes ring until the same string is re-struck (physical cut).""" + by_string = {} + for n in sorted(notes, key=lambda x: x["start"]): + by_string.setdefault(n["string"], []).append(n) + for seq in by_string.values(): + for a, b in zip(seq, seq[1:]): + limit = b["start"] - a["start"] + a["dur"] = min(max(a["dur"], min(max_ring, limit)) if a.get("ring") else a["dur"], limit) + if seq and seq[-1].get("ring"): + seq[-1]["dur"] = max(seq[-1]["dur"], max_ring) + + +def low_cluster(pitches, below=66, span=4): + """Three or more notes within `span` semitones under `below`: muddy.""" + low = sorted(p for p in pitches if p < below) + return any(c - a <= span for a, c in zip(low, low[2:])) + + +def voice_chord(pcs, bass_pc, lo, hi, prev_frets=None, n_strings=4, avoid_cluster=False): + """Return list of (string, fret, pitch) for a chord voicing whose pitch + classes are all in pcs, bass note pitch class == bass_pc, in [lo, hi].""" + best = None + for h in range(0, 15): + window = [0] + list(range(max(1, h), h + SPAN)) + for low_s in range(0, 6 - n_strings + 1): + strings = range(low_s, low_s + n_strings) + choice = [] + ok = True + for s in strings: + opts = [f for f in window if (OPEN[s] + f) % 12 in pcs and lo <= OPEN[s] + f <= hi] + if not opts: + ok = False + break + choice.append((s, opts)) + if not ok: + continue + voicing = [] + for s, opts in choice: + if s == low_s: + opts = [f for f in opts if (OPEN[s] + f) % 12 == bass_pc] or None + if opts is None: + ok = False + break + f = max(opts, key=lambda f: (f == 0, -f)) if h == 0 else min(opts, key=lambda f: abs(f - h - 1)) + voicing.append((s, f, OPEN[s] + f)) + if not ok or len({p for _, _, p in voicing}) < len(voicing): + continue + if avoid_cluster and low_cluster([p for _, _, p in voicing]): + continue + pcset = {p % 12 for _, _, p in voicing} + cost = (len(pcs) - len(pcset & set(pcs))) * 1.5 + fretted = [f for _, f, _ in voicing if f > 0] + if fretted: + cost += (max(fretted) - min(fretted)) * 0.2 + cost -= 0.25 * sum(1 for _, f, _ in voicing if f == 0) + if prev_frets is not None: + cost += 0.15 * abs((sum(fretted) / len(fretted) if fretted else 0) - prev_frets) + if best is None or cost < best[0]: + best = (cost, voicing) + return best[1] if best else None diff --git a/composer-lab/midiio.py b/composer-lab/midiio.py new file mode 100644 index 00000000..df753763 --- /dev/null +++ b/composer-lab/midiio.py @@ -0,0 +1,57 @@ +"""Minimal standard-library MIDI type-1 writer.""" +import struct + +PPQ = 480 +SIXTEENTH = PPQ // 4 + + +def _vlq(n): + out = [n & 0x7F] + n >>= 7 + while n: + out.append(0x80 | (n & 0x7F)) + n >>= 7 + return bytes(reversed(out)) + + +def _track(events): + events = sorted(events, key=lambda e: (e[0], e[1])) + data = bytearray() + last = 0 + for tick, _order, payload in events: + data += _vlq(tick - last) + payload + last = tick + data += _vlq(0) + b"\xff\x2f\x00" + return b"MTrk" + struct.pack(">I", len(data)) + bytes(data) + + +def midi_bytes(tempo_bpm, meters, tracks): + """meters: list of (start_tick, num, den). tracks: list of dicts with + name, channel, program, pan, notes=[(start16, dur16, pitch, vel)].""" + conductor = [(0, 0, b"\xff\x51\x03" + int(60_000_000 / tempo_bpm).to_bytes(3, "big"))] + for tick, num, den in meters: + dd = {2: 1, 4: 2, 8: 3, 16: 4}[den] + conductor.append((tick, 1, b"\xff\x58\x04" + bytes([num, dd, 24, 8]))) + chunks = [_track(conductor)] + for t in tracks: + ch = t["channel"] + name = t["name"].encode() + ev = [ + (0, 0, b"\xff\x03" + _vlq(len(name)) + name), + (0, 1, bytes([0xC0 | ch, t["program"]])), + (0, 2, bytes([0xB0 | ch, 10, t["pan"]])), + ] + for start, dur, pitch, vel in t["notes"]: + on = int(round(start * SIXTEENTH)) + off = max(on + 1, int(round((start + dur) * SIXTEENTH)) - 6) + ev.append((on, 4, bytes([0x90 | ch, pitch, vel]))) + ev.append((off, 3, bytes([0x80 | ch, pitch, 0]))) + chunks.append(_track(ev)) + header = b"MThd" + struct.pack(">IHHH", 6, 1, len(chunks), PPQ) + return header + b"".join(chunks) + + +def write_midi(path, tempo_bpm, meters, tracks): + data = midi_bytes(tempo_bpm, meters, tracks) + with open(path, "wb") as f: + f.write(data) diff --git a/composer-lab/musicxml.py b/composer-lab/musicxml.py new file mode 100644 index 00000000..70cbf5ff --- /dev/null +++ b/composer-lab/musicxml.py @@ -0,0 +1,155 @@ +"""MusicXML tablature export (opens in Guitar Pro, TuxGuitar, MuseScore). + +Written durations run onset-to-next-onset inside a bar; ringing is shown with +let-ring text instead of overlapping voices. Techniques are the generator's +own decisions: tap, hammer-on, pull-off, slide, palm mute. +""" +from xml.sax.saxutils import escape + +DIV = 4 # divisions per quarter = sixteenths +TYPES = {16: ("whole", 0), 12: ("half", 1), 8: ("half", 0), 6: ("quarter", 1), 4: ("quarter", 0), + 3: ("eighth", 1), 2: ("eighth", 0), 1: ("16th", 0)} +STEPS = ["C", "C", "D", "D", "E", "F", "F", "G", "G", "A", "A", "B"] +ALTER = [0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0] +TUNING = [("E", 2), ("A", 2), ("D", 3), ("G", 3), ("B", 3), ("E", 4)] + + +def split_dur(d): + out = [] + for v in sorted(TYPES, reverse=True): + while d >= v: + out.append(v) + d -= v + return out + + +def _pitch(p): + a = ALTER[p % 12] + return (f"{STEPS[p % 12]}" + (f"{a}" if a else "") + + f"{p // 12 - 1}") + + +def _bars(piece): + starts = [c["start"] for c in piece["chords"]] + [piece["total16"]] + meters = sorted(piece["meters"]) + out = [] + for i in range(len(starts) - 1): + t = starts[i] + num, den = next((n, d) for tick, n, d in reversed(meters) if tick <= t * 120) + out.append((t, starts[i + 1], num, den)) + return out + + +def part_xml(piece, g, pid): + notes = [n for n in piece["parts"][g] if n["start"] >= 0] + xml = [f''] + prev_meter = None + marks_next = {} + seq = sorted(notes, key=lambda n: (n["start"], n["string"])) + by_string_prev = {} + for n in seq: + p = by_string_prev.get(n["string"]) + for tech in n.get("tech", []): + if tech in ("hammer", "pull", "slide") and p is not None: + marks_next.setdefault(id(p), []).append(("start", tech)) + marks_next.setdefault(id(n), []).append(("stop", tech)) + by_string_prev[n["string"]] = n + for bi, (b0, b1, num, den) in enumerate(_bars(piece)): + xml.append(f'') + if bi == 0 or (num, den) != prev_meter: + xml.append("") + if bi == 0: + xml.append(f"{DIV}") + xml.append(f"") + if bi == 0: + xml.append('TAB56') + for i, (st, oc) in enumerate(TUNING): + xml.append(f'{st}' + f'{oc}') + xml.append("") + xml.append("") + if bi == 0: + xml.append(f'quarter' + f'{piece["tempo"]}' + f'') + prev_meter = (num, den) + inbar = [n for n in seq if b0 <= n["start"] < b1 and float(n["start"]).is_integer()] + onsets = sorted({int(n["start"]) for n in inbar}) + cur = b0 + pm_on = False + for k, on in enumerate(onsets): + if on > cur: + for d in split_dur(on - cur): + xml.append(f"{d}{TYPES[d][0]}" + + ("" if TYPES[d][1] else "") + "") + nxt = onsets[k + 1] if k + 1 < len(onsets) else b1 + group = [n for n in inbar if int(n["start"]) == on] + longest = max(n["dur"] for n in group) + written = max(1, min(nxt - on, int(round(longest)) if nxt == b1 else nxt - on)) + pieces = split_dur(written) + is_pm = any("pm" in n.get("tech", []) for n in group) + if is_pm and not pm_on: + xml.append('P.M.') + pm_on = is_pm + for ci, n in enumerate(group): + for pi, d in enumerate(pieces): + tie = [] + if len(pieces) > 1 and pi < len(pieces) - 1: + tie.append("start") + if pi > 0: + tie.append("stop") + x = [""] + if ci > 0: + x.append("") + x.append(_pitch(n["pitch"])) + x.append(f"{d}") + x += [f'' for t in tie] + x.append(f"{TYPES[d][0]}" + ("" if TYPES[d][1] else "")) + if pi == 0 and "dead" in n.get("tech", []): + x.append("x") + tech = [f"{6 - n['string']}{n['fret']}"] + other = [f'' for t in tie] + if pi == 0: + if "tap" in n.get("tech", []): + tech.append("") + for kind, tch in marks_next.get(id(n), []): + if tch == "hammer": + tech.append(f'H') + elif tch == "pull": + tech.append(f'P') + else: + other.append(f'') + x.append("" + "".join(tech) + "" + "".join(other) + "") + x.append("") + xml.append("".join(x)) + cur = on + written + if cur < b1: + for d in split_dur(b1 - cur): + xml.append(f"{d}{TYPES[d][0]}" + + ("" if TYPES[d][1] else "") + "") + xml.append("") + xml.append("") + return "\n".join(xml) + + +def musicxml_text(piece, title): + parts = [("g1", "P1", "Guitar 1"), ("g2", "P2", "Guitar 2")] + head = ['', + '', + '', + f"{escape(title)}", ""] + for g, pid, name in parts: + head.append(f'{name}' + f'Electric Guitar' + f'28' + f"") + head.append("") + body = [part_xml(piece, g, pid) for g, pid, _ in parts] + return "\n".join(head + body + [""]) + + +def write_musicxml(piece, path, title): + text = musicxml_text(piece, title) + with open(path, "w", encoding="utf-8") as f: + f.write(text) diff --git a/composer-lab/render/audition_midi.py b/composer-lab/render/audition_midi.py new file mode 100644 index 00000000..48c84093 --- /dev/null +++ b/composer-lab/render/audition_midi.py @@ -0,0 +1,68 @@ +"""Copy a MIDI file forcing every channel onto program 0 (the single-preset +guitar SoundFont) so every generator is heard through the same instrument.""" +import struct +import sys + + +def _vlq(data, i): + v = 0 + while True: + b = data[i] + i += 1 + v = (v << 7) | (b & 0x7F) + if b < 0x80: + return v, i + + +def remap(src, dst): + d = bytearray(open(src, "rb").read()) + pos = 14 + out = bytearray(d[:14]) + while pos < len(d): + tag, ln = d[pos:pos + 4], struct.unpack(">I", d[pos + 4:pos + 8])[0] + body = d[pos + 8:pos + 8 + ln] + if tag == b"MTrk": + i, run, seen = 0, None, set() + new = bytearray() + while i < len(body): + start = i + _, i = _vlq(body, i) + delta_bytes = body[start:i] + st = body[i] + if st >= 0x80: + i += 1 + if st < 0xF0: + run = st + else: + st = run + if st == 0xFF: + mt = body[i] + l, j = _vlq(body, i + 1) + new += delta_bytes + bytes([0xFF]) + body[i:j + l] + i = j + l + elif st in (0xF0, 0xF7): + l, j = _vlq(body, i) + new += delta_bytes + bytes([st]) + body[i:j + l] + i = j + l + else: + kind = st & 0xF0 + n = 1 if kind in (0xC0, 0xD0) else 2 + args = bytearray(body[i:i + n]) + i += n + ch = st & 0x0F + if kind == 0xC0: + args[0] = 0 + seen.add(ch) + if kind == 0x90 and ch not in seen: + new += delta_bytes + bytes([0xC0 | ch, 0]) + delta_bytes = b"\x00" + seen.add(ch) + new += delta_bytes + bytes([st]) + args + body = new + out += tag + struct.pack(">I", len(body)) + body + pos += 8 + ln + open(dst, "wb").write(out) + + +if __name__ == "__main__": + remap(sys.argv[1], sys.argv[2]) diff --git a/composer-lab/render/band.py b/composer-lab/render/band.py new file mode 100644 index 00000000..a3369c78 --- /dev/null +++ b/composer-lab/render/band.py @@ -0,0 +1,68 @@ +"""Bass and drums under a composed piece, for listening only (not part of the +composition): python band.py + +Bass plays the chord root on the group accents; drums play kick on the +accents, snare on the accent nearest the middle of the bar, closed hi-hat on +eighths, a crash at each section start. The intro has hi-hat only. +""" +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import composer +from midiio import write_midi + + +def band_tracks(rec): + p = composer.compose(rec) + th, it = p["theory"], rec["intent"] + bass, drums = [], [] + prev_sec = None + for i, c in enumerate(p["chords"]): + sec = rec["form"][i]["sec"] + start = c["start"] + end = p["chords"][i + 1]["start"] if i + 1 < len(p["chords"]) else p["total16"] + L = end - start + grouping = it["b_grouping"] if sec == "B" else it["grouping"] + acc = sorted(composer.accents_of(grouping)) + if sec != prev_sec and sec != "intro": + drums.append((start, 2, 49, 92)) + prev_sec = sec + if sec == "end": + drums.append((start, 2, 36, 100)) + root = th.midi(c["root_deg"]) + while root > 43: + root -= 12 + bass.append((start, L, root, 96)) + continue + for x in range(0, L, 2): + drums.append((start + x, 1, 42, 64 if x in acc else 52)) + if sec == "intro": + continue + snare = min(acc[1:] or [L // 2], key=lambda a: abs(a - L // 2)) + for a in acc: + if a != snare: + drums.append((start + a, 1, 36, 96 if a == 0 else 84)) + drums.append((start + snare, 1, 38, 92)) + root = th.midi(c["root_deg"]) + while root > 43: + root -= 12 + while root < 28: + root += 12 + for k, a in enumerate(acc): + nxt = acc[k + 1] if k + 1 < len(acc) else L + bass.append((start + a, max(1, nxt - a - 1), root, 92 if a == 0 else 80)) + tracks = [{"name": "Bass", "channel": 0, "program": 33, "pan": 64, "notes": bass}, + {"name": "Drums", "channel": 9, "program": 0, "pan": 64, "notes": drums}] + return p, tracks + + +def main(): + rec = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) + p, tracks = band_tracks(rec) + write_midi(Path(sys.argv[2]), p["tempo"], p["meters"], tracks) + + +if __name__ == "__main__": + main() diff --git a/composer-lab/render/band_render.sh b/composer-lab/render/band_render.sh new file mode 100644 index 00000000..3b22a9b6 --- /dev/null +++ b/composer-lab/render/band_render.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Usage (inside WSL, under `nix shell nixpkgs#fluidsynth nixpkgs#sox`): +# band_render.sh +# Mixes the guitars (same render as render.sh, before reverb) with bass and +# drums, then matches the RMS of so the band version is not +# louder than the clean one. +set -euo pipefail +sfg="$1"; sfb="$2"; gmid="$3"; bmid="$4"; clean="$5"; out="$6" +tmp=$(mktemp -d) +fluidsynth -ni -g 0.5 -r 44100 -F "$tmp/g.wav" "$sfg" "$gmid" >/dev/null 2>&1 +fluidsynth -ni -g 0.5 -r 44100 -F "$tmp/b.wav" "$sfb" "$bmid" >/dev/null 2>&1 +sox -m -v 1.0 "$tmp/g.wav" -v 0.6 "$tmp/b.wav" "$tmp/mix.wav" +sox "$tmp/mix.wav" "$tmp/rev.wav" gain -n -3 reverb 22 50 70 trim 0 "$(sox --i -D "$clean")" fade t 0 -0 0.5 2>/dev/null +rms() { sox "$1" -n stat 2>&1 | awk '/RMS +amplitude/ {print $3; exit}'; } +db=$(awk -v t="$(rms "$clean")" -v c="$(rms "$tmp/rev.wav")" 'BEGIN { printf "%.2f", 20 * log(t / c) / log(10) }') +sox "$tmp/rev.wav" "$out" gain -l "$db" 2>/dev/null +rm -rf "$tmp" diff --git a/composer-lab/render/check_wavs.sh b/composer-lab/render/check_wavs.sh new file mode 100644 index 00000000..5a4196aa --- /dev/null +++ b/composer-lab/render/check_wavs.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Usage (inside WSL with sox): check_wavs.sh ... prints duration and RMS amplitude +for w in "$@"; do + d=$(sox --i -D "$w") + rms=$(sox "$w" -n stat 2>&1 | awk '/RMS +amplitude/ {print $3; exit}') + echo "$(basename "$w") ${d}s rms=${rms}" +done diff --git a/composer-lab/render/render.sh b/composer-lab/render/render.sh new file mode 100644 index 00000000..e679a6c2 --- /dev/null +++ b/composer-lab/render/render.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Usage (inside WSL, under `nix shell nixpkgs#fluidsynth nixpkgs#sox`): +# render.sh +# The MIDI must already be remapped by audition_midi.py. +set -euo pipefail +sf="$1"; in="$2"; out="$3" +tmp=$(mktemp --suffix=.wav) +fluidsynth -ni -g 0.5 -r 44100 -F "$tmp" "$sf" "$in" >/dev/null 2>&1 +sox "$tmp" "$out" gain -n -3 reverb 22 50 70 gain -n -1 2>/dev/null +rm -f "$tmp" diff --git a/composer-lab/render/render_all.sh b/composer-lab/render/render_all.sh new file mode 100644 index 00000000..f4fc340b --- /dev/null +++ b/composer-lab/render/render_all.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Usage (inside WSL): render_all.sh ... -> writes .wav next to each +set -uo pipefail +here=$(dirname "$0"); sf="$1"; shift +for m in "$@"; do bash "$here/render.sh" "$sf" "$m" "${m%.mid}.wav" || echo "render failed: $m"; done diff --git a/composer-lab/render/render_pack.sh b/composer-lab/render/render_pack.sh new file mode 100644 index 00000000..b50049fb --- /dev/null +++ b/composer-lab/render/render_pack.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Usage (inside WSL, under `nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg`): +# render_pack.sh +# For every .mid with a .band.mid beside it in : clean render +# .wav, band render .b.wav (RMS-matched), MP3s of both. +set -uo pipefail +here=$(dirname "$0"); sfg="$1"; sfb="$2"; dir="$3" +cd "$dir" +for m in *.mid; do + case "$m" in *.band.mid) continue ;; esac + b="${m%.mid}" + bash "$here/render.sh" "$sfg" "$m" "$b.wav" || echo "clean render failed: $m" + if [ -f "$b.band.mid" ]; then + bash "$here/band_render.sh" "$sfg" "$sfb" "$m" "$b.band.mid" "$b.wav" "$b.b.wav" || echo "band render failed: $m" + fi +done +bash "$here/to_mp3.sh" *.wav +bash "$here/check_wavs.sh" *.wav diff --git a/composer-lab/render/to_mp3.sh b/composer-lab/render/to_mp3.sh new file mode 100644 index 00000000..d9d1e0e2 --- /dev/null +++ b/composer-lab/render/to_mp3.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Usage (inside WSL with ffmpeg): to_mp3.sh ... -> .mp3 at 192 kbit/s +for w in "$@"; do ffmpeg -loglevel error -y -i "$w" -codec:a libmp3lame -b:a 192k "${w%.wav}.mp3"; done diff --git a/composer-lab/studio/__init__.py b/composer-lab/studio/__init__.py new file mode 100644 index 00000000..d606e10b --- /dev/null +++ b/composer-lab/studio/__init__.py @@ -0,0 +1 @@ +"""Section-level curation studio for composer-lab.""" diff --git a/composer-lab/studio/engine.py b/composer-lab/studio/engine.py new file mode 100644 index 00000000..77b35e24 --- /dev/null +++ b/composer-lab/studio/engine.py @@ -0,0 +1,503 @@ +"""Pure recipe operations and filesystem-backed store for Studio.""" +import argparse +import copy +import datetime +import json +import math +import os +import random +import re +import shutil +import tempfile +import threading +import time +from pathlib import Path + +import composer +try: + from studio.render import default_render +except ImportError: + default_render = None + +SECTION_LABELS = { + "intro": "Вступление", + "A": "Куплет A", + "A2": "Куплет A2", + "B": "Середина B", + "A3": "Кульминация", + "end": "Концовка", +} + +LAYER_LABELS = { + "comp": "Перегенерировать ритм-гитару", + "texture": "Фактура", + "lead_rhythm": "Новый риф", + "b": "Вариант середины", + "intro": "Вступление", + "ending": "Концовка", + "tempo": "Темп", +} + +VALID_B_LEAD = ("augmented", "same_speed", "rest") +VALID_DOSE_FLOATS = ("octave_piece", "octave_sixteenths", "dead_notes") +PIECE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$") + + +def default_options(): + return { + "b_lead": "augmented", + "trailing_rest": True, + "octave_piece": float(composer.V8["octave_piece"]), + "octave_sixteenths": float(composer.V8["octave_sixteenths"]), + "dead_notes": float(composer.V8["dead_notes"]), + "slide_max": int(composer.V8["slide_max"]), + } + + +def _ensure_studio(rec): + out = copy.deepcopy(rec) + st = out.setdefault("studio", {}) + st.setdefault("salts", {}) + st.setdefault("locks", []) + opts = st.setdefault("options", {}) + for k, v in default_options().items(): + if k == "trailing_rest" and k not in opts: + v = composer.studio_base_trailing_rest(out) + opts.setdefault(k, v) + st.setdefault("comp_doses", {}) + return out + + +def new_recipe(seed=None): + if seed is None: + seed = random.SystemRandom().randrange(100000, 9999999) + args = argparse.Namespace(meter=None, mode=None, key=None, tempo=None, v8=True) + rec = composer.make_recipe(int(seed), args) + return _ensure_studio(rec) + + +def available_layers(recipe): + secs = [] + for b in recipe["form"]: + if b["sec"] not in secs: + secs.append(b["sec"]) + items = [] + if "intro" in secs: + items.append({"layer": "intro", "section": "intro"}) + for s in ("A", "A2"): + if s in secs: + items.append({"layer": "comp", "section": s}) + items.append({"layer": "texture", "section": s}) + if "B" in secs: + items.append({"layer": "b", "section": "B"}) + if "end" in secs: + items.append({"layer": "ending", "section": "end"}) + items.append({"layer": "lead_rhythm", "section": "all"}) + items.append({"layer": "tempo", "section": "all"}) + return items + + +def layer_key(layer, section): + return f"{layer}@{section}" + + +def _snapshot_comp_doses(st, sec): + opts = st["options"] + st.setdefault("comp_doses", {})[sec] = { + "octave_piece": float(opts["octave_piece"]), + "octave_sixteenths": float(opts["octave_sixteenths"]), + "dead_notes": float(opts["dead_notes"]), + "slide_max": int(opts["slide_max"]), + } + + +def _backfill_comp_doses(st): + for sec in ("A", "A2"): + if int(st["salts"].get(layer_key("comp", sec), 0)) > 0 and sec not in st["comp_doses"]: + _snapshot_comp_doses(st, sec) + + +def _require_text(value, what): + if not isinstance(value, str): + raise ValueError(f"{what} must be a string") + return value + + +def reroll(recipe, layer, section): + _require_text(layer, "layer") + _require_text(section, "section") + rec = _ensure_studio(recipe) + st = rec["studio"] + locks = set(st["locks"]) + if layer == "all" and section == "all": + _backfill_comp_doses(st) + for item in available_layers(rec): + l, s = item["layer"], item["section"] + key = layer_key(l, s) + if key not in locks: + st["salts"][key] = int(st["salts"].get(key, 0)) + 1 + if l == "comp": + _snapshot_comp_doses(st, s) + return rec + + valid = {(x["layer"], x["section"]) for x in available_layers(rec)} + if (layer, section) not in valid: + raise ValueError(f"invalid layer@section: {layer}@{section}") + key = layer_key(layer, section) + if key in locks: + return rec + st["salts"][key] = int(st["salts"].get(key, 0)) + 1 + if layer == "comp": + _snapshot_comp_doses(st, section) + return rec + + +def set_lock(recipe, layer, section, locked): + _require_text(layer, "layer") + _require_text(section, "section") + if not isinstance(locked, bool): + raise ValueError("locked must be a boolean") + rec = _ensure_studio(recipe) + if (layer, section) not in {(x["layer"], x["section"]) for x in available_layers(rec)}: + raise ValueError(f"invalid layer@section: {layer}@{section}") + key = layer_key(layer, section) + st = rec["studio"] + st["locks"] = [k for k in st["locks"] if k != key] + ([key] if locked else []) + if key == "ending@end": + riffs = st.setdefault("locked_riffs", {}) + if not locked: + riffs.pop(key, None) + elif key not in riffs: + trace = {} + composer.compose(rec, _trace=trace) + riffs[key] = json.loads(json.dumps(trace["riff"].get("A3") or trace["riff"].get("A") or [])) + return rec + + +def _number(value, what): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError(f"{what} must be a finite number") + return value + + +def set_option(recipe, name, value): + _require_text(name, "name") + rec = _ensure_studio(recipe) + st = rec["studio"] + opts = st["options"] + if name == "b_lead": + if value not in VALID_B_LEAD: + raise ValueError(f"invalid b_lead: {value}") + opts["b_lead"] = value + elif name == "trailing_rest": + if not isinstance(value, bool): + raise ValueError("trailing_rest must be a boolean") + opts["trailing_rest"] = value + elif name in VALID_DOSE_FLOATS: + num = _number(value, name) + _backfill_comp_doses(st) + opts[name] = max(0.0, min(1.0, float(num))) + elif name == "slide_max": + num = _number(value, name) + if num != int(num): + raise ValueError("slide_max must be an integer") + _backfill_comp_doses(st) + opts["slide_max"] = max(0, min(12, int(num))) + else: + raise ValueError(f"unknown option: {name}") + return rec + + +def piece_sections(piece): + sec_per_tick = 15.0 / piece["tempo"] + ch = piece["chords"] + spans = [] + for i, c in enumerate(ch): + s0 = c["start"] + s1 = ch[i + 1]["start"] if i + 1 < len(ch) else piece["total16"] + if spans and spans[-1]["section"] == c["sec"]: + spans[-1]["end16"] = s1 + else: + spans.append({"section": c["sec"], "start16": s0, "end16": s1}) + for sp in spans: + sp["start_sec"] = round(sp["start16"] * sec_per_tick, 2) + sp["end_sec"] = round(sp["end16"] * sec_per_tick, 2) + sp["label"] = SECTION_LABELS.get(sp["section"], sp["section"]) + return spans + + +def piece_detail(piece_id, recipe, piece, can_undo=False): + rec = _ensure_studio(recipe) + st = rec["studio"] + salts = st["salts"] + locks = set(st["locks"]) + avail = available_layers(rec) + + def layer_info(layer, section): + k = layer_key(layer, section) + return { + "layer": layer, + "section": section, + "label": LAYER_LABELS.get(layer, layer), + "salt": int(salts.get(k, 0)), + "locked": k in locks, + } + + sections = piece_sections(piece) + for sp in sections: + sec = sp["section"] + sp["layers"] = [ + layer_info(item["layer"], sec) + for item in avail + if item["section"] == sec + ] + + whole_layers = [ + layer_info(item["layer"], "all") + for item in avail + if item["section"] == "all" + ] + return { + "id": piece_id, + "seed": rec["seed"], + "meter": rec["intent"]["meter"], + "mode": rec["intent"]["mode"], + "key": rec["intent"]["tonic"], + "tempo": piece["tempo"], + "length": round(piece["total16"] * 15.0 / piece["tempo"], 2), + "sections": sections, + "whole_layers": whole_layers, + "options": dict(st["options"]), + "can_undo": can_undo, + } + + +def _now_iso(): + return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") + + +def _replace(src, dst): + for attempt in range(60): + try: + os.replace(src, dst) + return + except PermissionError: + if attempt == 59: + raise + time.sleep(0.02) + + +class StudioStore: + """Filesystem-backed persistence for Studio pieces. + + Writes to one piece are serialized and staged: a revision is published only + after it has rendered. Reads never wait for a render.""" + + def __init__(self, out_dir, render_fn=None): + if render_fn is None: + if default_render is None: + from studio.render import default_render as _default_render + render_fn = _default_render + else: + render_fn = default_render + self.out_dir = Path(out_dir) + self.out_dir.mkdir(parents=True, exist_ok=True) + self._root = self.out_dir.resolve() + self.render_fn = render_fn + self._guard = threading.Lock() + self._history_lock = threading.Lock() + self._piece_locks = {} + + def _write_lock(self, piece_id): + with self._guard: + return self._piece_locks.setdefault(piece_id, threading.Lock()) + + def _piece_dir(self, piece_id): + if not isinstance(piece_id, str) or not PIECE_ID_RE.match(piece_id): + raise KeyError(f"invalid piece id: {piece_id}") + try: + real = (self.out_dir / piece_id).resolve() + except OSError: + raise KeyError(f"unknown piece id: {piece_id}") + if real.parent != self._root or not real.is_dir(): + raise KeyError(f"unknown piece id: {piece_id}") + return real + + def _inside(self, pdir, name): + path = pdir / name + if path.resolve().parent != pdir: + raise KeyError(f"path escapes the piece directory: {name}") + return path + + def _allocate(self, seed): + base = f"piece_{seed}" + with self._guard: + n = 1 + while True: + pid = base if n == 1 else f"{base}_{n}" + try: + (self.out_dir / pid).mkdir() + return pid + except FileExistsError: + n += 1 + + def _read_recipe(self, pdir): + return json.loads(self._inside(pdir, "recipe.json").read_text(encoding="utf-8")) + + def _read_undo(self, pdir): + upath = self._inside(pdir, "undo.json") + if not upath.exists(): + return [] + return json.loads(upath.read_text(encoding="utf-8")) + + def _write_undo(self, pdir, stack): + tmp = self._inside(pdir, "undo.json.tmp") + tmp.write_text(json.dumps(stack), encoding="utf-8") + _replace(tmp, pdir / "undo.json") + + def _log_history(self, pdir, action, layer=None, section=None, salt=None, value=None): + row = { + "t": _now_iso(), + "action": action, + "layer": layer, + "section": section, + "salt": salt, + "value": value, + } + path = self._inside(pdir, "history.jsonl") + with self._history_lock, path.open("a", encoding="utf-8") as f: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + + def _build(self, pdir, recipe): + stage = Path(tempfile.mkdtemp(prefix=".stage-", dir=pdir)) + try: + piece = composer.compose(recipe) + composer.export(piece, stage / "piece") + (stage / "recipe.json").write_text(json.dumps(recipe, indent=1), encoding="utf-8") + cur_mid, cur_mp3 = pdir / "piece.mid", pdir / "piece.mp3" + reuse = ( + cur_mid.is_file() and cur_mp3.is_file() + and self._inside(pdir, "piece.mid").read_bytes() == (stage / "piece.mid").read_bytes() + ) + if not reuse: + self.render_fn(stage / "piece.mid", stage / "piece.mp3") + if not (stage / "piece.mp3").is_file(): + raise RuntimeError("renderer produced no audio") + return piece, stage, reuse + except BaseException: + shutil.rmtree(stage, ignore_errors=True) + raise + + def _publish(self, pdir, stage, reuse, stack): + names = ["piece.musicxml", "piece.tab.txt", "piece.mid"] + if not reuse: + names.insert(0, "piece.mp3") + try: + for name in names: + _replace(stage / name, pdir / name) + self._write_undo(pdir, stack) + _replace(stage / "recipe.json", pdir / "recipe.json") + finally: + shutil.rmtree(stage, ignore_errors=True) + + def create_piece(self, seed=None): + rec = new_recipe(seed) + pid = self._allocate(rec["seed"]) + pdir = self.out_dir / pid + try: + pdir = self._piece_dir(pid) + with self._write_lock(pid): + piece, stage, reuse = self._build(pdir, rec) + self._publish(pdir, stage, reuse, []) + self._log_history(pdir, "new", value=rec["seed"]) + return piece_detail(pid, rec, piece, can_undo=False) + except BaseException: + shutil.rmtree(pdir, ignore_errors=True) + raise + + def list_pieces(self): + entries = [] + for pdir in self.out_dir.iterdir(): + try: + if pdir.is_dir() and PIECE_ID_RE.match(pdir.name) and (pdir / "recipe.json").exists(): + entries.append((pdir.stat().st_mtime, pdir.name)) + except OSError: + continue + out = [] + for _, name in sorted(entries, reverse=True): + try: + det = self.get_piece(name) + except (KeyError, OSError, ValueError): + continue + out.append({ + "id": det["id"], + "seed": det["seed"], + "meter": det["meter"], + "mode": det["mode"], + "key": det["key"], + "tempo": det["tempo"], + "length": det["length"], + "sections": [s["section"] for s in det["sections"]], + }) + return out + + 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, can_undo=bool(self._read_undo(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) + new_rec = change(old_rec) + 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, can_undo=True) + + def reroll(self, piece_id, layer, section): + def log(pdir, rec): + whole = layer == "all" and section == "all" + salt = dict(rec["studio"]["salts"]) if whole else rec["studio"]["salts"].get(layer_key(layer, section), 0) + self._log_history(pdir, "reroll", layer=layer, section=section, salt=salt) + + return self._change(piece_id, lambda rec: reroll(rec, layer, section), log) + + def set_lock(self, piece_id, layer, section, locked): + return self._change( + piece_id, + lambda rec: set_lock(rec, layer, section, locked), + lambda pdir, rec: self._log_history(pdir, "lock", layer=layer, section=section, value=locked), + ) + + def set_option(self, piece_id, name, value): + return self._change( + piece_id, + lambda rec: set_option(rec, name, value), + lambda pdir, rec: self._log_history(pdir, "option", value={name: rec["studio"]["options"][name]}), + ) + + def undo(self, piece_id): + pdir = self._piece_dir(piece_id) + with self._write_lock(piece_id): + stack = self._read_undo(pdir) + if not stack: + rec = self._read_recipe(pdir) + return piece_detail(piece_id, rec, composer.compose(rec), can_undo=False) + prev_rec = stack.pop() + piece, stage, reuse = self._build(pdir, prev_rec) + self._publish(pdir, stage, reuse, stack) + self._log_history(pdir, "undo") + return piece_detail(piece_id, prev_rec, piece, can_undo=bool(stack)) + + def file_path(self, piece_id, filename, log_export=False): + pdir = self._piece_dir(piece_id) + path = self._inside(pdir, filename) + if not path.is_file(): + raise FileNotFoundError(filename) + if log_export: + self._log_history(pdir, "export", value=filename) + return path diff --git a/composer-lab/studio/index.html b/composer-lab/studio/index.html new file mode 100644 index 00000000..3c2ea473 --- /dev/null +++ b/composer-lab/studio/index.html @@ -0,0 +1,506 @@ + + + + + +Griff Studio + + + +
+ +
+
Нажмите «Новая пьеса» или выберите готовую из списка.
+
+
+ + + diff --git a/composer-lab/studio/render.py b/composer-lab/studio/render.py new file mode 100644 index 00000000..72c2426f --- /dev/null +++ b/composer-lab/studio/render.py @@ -0,0 +1,99 @@ +"""Audio rendering backends for Studio.""" +import os +import shlex +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from render import audition_midi + +ROOT = Path(__file__).resolve().parents[1] +SOUNDFONT = os.environ.get( + "GRIFF_SOUNDFONT", + str(ROOT.parents[1] / "_griff_out" / "sf" / "fsbs_clean.sf2"), +) + + +WSL_DISTRO = "NixOS" + + +def win_to_wsl_path(path): + s = str(path) + if s.startswith("\\\\?\\") and len(s) > 6 and s[5] == ":": + s = s[4:] + unc = s.replace("/", "\\") + for prefix in ("\\\\wsl.localhost\\", "\\\\wsl$\\"): + if unc.lower().startswith(prefix): + distro, _, rest = unc[len(prefix):].partition("\\") + if distro.lower() != WSL_DISTRO.lower(): + raise ValueError(f"path is in WSL distribution {distro}, renderer runs in {WSL_DISTRO}") + return "/" + rest.replace("\\", "/") + if len(s) >= 2 and s[1] == ":": + drive = s[0].lower() + rest = s[2:].replace("\\", "/") + if not rest.startswith("/"): + rest = "/" + rest + return f"/mnt/{drive}{rest}" + return s.replace("\\", "/") + + +def fake_render(mid_path, mp3_path): + """Write a small deterministic MP3 placeholder for tests.""" + mp3_path = Path(mp3_path) + mp3_path.parent.mkdir(parents=True, exist_ok=True) + tmp = mp3_path.with_suffix(".mp3.tmp") + tmp.write_bytes(b"ID3\x03\x00\x00\x00\x00\x00\x00FAKE_MP3") + tmp.replace(mp3_path) + + +def default_render(mid_path, mp3_path, soundfont=None): + """Remap MIDI to program 0 and render WAV -> MP3 via fluidsynth + sox + ffmpeg.""" + sf = soundfont or SOUNDFONT + mid_path = Path(mid_path).resolve() + mp3_path = Path(mp3_path).resolve() + mp3_path.parent.mkdir(parents=True, exist_ok=True) + render_sh = (ROOT / "render" / "render.sh").resolve() + to_mp3_sh = (ROOT / "render" / "to_mp3.sh").resolve() + + with tempfile.TemporaryDirectory(dir=str(mp3_path.parent)) as tmpdir: + tmp = Path(tmpdir) + aud_mid = tmp / "audition.mid" + wav_path = tmp / "out.wav" + rendered_mp3 = tmp / "out.mp3" + audition_midi.remap(str(mid_path), str(aud_mid)) + + if sys.platform == "win32": + inner = " && ".join([ + f"bash {shlex.quote(win_to_wsl_path(render_sh))} " + f"{shlex.quote(win_to_wsl_path(sf))} " + f"{shlex.quote(win_to_wsl_path(aud_mid))} " + f"{shlex.quote(win_to_wsl_path(wav_path))}", + f"bash {shlex.quote(win_to_wsl_path(to_mp3_sh))} " + f"{shlex.quote(win_to_wsl_path(wav_path))}", + ]) + cmd = [ + "wsl", "-d", "NixOS", "--", + "nix", "shell", "nixpkgs#fluidsynth", "nixpkgs#sox", "nixpkgs#ffmpeg", + "-c", "bash", "-c", inner, + ] + else: + inner = " && ".join([ + f"bash {shlex.quote(str(render_sh))} " + f"{shlex.quote(str(sf))} {shlex.quote(str(aud_mid))} {shlex.quote(str(wav_path))}", + f"bash {shlex.quote(str(to_mp3_sh))} {shlex.quote(str(wav_path))}", + ]) + has_tools = all(shutil.which(x) for x in ("fluidsynth", "sox", "ffmpeg")) + if has_tools: + cmd = ["bash", "-c", inner] + else: + cmd = [ + "nix", "shell", "nixpkgs#fluidsynth", "nixpkgs#sox", "nixpkgs#ffmpeg", + "-c", "bash", "-c", inner, + ] + + subprocess.run(cmd, check=True, timeout=120) + final_tmp = mp3_path.with_suffix(".mp3.tmp") + final_tmp.write_bytes(rendered_mp3.read_bytes()) + final_tmp.replace(mp3_path) diff --git a/composer-lab/studio/server.py b/composer-lab/studio/server.py new file mode 100644 index 00000000..7786316c --- /dev/null +++ b/composer-lab/studio/server.py @@ -0,0 +1,237 @@ +"""Local HTTP server for Studio.""" +import argparse +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +from urllib.parse import urlparse + +from studio.engine import StudioStore +from studio.render import default_render, fake_render + +INDEX_HTML = Path(__file__).with_name("index.html") +MAX_BODY = 64 * 1024 +MAX_DRAIN = 8 * 1024 * 1024 +MAX_SEED = 10**15 + + +class BodyTooLarge(Exception): + pass + + +def _text_field(body, name): + value = body.get(name) + if not isinstance(value, str) or not value: + raise ValueError(f"{name} must be a non-empty string") + return value + + +def _make_handler(store): + class StudioHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): + return + + def _send_json(self, code, obj): + body = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def _send_file(self, path, content_type, download_name=None, support_range=False): + data = path.read_bytes() + total = len(data) + rng = self.headers.get("Range") if support_range else None + span = None + if rng and rng.startswith("bytes="): + a_s, _, b_s = rng[6:].split(",", 1)[0].strip().partition("-") + try: + span = (int(a_s) if a_s else 0, int(b_s) if b_s else total - 1) + except ValueError: + span = None + if span is not None: + start, end = span + if start >= total or start < 0 or end < start: + self.send_response(HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE) + self.send_header("Content-Range", f"bytes */{total}") + self.send_header("Content-Length", "0") + self.end_headers() + return + end = min(end, total - 1) + chunk = data[start:end + 1] + self.send_response(HTTPStatus.PARTIAL_CONTENT) + self.send_header("Content-Type", content_type) + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Range", f"bytes {start}-{end}/{total}") + self.send_header("Content-Length", str(len(chunk))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(chunk) + return + + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", content_type) + if support_range: + self.send_header("Accept-Ranges", "bytes") + if download_name: + self.send_header("Content-Disposition", f'attachment; filename="{download_name}"') + self.send_header("Content-Length", str(total)) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + + def _read_json(self): + try: + ln = int(self.headers.get("Content-Length", "0") or "0") + except ValueError: + self.close_connection = True + raise ValueError("invalid Content-Length") + if ln < 0: + self.close_connection = True + raise ValueError("invalid Content-Length") + if ln > MAX_BODY: + if ln > MAX_DRAIN: + self.close_connection = True + else: + left = ln + while left > 0: + chunk = self.rfile.read(min(left, 65536)) + if not chunk: + self.close_connection = True + break + left -= len(chunk) + raise BodyTooLarge() + if ln == 0: + return {} + raw = self.rfile.read(ln) + try: + body = json.loads(raw.decode("utf-8")) + except UnicodeDecodeError as exc: + raise ValueError(f"invalid body: {exc}") + if not isinstance(body, dict): + raise ValueError("body must be a JSON object") + return body + + def do_GET(self): + path = urlparse(self.path).path + try: + if path == "/": + self._send_file(INDEX_HTML, "text/html; charset=utf-8") + return + if path == "/api/pieces": + self._send_json(HTTPStatus.OK, {"pieces": store.list_pieces()}) + return + parts = [p for p in path.split("/") if p] + if len(parts) == 3 and parts[:2] == ["api", "piece"]: + self._send_json(HTTPStatus.OK, store.get_piece(parts[2])) + return + if len(parts) == 4 and parts[:2] == ["api", "piece"]: + pid, res = parts[2], parts[3] + if res == "audio.mp3": + p = store.file_path(pid, "piece.mp3", log_export=False) + self._send_file(p, "audio/mpeg", support_range=True) + return + if res == "piece.mid": + p = store.file_path(pid, "piece.mid", log_export=True) + self._send_file(p, "audio/midi", download_name=f"{pid}.mid") + return + if res == "piece.musicxml": + p = store.file_path(pid, "piece.musicxml", log_export=True) + self._send_file( + p, "application/vnd.recordare.musicxml+xml; charset=utf-8", + download_name=f"{pid}.musicxml", + ) + return + if res == "piece.tab.txt": + p = store.file_path(pid, "piece.tab.txt", log_export=True) + self._send_file(p, "text/plain; charset=utf-8", download_name=f"{pid}.tab.txt") + return + self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"}) + except (KeyError, FileNotFoundError) as exc: + self._send_json(HTTPStatus.NOT_FOUND, {"error": str(exc)}) + except Exception as exc: + self._send_json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": str(exc)}) + + def do_POST(self): + path = urlparse(self.path).path + try: + body = self._read_json() + if path == "/api/new": + seed = body.get("seed") + if seed is not None and ( + isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < MAX_SEED + ): + raise ValueError("seed must be a non-negative integer or null") + self._send_json(HTTPStatus.OK, store.create_piece(seed)) + return + parts = [p for p in path.split("/") if p] + if len(parts) == 4 and parts[:2] == ["api", "piece"]: + pid, action = parts[2], parts[3] + if action == "reroll": + layer, section = _text_field(body, "layer"), _text_field(body, "section") + self._send_json(HTTPStatus.OK, store.reroll(pid, layer, section)) + return + if action == "lock": + layer, section = _text_field(body, "layer"), _text_field(body, "section") + if "locked" not in body: + raise ValueError("locked is required") + self._send_json(HTTPStatus.OK, store.set_lock(pid, layer, section, body["locked"])) + return + if action == "option": + name = _text_field(body, "name") + if "value" not in body: + raise ValueError("value is required") + self._send_json(HTTPStatus.OK, store.set_option(pid, name, body["value"])) + return + if action == "undo": + self._send_json(HTTPStatus.OK, store.undo(pid)) + return + self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"}) + except BodyTooLarge: + self._send_json(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, {"error": "request body too large"}) + except KeyError as exc: + self._send_json(HTTPStatus.NOT_FOUND, {"error": str(exc)}) + except (ValueError, TypeError, json.JSONDecodeError) as exc: + self._send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + except Exception as exc: + self._send_json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": str(exc)}) + + return StudioHandler + + +def create_server(out_dir, host="127.0.0.1", port=8765, render_fn=None): + store = StudioStore(out_dir, render_fn=render_fn or default_render) + return ThreadingHTTPServer((host, port), _make_handler(store)) + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Studio curation web server for composer-lab") + ap.add_argument("--port", type=int, default=8765) + ap.add_argument("--out", default="out_studio") + ap.add_argument("--soundfont", default=None) + ap.add_argument("--fake-render", action="store_true") + args = ap.parse_args(argv) + + if args.fake_render: + rfn = fake_render + elif args.soundfont: + rfn = lambda mid, mp3: default_render(mid, mp3, soundfont=args.soundfont) + else: + rfn = default_render + + srv = create_server(args.out, host="127.0.0.1", port=args.port, render_fn=rfn) + print(f"Studio listening on http://127.0.0.1:{srv.server_address[1]} (out={args.out})", flush=True) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + srv.server_close() + + +if __name__ == "__main__": + main() diff --git a/composer-lab/studio/summary.py b/composer-lab/studio/summary.py new file mode 100644 index 00000000..8366195c --- /dev/null +++ b/composer-lab/studio/summary.py @@ -0,0 +1,110 @@ +"""Usage log summary across all curated pieces in a Studio output directory.""" +import argparse +from collections import Counter +import json +from pathlib import Path + + +def _collect_log_files(target: Path): + if target.is_file(): + return [(target, target.stem)] + files = [] + root_hist = target / "history.jsonl" + if root_hist.is_file(): + files.append((root_hist, target.name)) + for pdir in sorted(target.iterdir()): + hpath = pdir / "history.jsonl" + if pdir.is_dir() and hpath.is_file(): + files.append((hpath, pdir.name)) + return files + + +def summarize(out_dir): + out_dir = Path(out_dir) + rerolls_per_layer = Counter() + rerolls_per_target = Counter() + options_used = Counter() + rerolls_before_first_export = [] + pieces_total = 0 + pieces_exported = 0 + + if not out_dir.exists(): + return { + "pieces_total": 0, + "pieces_exported": 0, + "rerolls_per_layer": {}, + "rerolls_per_target": {}, + "rerolls_before_first_export": [], + "options_used": {}, + } + + groups = {} + for hpath, fallback_key in _collect_log_files(out_dir): + for line in hpath.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + ev = json.loads(line) + raw_pid = ev.get("piece_id") + pid = raw_pid if isinstance(raw_pid, str) and raw_pid else fallback_key + groups.setdefault(pid, []).append(ev) + + for pid in sorted(groups): + pieces_total += 1 + rerolls_so_far = 0 + exported = False + for ev in groups[pid]: + act = ev.get("action") + if act == "reroll": + rerolls_so_far += 1 + layer = ev.get("layer") or "?" + sec = ev.get("section") or "?" + rerolls_per_layer[layer] += 1 + rerolls_per_target[f"{layer}@{sec}"] += 1 + elif act == "option": + val = ev.get("value") + if isinstance(val, dict): + for k, v in val.items(): + options_used[f"{k}={v}"] += 1 + options_used[k] += 1 + elif act == "export" and not exported: + exported = True + pieces_exported += 1 + rerolls_before_first_export.append(rerolls_so_far) + + return { + "pieces_total": pieces_total, + "pieces_exported": pieces_exported, + "rerolls_per_layer": dict(rerolls_per_layer), + "rerolls_per_target": dict(rerolls_per_target), + "rerolls_before_first_export": rerolls_before_first_export, + "options_used": dict(options_used), + } + + +def format_summary(stats): + lines = [ + f"Pieces: {stats['pieces_total']} total, {stats['pieces_exported']} exported", + f"Re-rolls before first export per piece: {stats['rerolls_before_first_export']}", + "Re-rolls per layer:", + ] + for k, v in sorted(stats["rerolls_per_layer"].items(), key=lambda kv: (-kv[1], kv[0])): + lines.append(f" {k}: {v}") + lines.append("Re-rolls per target:") + for k, v in sorted(stats["rerolls_per_target"].items(), key=lambda kv: (-kv[1], kv[0])): + lines.append(f" {k}: {v}") + lines.append("Options used:") + for k, v in sorted(stats["options_used"].items(), key=lambda kv: (-kv[1], kv[0])): + if "=" in k: + lines.append(f" {k}: {v}") + return "\n".join(lines) + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Summarize Studio usage logs") + ap.add_argument("dir", help="Studio output directory or history.jsonl file") + args = ap.parse_args(argv) + print(format_summary(summarize(args.dir))) + + +if __name__ == "__main__": + main() diff --git a/composer-lab/studio/web_api.py b/composer-lab/studio/web_api.py new file mode 100644 index 00000000..c3b2a5e5 --- /dev/null +++ b/composer-lab/studio/web_api.py @@ -0,0 +1,223 @@ +"""Pure in-memory JSON-in/JSON-out Studio API for browser/Pyodide execution.""" +import base64 +import copy +import json +import math + +import composer +import midiio +import musicxml +from studio import engine + +UNDO_LIMIT = 50 +MAX_SEED = 10**15 +VALID_SECTIONS = frozenset(engine.SECTION_LABELS) + + +def _is_int(value): + return isinstance(value, int) and not isinstance(value, bool) + + +def _validate_recipe(rec): + if not isinstance(rec, dict): + raise ValueError("recipe must be an object") + seed = rec.get("seed") + if not _is_int(seed) or not 0 <= seed < MAX_SEED: + raise ValueError("recipe.seed must be a non-negative integer") + form = rec.get("form") + if not isinstance(form, list) or not form: + raise ValueError("recipe.form must be a non-empty list") + for bar in form: + if not isinstance(bar, dict) or not isinstance(bar.get("sec"), str) or bar["sec"] not in VALID_SECTIONS: + raise ValueError("recipe.form contains an invalid section name") + intent = rec.get("intent") + if not isinstance(intent, dict): + raise ValueError("recipe.intent must be an object") + if intent.get("meter") not in composer.METERS: + raise ValueError("recipe.intent.meter is invalid") + if intent.get("b_meter", intent.get("meter")) not in composer.METERS: + raise ValueError("recipe.intent.b_meter is invalid") + if intent.get("mode") not in composer.SCALES: + raise ValueError("recipe.intent.mode is invalid") + if intent.get("tonic") not in composer.TONICS: + raise ValueError("recipe.intent.tonic is invalid") + tempo = intent.get("tempo") + if isinstance(tempo, bool) or not isinstance(tempo, (int, float)) or not math.isfinite(tempo) or tempo <= 0: + raise ValueError("recipe.intent.tempo must be a positive finite number") + st = rec.get("studio") + if st is not None: + if not isinstance(st, dict): + raise ValueError("recipe.studio must be an object") + if "salts" in st: + salts = st["salts"] + if not isinstance(salts, dict) or any(not isinstance(k, str) or not _is_int(v) for k, v in salts.items()): + raise ValueError("recipe.studio.salts is invalid") + if "locks" in st: + locks = st["locks"] + if not isinstance(locks, list) or any(not isinstance(k, str) for k in locks): + raise ValueError("recipe.studio.locks is invalid") + if "options" in st: + opts = st["options"] + if not isinstance(opts, dict): + raise ValueError("recipe.studio.options must be an object") + if "b_lead" in opts and opts["b_lead"] not in engine.VALID_B_LEAD: + raise ValueError("invalid studio.options.b_lead") + if "trailing_rest" in opts and not isinstance(opts["trailing_rest"], bool): + raise ValueError("invalid studio.options.trailing_rest") + for k in engine.VALID_DOSE_FLOATS: + if k in opts: + v = opts[k] + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0.0 <= float(v) <= 1.0: + raise ValueError(f"invalid studio.options.{k}") + if "slide_max" in opts: + sm = opts["slide_max"] + if not _is_int(sm) or not 0 <= sm <= 12: + raise ValueError("invalid studio.options.slide_max") + return copy.deepcopy(rec) + + +def _validate_state(state): + if not isinstance(state, dict) or not isinstance(state.get("recipe"), dict): + raise ValueError("state must be an object with a recipe") + rec = _validate_recipe(state["recipe"]) + raw_id = state.get("id") + pid = f"piece_{rec['seed']}" if raw_id is None or raw_id == "" else raw_id + if not isinstance(pid, str) or not engine.PIECE_ID_RE.match(pid): + raise ValueError("state.id must match piece id rules") + undo_raw = state.get("undo", []) + if not isinstance(undo_raw, list): + raise ValueError("state.undo must be a list") + undo_stack = [_validate_recipe(entry) for entry in undo_raw][-UNDO_LIMIT:] + return pid, rec, undo_stack + + +def _apply_change(state, fn): + pid, old_rec, undo_stack = _validate_state(state) + new_rec = fn(old_rec) + next_undo = (undo_stack + [old_rec])[-UNDO_LIMIT:] + return {"id": pid, "recipe": new_rec, "undo": next_undo} + + +def new_piece(seed=None): + if seed is not None and ( + isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < MAX_SEED + ): + raise ValueError("seed must be a non-negative integer or null") + rec = engine.new_recipe(seed) + return {"id": f"piece_{rec['seed']}", "recipe": rec, "undo": []} + + +def reroll(state, layer, section): + return _apply_change(state, lambda rec: engine.reroll(rec, layer, section)) + + +def lock(state, layer, section, locked): + return _apply_change(state, lambda rec: engine.set_lock(rec, layer, section, locked)) + + +def option(state, name, value): + return _apply_change(state, lambda rec: engine.set_option(rec, name, value)) + + +def undo(state): + pid, rec, undo_stack = _validate_state(state) + if not undo_stack: + return {"id": pid, "recipe": rec, "undo": []} + prev_rec = undo_stack.pop() + return {"id": pid, "recipe": prev_rec, "undo": undo_stack} + + +def _events_from_piece(piece): + sec_per_tick = 15.0 / piece["tempo"] + out = [] + for g_num, g in ((1, "g1"), (2, "g2")): + for n in piece["parts"][g]: + out.append({ + "t": float(n["start"] * sec_per_tick), + "dur": float(n["dur"] * sec_per_tick), + "pitch": int(n["pitch"]), + "vel": int(max(30, min(127, n["vel"]))), + "guitar": g_num, + "dead": "dead" in n.get("tech", []), + }) + out.sort(key=lambda e: (e["t"], e["guitar"], e["pitch"])) + return out + + +def detail(state): + pid, rec, undo_stack = _validate_state(state) + piece = composer.compose(rec) + return engine.piece_detail(pid, rec, piece, can_undo=bool(undo_stack)) + + +def events(state): + _, rec, _ = _validate_state(state) + piece = composer.compose(rec) + return _events_from_piece(piece) + + +def snapshot(state): + pid, rec, undo_stack = _validate_state(state) + piece = composer.compose(rec) + return { + "state": {"id": pid, "recipe": rec, "undo": undo_stack}, + "detail": engine.piece_detail(pid, rec, piece, can_undo=bool(undo_stack)), + "events": _events_from_piece(piece), + } + + +def export_midi(state): + _, rec, _ = _validate_state(state) + piece = composer.compose(rec) + raw = midiio.midi_bytes(piece["tempo"], piece["meters"], composer.midi_tracks(piece)) + return base64.b64encode(raw).decode("ascii") + + +def export_musicxml(state): + pid, rec, _ = _validate_state(state) + piece = composer.compose(rec) + return musicxml.musicxml_text(piece, pid) + + +def export_tab(state): + _, rec, _ = _validate_state(state) + piece = composer.compose(rec) + return composer.tab_text(piece) + + +def handle_json(req_json): + req = json.loads(req_json) + cmd = req.get("cmd") + payload = req.get("payload") or {} + if cmd == "new_piece": + return json.dumps(snapshot(new_piece(payload.get("seed"))), ensure_ascii=False) + if cmd == "reroll": + return json.dumps( + snapshot(reroll(payload["state"], payload["layer"], payload["section"])), + ensure_ascii=False, + ) + if cmd == "lock": + return json.dumps( + snapshot(lock(payload["state"], payload["layer"], payload["section"], payload["locked"])), + ensure_ascii=False, + ) + if cmd == "option": + return json.dumps( + snapshot(option(payload["state"], payload["name"], payload["value"])), + ensure_ascii=False, + ) + if cmd == "undo": + return json.dumps(snapshot(undo(payload["state"])), ensure_ascii=False) + if cmd == "snapshot": + return json.dumps(snapshot(payload["state"]), ensure_ascii=False) + if cmd == "detail": + return json.dumps(detail(payload["state"]), ensure_ascii=False) + if cmd == "events": + return json.dumps(events(payload["state"]), ensure_ascii=False) + if cmd == "export_midi": + return json.dumps(export_midi(payload["state"]), ensure_ascii=False) + if cmd == "export_musicxml": + return json.dumps(export_musicxml(payload["state"]), ensure_ascii=False) + if cmd == "export_tab": + return json.dumps(export_tab(payload["state"]), ensure_ascii=False) + raise ValueError(f"unknown command: {cmd}") diff --git a/composer-lab/test_composer.py b/composer-lab/test_composer.py new file mode 100644 index 00000000..1b17c53b --- /dev/null +++ b/composer-lab/test_composer.py @@ -0,0 +1,695 @@ +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +import composer +import fretboard + + +def build(seed, **kw): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **kw) + return composer.compose(composer.make_recipe(seed, args)) + + +class ComposerInvariants(unittest.TestCase): + seeds = range(1, 41) + + def test_same_seed_same_midi_bytes(self): + with tempfile.TemporaryDirectory() as d: + digests = [] + for i in range(2): + composer.export(build(7), Path(d) / f"x{i}") + digests.append(hashlib.sha256((Path(d) / f"x{i}.mid").read_bytes()).hexdigest()) + self.assertEqual(digests[0], digests[1], "fixed seed must reproduce the MIDI bytes") + + def test_every_note_is_on_its_string_and_fret(self): + for seed in self.seeds: + for g, notes in build(seed)["parts"].items(): + for n in notes: + self.assertTrue(0 <= n["fret"] <= fretboard.MAX_FRET, (seed, g, n)) + self.assertEqual(fretboard.OPEN[n["string"]] + n["fret"], n["pitch"], (seed, g, n)) + + def test_legato_only_between_notes_on_the_same_string(self): + for seed in self.seeds: + for g, notes in build(seed)["parts"].items(): + line = [n for n in notes if not n.get("chordtone") and not n.get("dyad") + and not (n.get("fixed") and "preset_tech" not in n)] + for prev, n in zip(line, line[1:]): + if {"hammer", "pull", "slide"} & set(n["tech"]): + self.assertEqual(prev["string"], n["string"], (seed, g, n)) + if "hammer" in n["tech"]: + self.assertGreater(n["fret"], prev["fret"], (seed, g, n)) + + def test_octave_shape_slides_from_the_same_string(self): + for seed in self.seeds: + for g, notes in build(seed)["parts"].items(): + last = {} + for n in sorted((x for x in notes if x.get("dyad")), key=lambda x: x["start"]): + if "slide" in n["tech"]: + p = last.get(n["string"]) + self.assertTrue(p is not None and p["fret"] != n["fret"], (seed, g, n)) + last[n["string"]] = n + + def test_tapped_notes_are_above_the_fretting_hand(self): + for seed in self.seeds: + for g, notes in build(seed)["parts"].items(): + for prev, n in zip(notes, notes[1:]): + if "tap" in n.get("tech", []) and n.get("fixed"): + nxt = [m for m in notes if n["start"] < m["start"] <= n["start"] + 2 + and m["string"] == n["string"] and "pull" in m.get("tech", [])][:1] + for m in nxt: + self.assertGreater(n["fret"], m["fret"], (seed, g, n)) + + def test_no_semitone_clash_on_shared_accented_onsets(self): + bad = shared = 0 + for seed in self.seeds: + p = build(seed) + g2 = {} + for n in p["parts"]["g2"]: + g2.setdefault(n["start"], []).append(n["pitch"]) + for n in p["parts"]["g1"]: + for q in g2.get(n["start"], []): + shared += 1 + bad += abs(n["pitch"] - q) % 12 in (1, 11) + self.assertLess(bad / shared, 0.03, f"semitone clashes {bad}/{shared} between guitars must stay rare") + + +class Harmony(unittest.TestCase): + def test_no_minor_ninth_against_the_chord_root_in_chords_and_arpeggios(self): + for seed in range(1, 41): + p = build(seed) + th = p["theory"] + starts = [c["start"] for c in p["chords"]] + [p["total16"]] + for i, c in enumerate(p["chords"]): + root_pc = th.midi(c["root_deg"]) % 12 + for g in ("g1", "g2"): + for n in p["parts"][g]: + if starts[i] <= n["start"] < starts[i + 1] and (n.get("fixed") or n.get("ring")): + self.assertNotEqual((n["pitch"] - root_pc) % 12, 1, (seed, g, n)) + + +class RhythmSkeleton(unittest.TestCase): + def recipe(self, seed, skeleton): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, skeleton=skeleton) + return composer.make_recipe(seed, args) + + def test_v1_without_flag_reproduces_the_frozen_test_set(self): + frozen = Path(__file__).resolve().parents[2] / "_griff_out" / "test_2e421df" / "new" + if not frozen.exists(): + self.skipTest("frozen test set not on this machine") + for seed in (101, 105, 112): + rec = json.loads((frozen / f"new_{seed:03d}.recipe.json").read_text(encoding="utf-8")) + with tempfile.TemporaryDirectory() as d: + composer.export(composer.compose(rec), Path(d) / "x") + self.assertEqual((Path(d) / "x.mid").read_bytes(), (frozen / f"new_{seed:03d}.mid").read_bytes(), + f"v1 output for seed {seed} must stay byte-identical") + + def test_v2_recipe_differs_from_v1_only_by_the_skeleton(self): + for seed in range(201, 213): + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + sk = b["motifs"].pop("skeleton") + self.assertTrue(sk["A"] and sk["B"], seed) + a.pop("generator"), b.pop("generator") + self.assertEqual(a, b, f"seed {seed}: only the skeleton may differ") + + def test_both_guitars_attack_every_skeleton_hit_in_a_sections(self): + missing = total = 0 + for seed in range(201, 213): + rec = self.recipe(seed * 1000, True) + p = composer.compose(rec) + hits = rec["motifs"]["skeleton"]["A"] + for c, bar in zip(p["chords"], rec["form"]): + if bar["sec"] not in ("A", "A2", "A3") or bar["prog"] in ("call",): + continue + for h in hits: + total += 1 + for g in ("g1", "g2"): + if not any(abs(n["start"] - (c["start"] + h)) < 1e-6 for n in p["parts"][g]): + missing += 1 + break + self.assertLess(missing / total, 0.1, f"{missing}/{total} skeleton hits not shared by both guitars") + + +class ArrangedInvariants(ComposerInvariants): + seeds = range(301, 341) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, arrange=True, **kw) + + def tearDown(self): + global build + build = self._build + + +def busy_bars(p, form, lead): + """Intro and A-type bars where the accompanying guitar attacks at least 3/4 of the sixteenths.""" + other = "g2" if lead == "g1" else "g1" + busy = 0 + for i, c in enumerate(p["chords"]): + if form[i]["sec"] not in ("intro", "A", "A2", "A3"): + continue + end = p["chords"][i + 1]["start"] if i + 1 < len(p["chords"]) else p["total16"] + ons = {n["start"] for n in p["parts"][other] if c["start"] <= n["start"] < end} + busy += len(ons) >= 0.75 * (end - c["start"]) + return busy, sum(b["sec"] in ("intro", "A", "A2", "A3") for b in form) + + +class Arrangement(unittest.TestCase): + seeds = range(301, 341) + + def recipe(self, seed, arrange, tempo=None): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=tempo, arrange=arrange) + return composer.make_recipe(seed, args) + + def test_v3_recipe_keeps_every_v1_field_except_form(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + self.assertIn("arrange", b) + for k in ("seed", "intent", "harmony", "motifs"): + self.assertEqual(a[k], b[k], (seed, k)) + + def test_sixteenth_texture_is_dosed(self): + busy = total = v1_busy = v1_total = 0 + for seed in self.seeds: + for arr in (False, True): + rec = self.recipe(seed * 1000, arr) + b, t = busy_bars(composer.compose(rec), rec["form"], rec["intent"]["lead"]) + if arr: + busy, total = busy + b, total + t + self.assertLessEqual(b, t / 2, f"seed {seed}: sixteenth texture in {b}/{t} bars") + else: + v1_busy, v1_total = v1_busy + b, v1_total + t + self.assertLess(busy / total, 0.75 * v1_busy / v1_total, (busy, total, v1_busy, v1_total)) + + def test_duration_stays_within_a_quarter_of_the_v1_twin(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + da = composer.form_seconds(a["form"], a["intent"], a["intent"]["tempo"]) + db = composer.form_seconds(b["form"], b["intent"], b["arrange"]["tempo"]) + self.assertTrue(0.79 <= db / da <= 1.26, (seed, da, db)) + + def test_pieces_vary_in_tempo_form_and_density(self): + recs = [self.recipe(seed * 1000, True) for seed in self.seeds] + slower = 0 + for r in recs: + self.assertLessEqual(r["arrange"]["tempo"], r["intent"]["tempo"], r["seed"]) + slower += r["arrange"]["tempo"] < 0.9 * r["intent"]["tempo"] + self.assertGreaterEqual(slower, len(recs) // 4) + self.assertEqual({r["arrange"]["template"] for r in recs}, {"classic", "double_b", "no_a2"}) + self.assertEqual({v for r in recs for v in r["arrange"]["b"]}, {"chug", "half", "clean"}) + self.assertGreater(len({len(r["form"]) for r in recs}), 2) + for r in recs: + self.assertGreater(len({b["dens"] for b in r["form"] if "dens" in b}), 1, r["seed"]) + + def test_midi_tempo_is_the_arranged_tempo_and_respects_the_cli(self): + rec = self.recipe(301000, True) + self.assertEqual(composer.compose(rec)["tempo"], rec["arrange"]["tempo"]) + self.assertEqual(self.recipe(301000, True, tempo=99)["arrange"]["tempo"], 99) + + def test_eighth_grid_keeps_every_accent(self): + for grouping in ([3, 4], [2, 2, 3], [3, 3, 4, 4], [3, 3]): + acc = composer.accents_of(grouping) + grid = composer.eighths(acc, sum(grouping)) + self.assertTrue(acc <= grid, grouping) + self.assertTrue(all(b - a >= 1 for a, b in zip(sorted(grid), sorted(grid)[1:]))) + self.assertLessEqual(len(grid), sum(grouping) // 2 + len(acc), grouping) + + +class RepeatedInvariants(ComposerInvariants): + seeds = range(401, 441) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, repeat=True, **kw) + + def tearDown(self): + global build + build = self._build + + +def bar_spans(p): + ch = p["chords"] + return [(c["start"], ch[i + 1]["start"] if i + 1 < len(ch) else p["total16"]) for i, c in enumerate(ch)] + + +def lead_repeats(p, form, lead): + """Share of A-type bars whose lead line repeats the previous bar verbatim.""" + bars = [] + for (s, e), b in zip(bar_spans(p), form): + bars.append((b["sec"], tuple(sorted((n["start"] - s, n["pitch"]) for n in p["parts"][lead] if s <= n["start"] < e)))) + pairs = [(a, b) for a, b in zip(bars, bars[1:]) if a[0] == b[0] and a[0] in ("A", "A2", "A3")] + return sum(a[1] == b[1] and a[1] != () for a, b in pairs) / len(pairs) + + +def both_busy(p, form): + """A-type bars in which both guitars attack at least half of the sixteenths.""" + n = 0 + for (s, e), b in zip(bar_spans(p), form): + if b["sec"] in ("A", "A2", "A3"): + n += all(len({x["start"] for x in p["parts"][g] if s <= x["start"] < e}) >= (e - s) / 2 for g in ("g1", "g2")) + return n + + +class Repetition(unittest.TestCase): + seeds = range(401, 441) + + def recipe(self, seed, repeat): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, arrange=True, repeat=repeat) + return composer.make_recipe(seed, args) + + def test_v4_recipe_differs_from_v3_only_in_phrase_programs_and_roles(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + self.assertIn("repeat", b) + for k in ("seed", "intent", "harmony", "motifs", "arrange"): + self.assertEqual(a[k], b[k], (seed, k)) + strip = lambda f: [{k: v for k, v in x.items() if k not in ("prog", "role")} for x in f] + self.assertEqual(strip(a["form"]), strip(b["form"]), seed) + + def test_lead_riff_repeats_verbatim(self): + v3 = v4 = 0 + for seed in self.seeds: + for rep in (False, True): + rec = self.recipe(seed * 1000, rep) + r = lead_repeats(composer.compose(rec), rec["form"], rec["intent"]["lead"]) + if rep: + v4 += r + self.assertGreaterEqual(r, 0.3, seed) + else: + v3 += r + self.assertGreater(v4, 3 * v3 + 0.2 * len(self.seeds), (v3, v4)) + + def test_guitars_rarely_chatter_together(self): + v3 = v4 = 0 + for seed in self.seeds: + for rep in (False, True): + rec = self.recipe(seed * 1000, rep) + n = both_busy(composer.compose(rec), rec["form"]) + if rep: + v4 += n + else: + v3 += n + self.assertLess(v4, v3, (v3, v4)) + + +class TexturedInvariants(ComposerInvariants): + seeds = range(501, 541) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, texture=True, **kw) + + def tearDown(self): + global build + build = self._build + + +class V6Invariants(ComposerInvariants): + seeds = range(601, 641) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, v6=True, **kw) + + def tearDown(self): + global build + build = self._build + + +def sounding_intervals(p): + a, b = [[(n["start"], n["start"] + n["dur"], n["pitch"]) for n in p["parts"][g]] for g in ("g1", "g2")] + for x, y in ((a, b), (b, a)): + for s, e, pa in x: + yield [abs(pa - q) for s2, e2, q in y if s2 <= s < e2 and pa != q] + + +class V6(unittest.TestCase): + seeds = range(601, 641) + + def recipe(self, seed, v6): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, texture=not v6, v6=v6) + return composer.make_recipe(seed, args) + + def test_v6_recipe_differs_from_v5_only_in_its_plan_and_ending(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + self.assertIn("v6", b) + for k in ("seed", "intent", "harmony", "motifs", "arrange", "repeat", "texture"): + self.assertEqual(a[k], b[k], (seed, k)) + strip = lambda f: [{k: v for k, v in x.items() if k != "end"} for x in f] + self.assertEqual(strip(a["form"]), strip(b["form"]), seed) + + def test_no_minor_ninths_but_major_sevenths_remain(self): + m9 = m7 = 0 + for seed in self.seeds: + for ds in sounding_intervals(composer.compose(self.recipe(seed * 1000, True))): + m9 += any(d % 12 == 1 for d in ds) + m7 += any(d % 12 == 11 for d in ds) + self.assertEqual(m9, 0) + self.assertGreater(m7, 100) + + def test_riff_stays_verbatim(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + lead = a["intent"]["lead"] + pa, pb = composer.compose(a), composer.compose(b) + for (s, e), bar in zip(zip([c["start"] for c in pa["chords"]], [c["start"] for c in pa["chords"][1:]] + [pa["total16"]]), a["form"]): + if bar["prog"] == "riff" and not b["v6"]["rests"]: + la = [(n["start"], n["pitch"]) for n in pa["parts"][lead] if s <= n["start"] < e] + lb = [(n["start"], n["pitch"]) for n in pb["parts"][lead] if s <= n["start"] < e] + self.assertEqual(la, lb, (seed, s)) + + def test_fast_moves_rarely_jump_or_skip(self): + bad = fast = 0 + for seed in self.seeds: + p = composer.compose(self.recipe(seed * 1000, True)) + sec = 15 / p["tempo"] + for ns in p["parts"].values(): + line = sorted((x for x in ns if not x.get("fixed")), key=lambda x: x["start"]) + for a, b in zip(line, line[1:]): + if 0 < (b["start"] - a["start"]) * sec <= 0.12: + fast += 1 + bad += bool(a["fret"] and b["fret"] and abs(b["fret"] - a["fret"]) >= 7) or \ + abs(b["string"] - a["string"]) >= 3 + self.assertLess(bad / fast, 0.025, (bad, fast)) + + def test_every_piece_has_a_rest_at_a_square_boundary(self): + for seed in self.seeds: + rec = self.recipe(seed * 1000, True) + self.assertTrue(rec["v6"]["rests"], seed) + + +class V7Invariants(ComposerInvariants): + seeds = range(701, 741) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, v7=True, **kw) + + def tearDown(self): + global build + build = self._build + + +class V7(unittest.TestCase): + seeds = range(701, 741) + + def piece(self, seed, **flags): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **flags) + rec = composer.make_recipe(seed * 1000, args) + return rec, composer.compose(rec) + + def accented_triad_share(self, **flags): + on = tot = 0 + for seed in self.seeds: + rec, p = self.piece(seed, **flags) + th, lead = p["theory"], rec["intent"]["lead"] + accs = composer.accents_of(rec["intent"]["grouping"]) + for i, (ch, bar) in enumerate(zip(p["chords"], rec["form"])): + if bar["sec"] not in ("A", "A2", "A3"): + continue + end = p["chords"][i + 1]["start"] if i + 1 < len(p["chords"]) else p["total16"] + triad = {th.midi(ch["root_deg"] + k) % 12 for k in (0, 2, 4)} + for n in p["parts"][lead]: + if ch["start"] <= n["start"] < end and n["start"] - ch["start"] in accs: + tot += 1 + on += n["pitch"] % 12 in triad + return on / tot + + def test_lead_uses_colour_tones_on_accents(self): + self.assertLess(self.accented_triad_share(v7=True), self.accented_triad_share(repeat=True) - 0.15) + + def test_no_minor_ninths_between_guitars(self): + for seed in self.seeds: + for ds in sounding_intervals(self.piece(seed, v7=True)[1]): + self.assertFalse(any(d % 12 == 1 for d in ds), seed) + + def test_modes_lean_minor(self): + modes = [self.piece(seed, v7=True)[0]["intent"]["mode"] for seed in self.seeds] + self.assertGreaterEqual(sum(m in ("aeolian", "dorian") for m in modes), len(modes) // 2) + + def test_v7_has_no_v5_or_v6_plans(self): + rec, _ = self.piece(701, v7=True) + self.assertNotIn("texture", rec) + self.assertNotIn("v6", rec) + self.assertIn("repeat", rec) + + +class V8Invariants(ComposerInvariants): + seeds = range(801, 841) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, v8=True, **kw) + + def tearDown(self): + global build + build = self._build + + +class V8(unittest.TestCase): + seeds = range(801, 841) + + def piece(self, seed, flag): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **{flag: True}) + rec = composer.make_recipe(seed * 1000, args) + return rec, composer.compose(rec) + + def test_octave_shapes_are_octaves_on_a_and_g_strings(self): + sections = 0 + for seed in self.seeds: + rec, p = self.piece(seed, "v8") + sections += len(rec["v8"]["octave"]) + for g, notes in p["parts"].items(): + by = {} + for n in notes: + if n.get("dyad"): + by.setdefault(n["start"], []).append(n) + planned = [b for b in rec["form"] if b.get("role") == "octave"] + self.assertEqual(bool(rec["v8"]["octave"]), bool(planned), seed) + for pair in by.values(): + self.assertEqual(sorted(x["string"] for x in pair), [1, 3], (seed, pair)) + lo, hi = sorted(x["pitch"] for x in pair) + self.assertEqual(hi - lo, 12, (seed, pair)) + self.assertTrue(0.3 * 40 <= sections <= 0.7 * 40, sections) + + def test_dead_notes_and_slides_appear_but_stay_rare(self): + dead = slide = dyads = 0 + for seed in self.seeds: + _, p = self.piece(seed, "v8") + for notes in p["parts"].values(): + for n in notes: + if n.get("dyad"): + dyads += 1 + dead += "dead" in n["tech"] + slide += "slide" in n["tech"] + self.assertGreater(slide, 0) + self.assertTrue(0 < dead < 0.15 * dyads, (dead, dyads)) + + def test_no_low_close_clusters_in_chords(self): + for seed in self.seeds: + _, p = self.piece(seed, "v8") + for g, notes in p["parts"].items(): + by = {} + for n in notes: + if n.get("fixed") and not n.get("dyad") and "preset_tech" not in n: + by.setdefault(n["start"], []).append(n["pitch"]) + for start, pitches in by.items(): + self.assertFalse(fretboard.low_cluster(pitches), (seed, g, start, pitches)) + + def test_arpeggio_cycle_skips(self): + steps = lambda cyc: sum(abs(a - b) <= 1 for a, b in zip(cyc, cyc[1:] + cyc[:1])) + worse = 0 + for seed in self.seeds: + rec, _ = self.piece(seed, "v8") + cyc = rec["motifs"]["arp"]["cycle"] + worse += steps(composer.leap_cycle(cyc)) > steps(cyc) + self.assertEqual(worse, 0) + + def test_no_minor_ninths_between_guitars(self): + for seed in self.seeds: + for ds in sounding_intervals(self.piece(seed, "v8")[1]): + self.assertFalse(any(d % 12 == 1 for d in ds), seed) + + +class V9Invariants(ComposerInvariants): + seeds = range(901, 941) + + def setUp(self): + global build + self._build = build + build = lambda seed, **kw: self._build(seed, v9=True, **kw) + + def tearDown(self): + global build + build = self._build + + +class V9(unittest.TestCase): + seeds = range(901, 941) + + def comping(self, flag): + from collections import Counter + pats = Counter() + recs = [] + for seed in self.seeds: + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, **{flag: True}) + rec = composer.make_recipe(seed * 1000, args) + p = composer.compose(rec) + recs.append((rec, p)) + other = "g2" if rec["intent"]["lead"] == "g1" else "g1" + for i, ch in enumerate(p["chords"]): + b = rec["form"][i] + if b["sec"] in ("A", "A2") and (b.get("role") == "chords" or b["prog"] == "cad_open"): + end = p["chords"][i + 1]["start"] if i + 1 < len(p["chords"]) else p["total16"] + ons = tuple(sorted({n["start"] - ch["start"] for n in p["parts"][other] + if ch["start"] <= n["start"] < end})) + pats[(rec["intent"]["meter"], ons)] += 1 + return pats, recs + + def test_comping_patterns_differ_between_pieces(self): + v8, _ = self.comping("v8") + v9, _ = self.comping("v9") + self.assertGreaterEqual(len(v9), 3 * len(v8), (len(v8), len(v9))) + + def test_variations_land_mostly_on_bar_four(self): + _, recs = self.comping("v9") + where = [k.split(":")[1] for rec, _ in recs for k in rec["v9"]["events"]] + self.assertGreater(where.count("3"), where.count("0") + where.count("1"), where) + self.assertGreater(where.count("0") + where.count("1"), 0, where) + + def test_every_intro_hands_over(self): + _, recs = self.comping("v9") + for rec, _ in recs: + intro = [b for b in rec["form"] if b["sec"] == "intro"] + if rec["v9"]["intro"] == "short": + self.assertLessEqual(len(intro), 1) + else: + self.assertEqual(intro[-1].get("handover"), rec["v9"]["intro"]) + + def test_dead_strums_are_short_and_quiet(self): + _, recs = self.comping("v9") + dead = [n for _, p in recs for ns in p["parts"].values() for n in ns + if "dead" in n.get("tech", []) and not n.get("dyad")] + self.assertTrue(dead) + self.assertTrue(all(n["dur"] == 1 and n["vel"] <= 50 for n in dead)) + + +class NoTail(unittest.TestCase): + """--notail removes the trailing rest of the riff bar and changes nothing else.""" + liked = (801, 802, 805, 807, 809, 810) + + def recipe(self, seed, notail): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, v8=True, notail=notail) + return composer.make_recipe(seed * 1000, args) + + def test_only_the_hook_differs_from_v8(self): + for seed in list(self.liked) + list(range(1001, 1041)): + a, b = self.recipe(seed, False), self.recipe(seed, True) + for r in (a, b): + r["motifs"] = {k: v for k, v in r["motifs"].items() if k != "hook"} + r["lead"] = {k: v for k, v in r["lead"].items() if k not in ("tie", "pickup")} + r.pop("generator") + self.assertEqual(a, b, seed) + + def test_pieces_without_a_trailing_rest_are_unchanged(self): + for seed in self.liked: + a, b = self.recipe(seed, False), self.recipe(seed, True) + if a["motifs"]["hook"]["rhythm"] == b["motifs"]["hook"]["rhythm"]: + with tempfile.TemporaryDirectory() as d: + composer.export(composer.compose(a), Path(d) / "a") + composer.export(composer.compose(b), Path(d) / "b") + self.assertEqual((Path(d) / "a.mid").read_bytes(), (Path(d) / "b.mid").read_bytes(), seed) + + def test_riff_bars_rarely_end_in_a_long_rest(self): + def share(notail): + long_tail = bars = 0 + for seed in range(1001, 1041): + rec = self.recipe(seed, notail) + hook = rec["motifs"]["hook"]["rhythm"] + L = composer.METERS[rec["intent"]["meter"]][0] + bars += 1 + long_tail += L - hook[-1] >= 4 + return long_tail / bars + self.assertLess(share(True), share(False) / 2, (share(False), share(True))) + + +class CorpusDoses(unittest.TestCase): + """v5 lands inside the corpus interquartile ranges of CORPUS-STUDY.md.""" + seeds = range(501, 541) + + @classmethod + def setUpClass(cls): + import sys + sys.path.insert(0, str(Path(__file__).with_name("corpus"))) + import study + cls.study = study + cls.stats = study.generator_stats(cls.seeds, texture=True) + + def recipe(self, seed, texture): + args = composer.argparse.Namespace(meter=None, mode=None, key=None, tempo=None, arrange=True, repeat=True, + texture=texture) + return composer.make_recipe(seed, args) + + def median(self, f): + import statistics + return statistics.median(f(s) for s in self.stats) + + def test_v5_recipe_differs_from_v4_only_in_the_form_plan(self): + for seed in self.seeds: + a, b = self.recipe(seed * 1000, False), self.recipe(seed * 1000, True) + self.assertIn("texture", b) + for k in ("seed", "intent", "harmony", "motifs", "arrange", "repeat"): + self.assertEqual(a[k], b[k], (seed, k)) + strip = lambda f: [{k: v for k, v in x.items() if k not in ("prog", "role", "tex", "end")} for x in f] + self.assertEqual(strip(a["form"]), strip(b["form"]), seed) + + def test_one_guitar_plays_alone_in_corpus_range(self): + m = self.median(lambda s: s["relation"]["one_silent"]) + self.assertTrue(0.11 <= m <= 0.65, m) + + def test_same_rhythm_doubling_in_corpus_range(self): + m = self.median(lambda s: sum(s["relation"][k] for k in ("unison", "octave", "harmony", "same_rhythm"))) + self.assertTrue(0.11 <= m <= 0.52, m) + + def test_square_ends_vary_rarely(self): + m = self.median(lambda s: s["square_varied"] if s["square_varied"] is not None else 0) + self.assertLessEqual(m, 0.4) + + def test_endings_are_not_all_held(self): + held = sum(s["last_bar"] == "held" for s in self.stats) / len(self.stats) + self.assertTrue(0.3 <= held <= 0.8, held) + + def test_octave_doubling_is_rare(self): + n = sum(any(b.get("tex") == "octave" for b in self.recipe(seed * 1000, True)["form"]) for seed in self.seeds) + self.assertTrue(0.1 * len(self.seeds) <= n <= 0.45 * len(self.seeds), n) + + +class MusicXmlExport(unittest.TestCase): + def test_every_measure_fills_its_meter_exactly(self): + import xml.etree.ElementTree as ET + for seed in range(1, 21): + with tempfile.TemporaryDirectory() as d: + composer.export(build(seed, arrange=seed % 4 == 1, repeat=seed % 4 == 2, texture=seed % 4 == 3), Path(d) / "x") + root = ET.parse(Path(d) / "x.musicxml").getroot() + for part in root.iter("part"): + num = den = None + for m in part.iter("measure"): + t = m.find("attributes/time") + if t is not None: + num, den = int(t.findtext("beats")), int(t.findtext("beat-type")) + total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None) + self.assertEqual(total, num * 16 // den, (seed, part.get("id"), m.get("number"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/composer-lab/test_studio.py b/composer-lab/test_studio.py new file mode 100644 index 00000000..82f7e70f --- /dev/null +++ b/composer-lab/test_studio.py @@ -0,0 +1,1306 @@ +import argparse +import copy +import hashlib +import json +import random +import shutil +import sys +import tempfile +import threading +import unittest +import urllib.error +import urllib.request +import xml.etree.ElementTree as ET +from pathlib import Path + +import composer +import fretboard +from studio import engine as studio_engine +from studio import render as studio_render +from studio import server as studio_server +from studio import summary as studio_summary + + +GOLDEN_V8_MID_SHA256 = { + 801: "35bfc27c463990048b6286f4d5c54fd33bb5810ba337e16d132b955965981fd7", + 802: "bd23545662eea92ba1bee302a6b17d9a0b45e71ad8dc9214a7432712a6a0ffac", + 805: "f282b2b7928be26d8724d080f4ace15a59fe7b13a180556e26b4083504c503ef", + 807: "bf33165ac246f61fd9a2424ae933d62239887be3c3a8b2236d60e355aaf4ddb1", + 809: "de2977c3a95c0932161c93541d3709f673b8cdef59967a85f762cfcaaf12cc89", + 810: "f11bfbfac1e772e5842bf6503ece98880f531d6ab3f9f388190cc5b40807fc1a", +} + + +def midi_sha256(piece): + with tempfile.TemporaryDirectory() as d: + base = Path(d) / "p" + composer.export(piece, base) + return hashlib.sha256(base.with_suffix(".mid").read_bytes()).hexdigest() + + +def section_spans(piece): + ch = piece["chords"] + bars = [ + (c["sec"], c["start"], ch[i + 1]["start"] if i + 1 < len(ch) else piece["total16"]) + for i, c in enumerate(ch) + ] + spans = [] + for sec, s, e in bars: + if spans and spans[-1][0] == sec: + spans[-1][2] = e + else: + spans.append([sec, s, e]) + return [(sec, s, e) for sec, s, e in spans] + + +def section_notes(piece, g, start16, end16): + out = [] + for n in piece["parts"][g]: + if start16 <= n["start"] < end16: + out.append(( + n["start"] - start16, + n["dur"], + n["pitch"], + n["vel"], + n["string"], + n["fret"], + tuple(n.get("tech", [])), + )) + return sorted(out) + + +def boundary_equal(a, b, end16): + """Section notes equal, except what the neighbouring section can legitimately change: + the duration of a note ringing past the section end and the legato mark of its first note.""" + if len(a) != len(b): + return False + key = lambda n: (n[0], n[2], n[3], n[4], n[5]) + a, b = sorted(a, key=key), sorted(b, key=key) + first = min((n[0] for n in a), default=0) + for x, y in zip(a, b): + if key(x) != key(y): + return False + if x[1] != y[1] and x[0] + max(x[1], y[1]) <= end16: + return False + if x[6] != y[6] and x[0] != first: + return False + return True + + +def has_active_chatter(rec, piece, sec): + lead = rec["intent"]["lead"] + L = composer.METERS[rec["intent"]["meter"]][0] + ch = piece["chords"] + for i, b in enumerate(rec["form"]): + if b["sec"] != sec: + continue + s = ch[i]["start"] + e = ch[i + 1]["start"] if i + 1 < len(ch) else piece["total16"] + mask = {int(n["start"] - s) for n in piece["parts"][lead] if s <= n["start"] < e} + if b.get("role") == "chatter" and len(mask) < L / 2: + return True + return False + + +def pick_seeds(predicate, count=20, start=801): + out = [] + s = start + while len(out) < count: + rec = studio_engine.new_recipe(s * 1000) + if predicate(rec): + out.append(s * 1000) + s += 1 + return out + + +class TestBaselineIdentity(unittest.TestCase): + def test_no_studio_byte_identical_v8(self): + for seed, expected_hash in GOLDEN_V8_MID_SHA256.items(): + args = argparse.Namespace(meter=None, mode=None, key=None, tempo=None, v8=True) + rec = composer.make_recipe(seed * 1000, args) + self.assertNotIn("studio", rec) + actual = midi_sha256(composer.compose(rec)) + self.assertEqual(actual, expected_hash, f"seed {seed} v8 MIDI drifted") + + +class TestLayerIsolation(unittest.TestCase): + def _assert_section_layer(self, layer, sec, seeds, check_other_changed=True): + for seed in seeds: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, layer, sec) + p1 = composer.compose(rec1) + + lead = rec0["intent"]["lead"] + other = "g2" if lead == "g1" else "g1" + + spans0 = section_spans(p0) + spans1 = section_spans(p1) + self.assertEqual(spans0, spans1, (layer, sec, seed)) + self.assertEqual(p0["tempo"], p1["tempo"], (layer, sec, seed)) + self.assertEqual(rec0["harmony"], rec1["harmony"], (layer, sec, seed)) + + # Lead guitar is never touched by accompaniment / B / ending layers + for sname, s0, e0 in spans0: + self.assertEqual( + section_notes(p0, lead, s0, e0), + section_notes(p1, lead, s0, e0), + (layer, sec, seed, sname, "lead changed"), + ) + if sname != sec: + self.assertTrue( + boundary_equal(section_notes(p0, other, s0, e0), section_notes(p1, other, s0, e0), e0 - s0), + (layer, sec, seed, sname, "other section changed"), + ) + + if check_other_changed: + target0 = [section_notes(p0, other, s0, e0) for sn, s0, e0 in spans0 if sn == sec] + target1 = [section_notes(p1, other, s0, e0) for sn, s0, e0 in spans1 if sn == sec] + self.assertNotEqual(target0, target1, (layer, sec, seed, "target did not change")) + + def test_layer_isolation_and_target_change(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + seeds_a2 = pick_seeds(lambda r: any(b["sec"] == "A2" for b in r["form"]), 20) + + # comp@A and comp@A2 + self._assert_section_layer("comp", "A", seeds_20, check_other_changed=True) + self._assert_section_layer("comp", "A2", seeds_a2, check_other_changed=True) + + # texture@A and texture@A2: isolation on 20 seeds + target change on 20 active chatter seeds + self._assert_section_layer("texture", "A", seeds_20, check_other_changed=False) + self._assert_section_layer("texture", "A2", seeds_a2, check_other_changed=False) + chatter_a = pick_seeds(lambda r: has_active_chatter(r, composer.compose(r), "A"), 20) + chatter_a2 = pick_seeds( + lambda r: any(b["sec"] == "A2" for b in r["form"]) and has_active_chatter(r, composer.compose(r), "A2"), + 20, + ) + self._assert_section_layer("texture", "A", chatter_a, check_other_changed=True) + self._assert_section_layer("texture", "A2", chatter_a2, check_other_changed=True) + + # Verify texture never changes the realized roles of the second guitar + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0, t0 = traced(rec0) + p1, t1 = traced(studio_engine.reroll(rec0, "texture", "A")) + og = "g2" if rec0["intent"]["lead"] == "g1" else "g1" + for sec in ("A", "A2", "A3"): + for (sn, s0, e0), (_, s1, e1) in zip(section_spans(p0), section_spans(p1)): + if sn == sec: + self.assertEqual(strum_onsets(t0, og, s0, e0), strum_onsets(t1, og, s1, e1), (seed, sec)) + + # b@B + self._assert_section_layer("b", "B", seeds_20, check_other_changed=True) + + # lead_rhythm@all + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, "lead_rhythm", "all") + p1 = composer.compose(rec1) + lead = rec0["intent"]["lead"] + other = "g2" if lead == "g1" else "g1" + + self.assertEqual(rec0["harmony"], rec1["harmony"], seed) + self.assertEqual(rec0["form"], rec1["form"], seed) + self.assertEqual(p0["tempo"], p1["tempo"], seed) + self.assertEqual(p0["meters"], p1["meters"], seed) + self.assertEqual(p0["total16"], p1["total16"], seed) + self.assertEqual(p0["chords"], p1["chords"], seed) + + self.assertNotEqual( + [(n["start"], n["dur"], n["pitch"]) for n in p0["parts"][lead]], + [(n["start"], n["dur"], n["pitch"]) for n in p1["parts"][lead]], + ("lead_rhythm", seed), + ) + spans0 = section_spans(p0) + for sname, s0, e0 in spans0: + if sname in ("intro", "end"): + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, s0, e0), section_notes(p1, g, s0, e0), e0 - s0), + ("lead_rhythm", seed, sname, g), + ) + elif sname == "B": + # Second-guitar plan in B is unchanged; only minor-9th resolution against the new lead may cut/drop a note. + b0 = section_notes(p0, other, s0, e0) + b1 = section_notes(p1, other, s0, e0) + if b0 != b1: + lead_b1 = [(n["start"] - s0, n["start"] + n["dur"] - s0, n["pitch"]) for n in p1["parts"][lead] if s0 <= n["start"] < e0] + b1_map = {(n[0], n[2]): n for n in b1} + for n0 in b0: + n1 = b1_map.get((n0[0], n0[2])) + if n1 is None or n1 != n0: + clash = any( + composer.minor_ninth(lp, n0[2]) and not (ls >= n0[0] + n0[1] or le <= n0[0]) + for ls, le, lp in lead_b1 + ) + if not clash: + # Check whether p0 had a minor-9th cut/drop against p0's lead that no longer applies in p1 + lead_b0 = [(n["start"] - s0, n["start"] + n["dur"] - s0, n["pitch"]) for n in p0["parts"][lead] if s0 <= n["start"] < e0] + clash0 = any( + composer.minor_ninth(lp, n0[2]) and not (ls >= n0[0] + n0[1] or le <= n0[0]) + for ls, le, lp in lead_b0 + ) + self.assertTrue(clash0 or n1 is not None and (n1[0], n1[2], n1[3]) == (n0[0], n0[2], n0[3]), ("lead_rhythm leaked to B", seed, n0, n1)) + + # intro@intro + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, "intro", "intro") + p1 = composer.compose(rec1) + + spans0 = section_spans(p0) + spans1 = section_spans(p1) + self.assertEqual([x[0] for x in spans0], [x[0] for x in spans1], ("intro", seed)) + + in0 = [section_notes(p0, g, spans0[0][1], spans0[0][2]) for g in ("g1", "g2")] + in1 = [section_notes(p1, g, spans1[0][1], spans1[0][2]) for g in ("g1", "g2")] + self.assertTrue( + spans0[0][2] != spans1[0][2] or in0 != in1, + ("intro did not change", seed), + ) + for (sn0, s0, e0), (sn1, s1, e1) in zip(spans0[1:], spans1[1:]): + self.assertEqual(sn0, sn1) + self.assertEqual(e0 - s0, e1 - s1) + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, s0, e0), section_notes(p1, g, s1, e1), e0 - s0), + ("intro leaked", seed, sn0, g), + ) + + # ending@end + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, "ending", "end") + p1 = composer.compose(rec1) + spans0 = section_spans(p0) + spans1 = section_spans(p1) + self.assertEqual(spans0, spans1, ("ending", seed)) + for sn, s0, e0 in spans0: + if sn == "end": + n0 = [section_notes(p0, g, s0, e0) for g in ("g1", "g2")] + n1 = [section_notes(p1, g, s0, e0) for g in ("g1", "g2")] + self.assertNotEqual(n0, n1, ("ending did not change", seed)) + else: + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, s0, e0), section_notes(p1, g, s0, e0), e0 - s0), + ("ending leaked", seed, sn, g), + ) + + # tempo@all + for seed in seeds_20: + rec0 = studio_engine.new_recipe(seed) + p0 = composer.compose(rec0) + rec1 = studio_engine.reroll(rec0, "tempo", "all") + p1 = composer.compose(rec1) + self.assertNotEqual(p0["tempo"], p1["tempo"], ("tempo did not change", seed)) + lo = max(60, int(round(p0["tempo"] * 0.8))) + hi = min(220, int(round(p0["tempo"] * 1.1))) + self.assertTrue(lo <= p1["tempo"] <= hi, (seed, p0["tempo"], p1["tempo"], lo, hi)) + for g in ("g1", "g2"): + self.assertEqual( + section_notes(p0, g, 0, p0["total16"]), + section_notes(p1, g, 0, p1["total16"]), + ("tempo changed notes", seed, g), + ) + + +class TestDeterminismAndSalts(unittest.TestCase): + def test_same_salt_deterministic_and_different_salts_vary(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + seeds_a2 = pick_seeds(lambda r: any(b["sec"] == "A2" for b in r["form"]), 20) + chatter_a = pick_seeds(lambda r: has_active_chatter(r, composer.compose(r), "A"), 20) + + cases = [ + ("comp", "A", seeds_20), + ("comp", "A2", seeds_a2), + ("texture", "A", chatter_a), + ("lead_rhythm", "all", seeds_20), + ("b", "B", seeds_20), + ("intro", "intro", seeds_20), + ("ending", "end", seeds_20), + ("tempo", "all", seeds_20), + ] + for layer, sec, seeds in cases: + diff = 0 + for seed in seeds: + a1 = studio_engine.reroll(studio_engine.new_recipe(seed), layer, sec) + a2 = studio_engine.reroll(studio_engine.new_recipe(seed), layer, sec) + self.assertEqual(a1, a2, (layer, sec, seed)) + h1 = midi_sha256(composer.compose(a1)) + h2 = midi_sha256(composer.compose(a2)) + self.assertEqual(h1, h2, (layer, sec, seed)) + + b = studio_engine.reroll(copy.deepcopy(a1), layer, sec) + hb = midi_sha256(composer.compose(b)) + if hb != h1: + diff += 1 + self.assertGreaterEqual(diff, 15, (layer, sec, diff)) + + +class TestLocks(unittest.TestCase): + def test_locked_layer_not_changed_by_reroll_all(self): + for seed in [s * 1000 for s in range(801, 811)]: + rec = studio_engine.new_recipe(seed) + rec = studio_engine.set_lock(rec, "intro", "intro", True) + rec = studio_engine.set_lock(rec, "tempo", "all", True) + rec = studio_engine.set_lock(rec, "ending", "end", True) + rec = studio_engine.set_lock(rec, "comp", "A", True) + rec = studio_engine.set_lock(rec, "lead_rhythm", "all", True) + + # Direct reroll of locked layer is a no-op + direct = studio_engine.reroll(rec, "comp", "A") + self.assertEqual(direct, rec) + + p0 = composer.compose(rec) + rec_all = studio_engine.reroll(rec, "all", "all") + p1 = composer.compose(rec_all) + + for key in ("intro@intro", "tempo@all", "ending@end", "comp@A", "lead_rhythm@all"): + self.assertEqual(rec_all["studio"]["salts"].get(key, 0), 0, (seed, key)) + + self.assertEqual(rec_all["studio"]["salts"].get("b@B", 0), 1, seed) + self.assertEqual(p0["tempo"], p1["tempo"], seed) + + spans0 = section_spans(p0) + spans1 = section_spans(p1) + self.assertEqual(spans0, spans1, seed) + for sn, s0, e0 in spans0: + if sn in ("intro", "end"): + for g in ("g1", "g2"): + self.assertEqual(section_notes(p0, g, s0, e0), section_notes(p1, g, s0, e0), (seed, sn, g)) + lead = rec["intent"]["lead"] + self.assertEqual(p0["parts"][lead], p1["parts"][lead], seed) + + +class TestBLeadOption(unittest.TestCase): + def test_b_lead_modes(self): + seeds_20 = [s * 1000 for s in range(801, 821)] + for seed in seeds_20: + rec_plain = composer.make_recipe( + seed, argparse.Namespace(meter=None, mode=None, key=None, tempo=None, v8=True) + ) + rec_def = studio_engine.new_recipe(seed) + rec_aug = studio_engine.set_option(rec_def, "b_lead", "augmented") + self.assertEqual(midi_sha256(composer.compose(rec_def)), midi_sha256(composer.compose(rec_aug)), seed) + + lead = rec_def["intent"]["lead"] + p_plain = composer.compose(rec_plain) + p_aug = composer.compose(rec_aug) + for sn, s0, e0 in section_spans(p_plain): + if sn == "B": + b_plain = section_notes(p_plain, lead, s0, e0) + b_aug = section_notes(p_aug, lead, s0, e0) + self.assertEqual( + [(n[0], n[2], n[3]) for n in b_plain], + [(n[0], n[2], n[3]) for n in b_aug], + seed, + ) + + # rest: no lead notes in B + rec_rest = studio_engine.set_option(rec_def, "b_lead", "rest") + p_rest = composer.compose(rec_rest) + for sn, s0, e0 in section_spans(p_rest): + if sn == "B": + self.assertEqual(section_notes(p_rest, lead, s0, e0), [], seed) + + # same_speed: B lead notes use hook's shaped durations + rec_same = studio_engine.set_option(rec_def, "b_lead", "same_speed") + p_same = composer.compose(rec_same) + hook_L = composer.METERS[rec_same["intent"]["meter"]][0] + b_L = composer.METERS[rec_same["intent"]["b_meter"]][0] + expected_ev = composer.shape_lead(composer.motif_events(rec_same["motifs"]["hook"], hook_L), rec_same["lead"]) + expected_durs = [min(e["dur"], b_L - e["on"]) for e in expected_ev if e["on"] < b_L] + b_bars = [ + (c["start"], p_same["chords"][i + 1]["start"] if i + 1 < len(p_same["chords"]) else p_same["total16"]) + for i, c in enumerate(p_same["chords"]) + if c["sec"] == "B" + ] + for bs, be in b_bars: + notes = sorted((n for n in p_same["parts"][lead] if bs <= n["start"] < be), key=lambda n: n["start"]) + self.assertEqual([n["dur"] for n in notes], expected_durs, (seed, bs)) + + def test_trailing_rest_and_v8_doses(self): + # 809 has a trailing rest in v8 that --notail removes + rec_nt_base = studio_engine.new_recipe(809000) + rec_nt = studio_engine.set_option(rec_nt_base, "trailing_rest", False) + p0 = composer.compose(rec_nt_base) + p1 = composer.compose(rec_nt) + self.assertNotEqual(midi_sha256(p0), midi_sha256(p1)) + + # V8 doses apply on the next comp re-roll, without retroactively changing already-rolled sections + seed_a2 = pick_seeds(lambda r: any(b["sec"] == "A2" for b in r["form"]), 1)[0] + rec = studio_engine.new_recipe(seed_a2) + rec_a = studio_engine.reroll(rec, "comp", "A") + p_before_dose = composer.compose(rec_a) + rec_dose = studio_engine.set_option(rec_a, "octave_piece", 1.0) + rec_dose = studio_engine.set_option(rec_dose, "octave_sixteenths", 1.0) + rec_dose = studio_engine.set_option(rec_dose, "dead_notes", 0.0) + rec_dose = studio_engine.set_option(rec_dose, "slide_max", 7) + p_after_dose = composer.compose(rec_dose) + self.assertEqual(midi_sha256(p_before_dose), midi_sha256(p_after_dose)) + + rec_a2 = studio_engine.reroll(rec_dose, "comp", "A2") + p_after_reroll = composer.compose(rec_a2) + other = "g2" if rec["intent"]["lead"] == "g1" else "g1" + for sn, s0, e0 in section_spans(p_after_reroll): + if sn == "A2": + dyads = [n for n in p_after_reroll["parts"][other] if s0 <= n["start"] < e0 and n.get("dyad")] + self.assertTrue(dyads, "octave_piece=1.0 should force octave dyads on next comp reroll") + + +class TestStudioInvariants(unittest.TestCase): + def test_composer_invariants_after_random_rerolls(self): + bad_clash = shared_clash = 0 + for s in range(801, 821): + rng = random.Random(s + 4242) + rec = studio_engine.new_recipe(s * 1000) + choices = [(item["layer"], item["section"]) for item in studio_engine.available_layers(rec)] + for _ in range(5): + layer, sec = rng.choice(choices) + rec = studio_engine.reroll(rec, layer, sec) + if rng.random() < 0.3: + rec = studio_engine.set_option(rec, "b_lead", rng.choice(["augmented", "same_speed", "rest"])) + if rng.random() < 0.2: + rec = studio_engine.set_option(rec, "trailing_rest", rng.choice([True, False])) + + p = composer.compose(rec) + + # 1. String and fret consistency + for g, notes in p["parts"].items(): + for n in notes: + self.assertTrue(0 <= n["fret"] <= fretboard.MAX_FRET, (s, g, n)) + self.assertEqual(fretboard.OPEN[n["string"]] + n["fret"], n["pitch"], (s, g, n)) + + # 2. Legato only on same string + hammer ascending + for g, notes in p["parts"].items(): + line = [ + n for n in notes + if not n.get("chordtone") and not n.get("dyad") and not (n.get("fixed") and "preset_tech" not in n) + ] + for prev, n in zip(line, line[1:]): + if {"hammer", "pull", "slide"} & set(n["tech"]): + self.assertEqual(prev["string"], n["string"], (s, g, n)) + if "hammer" in n["tech"]: + self.assertGreater(n["fret"], prev["fret"], (s, g, n)) + + # 3. Octave slides from same string + for g, notes in p["parts"].items(): + last = {} + for n in sorted((x for x in notes if x.get("dyad")), key=lambda x: x["start"]): + if "slide" in n["tech"]: + prev = last.get(n["string"]) + self.assertTrue(prev is not None and prev["fret"] != n["fret"], (s, g, n)) + last[n["string"]] = n + + # 4. Taps above fretting hand + for g, notes in p["parts"].items(): + for _, n in zip(notes, notes[1:]): + if "tap" in n.get("tech", []) and n.get("fixed"): + nxt = [ + m for m in notes + if n["start"] < m["start"] <= n["start"] + 2 + and m["string"] == n["string"] + and "pull" in m.get("tech", []) + ][:1] + for m in nxt: + self.assertGreater(n["fret"], m["fret"], (s, g, n)) + + # 5. Semitone clash count + g2 = {} + for n in p["parts"]["g2"]: + g2.setdefault(n["start"], []).append(n["pitch"]) + for n in p["parts"]["g1"]: + for q in g2.get(n["start"], []): + shared_clash += 1 + bad_clash += abs(n["pitch"] - q) % 12 in (1, 11) + + # 6. No minor ninths between guitars (v7+) + a = [(n["start"], n["start"] + n["dur"], n["pitch"]) for n in p["parts"]["g1"]] + b = [(n["start"], n["start"] + n["dur"], n["pitch"]) for n in p["parts"]["g2"]] + for x, y in ((a, b), (b, a)): + for s0, _, pa in x: + for s2, e2, q in y: + if s2 <= s0 < e2 and pa != q: + self.assertNotEqual(abs(pa - q) % 12, 1, (s, s0, pa, q)) + + # 7. MusicXML measures fill meter + with tempfile.TemporaryDirectory() as d: + composer.export(p, Path(d) / "x") + root = ET.parse(Path(d) / "x.musicxml").getroot() + for part in root.iter("part"): + num = den = None + for m in part.iter("measure"): + t = m.find("attributes/time") + if t is not None: + num, den = int(t.findtext("beats")), int(t.findtext("beat-type")) + total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None) + self.assertEqual(total, num * 16 // den, (s, part.get("id"), m.get("number"))) + + self.assertLess(bad_clash / max(1, shared_clash), 0.03, (bad_clash, shared_clash)) + + +class TestUndo(unittest.TestCase): + def test_undo_restores_previous_recipe(self): + with tempfile.TemporaryDirectory() as d: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + det0 = store.create_piece(801000) + pid = det0["id"] + pdir = Path(d) / pid + r0 = json.loads((pdir / "recipe.json").read_text(encoding="utf-8")) + + store.reroll(pid, "comp", "A") + r1 = json.loads((pdir / "recipe.json").read_text(encoding="utf-8")) + self.assertNotEqual(r1, r0) + + store.set_option(pid, "b_lead", "rest") + r2 = json.loads((pdir / "recipe.json").read_text(encoding="utf-8")) + self.assertNotEqual(r2, r1) + + store.set_lock(pid, "comp", "A", True) + r3 = json.loads((pdir / "recipe.json").read_text(encoding="utf-8")) + self.assertNotEqual(r3, r2) + + store.undo(pid) + self.assertEqual(json.loads((pdir / "recipe.json").read_text(encoding="utf-8")), r2) + store.undo(pid) + self.assertEqual(json.loads((pdir / "recipe.json").read_text(encoding="utf-8")), r1) + store.undo(pid) + self.assertEqual(json.loads((pdir / "recipe.json").read_text(encoding="utf-8")), r0) + + +class TestServerAndSummary(unittest.TestCase): + def _req(self, url, method="GET", body=None, headers=None): + hdrs = dict(headers or {}) + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + hdrs["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, method=method, headers=hdrs) + with urllib.request.urlopen(req, timeout=10) as resp: + return resp.status, dict(resp.headers), resp.read() + + def test_server_end_to_end(self): + with tempfile.TemporaryDirectory() as d: + srv = studio_server.create_server(d, host="127.0.0.1", port=0, render_fn=studio_render.fake_render) + port = srv.server_address[1] + t = threading.Thread(target=srv.serve_forever, daemon=True) + t.start() + base = f"http://127.0.0.1:{port}" + try: + st, _, html_bytes = self._req(f"{base}/") + self.assertEqual(st, 200) + html = html_bytes.decode("utf-8") + self.assertIn("Новая пьеса", html) + self.assertIn("Отменить", html) + self.assertIn("Скачать MIDI", html) + + st, _, raw = self._req(f"{base}/api/new", method="POST", body={"seed": 801000}) + self.assertEqual(st, 200) + created = json.loads(raw) + pid = created["id"] + for key in ("id", "seed", "meter", "mode", "key", "tempo", "length", "sections", "whole_layers", "options"): + self.assertIn(key, created) + self.assertTrue(created["sections"]) + for sec in created["sections"]: + for sk in ("section", "start_sec", "end_sec", "layers"): + self.assertIn(sk, sec) + + st, _, raw = self._req(f"{base}/api/pieces") + self.assertEqual(st, 200) + pieces = json.loads(raw)["pieces"] + self.assertEqual(len(pieces), 1) + for key in ("id", "seed", "meter", "mode", "key", "tempo", "length", "sections"): + self.assertIn(key, pieces[0]) + + st, _, raw = self._req(f"{base}/api/piece/{pid}") + self.assertEqual(st, 200) + self.assertEqual(json.loads(raw)["id"], pid) + + st, _, raw = self._req(f"{base}/api/piece/{pid}/reroll", method="POST", body={"layer": "comp", "section": "A"}) + self.assertEqual(st, 200) + det = json.loads(raw) + sec_a = next(s for s in det["sections"] if s["section"] == "A") + comp_a = next(l for l in sec_a["layers"] if l["layer"] == "comp") + self.assertEqual(comp_a["salt"], 1) + + st, _, raw = self._req(f"{base}/api/piece/{pid}/lock", method="POST", body={"layer": "comp", "section": "A", "locked": True}) + self.assertEqual(st, 200) + det = json.loads(raw) + sec_a = next(s for s in det["sections"] if s["section"] == "A") + comp_a = next(l for l in sec_a["layers"] if l["layer"] == "comp") + self.assertTrue(comp_a["locked"]) + + st, _, raw = self._req(f"{base}/api/piece/{pid}/option", method="POST", body={"name": "b_lead", "value": "rest"}) + self.assertEqual(st, 200) + self.assertEqual(json.loads(raw)["options"]["b_lead"], "rest") + + st, _, raw = self._req(f"{base}/api/piece/{pid}/undo", method="POST", body={}) + self.assertEqual(st, 200) + self.assertEqual(json.loads(raw)["options"]["b_lead"], "augmented") + + st, _, mid = self._req(f"{base}/api/piece/{pid}/piece.mid") + self.assertEqual(st, 200) + self.assertTrue(mid.startswith(b"MThd")) + + st, _, mxml = self._req(f"{base}/api/piece/{pid}/piece.musicxml") + self.assertEqual(st, 200) + ET.fromstring(mxml) + + st, _, tab = self._req(f"{base}/api/piece/{pid}/piece.tab.txt") + self.assertEqual(st, 200) + self.assertIn("== g1 ==", tab.decode("utf-8")) + + st, _, mp3 = self._req(f"{base}/api/piece/{pid}/audio.mp3") + self.assertEqual(st, 200) + self.assertTrue(len(mp3) > 0) + + st, hdrs, part = self._req(f"{base}/api/piece/{pid}/audio.mp3", headers={"Range": "bytes=0-3"}) + self.assertEqual(st, 206) + self.assertEqual(len(part), 4) + self.assertIn("Content-Range", {k.title(): v for k, v in hdrs.items()}) + + pdir = Path(d) / pid + for fname in ("recipe.json", "piece.mid", "piece.musicxml", "piece.tab.txt", "piece.mp3", "history.jsonl"): + self.assertTrue((pdir / fname).exists(), fname) + + lines = [json.loads(line) for line in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line] + self.assertEqual(len(lines), 8) + self.assertEqual( + [x["action"] for x in lines], + ["new", "reroll", "lock", "option", "undo", "export", "export", "export"], + ) + for row in lines: + for k in ("t", "action", "layer", "section", "salt", "value"): + self.assertIn(k, row) + + stats = studio_summary.summarize(d) + self.assertEqual(stats["pieces_total"], 1) + self.assertEqual(stats["pieces_exported"], 1) + self.assertEqual(stats["rerolls_per_layer"].get("comp"), 1) + self.assertEqual(stats["rerolls_before_first_export"], [1]) + self.assertIn("b_lead", stats["options_used"]) + finally: + srv.shutdown() + srv.server_close() + + +def plain_recipe(seed, **flags): + args = argparse.Namespace( + meter=flags.pop("meter", None), mode=flags.pop("mode", None), + key=flags.pop("key", None), tempo=flags.pop("tempo", None), **flags, + ) + return composer.make_recipe(seed, args) + + +def piece_sha256(piece): + with tempfile.TemporaryDirectory() as d: + base = Path(d) / "p" + composer.export(piece, base) + h = hashlib.sha256() + for suffix in (".mid", ".musicxml", ".tab.txt"): + h.update(Path(str(base) + suffix).read_bytes()) + return h.hexdigest() + + +def other_of(rec): + return "g2" if rec["intent"]["lead"] == "g1" else "g1" + + +def strum_onsets(trace, g, s0, e0): + count = {} + for n in trace["pre"][g]: + if s0 <= n["start"] < e0: + count[n["start"]] = count.get(n["start"], 0) + 1 + return sorted(k - s0 for k, v in count.items() if v >= 3) + + +def traced(rec): + trace = {} + return composer.compose(rec, _trace=trace), trace + + +def span_of(piece, sec): + return next((s0, e0) for sn, s0, e0 in section_spans(piece) if sn == sec) + + +class TestAccompanimentFollowsItsOwnPlan(unittest.TestCase): + def test_locked_comp_and_texture_survive_reroll_all(self): + for seed in [6] + list(range(0, 14)): + rec = studio_engine.new_recipe(seed) + rec = studio_engine.set_lock(rec, "comp", "A", True) + rec = studio_engine.set_lock(rec, "texture", "A", True) + p0, t0 = traced(rec) + p1, t1 = traced(studio_engine.reroll(rec, "all", "all")) + other = other_of(rec) + self.assertEqual( + strum_onsets(t0, other, *span_of(p0, "A")), + strum_onsets(t1, other, *span_of(p1, "A")), + ("locked accompaniment changed", seed), + ) + + def test_salted_locked_comp_survives_lead_reroll(self): + for seed in range(0, 14): + rec = studio_engine.reroll(studio_engine.new_recipe(seed), "comp", "A") + rec = studio_engine.set_lock(rec, "comp", "A", True) + p0, t0 = traced(rec) + p1, t1 = traced(studio_engine.reroll(rec, "lead_rhythm", "all")) + other = other_of(rec) + self.assertEqual( + strum_onsets(t0, other, *span_of(p0, "A")), strum_onsets(t1, other, *span_of(p1, "A")), seed + ) + + def test_texture_reroll_keeps_realized_roles(self): + for seed in range(0, 14): + rec = studio_engine.new_recipe(seed) + p0, t0 = traced(rec) + p1, t1 = traced(studio_engine.reroll(rec, "texture", "A")) + other = other_of(rec) + self.assertEqual( + strum_onsets(t0, other, *span_of(p0, "A")), strum_onsets(t1, other, *span_of(p1, "A")), seed + ) + + def test_lead_reroll_keeps_accompaniment_roles(self): + for seed in range(0, 14): + rec = studio_engine.new_recipe(seed) + p0, t0 = traced(rec) + p1, t1 = traced(studio_engine.reroll(rec, "lead_rhythm", "all")) + other = other_of(rec) + for sec in ("A", "A2", "A3"): + if not any(sn == sec for sn, _, _ in section_spans(p0)): + continue + self.assertEqual( + strum_onsets(t0, other, *span_of(p0, sec)), + strum_onsets(t1, other, *span_of(p1, sec)), + (seed, sec), + ) + + def test_call_response_does_not_follow_a_new_lead(self): + checked = 0 + for seed in range(0, 20): + rec = studio_engine.new_recipe(seed) + call = [i for i, b in enumerate(rec["form"]) if b.get("prog") == "call" and b["sec"] == "A2"] + if not call: + continue + L = composer.METERS[rec["intent"]["meter"]][0] + p0, t0 = traced(rec) + p1, t1 = traced(studio_engine.reroll(rec, "lead_rhythm", "all")) + other = other_of(rec) + start = p0["chords"][call[0]]["start"] + + def window(tr): + return sorted( + (n["start"] - start, n["dur"], n["pitch"]) + for n in tr["pre"][other] + if start + L // 2 <= n["start"] < start + L + ) + + self.assertTrue(window(t0)) + self.assertEqual(window(t0), window(t1), seed) + checked += 1 + self.assertGreater(checked, 3) + + def test_locked_ending_survives_reroll_all(self): + checked = 0 + for seed in range(0, 24): + rec = studio_engine.new_recipe(seed) + base_end = next(b.get("end") for b in rec["form"] if b["sec"] == "end") + salt = next( + (k for k in (1, 2, 3) if composer._studio_ending(rec["seed"], k, base_end) == "busy"), None + ) + if salt is None: + continue + rec["studio"]["salts"]["ending@end"] = salt + rec = studio_engine.set_lock(rec, "ending", "end", True) + p0 = composer.compose(rec) + p1 = composer.compose(studio_engine.reroll(rec, "all", "all")) + e0, e1 = span_of(p0, "end"), span_of(p1, "end") + for g in ("g1", "g2"): + self.assertEqual(section_notes(p0, g, *e0), section_notes(p1, g, *e1), (seed, g)) + checked += 1 + self.assertGreater(checked, 3) + + +class TestOlderRecipesAreNotRewritten(unittest.TestCase): + FLAGS = ({"v6": True}, {"v7": True}, {"v8": True}, {"v8": True, "notail": True}) + + def test_metadata_only_edits_keep_the_music(self): + for flags in self.FLAGS: + for seed in range(0, 8): + rec = plain_recipe(seed, **flags) + expected = piece_sha256(composer.compose(rec)) + locked = studio_engine.set_lock(rec, "comp", "A", True) + self.assertEqual(piece_sha256(composer.compose(locked)), expected, (flags, seed, "lock")) + again = studio_engine.set_option(locked, "octave_piece", 0.5) + self.assertEqual(piece_sha256(composer.compose(again)), expected, (flags, seed, "dose")) + + def test_reroll_leaves_untouched_sections_as_generated(self): + for flags in self.FLAGS: + for seed in range(0, 8): + rec = plain_recipe(seed, **flags) + p0 = composer.compose(rec) + spans = section_spans(p0) + for layer, sec in (("comp", "A"), ("b", "B"), ("intro", "intro"), ("ending", "end")): + if sec not in {sn for sn, _, _ in spans}: + continue + p1 = composer.compose(studio_engine.reroll(rec, layer, sec)) + for (sn, s0, e0), (_, s1, e1) in zip(spans, section_spans(p1)): + if sn == sec: + continue + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, s0, e0), section_notes(p1, g, s1, e1), e0 - s0), + (flags, seed, layer, sn, g), + ) + + def test_intro_reroll_does_not_move_saved_pushes(self): + moved = 0 + for seed in range(0, 40): + rec = plain_recipe(seed, v6=True) + if not rec["v6"]["pushes"]: + continue + p0 = composer.compose(rec) + p1 = composer.compose(studio_engine.reroll(rec, "intro", "intro")) + s0, s1 = section_spans(p0), section_spans(p1) + if s0[0][2] - s0[0][1] == s1[0][2] - s1[0][1]: + continue + moved += 1 + for (sn, a0, b0), (_, a1, b1) in zip(s0[1:], s1[1:]): + for g in ("g1", "g2"): + self.assertTrue( + boundary_equal(section_notes(p0, g, a0, b0), section_notes(p1, g, a1, b1), b0 - a0), + (seed, sn, g), + ) + self.assertGreater(moved, 2) + + +class TestOptionsKeepLockedMaterial(unittest.TestCase): + def test_trailing_rest_off_keeps_a_valid_hook(self): + kw = dict(v8=True, meter="6/8", key="E", mode="lydian", tempo=150) + rec = plain_recipe(1, **kw) + expected = plain_recipe(1, notail=True, **kw) + off = studio_engine.set_option(rec, "trailing_rest", False) + piece, trace = traced(off) + L = composer.METERS["6/8"][0] + self.assertTrue(all(o < L for o in trace["hook"]["rhythm"]), trace["hook"]["rhythm"]) + self.assertEqual(trace["hook"]["rhythm"], expected["motifs"]["hook"]["rhythm"]) + for g in ("g1", "g2"): + self.assertTrue(all(n["dur"] > 0 for n in piece["parts"][g]), g) + + def test_trailing_rest_follows_the_recipe_version(self): + checked = 0 + for seed in range(0, 12): + with_tail = plain_recipe(seed, v8=True) + no_tail = plain_recipe(seed, v8=True, notail=True) + if with_tail["motifs"]["hook"] == no_tail["motifs"]["hook"]: + continue + st = studio_engine.set_lock(no_tail, "comp", "A", True) + self.assertFalse(st["studio"]["options"]["trailing_rest"], seed) + on = studio_engine.set_option(st, "trailing_rest", True) + self.assertEqual(traced(on)[1]["hook"]["rhythm"], with_tail["motifs"]["hook"]["rhythm"], seed) + self.assertEqual(piece_sha256(composer.compose(st)), piece_sha256(composer.compose(no_tail)), seed) + self.assertNotEqual(piece_sha256(composer.compose(on)), piece_sha256(composer.compose(st)), seed) + checked += 1 + self.assertGreater(checked, 3) + + def test_dose_edit_keeps_locked_comp_notes(self): + rec = studio_engine.new_recipe(0) + st = rec["studio"] + st["salts"]["comp@A"] = 1 + st["locks"] = ["comp@A"] + st["options"]["octave_piece"] = 1.0 + st.pop("comp_doses", None) + p0 = composer.compose(rec) + other = other_of(rec) + s0, e0 = span_of(p0, "A") + self.assertTrue([n for n in p0["parts"][other] if s0 <= n["start"] < e0 and n.get("dyad")]) + edited = studio_engine.set_option(rec, "octave_piece", 0.0) + p1 = composer.compose(edited) + self.assertEqual(section_notes(p0, other, s0, e0), section_notes(p1, other, *span_of(p1, "A"))) + + +class TestTempoAndVariants(unittest.TestCase): + def test_tempo_rolls_stay_within_the_range_of_the_current_tempo(self): + for seed in (2, 5, 11): + rec = studio_engine.new_recipe(seed) + prev = composer.compose(rec)["tempo"] + for _ in range(12): + rec = studio_engine.reroll(rec, "tempo", "all") + cur = composer.compose(rec)["tempo"] + lo = max(60, int(round(prev * 0.8))) + hi = min(220, int(round(prev * 1.1))) + self.assertTrue(lo <= cur <= hi, (seed, prev, cur)) + self.assertEqual(composer.compose(copy.deepcopy(rec))["tempo"], cur) + prev = cur + + def test_single_b_keeps_one_variant(self): + split_seen = False + for seed in range(0, 40): + rec = studio_engine.new_recipe(seed) + if "B" not in {b["sec"] for b in rec["form"]}: + continue + for k in range(1, 4): + rec["studio"]["salts"]["b@B"] = k + _, tr = traced(rec) + variants = {b["var"] for b in tr["form"] if b["sec"] == "B"} + if rec["arrange"]["template"] == "double_b": + split_seen = split_seen or len(variants) == 2 + else: + self.assertEqual(len(variants), 1, (seed, k, variants)) + self.assertTrue(split_seen) + + +class RecordingRender: + def __init__(self): + self.calls = 0 + self.fail = False + self.gate = None + self.entered = threading.Event() + + def __call__(self, mid_path, mp3_path): + self.calls += 1 + self.entered.set() + if self.gate is not None: + self.gate.wait(20) + if self.fail: + raise RuntimeError("render failed") + digest = hashlib.sha256(Path(mid_path).read_bytes()).hexdigest().encode() + Path(mp3_path).write_bytes(b"MP3:" + digest) + + +def mp3_matches_mid(testcase, pdir): + digest = hashlib.sha256((pdir / "piece.mid").read_bytes()).hexdigest().encode() + testcase.assertEqual((pdir / "piece.mp3").read_bytes(), b"MP3:" + digest) + + +def snapshot_files(pdir): + return {p.name: p.read_bytes() for p in sorted(pdir.iterdir()) if p.is_file()} + + +class TestStorePublishing(unittest.TestCase): + def test_failed_render_publishes_nothing(self): + with tempfile.TemporaryDirectory() as d: + render = RecordingRender() + store = studio_engine.StudioStore(d, render_fn=render) + pid = store.create_piece(801000)["id"] + pdir = Path(d) / pid + before = snapshot_files(pdir) + render.fail = True + with self.assertRaises(RuntimeError): + store.reroll(pid, "comp", "A") + self.assertEqual(snapshot_files(pdir), before) + self.assertEqual([p.name for p in pdir.iterdir() if p.is_dir()], []) + self.assertFalse(store.get_piece(pid)["can_undo"]) + render.fail = False + store.set_lock(pid, "comp", "A", True) + mp3_matches_mid(self, pdir) + calls = render.calls + store.reroll(pid, "texture", "A") + self.assertGreater(render.calls, calls) + mp3_matches_mid(self, pdir) + lines = (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() + self.assertEqual([json.loads(x)["action"] for x in lines], ["new", "lock", "reroll"]) + + def test_failed_undo_keeps_the_stack(self): + with tempfile.TemporaryDirectory() as d: + render = RecordingRender() + store = studio_engine.StudioStore(d, render_fn=render) + pid = store.create_piece(801000)["id"] + store.reroll(pid, "comp", "A") + store.reroll(pid, "lead_rhythm", "all") + pdir = Path(d) / pid + before = snapshot_files(pdir) + render.fail = True + with self.assertRaises(RuntimeError): + store.undo(pid) + self.assertEqual(snapshot_files(pdir), before) + render.fail = False + store.undo(pid) + store.undo(pid) + self.assertFalse(store.get_piece(pid)["can_undo"]) + mp3_matches_mid(self, pdir) + + def test_failed_create_leaves_no_piece(self): + with tempfile.TemporaryDirectory() as d: + render = RecordingRender() + render.fail = True + store = studio_engine.StudioStore(d, render_fn=render) + with self.assertRaises(RuntimeError): + store.create_piece(801000) + self.assertEqual(list(Path(d).iterdir()), []) + self.assertEqual(store.list_pieces(), []) + + def test_render_of_one_piece_does_not_block_reads_of_another(self): + with tempfile.TemporaryDirectory() as d: + render = RecordingRender() + store = studio_engine.StudioStore(d, render_fn=render) + a = store.create_piece(801000)["id"] + b = store.create_piece(802000)["id"] + render.gate = threading.Event() + render.entered.clear() + done = {} + + def mutate(key, fn): + done[key] = fn() + + t1 = threading.Thread(target=mutate, args=("first", lambda: store.reroll(a, "comp", "A"))) + t1.start() + self.assertTrue(render.entered.wait(10)) + results = {} + + def reads(): + results["b"] = store.get_piece(b) + results["b_audio"] = store.file_path(b, "piece.mp3") + results["a"] = store.get_piece(a) + results["a_audio"] = store.file_path(a, "piece.mp3") + results["list"] = store.list_pieces() + + t2 = threading.Thread(target=reads) + t2.start() + t2.join(5) + self.assertFalse(t2.is_alive(), "reads were blocked by a running render") + self.assertFalse(results["a"]["can_undo"]) + self.assertEqual(len(results["list"]), 2) + + t3 = threading.Thread(target=mutate, args=("second", lambda: store.reroll(a, "texture", "A"))) + t3.start() + t3.join(0.5) + self.assertTrue(t3.is_alive(), "writes to one piece must be serialized") + render.gate.set() + t1.join(20) + t3.join(20) + self.assertTrue(done["second"]["can_undo"]) + self.assertEqual(len(store._read_undo(store._piece_dir(a))), 2) + mp3_matches_mid(self, Path(d) / a) + + +def make_dir_link(link, target): + try: + link.symlink_to(target, target_is_directory=True) + return True + except (OSError, NotImplementedError): + pass + if sys.platform == "win32": + import subprocess + + r = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], capture_output=True) + return r.returncode == 0 + return False + + +class TestStoreContainment(unittest.TestCase): + def test_piece_directory_link_outside_out_is_refused(self): + with tempfile.TemporaryDirectory() as d, tempfile.TemporaryDirectory() as outside: + root = Path(d) / "out" + store = studio_engine.StudioStore(root, render_fn=studio_render.fake_render) + pid = store.create_piece(801000)["id"] + foreign = Path(outside) / "piece_x" + shutil.copytree(root / pid, foreign) + if not make_dir_link(root / "piece_link", foreign): + self.skipTest("cannot create directory links here") + for call in ( + lambda: store.get_piece("piece_link"), + lambda: store.file_path("piece_link", "piece.mid"), + lambda: store.reroll("piece_link", "comp", "A"), + lambda: store.undo("piece_link"), + ): + with self.assertRaises(KeyError): + call() + self.assertEqual([p["id"] for p in store.list_pieces()], [pid]) + self.assertEqual( + (foreign / "recipe.json").read_bytes(), (root / pid / "recipe.json").read_bytes() + ) + + def test_file_link_outside_piece_is_refused(self): + with tempfile.TemporaryDirectory() as d, tempfile.TemporaryDirectory() as outside: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + pid = store.create_piece(801000)["id"] + secret = Path(outside) / "secret.mid" + secret.write_bytes(b"MThd-secret") + target = Path(d) / pid / "piece.mid" + target.unlink() + try: + target.symlink_to(secret) + except (OSError, NotImplementedError): + self.skipTest("cannot create file symlinks here") + with self.assertRaises((KeyError, FileNotFoundError)): + store.file_path(pid, "piece.mid") + + +class TestRequestValidation(unittest.TestCase): + def _call(self, base, path, body=None, method="POST", raw=None): + data = raw if raw is not None else (None if body is None else json.dumps(body).encode("utf-8")) + req = urllib.request.Request( + base + path, data=data, method=method, headers={"Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(req, timeout=10) as resp: + return resp.status, json.loads(resp.read()) + except urllib.error.HTTPError as exc: + return exc.code, json.loads(exc.read()) + + def test_bad_requests_get_precise_codes(self): + with tempfile.TemporaryDirectory() as d: + srv = studio_server.create_server(d, host="127.0.0.1", port=0, render_fn=studio_render.fake_render) + threading.Thread(target=srv.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + try: + st, det = self._call(base, "/api/new", {"seed": 801000}) + self.assertEqual(st, 200) + pid = det["id"] + p = f"/api/piece/{pid}" + pdir = Path(d) / pid + before = snapshot_files(pdir) + cases = [ + ("/api/new", [], 400), + ("/api/new", "text", 400), + ("/api/new", {"seed": "7"}, 400), + ("/api/new", {"seed": True}, 400), + ("/api/new", {"seed": 1.5}, 400), + ("/api/new", {"seed": -3}, 400), + (p + "/reroll", {}, 400), + (p + "/reroll", {"layer": 3, "section": "A"}, 400), + (p + "/reroll", {"layer": "comp", "section": "B"}, 400), + (p + "/reroll", {"layer": "all", "section": "A"}, 400), + (p + "/lock", {"layer": "comp", "section": "A"}, 400), + (p + "/lock", {"layer": "comp", "section": "A", "locked": "false"}, 400), + (p + "/lock", {"layer": "comp", "section": "B", "locked": True}, 400), + (p + "/lock", {"layer": "all", "section": "all", "locked": True}, 400), + (p + "/option", {"name": "b_lead"}, 400), + (p + "/option", {"name": "nope", "value": 1}, 400), + (p + "/option", {"name": "b_lead", "value": "x"}, 400), + (p + "/option", {"name": "trailing_rest", "value": "false"}, 400), + (p + "/option", {"name": "octave_piece", "value": "0.5"}, 400), + (p + "/option", {"name": "octave_piece", "value": True}, 400), + (p + "/option", {"name": "slide_max", "value": 2.5}, 400), + ("/api/piece/missing/reroll", {"layer": "comp", "section": "A"}, 404), + ("/api/piece/missing/undo", {}, 404), + ("/api/nothing", {}, 404), + ] + for path, body, code in cases: + st, out = self._call(base, path, body) + self.assertEqual(st, code, (path, body, out)) + self.assertIn("error", out) + st, out = self._call(base, p + "/undo", raw=b"{not json") + self.assertEqual(st, 400) + st, out = self._call(base, p + "/undo", raw=b"x" * (1 << 20)) + self.assertEqual(st, 413) + self.assertEqual(snapshot_files(pdir), before) + st, out = self._call(base, p + "/reroll", {"layer": "all", "section": "all"}) + self.assertEqual(st, 200) + st, out = self._call(base, p + "/lock", {"layer": "comp", "section": "A", "locked": False}) + self.assertEqual(st, 200) + finally: + srv.shutdown() + srv.server_close() + + +class TestWslPaths(unittest.TestCase): + def test_conversion(self): + conv = studio_render.win_to_wsl_path + self.assertEqual(conv("C:\\Users\\me\\x.mid"), "/mnt/c/Users/me/x.mid") + self.assertEqual(conv("\\\\?\\C:\\Users\\me"), "/mnt/c/Users/me") + self.assertEqual(conv("\\\\wsl.localhost\\NixOS\\home\\me\\x"), "/home/me/x") + self.assertEqual(conv("\\\\wsl$\\NixOS\\home\\me"), "/home/me") + self.assertEqual(conv("\\\\wsl.localhost\\nixos"), "/") + with self.assertRaises(ValueError): + conv("\\\\wsl.localhost\\Ubuntu\\home\\me") + self.assertEqual(conv("/home/me/x"), "/home/me/x") + + +UI_HARNESS = r""" +const fs = require("fs"), vm = require("vm"); +const html = fs.readFileSync(process.argv[2], "utf8"); +const script = html.split("")[0]; +const pending = {}; +function el() { + return { classList: { toggle() {}, add() {}, remove() {} }, style: {}, dataset: {}, children: [], + appendChild(c) { this.children.push(c); }, addEventListener() {}, set innerHTML(v) {}, + get innerHTML() { return ""; }, set onclick(v) {}, value: "", currentTime: 0, + play() { return Promise.resolve(); } }; +} +const ctx = { + document: { getElementById: () => el(), createElement: () => el() }, + fetch: (url, opts) => new Promise((resolve) => { + const key = url + (opts && opts.method ? " " + opts.method : ""); + (pending[key] = pending[key] || []).push((body) => resolve({ ok: true, json: async () => body })); + }), + alert() {}, console, Date, Math, Number, String, Promise, encodeURIComponent, parseInt, parseFloat, +}; +vm.createContext(ctx); +vm.runInContext(script, ctx); +vm.runInContext("renderWorkspace = () => {}; renderList = () => {};", ctx); +const tick = () => new Promise((r) => setTimeout(r, 5)); +const piece = (id, seed) => ({ id, seed: seed || 1, sections: [], whole_layers: [], options: {}, length: 1 }); +const flushList = () => (pending["/api/pieces"] || []).splice(0).forEach((f) => f({ pieces: [] })); +const cur = (expr) => vm.runInContext(expr, ctx); +(async () => { + await tick(); + flushList(); + await tick(); + const out = {}; + cur("selectPiece('a'); selectPiece('b');"); + await tick(); + pending["/api/piece/b"].shift()(piece("b")); + await tick(); + pending["/api/piece/a"].shift()(piece("a")); + await tick(); + out.afterSelect = cur("state.current && state.current.id"); + cur("selectPiece('a')"); + await tick(); + pending["/api/piece/a"].shift()(piece("a")); + await tick(); + cur("mutate('/api/piece/a/reroll', {layer:'comp'}, 'a'); selectPiece('b');"); + await tick(); + pending["/api/piece/b"].shift()(piece("b")); + await tick(); + pending["/api/piece/a/reroll POST"].shift()(piece("a")); + await tick(); + flushList(); + await tick(); + out.afterMutate = cur("state.current && state.current.id"); + cur("mutate('/api/piece/b/undo', {}, 'b'); mutate('/api/piece/b/reroll', {}, 'b');"); + await tick(); + pending["/api/piece/b/reroll POST"].shift()(piece("b", 2)); + await tick(); + pending["/api/piece/b/undo POST"].shift()(piece("b", 1)); + await tick(); + flushList(); + await tick(); + out.latestSeed = cur("state.current.seed"); + console.log(JSON.stringify(out)); + process.exit(0); +})(); +""" + + +class TestStudioPage(unittest.TestCase): + def test_grid_does_not_overflow_a_narrow_viewport(self): + html = studio_server.INDEX_HTML.read_text(encoding="utf-8") + self.assertIn("minmax(min(100%, 260px), 1fr)", html) + self.assertNotIn("minmax(260px, 1fr)", html) + + def test_stale_responses_do_not_change_the_selection(self): + import subprocess + + node = shutil.which("node") + if node is None: + self.skipTest("node is not available") + with tempfile.TemporaryDirectory() as d: + harness = Path(d) / "harness.js" + harness.write_text(UI_HARNESS, encoding="utf-8") + res = subprocess.run( + [node, str(harness), str(studio_server.INDEX_HTML)], capture_output=True, text=True, timeout=60 + ) + self.assertEqual(res.returncode, 0, res.stderr) + out = json.loads(res.stdout.strip().splitlines()[-1]) + self.assertEqual(out["afterSelect"], "b") + self.assertEqual(out["afterMutate"], "b") + self.assertEqual(out["latestSeed"], 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/composer-lab/test_web_api.py b/composer-lab/test_web_api.py new file mode 100644 index 00000000..aef90ee8 --- /dev/null +++ b/composer-lab/test_web_api.py @@ -0,0 +1,358 @@ +import base64 +import copy +import importlib.util +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import composer +import midiio +import musicxml +from studio import engine as studio_engine +from studio import render as studio_render +from studio import summary as studio_summary + +try: + from studio import web_api +except ImportError: + web_api = None + + +class TestWebApi(unittest.TestCase): + def setUp(self): + if web_api is None: + self.fail("studio.web_api is not implemented yet") + + def test_events_match_engine_piece(self): + st = web_api.new_piece(801000) + evs = web_api.events(st) + + rec = studio_engine.new_recipe(801000) + piece = composer.compose(rec) + sec_per_tick = 15.0 / piece["tempo"] + expected = [] + for g_num, g in ((1, "g1"), (2, "g2")): + for n in piece["parts"][g]: + expected.append({ + "t": n["start"] * sec_per_tick, + "dur": n["dur"] * sec_per_tick, + "pitch": int(n["pitch"]), + "vel": int(max(30, min(127, n["vel"]))), + "guitar": g_num, + "dead": "dead" in n.get("tech", []), + }) + expected.sort(key=lambda e: (e["t"], e["guitar"], e["pitch"])) + + self.assertEqual(len(evs), len(expected)) + self.assertEqual([e["t"] for e in evs], sorted(e["t"] for e in evs)) + for actual, exp in zip(evs, expected): + self.assertAlmostEqual(actual["t"], exp["t"], places=9) + self.assertAlmostEqual(actual["dur"], exp["dur"], places=9) + self.assertEqual(actual["pitch"], exp["pitch"]) + self.assertEqual(actual["vel"], exp["vel"]) + self.assertEqual(actual["guitar"], exp["guitar"]) + self.assertEqual(actual["dead"], exp["dead"]) + + def test_fixed_sequence_matches_studio_store(self): + with tempfile.TemporaryDirectory() as d: + store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render) + det = store.create_piece(801000) + pid = det["id"] + store.reroll(pid, "comp", "A") + store.set_lock(pid, "b", "B", True) + store.set_option(pid, "b_lead", "same_speed") + store.reroll(pid, "all", "all") + store.undo(pid) + + st = web_api.new_piece(801000) + st = web_api.reroll(st, "comp", "A") + st = web_api.lock(st, "b", "B", True) + st = web_api.option(st, "b_lead", "same_speed") + st = web_api.reroll(st, "all", "all") + st = web_api.undo(st) + + pdir = Path(d) / pid + store_rec = json.loads((pdir / "recipe.json").read_text(encoding="utf-8")) + self.assertEqual(st["recipe"], store_rec) + self.assertEqual( + base64.b64decode(web_api.export_midi(st)), + (pdir / "piece.mid").read_bytes(), + ) + + def test_state_json_roundtrip(self): + def rt(obj): + return json.loads(json.dumps(obj)) + + st = rt(web_api.new_piece(801000)) + snap = copy.deepcopy(st) + + st1 = rt(web_api.reroll(st, "comp", "A")) + self.assertEqual(st, snap) + + st2 = rt(web_api.lock(st1, "b", "B", True)) + st3 = rt(web_api.option(st2, "b_lead", "same_speed")) + st4 = rt(web_api.reroll(st3, "all", "all")) + st5 = rt(web_api.undo(st4)) + + det = rt(web_api.detail(st5)) + evs = rt(web_api.events(st5)) + self.assertTrue(det["can_undo"]) + self.assertTrue(len(evs) > 0) + self.assertTrue(base64.b64decode(web_api.export_midi(st5)).startswith(b"MThd")) + self.assertIn(" 0 and len(m) > 0" + ) + res = subprocess.run( + [sys.executable, "-c", code], + cwd=str(Path(__file__).resolve().parent), + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(res.returncode, 0, res.stderr) + + +class TestReviewFixesPython(unittest.TestCase): + def _load_check_site(self): + path = Path(__file__).resolve().parent / "web" / "check_site.py" + spec = importlib.util.spec_from_file_location("check_site", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + def _make_minimal_web_dir(self, root: Path, samples_base="./samples/", py_base="./py/", sample_fname="p040_v072.mp3"): + root.mkdir(parents=True, exist_ok=True) + (root / "index.html").write_text('', encoding="utf-8") + (root / "app.js").write_text( + f'const SAMPLES_BASE = "{samples_base}";\nconst w = new Worker("./worker.js");\n', + encoding="utf-8", + ) + (root / "worker.js").write_text( + f'const PY_BASE = "{py_base}";\nconst PY_FILES = ["web_api.py"];\n', + encoding="utf-8", + ) + py_dir = root / "py" + py_dir.mkdir(parents=True, exist_ok=True) + (py_dir / "web_api.py").write_text("# stub\n", encoding="utf-8") + sdir = root / "samples" + sdir.mkdir(parents=True, exist_ok=True) + (sdir / "fsbs_LICENSE.txt").write_text("CC0", encoding="utf-8") + files_map = {} + for pitch in range(40, 89): + files_map[str(pitch)] = {"72": sample_fname, "100": sample_fname} + (sdir / sample_fname).write_bytes(b"MP3DATA") + (sdir / "manifest.json").write_text( + json.dumps({"license": "fsbs_LICENSE.txt", "files": files_map}), + encoding="utf-8", + ) + + def test_summary_accepts_downloaded_jsonl_file_grouped_by_piece_id(self): + rows = [ + {"t": "2026-11-23T00:00:00+00:00", "action": "new", "layer": None, "section": None, "salt": None, "value": 801000, "piece_id": "piece_1"}, + {"t": "2026-11-23T00:00:01+00:00", "action": "reroll", "layer": "comp", "section": "A", "salt": 1, "value": None, "piece_id": "piece_1"}, + {"t": "2026-11-23T00:00:02+00:00", "action": "new", "layer": None, "section": None, "salt": None, "value": 802000, "piece_id": "piece_2"}, + {"t": "2026-11-23T00:00:03+00:00", "action": "option", "layer": None, "section": None, "salt": None, "value": {"b_lead": "rest"}, "piece_id": "piece_2"}, + {"t": "2026-11-23T00:00:04+00:00", "action": "export", "layer": None, "section": None, "salt": None, "value": "piece.mid", "piece_id": "piece_1"}, + {"t": "2026-11-23T00:00:05+00:00", "action": "reroll", "layer": "b", "section": "B", "salt": 1, "value": None, "piece_id": "piece_2"}, + {"t": "2026-11-23T00:00:06+00:00", "action": "reroll", "layer": "tempo", "section": "all", "salt": 1, "value": None, "piece_id": "piece_2"}, + {"t": "2026-11-23T00:00:07+00:00", "action": "export", "layer": None, "section": None, "salt": None, "value": "piece.musicxml", "piece_id": "piece_2"}, + ] + with tempfile.TemporaryDirectory() as d: + jpath = Path(d) / "history.jsonl" + jpath.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + stats = studio_summary.summarize(jpath) + self.assertEqual(stats["pieces_total"], 2) + self.assertEqual(stats["pieces_exported"], 2) + self.assertEqual(stats["rerolls_before_first_export"], [1, 2]) + self.assertEqual(stats["rerolls_per_layer"], {"comp": 1, "b": 1, "tempo": 1}) + self.assertEqual(stats["options_used"], {"b_lead=rest": 1, "b_lead": 1}) + + def test_summary_directory_with_root_or_child_downloaded_jsonl(self): + rows = [ + {"t": "2026-11-23T00:00:00+00:00", "action": "reroll", "layer": "comp", "section": "A", "salt": 1, "value": None, "piece_id": "pA"}, + {"t": "2026-11-23T00:00:01+00:00", "action": "export", "layer": None, "section": None, "salt": None, "value": "piece.mid", "piece_id": "pA"}, + {"t": "2026-11-23T00:00:02+00:00", "action": "reroll", "layer": "b", "section": "B", "salt": 1, "value": None, "piece_id": "pB"}, + ] + text = "\n".join(json.dumps(r) for r in rows) + "\n" + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "history.jsonl").write_text(text, encoding="utf-8") + s_root = studio_summary.summarize(root) + self.assertEqual(s_root["pieces_total"], 2) + self.assertEqual(s_root["pieces_exported"], 1) + + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "web").mkdir() + (root / "web" / "history.jsonl").write_text(text, encoding="utf-8") + s_child = studio_summary.summarize(root) + self.assertEqual(s_child["pieces_total"], 2) + self.assertEqual(s_child["pieces_exported"], 1) + + def test_summary_preserves_per_piece_directory_layout(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "piece_1").mkdir() + (root / "piece_1" / "history.jsonl").write_text( + json.dumps({"t": "2026-11-23T00:00:00+00:00", "action": "reroll", "layer": "comp", "section": "A", "salt": 1, "value": None}) + "\n" + + json.dumps({"t": "2026-11-23T00:00:01+00:00", "action": "export", "layer": None, "section": None, "salt": None, "value": "piece.mid"}) + "\n", + encoding="utf-8", + ) + (root / "piece_2").mkdir() + (root / "piece_2" / "history.jsonl").write_text( + json.dumps({"t": "2026-11-23T00:00:02+00:00", "action": "new", "layer": None, "section": None, "salt": None, "value": 802000}) + "\n", + encoding="utf-8", + ) + stats = studio_summary.summarize(root) + self.assertEqual(stats["pieces_total"], 2) + self.assertEqual(stats["pieces_exported"], 1) + self.assertEqual(stats["rerolls_before_first_export"], [1]) + + def test_rejects_arbitrary_section_names_in_recipe_and_undo(self): + st = web_api.new_piece(801000) + bad = copy.deepcopy(st) + bad["recipe"]["form"][0]["sec"] = "" + for fn in (web_api.snapshot, web_api.detail, web_api.events): + with self.assertRaises(ValueError): + fn(bad) + + bad_undo = copy.deepcopy(st) + bad_undo_rec = copy.deepcopy(st["recipe"]) + bad_undo_rec["form"][0]["sec"] = "" + bad_undo["undo"] = [bad_undo_rec] + with self.assertRaises(ValueError): + web_api.snapshot(bad_undo) + + def test_rejects_invalid_piece_id(self): + st = web_api.new_piece(801000) + for bad_id in ("../bad", " + + +Griff Studio + + + +
+ +
+
Нажмите «Новая пьеса» или выберите готовую из списка.
+
+
+ + + diff --git a/composer-lab/web/samples/fsbs_LICENSE.txt b/composer-lab/web/samples/fsbs_LICENSE.txt new file mode 100644 index 00000000..0e259d42 --- /dev/null +++ b/composer-lab/web/samples/fsbs_LICENSE.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/composer-lab/web/samples/manifest.json b/composer-lab/web/samples/manifest.json new file mode 100644 index 00000000..c100b472 --- /dev/null +++ b/composer-lab/web/samples/manifest.json @@ -0,0 +1,207 @@ +{ + "min_pitch": 40, + "max_pitch": 88, + "velocities": [72, 100], + "duration_sec": 2.5, + "sample_rate": 44100, + "bitrate_kbps": 96, + "license": "fsbs_LICENSE.txt", + "files": { + "40": { + "72": "p040_v072.mp3", + "100": "p040_v100.mp3" + }, + "41": { + "72": "p041_v072.mp3", + "100": "p041_v100.mp3" + }, + "42": { + "72": "p042_v072.mp3", + "100": "p042_v100.mp3" + }, + "43": { + "72": "p043_v072.mp3", + "100": "p043_v100.mp3" + }, + "44": { + "72": "p044_v072.mp3", + "100": "p044_v100.mp3" + }, + "45": { + "72": "p045_v072.mp3", + "100": "p045_v100.mp3" + }, + "46": { + "72": "p046_v072.mp3", + "100": "p046_v100.mp3" + }, + "47": { + "72": "p047_v072.mp3", + "100": "p047_v100.mp3" + }, + "48": { + "72": "p048_v072.mp3", + "100": "p048_v100.mp3" + }, + "49": { + "72": "p049_v072.mp3", + "100": "p049_v100.mp3" + }, + "50": { + "72": "p050_v072.mp3", + "100": "p050_v100.mp3" + }, + "51": { + "72": "p051_v072.mp3", + "100": "p051_v100.mp3" + }, + "52": { + "72": "p052_v072.mp3", + "100": "p052_v100.mp3" + }, + "53": { + "72": "p053_v072.mp3", + "100": "p053_v100.mp3" + }, + "54": { + "72": "p054_v072.mp3", + "100": "p054_v100.mp3" + }, + "55": { + "72": "p055_v072.mp3", + "100": "p055_v100.mp3" + }, + "56": { + "72": "p056_v072.mp3", + "100": "p056_v100.mp3" + }, + "57": { + "72": "p057_v072.mp3", + "100": "p057_v100.mp3" + }, + "58": { + "72": "p058_v072.mp3", + "100": "p058_v100.mp3" + }, + "59": { + "72": "p059_v072.mp3", + "100": "p059_v100.mp3" + }, + "60": { + "72": "p060_v072.mp3", + "100": "p060_v100.mp3" + }, + "61": { + "72": "p061_v072.mp3", + "100": "p061_v100.mp3" + }, + "62": { + "72": "p062_v072.mp3", + "100": "p062_v100.mp3" + }, + "63": { + "72": "p063_v072.mp3", + "100": "p063_v100.mp3" + }, + "64": { + "72": "p064_v072.mp3", + "100": "p064_v100.mp3" + }, + "65": { + "72": "p065_v072.mp3", + "100": "p065_v100.mp3" + }, + "66": { + "72": "p066_v072.mp3", + "100": "p066_v100.mp3" + }, + "67": { + "72": "p067_v072.mp3", + "100": "p067_v100.mp3" + }, + "68": { + "72": "p068_v072.mp3", + "100": "p068_v100.mp3" + }, + "69": { + "72": "p069_v072.mp3", + "100": "p069_v100.mp3" + }, + "70": { + "72": "p070_v072.mp3", + "100": "p070_v100.mp3" + }, + "71": { + "72": "p071_v072.mp3", + "100": "p071_v100.mp3" + }, + "72": { + "72": "p072_v072.mp3", + "100": "p072_v100.mp3" + }, + "73": { + "72": "p073_v072.mp3", + "100": "p073_v100.mp3" + }, + "74": { + "72": "p074_v072.mp3", + "100": "p074_v100.mp3" + }, + "75": { + "72": "p075_v072.mp3", + "100": "p075_v100.mp3" + }, + "76": { + "72": "p076_v072.mp3", + "100": "p076_v100.mp3" + }, + "77": { + "72": "p077_v072.mp3", + "100": "p077_v100.mp3" + }, + "78": { + "72": "p078_v072.mp3", + "100": "p078_v100.mp3" + }, + "79": { + "72": "p079_v072.mp3", + "100": "p079_v100.mp3" + }, + "80": { + "72": "p080_v072.mp3", + "100": "p080_v100.mp3" + }, + "81": { + "72": "p081_v072.mp3", + "100": "p081_v100.mp3" + }, + "82": { + "72": "p082_v072.mp3", + "100": "p082_v100.mp3" + }, + "83": { + "72": "p083_v072.mp3", + "100": "p083_v100.mp3" + }, + "84": { + "72": "p084_v072.mp3", + "100": "p084_v100.mp3" + }, + "85": { + "72": "p085_v072.mp3", + "100": "p085_v100.mp3" + }, + "86": { + "72": "p086_v072.mp3", + "100": "p086_v100.mp3" + }, + "87": { + "72": "p087_v072.mp3", + "100": "p087_v100.mp3" + }, + "88": { + "72": "p088_v072.mp3", + "100": "p088_v100.mp3" + } + } +} diff --git a/composer-lab/web/samples/p040_v072.mp3 b/composer-lab/web/samples/p040_v072.mp3 new file mode 100644 index 00000000..249bc8ce Binary files /dev/null and b/composer-lab/web/samples/p040_v072.mp3 differ diff --git a/composer-lab/web/samples/p040_v100.mp3 b/composer-lab/web/samples/p040_v100.mp3 new file mode 100644 index 00000000..4b00c536 Binary files /dev/null and b/composer-lab/web/samples/p040_v100.mp3 differ diff --git a/composer-lab/web/samples/p041_v072.mp3 b/composer-lab/web/samples/p041_v072.mp3 new file mode 100644 index 00000000..d7b3f1a8 Binary files /dev/null and b/composer-lab/web/samples/p041_v072.mp3 differ diff --git a/composer-lab/web/samples/p041_v100.mp3 b/composer-lab/web/samples/p041_v100.mp3 new file mode 100644 index 00000000..8172b87b Binary files /dev/null and b/composer-lab/web/samples/p041_v100.mp3 differ diff --git a/composer-lab/web/samples/p042_v072.mp3 b/composer-lab/web/samples/p042_v072.mp3 new file mode 100644 index 00000000..e81cd714 Binary files /dev/null and b/composer-lab/web/samples/p042_v072.mp3 differ diff --git a/composer-lab/web/samples/p042_v100.mp3 b/composer-lab/web/samples/p042_v100.mp3 new file mode 100644 index 00000000..8f54fb0e Binary files /dev/null and b/composer-lab/web/samples/p042_v100.mp3 differ diff --git a/composer-lab/web/samples/p043_v072.mp3 b/composer-lab/web/samples/p043_v072.mp3 new file mode 100644 index 00000000..79895ee5 Binary files /dev/null and b/composer-lab/web/samples/p043_v072.mp3 differ diff --git a/composer-lab/web/samples/p043_v100.mp3 b/composer-lab/web/samples/p043_v100.mp3 new file mode 100644 index 00000000..67e3d2cf Binary files /dev/null and b/composer-lab/web/samples/p043_v100.mp3 differ diff --git a/composer-lab/web/samples/p044_v072.mp3 b/composer-lab/web/samples/p044_v072.mp3 new file mode 100644 index 00000000..21840242 Binary files /dev/null and b/composer-lab/web/samples/p044_v072.mp3 differ diff --git a/composer-lab/web/samples/p044_v100.mp3 b/composer-lab/web/samples/p044_v100.mp3 new file mode 100644 index 00000000..e5720099 Binary files /dev/null and b/composer-lab/web/samples/p044_v100.mp3 differ diff --git a/composer-lab/web/samples/p045_v072.mp3 b/composer-lab/web/samples/p045_v072.mp3 new file mode 100644 index 00000000..8f5901c6 Binary files /dev/null and b/composer-lab/web/samples/p045_v072.mp3 differ diff --git a/composer-lab/web/samples/p045_v100.mp3 b/composer-lab/web/samples/p045_v100.mp3 new file mode 100644 index 00000000..7234c8ad Binary files /dev/null and b/composer-lab/web/samples/p045_v100.mp3 differ diff --git a/composer-lab/web/samples/p046_v072.mp3 b/composer-lab/web/samples/p046_v072.mp3 new file mode 100644 index 00000000..9280503d Binary files /dev/null and b/composer-lab/web/samples/p046_v072.mp3 differ diff --git a/composer-lab/web/samples/p046_v100.mp3 b/composer-lab/web/samples/p046_v100.mp3 new file mode 100644 index 00000000..99732e48 Binary files /dev/null and b/composer-lab/web/samples/p046_v100.mp3 differ diff --git a/composer-lab/web/samples/p047_v072.mp3 b/composer-lab/web/samples/p047_v072.mp3 new file mode 100644 index 00000000..2a96fe9b Binary files /dev/null and b/composer-lab/web/samples/p047_v072.mp3 differ diff --git a/composer-lab/web/samples/p047_v100.mp3 b/composer-lab/web/samples/p047_v100.mp3 new file mode 100644 index 00000000..5883dc71 Binary files /dev/null and b/composer-lab/web/samples/p047_v100.mp3 differ diff --git a/composer-lab/web/samples/p048_v072.mp3 b/composer-lab/web/samples/p048_v072.mp3 new file mode 100644 index 00000000..d25a8e24 Binary files /dev/null and b/composer-lab/web/samples/p048_v072.mp3 differ diff --git a/composer-lab/web/samples/p048_v100.mp3 b/composer-lab/web/samples/p048_v100.mp3 new file mode 100644 index 00000000..33d41080 Binary files /dev/null and b/composer-lab/web/samples/p048_v100.mp3 differ diff --git a/composer-lab/web/samples/p049_v072.mp3 b/composer-lab/web/samples/p049_v072.mp3 new file mode 100644 index 00000000..4ca67e43 Binary files /dev/null and b/composer-lab/web/samples/p049_v072.mp3 differ diff --git a/composer-lab/web/samples/p049_v100.mp3 b/composer-lab/web/samples/p049_v100.mp3 new file mode 100644 index 00000000..aaaa4fde Binary files /dev/null and b/composer-lab/web/samples/p049_v100.mp3 differ diff --git a/composer-lab/web/samples/p050_v072.mp3 b/composer-lab/web/samples/p050_v072.mp3 new file mode 100644 index 00000000..4314127b Binary files /dev/null and b/composer-lab/web/samples/p050_v072.mp3 differ diff --git a/composer-lab/web/samples/p050_v100.mp3 b/composer-lab/web/samples/p050_v100.mp3 new file mode 100644 index 00000000..52b9d87a Binary files /dev/null and b/composer-lab/web/samples/p050_v100.mp3 differ diff --git a/composer-lab/web/samples/p051_v072.mp3 b/composer-lab/web/samples/p051_v072.mp3 new file mode 100644 index 00000000..bf11a0cc Binary files /dev/null and b/composer-lab/web/samples/p051_v072.mp3 differ diff --git a/composer-lab/web/samples/p051_v100.mp3 b/composer-lab/web/samples/p051_v100.mp3 new file mode 100644 index 00000000..b8ac65ce Binary files /dev/null and b/composer-lab/web/samples/p051_v100.mp3 differ diff --git a/composer-lab/web/samples/p052_v072.mp3 b/composer-lab/web/samples/p052_v072.mp3 new file mode 100644 index 00000000..2a1d996b Binary files /dev/null and b/composer-lab/web/samples/p052_v072.mp3 differ diff --git a/composer-lab/web/samples/p052_v100.mp3 b/composer-lab/web/samples/p052_v100.mp3 new file mode 100644 index 00000000..8659373d Binary files /dev/null and b/composer-lab/web/samples/p052_v100.mp3 differ diff --git a/composer-lab/web/samples/p053_v072.mp3 b/composer-lab/web/samples/p053_v072.mp3 new file mode 100644 index 00000000..5b86dea1 Binary files /dev/null and b/composer-lab/web/samples/p053_v072.mp3 differ diff --git a/composer-lab/web/samples/p053_v100.mp3 b/composer-lab/web/samples/p053_v100.mp3 new file mode 100644 index 00000000..e6fe0abe Binary files /dev/null and b/composer-lab/web/samples/p053_v100.mp3 differ diff --git a/composer-lab/web/samples/p054_v072.mp3 b/composer-lab/web/samples/p054_v072.mp3 new file mode 100644 index 00000000..b06ce86f Binary files /dev/null and b/composer-lab/web/samples/p054_v072.mp3 differ diff --git a/composer-lab/web/samples/p054_v100.mp3 b/composer-lab/web/samples/p054_v100.mp3 new file mode 100644 index 00000000..2c6b8df4 Binary files /dev/null and b/composer-lab/web/samples/p054_v100.mp3 differ diff --git a/composer-lab/web/samples/p055_v072.mp3 b/composer-lab/web/samples/p055_v072.mp3 new file mode 100644 index 00000000..ef7ebf23 Binary files /dev/null and b/composer-lab/web/samples/p055_v072.mp3 differ diff --git a/composer-lab/web/samples/p055_v100.mp3 b/composer-lab/web/samples/p055_v100.mp3 new file mode 100644 index 00000000..b9ab421e Binary files /dev/null and b/composer-lab/web/samples/p055_v100.mp3 differ diff --git a/composer-lab/web/samples/p056_v072.mp3 b/composer-lab/web/samples/p056_v072.mp3 new file mode 100644 index 00000000..f7c32f53 Binary files /dev/null and b/composer-lab/web/samples/p056_v072.mp3 differ diff --git a/composer-lab/web/samples/p056_v100.mp3 b/composer-lab/web/samples/p056_v100.mp3 new file mode 100644 index 00000000..09ad3a01 Binary files /dev/null and b/composer-lab/web/samples/p056_v100.mp3 differ diff --git a/composer-lab/web/samples/p057_v072.mp3 b/composer-lab/web/samples/p057_v072.mp3 new file mode 100644 index 00000000..f2c93894 Binary files /dev/null and b/composer-lab/web/samples/p057_v072.mp3 differ diff --git a/composer-lab/web/samples/p057_v100.mp3 b/composer-lab/web/samples/p057_v100.mp3 new file mode 100644 index 00000000..9a2cf1ad Binary files /dev/null and b/composer-lab/web/samples/p057_v100.mp3 differ diff --git a/composer-lab/web/samples/p058_v072.mp3 b/composer-lab/web/samples/p058_v072.mp3 new file mode 100644 index 00000000..1f31d785 Binary files /dev/null and b/composer-lab/web/samples/p058_v072.mp3 differ diff --git a/composer-lab/web/samples/p058_v100.mp3 b/composer-lab/web/samples/p058_v100.mp3 new file mode 100644 index 00000000..2d5deaab Binary files /dev/null and b/composer-lab/web/samples/p058_v100.mp3 differ diff --git a/composer-lab/web/samples/p059_v072.mp3 b/composer-lab/web/samples/p059_v072.mp3 new file mode 100644 index 00000000..a6b2f61a Binary files /dev/null and b/composer-lab/web/samples/p059_v072.mp3 differ diff --git a/composer-lab/web/samples/p059_v100.mp3 b/composer-lab/web/samples/p059_v100.mp3 new file mode 100644 index 00000000..46ec79c5 Binary files /dev/null and b/composer-lab/web/samples/p059_v100.mp3 differ diff --git a/composer-lab/web/samples/p060_v072.mp3 b/composer-lab/web/samples/p060_v072.mp3 new file mode 100644 index 00000000..47dfcaa5 Binary files /dev/null and b/composer-lab/web/samples/p060_v072.mp3 differ diff --git a/composer-lab/web/samples/p060_v100.mp3 b/composer-lab/web/samples/p060_v100.mp3 new file mode 100644 index 00000000..0e23e788 Binary files /dev/null and b/composer-lab/web/samples/p060_v100.mp3 differ diff --git a/composer-lab/web/samples/p061_v072.mp3 b/composer-lab/web/samples/p061_v072.mp3 new file mode 100644 index 00000000..c8419647 Binary files /dev/null and b/composer-lab/web/samples/p061_v072.mp3 differ diff --git a/composer-lab/web/samples/p061_v100.mp3 b/composer-lab/web/samples/p061_v100.mp3 new file mode 100644 index 00000000..9f3ef545 Binary files /dev/null and b/composer-lab/web/samples/p061_v100.mp3 differ diff --git a/composer-lab/web/samples/p062_v072.mp3 b/composer-lab/web/samples/p062_v072.mp3 new file mode 100644 index 00000000..331436a1 Binary files /dev/null and b/composer-lab/web/samples/p062_v072.mp3 differ diff --git a/composer-lab/web/samples/p062_v100.mp3 b/composer-lab/web/samples/p062_v100.mp3 new file mode 100644 index 00000000..505c77cc Binary files /dev/null and b/composer-lab/web/samples/p062_v100.mp3 differ diff --git a/composer-lab/web/samples/p063_v072.mp3 b/composer-lab/web/samples/p063_v072.mp3 new file mode 100644 index 00000000..722f23c3 Binary files /dev/null and b/composer-lab/web/samples/p063_v072.mp3 differ diff --git a/composer-lab/web/samples/p063_v100.mp3 b/composer-lab/web/samples/p063_v100.mp3 new file mode 100644 index 00000000..56088051 Binary files /dev/null and b/composer-lab/web/samples/p063_v100.mp3 differ diff --git a/composer-lab/web/samples/p064_v072.mp3 b/composer-lab/web/samples/p064_v072.mp3 new file mode 100644 index 00000000..118ffaa5 Binary files /dev/null and b/composer-lab/web/samples/p064_v072.mp3 differ diff --git a/composer-lab/web/samples/p064_v100.mp3 b/composer-lab/web/samples/p064_v100.mp3 new file mode 100644 index 00000000..6ca32bfa Binary files /dev/null and b/composer-lab/web/samples/p064_v100.mp3 differ diff --git a/composer-lab/web/samples/p065_v072.mp3 b/composer-lab/web/samples/p065_v072.mp3 new file mode 100644 index 00000000..f91d9127 Binary files /dev/null and b/composer-lab/web/samples/p065_v072.mp3 differ diff --git a/composer-lab/web/samples/p065_v100.mp3 b/composer-lab/web/samples/p065_v100.mp3 new file mode 100644 index 00000000..15bdb480 Binary files /dev/null and b/composer-lab/web/samples/p065_v100.mp3 differ diff --git a/composer-lab/web/samples/p066_v072.mp3 b/composer-lab/web/samples/p066_v072.mp3 new file mode 100644 index 00000000..6971844e Binary files /dev/null and b/composer-lab/web/samples/p066_v072.mp3 differ diff --git a/composer-lab/web/samples/p066_v100.mp3 b/composer-lab/web/samples/p066_v100.mp3 new file mode 100644 index 00000000..31ff76e0 Binary files /dev/null and b/composer-lab/web/samples/p066_v100.mp3 differ diff --git a/composer-lab/web/samples/p067_v072.mp3 b/composer-lab/web/samples/p067_v072.mp3 new file mode 100644 index 00000000..2a2ed91a Binary files /dev/null and b/composer-lab/web/samples/p067_v072.mp3 differ diff --git a/composer-lab/web/samples/p067_v100.mp3 b/composer-lab/web/samples/p067_v100.mp3 new file mode 100644 index 00000000..0968902e Binary files /dev/null and b/composer-lab/web/samples/p067_v100.mp3 differ diff --git a/composer-lab/web/samples/p068_v072.mp3 b/composer-lab/web/samples/p068_v072.mp3 new file mode 100644 index 00000000..127aff0e Binary files /dev/null and b/composer-lab/web/samples/p068_v072.mp3 differ diff --git a/composer-lab/web/samples/p068_v100.mp3 b/composer-lab/web/samples/p068_v100.mp3 new file mode 100644 index 00000000..a1a6f756 Binary files /dev/null and b/composer-lab/web/samples/p068_v100.mp3 differ diff --git a/composer-lab/web/samples/p069_v072.mp3 b/composer-lab/web/samples/p069_v072.mp3 new file mode 100644 index 00000000..ab5ac01b Binary files /dev/null and b/composer-lab/web/samples/p069_v072.mp3 differ diff --git a/composer-lab/web/samples/p069_v100.mp3 b/composer-lab/web/samples/p069_v100.mp3 new file mode 100644 index 00000000..dca72cb0 Binary files /dev/null and b/composer-lab/web/samples/p069_v100.mp3 differ diff --git a/composer-lab/web/samples/p070_v072.mp3 b/composer-lab/web/samples/p070_v072.mp3 new file mode 100644 index 00000000..3d212c2c Binary files /dev/null and b/composer-lab/web/samples/p070_v072.mp3 differ diff --git a/composer-lab/web/samples/p070_v100.mp3 b/composer-lab/web/samples/p070_v100.mp3 new file mode 100644 index 00000000..6b998c81 Binary files /dev/null and b/composer-lab/web/samples/p070_v100.mp3 differ diff --git a/composer-lab/web/samples/p071_v072.mp3 b/composer-lab/web/samples/p071_v072.mp3 new file mode 100644 index 00000000..cd27d4ec Binary files /dev/null and b/composer-lab/web/samples/p071_v072.mp3 differ diff --git a/composer-lab/web/samples/p071_v100.mp3 b/composer-lab/web/samples/p071_v100.mp3 new file mode 100644 index 00000000..c3cf3772 Binary files /dev/null and b/composer-lab/web/samples/p071_v100.mp3 differ diff --git a/composer-lab/web/samples/p072_v072.mp3 b/composer-lab/web/samples/p072_v072.mp3 new file mode 100644 index 00000000..c2ffacab Binary files /dev/null and b/composer-lab/web/samples/p072_v072.mp3 differ diff --git a/composer-lab/web/samples/p072_v100.mp3 b/composer-lab/web/samples/p072_v100.mp3 new file mode 100644 index 00000000..2ad3976c Binary files /dev/null and b/composer-lab/web/samples/p072_v100.mp3 differ diff --git a/composer-lab/web/samples/p073_v072.mp3 b/composer-lab/web/samples/p073_v072.mp3 new file mode 100644 index 00000000..5143c9ec Binary files /dev/null and b/composer-lab/web/samples/p073_v072.mp3 differ diff --git a/composer-lab/web/samples/p073_v100.mp3 b/composer-lab/web/samples/p073_v100.mp3 new file mode 100644 index 00000000..410e4b6f Binary files /dev/null and b/composer-lab/web/samples/p073_v100.mp3 differ diff --git a/composer-lab/web/samples/p074_v072.mp3 b/composer-lab/web/samples/p074_v072.mp3 new file mode 100644 index 00000000..8c777839 Binary files /dev/null and b/composer-lab/web/samples/p074_v072.mp3 differ diff --git a/composer-lab/web/samples/p074_v100.mp3 b/composer-lab/web/samples/p074_v100.mp3 new file mode 100644 index 00000000..720afe1c Binary files /dev/null and b/composer-lab/web/samples/p074_v100.mp3 differ diff --git a/composer-lab/web/samples/p075_v072.mp3 b/composer-lab/web/samples/p075_v072.mp3 new file mode 100644 index 00000000..c24c1e9e Binary files /dev/null and b/composer-lab/web/samples/p075_v072.mp3 differ diff --git a/composer-lab/web/samples/p075_v100.mp3 b/composer-lab/web/samples/p075_v100.mp3 new file mode 100644 index 00000000..5dc85997 Binary files /dev/null and b/composer-lab/web/samples/p075_v100.mp3 differ diff --git a/composer-lab/web/samples/p076_v072.mp3 b/composer-lab/web/samples/p076_v072.mp3 new file mode 100644 index 00000000..094eb7c1 Binary files /dev/null and b/composer-lab/web/samples/p076_v072.mp3 differ diff --git a/composer-lab/web/samples/p076_v100.mp3 b/composer-lab/web/samples/p076_v100.mp3 new file mode 100644 index 00000000..f40c8d30 Binary files /dev/null and b/composer-lab/web/samples/p076_v100.mp3 differ diff --git a/composer-lab/web/samples/p077_v072.mp3 b/composer-lab/web/samples/p077_v072.mp3 new file mode 100644 index 00000000..f4a9e5aa Binary files /dev/null and b/composer-lab/web/samples/p077_v072.mp3 differ diff --git a/composer-lab/web/samples/p077_v100.mp3 b/composer-lab/web/samples/p077_v100.mp3 new file mode 100644 index 00000000..984c4ba5 Binary files /dev/null and b/composer-lab/web/samples/p077_v100.mp3 differ diff --git a/composer-lab/web/samples/p078_v072.mp3 b/composer-lab/web/samples/p078_v072.mp3 new file mode 100644 index 00000000..284b9f3d Binary files /dev/null and b/composer-lab/web/samples/p078_v072.mp3 differ diff --git a/composer-lab/web/samples/p078_v100.mp3 b/composer-lab/web/samples/p078_v100.mp3 new file mode 100644 index 00000000..230b9568 Binary files /dev/null and b/composer-lab/web/samples/p078_v100.mp3 differ diff --git a/composer-lab/web/samples/p079_v072.mp3 b/composer-lab/web/samples/p079_v072.mp3 new file mode 100644 index 00000000..38b176de Binary files /dev/null and b/composer-lab/web/samples/p079_v072.mp3 differ diff --git a/composer-lab/web/samples/p079_v100.mp3 b/composer-lab/web/samples/p079_v100.mp3 new file mode 100644 index 00000000..039ae147 Binary files /dev/null and b/composer-lab/web/samples/p079_v100.mp3 differ diff --git a/composer-lab/web/samples/p080_v072.mp3 b/composer-lab/web/samples/p080_v072.mp3 new file mode 100644 index 00000000..3a0a8817 Binary files /dev/null and b/composer-lab/web/samples/p080_v072.mp3 differ diff --git a/composer-lab/web/samples/p080_v100.mp3 b/composer-lab/web/samples/p080_v100.mp3 new file mode 100644 index 00000000..43e0740a Binary files /dev/null and b/composer-lab/web/samples/p080_v100.mp3 differ diff --git a/composer-lab/web/samples/p081_v072.mp3 b/composer-lab/web/samples/p081_v072.mp3 new file mode 100644 index 00000000..f84fc53b Binary files /dev/null and b/composer-lab/web/samples/p081_v072.mp3 differ diff --git a/composer-lab/web/samples/p081_v100.mp3 b/composer-lab/web/samples/p081_v100.mp3 new file mode 100644 index 00000000..a87a2880 Binary files /dev/null and b/composer-lab/web/samples/p081_v100.mp3 differ diff --git a/composer-lab/web/samples/p082_v072.mp3 b/composer-lab/web/samples/p082_v072.mp3 new file mode 100644 index 00000000..864c1cb5 Binary files /dev/null and b/composer-lab/web/samples/p082_v072.mp3 differ diff --git a/composer-lab/web/samples/p082_v100.mp3 b/composer-lab/web/samples/p082_v100.mp3 new file mode 100644 index 00000000..c14bfca4 Binary files /dev/null and b/composer-lab/web/samples/p082_v100.mp3 differ diff --git a/composer-lab/web/samples/p083_v072.mp3 b/composer-lab/web/samples/p083_v072.mp3 new file mode 100644 index 00000000..9f37711d Binary files /dev/null and b/composer-lab/web/samples/p083_v072.mp3 differ diff --git a/composer-lab/web/samples/p083_v100.mp3 b/composer-lab/web/samples/p083_v100.mp3 new file mode 100644 index 00000000..504c2811 Binary files /dev/null and b/composer-lab/web/samples/p083_v100.mp3 differ diff --git a/composer-lab/web/samples/p084_v072.mp3 b/composer-lab/web/samples/p084_v072.mp3 new file mode 100644 index 00000000..4dc289c4 Binary files /dev/null and b/composer-lab/web/samples/p084_v072.mp3 differ diff --git a/composer-lab/web/samples/p084_v100.mp3 b/composer-lab/web/samples/p084_v100.mp3 new file mode 100644 index 00000000..13cd4580 Binary files /dev/null and b/composer-lab/web/samples/p084_v100.mp3 differ diff --git a/composer-lab/web/samples/p085_v072.mp3 b/composer-lab/web/samples/p085_v072.mp3 new file mode 100644 index 00000000..bfefc131 Binary files /dev/null and b/composer-lab/web/samples/p085_v072.mp3 differ diff --git a/composer-lab/web/samples/p085_v100.mp3 b/composer-lab/web/samples/p085_v100.mp3 new file mode 100644 index 00000000..486ba3f9 Binary files /dev/null and b/composer-lab/web/samples/p085_v100.mp3 differ diff --git a/composer-lab/web/samples/p086_v072.mp3 b/composer-lab/web/samples/p086_v072.mp3 new file mode 100644 index 00000000..eb91150f Binary files /dev/null and b/composer-lab/web/samples/p086_v072.mp3 differ diff --git a/composer-lab/web/samples/p086_v100.mp3 b/composer-lab/web/samples/p086_v100.mp3 new file mode 100644 index 00000000..9f92386e Binary files /dev/null and b/composer-lab/web/samples/p086_v100.mp3 differ diff --git a/composer-lab/web/samples/p087_v072.mp3 b/composer-lab/web/samples/p087_v072.mp3 new file mode 100644 index 00000000..4a0f3532 Binary files /dev/null and b/composer-lab/web/samples/p087_v072.mp3 differ diff --git a/composer-lab/web/samples/p087_v100.mp3 b/composer-lab/web/samples/p087_v100.mp3 new file mode 100644 index 00000000..402511ee Binary files /dev/null and b/composer-lab/web/samples/p087_v100.mp3 differ diff --git a/composer-lab/web/samples/p088_v072.mp3 b/composer-lab/web/samples/p088_v072.mp3 new file mode 100644 index 00000000..53204bff Binary files /dev/null and b/composer-lab/web/samples/p088_v072.mp3 differ diff --git a/composer-lab/web/samples/p088_v100.mp3 b/composer-lab/web/samples/p088_v100.mp3 new file mode 100644 index 00000000..62a4c7cc Binary files /dev/null and b/composer-lab/web/samples/p088_v100.mp3 differ diff --git a/composer-lab/web/tests/harness.js b/composer-lab/web/tests/harness.js new file mode 100644 index 00000000..59650170 --- /dev/null +++ b/composer-lab/web/tests/harness.js @@ -0,0 +1,911 @@ +import fs from "node:fs"; +import path from "node:path"; +import vm from "node:vm"; +import { fileURLToPath } from "node:url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const WEB_DIR = path.resolve(__dirname, ".."); + +function deepClone(v) { + return v === undefined ? undefined : JSON.parse(JSON.stringify(v)); +} + +function makeFakeState(seed = 801000, overrides = {}) { + const recipe = { + seed, + intent: { + meter: "4/4", + grouping: [4, 4, 4, 4], + mode: "lydian", + tonic: "E", + tempo: 140, + b_meter: "4/4", + b_grouping: [4, 4, 4, 4], + lead: "g1", + intro_bars: 1, + }, + form: [ + { sec: "intro", chord: 0, prog: "intro" }, + { sec: "A", chord: 0, prog: "stmt", role: "chords" }, + { sec: "B", chord: 3, prog: "b1" }, + { sec: "end", chord: 0, prog: "end" }, + ], + studio: { + salts: {}, + locks: [], + options: { + b_lead: "augmented", + trailing_rest: true, + octave_piece: 0.25, + octave_sixteenths: 0.3, + dead_notes: 0.2, + slide_max: 5, + }, + comp_doses: {}, + }, + }; + return { + id: `piece_${seed}`, + recipe, + undo: [], + ...overrides, + }; +} + +function buildDetailFromState(st, sectionLabels = {}) { + const rec = st.recipe; + const salts = (rec.studio && rec.studio.salts) || {}; + const locks = new Set((rec.studio && rec.studio.locks) || []); + const opts = (rec.studio && rec.studio.options) || {}; + const defaultLabels = { + intro: "Вступление", + A: "Куплет A", + A2: "Куплет A2", + B: "Середина B", + A3: "Кульминация", + end: "Концовка", + }; + const secsSeen = []; + for (const bar of rec.form || []) { + if (!secsSeen.includes(bar.sec)) secsSeen.push(bar.sec); + } + const sections = secsSeen.map((sec, idx) => { + const layers = []; + if (sec === "A" || sec === "A2") { + const k = `comp@${sec}`; + layers.push({ + layer: "comp", + section: sec, + label: "Перегенерировать ритм-гитару", + salt: Number(salts[k] || 0), + locked: locks.has(k), + }); + } else if (sec === "B") { + const k = "b@B"; + layers.push({ + layer: "b", + section: "B", + label: "Вариант середины", + salt: Number(salts[k] || 0), + locked: locks.has(k), + }); + } + return { + section: sec, + start_sec: idx * 2, + end_sec: idx * 2 + 2, + label: sectionLabels[sec] || defaultLabels[sec] || sec, + layers, + }; + }); + return { + id: st.id, + seed: rec.seed, + meter: rec.intent.meter, + mode: rec.intent.mode, + key: rec.intent.tonic, + tempo: rec.intent.tempo, + length: Math.max(2, sections.length * 2), + sections, + whole_layers: [ + { + layer: "lead_rhythm", + section: "all", + label: "Новый риф", + salt: Number(salts["lead_rhythm@all"] || 0), + locked: locks.has("lead_rhythm@all"), + }, + { + layer: "tempo", + section: "all", + label: "Темп", + salt: Number(salts["tempo@all"] || 0), + locked: locks.has("tempo@all"), + }, + ], + options: { + b_lead: opts.b_lead || "augmented", + trailing_rest: opts.trailing_rest !== undefined ? opts.trailing_rest : true, + octave_piece: opts.octave_piece ?? 0.25, + octave_sixteenths: opts.octave_sixteenths ?? 0.3, + dead_notes: opts.dead_notes ?? 0.2, + slide_max: opts.slide_max ?? 5, + }, + can_undo: Array.isArray(st.undo) && st.undo.length > 0, + }; +} + +function defaultFakeEvents(st) { + return [ + { t: 0, dur: 0.5, pitch: 60, vel: 90, guitar: 1, dead: false }, + { t: 0.5, dur: 0.5, pitch: 64, vel: 90, guitar: 2, dead: false }, + ]; +} + +class StubClassList { + constructor(el) { + this.el = el; + this._set = new Set(); + } + _syncFromClassName(cn) { + this._set = new Set(String(cn || "").split(/\s+/).filter(Boolean)); + } + _syncToClassName() { + this.el._className = Array.from(this._set).join(" "); + } + add(...tokens) { + for (const t of tokens) if (t) this._set.add(t); + this._syncToClassName(); + } + remove(...tokens) { + for (const t of tokens) this._set.delete(t); + this._syncToClassName(); + } + toggle(token, force) { + if (force === undefined) { + if (this._set.has(token)) this._set.delete(token); + else this._set.add(token); + } else if (force) { + this._set.add(token); + } else { + this._set.delete(token); + } + this._syncToClassName(); + return this._set.has(token); + } + contains(token) { + return this._set.has(token); + } +} + +class StubElement { + constructor(tagName, env, id = "") { + this.tagName = String(tagName || "div").toUpperCase(); + this._env = env; + this.id = id; + this._className = ""; + this.classList = new StubClassList(this); + this.dataset = {}; + this.style = {}; + this.children = []; + this.parentNode = null; + this.disabled = false; + this.hidden = false; + this.value = ""; + this.title = ""; + this.type = ""; + this.min = ""; + this.max = ""; + this.step = ""; + this.href = ""; + this.download = ""; + this.files = []; + this._textContent = ""; + this._innerHTML = ""; + this.onclick = null; + this.onchange = null; + this.oninput = null; + } + + get className() { + return this._className; + } + set className(val) { + this._className = String(val || ""); + this.classList._syncFromClassName(this._className); + } + + get textContent() { + if (this.children.length === 0) return this._textContent; + return this._textContent + this.children.map((c) => c.textContent).join(""); + } + set textContent(val) { + this._textContent = String(val ?? ""); + this.children = []; + this._innerHTML = ""; + } + + get innerHTML() { + return this._innerHTML; + } + set innerHTML(val) { + const html = String(val ?? ""); + this._innerHTML = html; + this._textContent = ""; + this.children = []; + if (html !== "") { + this._env.innerHTMLWrites.push({ id: this.id, tagName: this.tagName, html }); + const tagRe = /<(div|span|button|input|h2)\b([^>]*)>/gi; + let m; + while ((m = tagRe.exec(html)) !== null) { + const tag = m[1]; + const attrs = m[2] || ""; + const idM = /\bid\s*=\s*["']([^"']+)["']/i.exec(attrs); + if (idM) { + const child = new StubElement(tag, this._env, idM[1]); + const disabledM = /\bdisabled\b/i.test(attrs); + if (disabledM) child.disabled = true; + this.appendChild(child); + } + } + } + } + + appendChild(child) { + if (!child) return child; + child.parentNode = this; + this.children.push(child); + return child; + } + + remove() { + if (this.parentNode) { + this.parentNode.children = this.parentNode.children.filter((c) => c !== this); + this.parentNode = null; + } + } + + click() { + if (this.disabled) return; + if (typeof this.onclick === "function") return this.onclick({ target: this }); + } + + _walk(fn) { + fn(this); + for (const c of this.children) c._walk(fn); + } + + querySelectorAll(selector) { + const parts = selector.split(",").map((s) => s.trim().toLowerCase()); + const out = []; + this._walk((el) => { + if (el === this) return; + for (const p of parts) { + if (p.startsWith(".")) { + if (el.classList.contains(p.slice(1))) { + out.push(el); + break; + } + } else if (el.tagName.toLowerCase() === p) { + out.push(el); + break; + } + } + }); + return out; + } +} + +function createAppHarness(options = {}) { + const { + autoReadyWorker = true, + autoPreloadSamples = true, + failSampleFetch = false, + initialPieces = [], + initialLogs = [], + sectionLabels = {}, + eventsForState = null, + sampleDuration = 2.5, + audioInitialState = "suspended", + resumeBehavior = "resolve", // "resolve" | "reject" | "stay-suspended" + decodeDelayMs = 0, + failDecode = false, + autoRunWorkerCalls = true, + } = options; + + const env = { + innerHTMLWrites: [], + alerts: [], + downloads: [], + workerMessages: [], + workersCreated: 0, + activeWorker: null, + audioContexts: [], + sourcesCreated: [], + txLog: [], + nextTimerId: 1, + timers: new Map(), + pendingWorkerCalls: [], + autoRunWorkerCalls, + failSampleFetch, + decodeDelayMs, + failDecode, + resumeBehavior, + audioInitialState, + idbFailNextWrite: null, + idbUnavailable: Boolean(options.idbUnavailable), + sectionLabels, + }; + + // DOM setup + const root = new StubElement("body", env, "body"); + const staticIds = [ + ["h1", "title"], + ["span", "busy"], + ["div", "loadBanner"], + ["div", "storageBanner"], + ["div", "audioBanner"], + ["button", "newBtn"], + ["input", "seedInput"], + ["div", "pieceList"], + ["button", "logBtn"], + ["button", "exportPiecesBtn"], + ["button", "importPiecesBtn"], + ["input", "importPiecesInput"], + ["main", "workspace"], + ]; + for (const [tag, id] of staticIds) { + root.appendChild(new StubElement(tag, env, id)); + } + + const documentStub = { + body: root, + createElement(tag) { + return new StubElement(tag, env); + }, + createTextNode(text) { + const el = new StubElement("#text", env); + el.textContent = String(text ?? ""); + return el; + }, + getElementById(id) { + let found = null; + root._walk((el) => { + if (!found && el.id === id) found = el; + }); + return found; + }, + }; + + // IndexedDB setup + const dbPieces = new Map(); + for (const p of initialPieces) { + dbPieces.set(p.id, deepClone(p)); + } + const dbLogs = initialLogs.map((r, i) => ({ ...deepClone(r), seq: i + 1 })); + let nextLogSeq = dbLogs.length + 1; + let dbTxChain = Promise.resolve(); + + const indexedDBStub = { + _pieces: dbPieces, + _logs: dbLogs, + open() { + const req = { result: null, onupgradeneeded: null, onsuccess: null, onerror: null }; + queueMicrotask(() => { + if (env.idbUnavailable) { + req.error = { name: "SecurityError", message: "IndexedDB unavailable" }; + if (req.onerror) req.onerror({ target: req }); + return; + } + const db = { + objectStoreNames: { + contains: () => true, + }, + createObjectStore: () => {}, + transaction(storeNames, mode = "readonly") { + const stores = Array.isArray(storeNames) ? [...storeNames] : [storeNames]; + const txRecord = { storeNames: stores, mode, ops: [], status: "pending", error: null }; + env.txLog.push(txRecord); + + let resolveTxLock; + const prevLock = dbTxChain; + const myLock = new Promise((r) => { + resolveTxLock = r; + }); + if (mode === "readwrite") { + dbTxChain = prevLock.then(() => myLock); + } + const readyToRun = mode === "readwrite" ? prevLock : Promise.resolve(); + + let stagedPieces = null; + let stagedLogs = null; + let pendingOps = 0; + let aborted = false; + let finalized = false; + + const tx = { + oncomplete: null, + onerror: null, + onabort: null, + error: null, + abort() { + if (finalized) return; + aborted = true; + txRecord.status = "aborted"; + }, + objectStore(name) { + if (!stores.includes(name)) { + throw new Error(`NotFoundError: store ${name} not in transaction [${stores.join(",")}]`); + } + const makeReq = (opName, fn) => { + const r = { result: undefined, error: null, onsuccess: null, onerror: null }; + pendingOps += 1; + readyToRun.then(() => queueMicrotask(() => { + if (!stagedPieces) { + stagedPieces = new Map(dbPieces); + stagedLogs = [...dbLogs]; + } + try { + if (aborted) { + r.error = tx.error || { name: "AbortError", message: "Transaction aborted" }; + if (r.onerror) r.onerror({ target: r }); + return; + } + if (mode === "readwrite" && env.idbFailNextWrite) { + const errName = env.idbFailNextWrite; + env.idbFailNextWrite = null; + const err = { name: errName, message: errName }; + tx.error = err; + r.error = err; + aborted = true; + txRecord.status = "aborted"; + txRecord.error = errName; + if (r.onerror) r.onerror({ target: r }); + return; + } + r.result = fn(); + txRecord.ops.push({ store: name, op: opName }); + if (r.onsuccess) r.onsuccess({ target: r }); + } catch (err) { + const eObj = { name: err.name || "Error", message: err.message || String(err) }; + tx.error = eObj; + r.error = eObj; + aborted = true; + txRecord.status = "aborted"; + txRecord.error = eObj.name; + if (r.onerror) r.onerror({ target: r }); + } finally { + pendingOps -= 1; + if (pendingOps === 0 && !finalized) { + finalized = true; + queueMicrotask(() => { + if (aborted) { + resolveTxLock(); + if (tx.onabort) tx.onabort({ target: tx }); + else if (tx.onerror) tx.onerror({ target: tx }); + } else { + if (mode === "readwrite") { + dbPieces.clear(); + for (const [k, v] of stagedPieces.entries()) dbPieces.set(k, v); + dbLogs.length = 0; + for (const row of stagedLogs) dbLogs.push(row); + } + txRecord.status = "complete"; + resolveTxLock(); + if (tx.oncomplete) tx.oncomplete({ target: tx }); + } + }); + } + } + })); + return r; + }; + + if (name === "pieces") { + return { + getAll: () => makeReq("getAll", () => Array.from(stagedPieces.values()).map(deepClone)), + get: (id) => makeReq("get", () => deepClone(stagedPieces.get(id))), + put: (rec) => makeReq("put", () => { + stagedPieces.set(rec.id, deepClone(rec)); + return rec.id; + }), + add: (rec) => makeReq("add", () => { + if (stagedPieces.has(rec.id)) { + const err = new Error(`Key ${rec.id} already exists`); + err.name = "ConstraintError"; + throw err; + } + stagedPieces.set(rec.id, deepClone(rec)); + return rec.id; + }), + }; + } + if (name === "logs") { + return { + getAll: () => makeReq("getAll", () => stagedLogs.map(deepClone)), + add: (row) => makeReq("add", () => { + const seq = nextLogSeq++; + stagedLogs.push({ ...deepClone(row), seq }); + return seq; + }), + }; + } + throw new Error(`Unknown store: ${name}`); + }, + }; + return tx; + }, + }; + req.result = db; + if (req.onupgradeneeded) req.onupgradeneeded({ target: req }); + if (req.onsuccess) req.onsuccess({ target: req }); + }); + return req; + }, + }; + + // Fake Python command handler + function runFakePy(cmd, payload) { + if (cmd === "new_piece") { + const seed = payload.seed ?? 801000; + const st = makeFakeState(seed); + return { + state: st, + detail: buildDetailFromState(st, env.sectionLabels), + events: eventsForState ? eventsForState(st) : defaultFakeEvents(st), + }; + } + if (cmd === "snapshot") { + const st = deepClone(payload.state); + return { + state: st, + detail: buildDetailFromState(st, env.sectionLabels), + events: eventsForState ? eventsForState(st) : defaultFakeEvents(st), + }; + } + if (cmd === "reroll") { + const oldSt = deepClone(payload.state); + const nextRec = deepClone(oldSt.recipe); + const key = `${payload.layer}@${payload.section}`; + nextRec.studio.salts[key] = (nextRec.studio.salts[key] || 0) + 1; + const nextUndo = [...(oldSt.undo || []), deepClone(oldSt.recipe)].slice(-50); + const nextSt = { id: oldSt.id, recipe: nextRec, undo: nextUndo }; + return { + state: nextSt, + detail: buildDetailFromState(nextSt, env.sectionLabels), + events: eventsForState ? eventsForState(nextSt) : defaultFakeEvents(nextSt), + }; + } + if (cmd === "lock") { + const oldSt = deepClone(payload.state); + const nextRec = deepClone(oldSt.recipe); + const key = `${payload.layer}@${payload.section}`; + const locks = new Set(nextRec.studio.locks || []); + if (payload.locked) locks.add(key); + else locks.delete(key); + nextRec.studio.locks = Array.from(locks); + const nextUndo = [...(oldSt.undo || []), deepClone(oldSt.recipe)].slice(-50); + const nextSt = { id: oldSt.id, recipe: nextRec, undo: nextUndo }; + return { + state: nextSt, + detail: buildDetailFromState(nextSt, env.sectionLabels), + events: eventsForState ? eventsForState(nextSt) : defaultFakeEvents(nextSt), + }; + } + if (cmd === "option") { + const oldSt = deepClone(payload.state); + const nextRec = deepClone(oldSt.recipe); + nextRec.studio.options[payload.name] = payload.value; + const nextUndo = [...(oldSt.undo || []), deepClone(oldSt.recipe)].slice(-50); + const nextSt = { id: oldSt.id, recipe: nextRec, undo: nextUndo }; + return { + state: nextSt, + detail: buildDetailFromState(nextSt, env.sectionLabels), + events: eventsForState ? eventsForState(nextSt) : defaultFakeEvents(nextSt), + }; + } + if (cmd === "undo") { + const oldSt = deepClone(payload.state); + const undo = [...(oldSt.undo || [])]; + const rec = undo.length ? undo.pop() : oldSt.recipe; + const nextSt = { id: oldSt.id, recipe: rec, undo }; + return { + state: nextSt, + detail: buildDetailFromState(nextSt, env.sectionLabels), + events: eventsForState ? eventsForState(nextSt) : defaultFakeEvents(nextSt), + }; + } + if (cmd === "export_midi") { + const salt = payload.state?.recipe?.studio?.salts?.["comp@A"] || 0; + return Buffer.from(`MIDI:${payload.state.id}:salt=${salt}`).toString("base64"); + } + if (cmd === "export_musicxml") { + return `${payload.state.id}`; + } + if (cmd === "export_tab") { + return `== g1 == ${payload.state.id}`; + } + throw new Error(`Unknown cmd: ${cmd}`); + } + + class StubWorker { + constructor(url) { + this.url = url; + this.onmessage = null; + this.onerror = null; + this.onmessageerror = null; + this.terminated = false; + env.workersCreated += 1; + env.activeWorker = this; + } + terminate() { + this.terminated = true; + } + postMessage(msg) { + env.workerMessages.push(deepClone(msg)); + if (msg.type === "init") { + if (autoReadyWorker) { + queueMicrotask(() => { + if (!this.terminated && this.onmessage) { + this.onmessage({ data: { type: "ready", version: "v0.27.7", loadMs: 10 } }); + } + }); + } + return; + } + if (msg.type === "call") { + const entry = { + msg: deepClone(msg), + worker: this, + resolve: (res) => { + if (!this.terminated && this.onmessage) { + this.onmessage({ data: { type: "result", id: msg.id, ok: true, result: res, elapsedMs: 5 } }); + } + }, + reject: (err) => { + if (!this.terminated && this.onmessage) { + this.onmessage({ + data: { type: "result", id: msg.id, ok: false, error: String(err), elapsedMs: 5 }, + }); + } + }, + }; + if (env.autoRunWorkerCalls) { + queueMicrotask(() => { + try { + entry.resolve(runFakePy(msg.cmd, msg.payload)); + } catch (e) { + entry.reject(e.message || String(e)); + } + }); + } else { + env.pendingWorkerCalls.push(entry); + } + } + } + } + + // AudioContext stub + class StubAudioContext { + constructor() { + this.currentTime = 0; + this.state = env.audioInitialState; + this._listeners = new Map(); + this.onstatechange = null; + this.destination = {}; + env.audioContexts.push(this); + } + addEventListener(type, fn) { + if (!this._listeners.has(type)) this._listeners.set(type, []); + this._listeners.get(type).push(fn); + } + emitStateChange(nextState) { + this.state = nextState; + const ev = { type: "statechange", target: this }; + if (typeof this.onstatechange === "function") this.onstatechange(ev); + for (const fn of this._listeners.get("statechange") || []) fn(ev); + } + resume() { + if (env.resumeBehavior === "reject") { + return Promise.reject(new Error("NotAllowedError: play() denied")); + } + if (env.resumeBehavior === "stay-suspended") { + return Promise.resolve(); + } + this.state = "running"; + return Promise.resolve(); + } + createDynamicsCompressor() { + return { threshold: { value: 0 }, ratio: { value: 1 }, connect() {} }; + } + createGain() { + const sched = []; + return { + gain: { + value: 1, + _sched: sched, + setValueAtTime(v, t) { + sched.push({ op: "setValueAtTime", v, t }); + }, + linearRampToValueAtTime(v, t) { + sched.push({ op: "linearRampToValueAtTime", v, t }); + }, + }, + _sched: sched, + connect() {}, + }; + } + createDelay() { + return { delayTime: { value: 0 }, connect() {} }; + } + createBiquadFilter() { + return { type: "", frequency: { value: 0 }, connect() {} }; + } + createStereoPanner() { + return { pan: { value: 0 }, connect() {} }; + } + createBufferSource() { + const src = { + buffer: null, + playbackRate: { value: 1 }, + loop: false, + loopStart: 0, + loopEnd: 0, + startArgs: null, + stopArgs: null, + stopped: false, + onended: null, + _gainNode: null, + connect(node) { + this._gainNode = node; + }, + start(...args) { + src.startArgs = args; + }, + stop(...args) { + src.stopArgs = args; + src.stopped = true; + if (typeof src.onended === "function") src.onended(); + }, + }; + env.sourcesCreated.push(src); + return src; + } + decodeAudioData() { + const run = () => { + if (env.failDecode) { + return Promise.reject(new Error("EncodingError: decode failed")); + } + const len = Math.floor(44100 * sampleDuration); + const pcm = new Float32Array(len); + for (let i = 0; i < len; i++) { + pcm[i] = Math.sin((2 * Math.PI * 220 * i) / 44100); + } + return Promise.resolve({ + duration: sampleDuration, + sampleRate: 44100, + length: len, + getChannelData: () => pcm, + }); + }; + if (env.decodeDelayMs > 0) { + return new Promise((resolve, reject) => { + setTimeout(() => run().then(resolve, reject), env.decodeDelayMs); + }); + } + return run(); + } + } + + // Fetch stub (manifest + samples) + const manifestData = { + files: { + "60": { "72": "p060_v072.mp3", "100": "p060_v100.mp3" }, + "64": { "72": "p064_v072.mp3", "100": "p064_v100.mp3" }, + }, + }; + + async function fetchStub(url) { + if (!autoPreloadSamples) { + await new Promise(() => {}); + } + if (env.failSampleFetch) { + return { ok: false, status: 500 }; + } + if (String(url).endsWith("manifest.json")) { + return { ok: true, status: 200, json: async () => deepClone(manifestData) }; + } + return { + ok: true, + status: 200, + arrayBuffer: async () => new Uint8Array([1, 2, 3, 4]).buffer, + }; + } + + const windowStub = { + indexedDB: env.idbUnavailable ? null : indexedDBStub, + AudioContext: StubAudioContext, + alert: (msg) => env.alerts.push(String(msg)), + }; + + const context = { + window: windowStub, + document: documentStub, + Worker: StubWorker, + fetch: fetchStub, + Blob: class StubBlob { + constructor(parts, opts) { + this.parts = parts; + this.type = opts?.type || ""; + } + }, + URL: { + createObjectURL(blob) { + env.downloads.push(blob); + return "blob:stub"; + }, + revokeObjectURL() {}, + }, + File: class StubFile {}, + performance: { now: () => Date.now() }, + atob: (b64) => Buffer.from(b64, "base64").toString("binary"), + btoa: (str) => Buffer.from(str, "binary").toString("base64"), + requestAnimationFrame: () => env.nextTimerId++, + cancelAnimationFrame: () => {}, + setInterval: (fn, ms) => { + const id = env.nextTimerId++; + env.timers.set(id, { fn, ms }); + return id; + }, + clearInterval: (id) => { + env.timers.delete(id); + }, + setTimeout, + clearTimeout, + console, + Promise, + Map, + Set, + Array, + Object, + Number, + String, + Boolean, + Math, + JSON, + Date, + Error, + Uint8Array, + Buffer, + parseInt, + parseFloat, + }; + windowStub.window = windowStub; + + const appCode = fs.readFileSync(path.join(WEB_DIR, "app.js"), "utf8"); + vm.runInNewContext(appCode, context, { filename: "app.js" }); + + env.window = windowStub; + env.document = documentStub; + env.indexedDB = indexedDBStub; + env.runFakePy = runFakePy; + env.tickTimers = () => { + for (const { fn } of env.timers.values()) fn(); + }; + env.flushMicrotasks = async (rounds = 8) => { + for (let i = 0; i < rounds; i++) { + await new Promise((resolve) => queueMicrotask(resolve)); + } + }; + env.flushAll = async (ms = 10) => { + await env.flushMicrotasks(10); + await new Promise((resolve) => setTimeout(resolve, ms)); + await env.flushMicrotasks(10); + }; + env.makeFakeState = makeFakeState; + env.buildDetailFromState = buildDetailFromState; + + return env; +} + +export { createAppHarness, makeFakeState, buildDetailFromState, deepClone }; diff --git a/composer-lab/web/tests/test_app.mjs b/composer-lab/web/tests/test_app.mjs new file mode 100644 index 00000000..7c6a03be --- /dev/null +++ b/composer-lab/web/tests/test_app.mjs @@ -0,0 +1,359 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createAppHarness, makeFakeState, buildDetailFromState } from "./harness.js"; + +async function bootWithPiece(options = {}) { + const st = makeFakeState(801000); + const rec = { + id: st.id, + state: st, + detail: buildDetailFromState(st, options.sectionLabels), + updatedAt: "2026-11-23T00:00:00.000Z", + }; + const env = createAppHarness({ + initialPieces: [rec], + ...options, + }); + await env.flushAll(20); + return env; +} + +test("Finding 1: rapid edits are queued per piece and export waits for preceding edits", async () => { + const env = await bootWithPiece({ autoRunWorkerCalls: true }); + env.autoRunWorkerCalls = false; + + const compButtons = env.document + .getElementById("workspace") + .querySelectorAll(".reroll-btn") + .filter((b) => b.dataset.layer === "comp" && b.dataset.section === "A"); + assert.equal(compButtons.length, 1); + + // Trigger two rapid comp@A rerolls before any worker reply completes, plus an export + compButtons[0].click(); + compButtons[0].click(); + env.document.getElementById("dlMidiBtn").click(); + await env.flushMicrotasks(6); + + // Process pending worker calls sequentially as they arrive + let exportedSalt = null; + for (let safety = 0; safety < 20 && env.pendingWorkerCalls.length > 0; safety++) { + const call = env.pendingWorkerCalls.shift(); + if (call.msg.cmd === "export_midi") { + exportedSalt = call.msg.payload.state.recipe.studio.salts["comp@A"] || 0; + } + call.resolve(env.runFakePy(call.msg.cmd, call.msg.payload)); + await env.flushAll(10); + } + + const saved = env.indexedDB._pieces.get("piece_801000"); + assert.equal(saved.state.recipe.studio.salts["comp@A"], 2, "two rapid rerolls must reach salt 2"); + assert.equal(saved.state.undo.length, 2, "two rapid rerolls must keep 2 undo entries"); + const rerollLogs = env.indexedDB._logs.filter((l) => l.action === "reroll"); + assert.equal(rerollLogs.length, 2); + assert.equal(exportedSalt, 2, "export must wait for both preceding edits"); +}); + +test("Finding 2: selecting B while A is visible disables A and commits currentId + state together", async () => { + const stA = makeFakeState(801000); + const stB = makeFakeState(802000); + const env = createAppHarness({ + initialPieces: [ + { id: stA.id, state: stA, detail: buildDetailFromState(stA), updatedAt: "2026-11-23T00:00:02.000Z" }, + { id: stB.id, state: stB, detail: buildDetailFromState(stB), updatedAt: "2026-11-23T00:00:01.000Z" }, + ], + }); + await env.flushAll(20); + env.autoRunWorkerCalls = false; + + const items = env.document.getElementById("pieceList").querySelectorAll(".piece-item"); + assert.equal(items.length, 2); + + // Click B to start navigation + items[1].click(); + await env.flushMicrotasks(4); + + // While navigation to B is pending, outgoing editor controls for A must be disabled + const compBtnA = env.document + .getElementById("workspace") + .querySelectorAll(".reroll-btn") + .find((b) => b.dataset.layer === "comp"); + assert.equal(compBtnA.disabled, true, "outgoing editor must be disabled while navigation is pending"); + + // Even if an edit on A were invoked programmatically before navigation commits, A is blocked or B still loads cleanly + compBtnA.onclick?.(); + await env.flushMicrotasks(4); + + for (let safety = 0; safety < 20 && env.pendingWorkerCalls.length > 0; safety++) { + const call = env.pendingWorkerCalls.shift(); + call.resolve(env.runFakePy(call.msg.cmd, call.msg.payload)); + await env.flushAll(10); + } + + const titleText = env.document.getElementById("workspace").textContent; + assert.match(titleText, /#802000/, "workspace must finish on piece B, not get stuck on A"); + assert.equal(env.window.__studioDebug.getCurrentId?.(), "piece_802000"); +}); + +test("Finding 3: piece + log write uses single transaction and quota error switches consistently to visible memory fallback", async () => { + const env = await bootWithPiece(); + env.txLog.length = 0; + + const compBtn = env.document + .getElementById("workspace") + .querySelectorAll(".reroll-btn") + .find((b) => b.dataset.layer === "comp" && b.dataset.section === "A"); + compBtn.click(); + await env.flushAll(15); + + const writeTxs = env.txLog.filter((t) => t.mode === "readwrite" && t.status === "complete"); + assert.ok( + writeTxs.some((t) => t.storeNames.includes("pieces") && t.storeNames.includes("logs")), + "piece and log must be written in one IndexedDB transaction" + ); + + // Inject QuotaExceededError on next write + env.idbFailNextWrite = "QuotaExceededError"; + const compBtn2 = env.document + .getElementById("workspace") + .querySelectorAll(".reroll-btn") + .find((b) => b.dataset.layer === "comp" && b.dataset.section === "A"); + compBtn2.click(); + await env.flushAll(15); + + // Subsequent reads must reflect salt 2 from memory, NOT stale salt 1 from IDB + assert.equal(env.indexedDB._pieces.get("piece_801000").state.recipe.studio.salts["comp@A"], 1); + const banner = env.document.getElementById("storageBanner"); + assert.ok(banner && !banner.hidden && banner.textContent.length > 0, "storage fallback must be visible"); + + // Download logs and export pieces should both include the in-memory salt-2 mutation + env.downloads.length = 0; + env.document.getElementById("logBtn").click(); + await env.flushAll(15); + assert.equal(env.downloads.length, 1); + const logLines = env.downloads[0].parts.join("").trim().split("\n"); + assert.equal(logLines.length, 2, "memory fallback log must include both rerolls"); + + env.downloads.length = 0; + env.document.getElementById("exportPiecesBtn").click(); + await env.flushAll(15); + const exported = JSON.parse(env.downloads[0].parts.join("")); + assert.equal(exported.pieces[0].state.recipe.studio.salts["comp@A"], 2, "memory fallback piece must reflect salt 2"); +}); + +test("Finding 4: concurrent same-seed creation produces distinct IDs and conflicting import does not overwrite local piece", async () => { + const env = await bootWithPiece(); + env.autoRunWorkerCalls = false; + + // Trigger two concurrent creations with the same seed 805000 + env.document.getElementById("seedInput").value = "805000"; + env.document.getElementById("newBtn").click(); + env.document.getElementById("newBtn").click(); + await env.flushMicrotasks(6); + + // Resolve both new_piece calls simultaneously + assert.equal(env.pendingWorkerCalls.length, 2); + for (const call of env.pendingWorkerCalls.splice(0)) { + call.resolve(env.runFakePy(call.msg.cmd, call.msg.payload)); + } + await env.flushAll(20); + + assert.ok(env.indexedDB._pieces.has("piece_805000"), "first piece_805000 must exist"); + assert.ok(env.indexedDB._pieces.has("piece_805000_2"), "second concurrent piece must get piece_805000_2"); + + // Now modify local piece_801000 so it differs from an imported backup with the same id piece_801000 + env.autoRunWorkerCalls = true; + const localPiece = env.indexedDB._pieces.get("piece_801000"); + localPiece.state.recipe.studio.salts["comp@A"] = 9; + localPiece.state.undo = [makeFakeState(801000).recipe]; + + const importedState = makeFakeState(801000); + importedState.recipe.studio.salts["comp@A"] = 1; + const fakeFile = { + text: async () => JSON.stringify({ version: 1, pieces: [{ id: "piece_801000", state: importedState }] }), + }; + const impInput = env.document.getElementById("importPiecesInput"); + impInput.files = [fakeFile]; + await impInput.onchange(); + await env.flushAll(20); + + const keptLocal = env.indexedDB._pieces.get("piece_801000"); + assert.equal(keptLocal.state.recipe.studio.salts["comp@A"], 9, "local piece_801000 must not be overwritten"); + assert.equal(keptLocal.state.undo.length, 1, "local undo stack must stay intact"); + const allocatedImport = env.indexedDB._pieces.get("piece_801000_2"); + assert.ok(allocatedImport, "conflicting distinct import must allocate piece_801000_2"); + assert.equal(allocatedImport.state.recipe.studio.salts["comp@A"], 1); +}); + +test("Finding 6: section labels and piece metadata never reach innerHTML", async () => { + const xss = ''; + const env = await bootWithPiece({ + sectionLabels: { A: xss }, + }); + + const badWrite = env.innerHTMLWrites.find((w) => w.html.includes(xss) || w.html.includes(" b.textContent.includes(xss)), "label should still render safely via textContent"); +}); + +test("Finding 7: seeking into sustained note plays remaining slice and stale pre-seek decodes are invalidated", async () => { + const longNoteEvents = () => [{ t: 0.0, dur: 2.0, pitch: 60, vel: 100, guitar: 1, dead: false }]; + const env = await bootWithPiece({ + eventsForState: longNoteEvents, + audioInitialState: "running", + }); + + const sampler = env.window.__studioDebug.sampler; + await sampler.seek(1.0, true); + await env.flushAll(10); + + assert.equal(env.sourcesCreated.length, 1, "seeking into [0, 2.0] at t=1.0 must start the overlapping note"); + const src = env.sourcesCreated[0]; + assert.equal(src.startArgs.length, 2, "must pass buffer offset to src.start(when, offset)"); + assert.ok(Math.abs(src.startArgs[1] - 1.0) < 0.05, `buffer offset should be ~1.0, got ${src.startArgs[1]}`); + const playedDur = src.stopArgs[0] - src.startArgs[0]; + assert.ok(Math.abs(playedDur - 1.035) < 0.05, `remaining dur+release should be ~1.035, got ${playedDur}`); + + // Now test stale decode invalidation across seek into rest + const twoNoteEvents = () => [ + { t: 0.0, dur: 0.5, pitch: 60, vel: 100, guitar: 1, dead: false }, + { t: 2.0, dur: 0.5, pitch: 64, vel: 100, guitar: 1, dead: false }, + ]; + const env2 = await bootWithPiece({ + eventsForState: twoNoteEvents, + audioInitialState: "running", + decodeDelayMs: 60, + }); + const sampler2 = env2.window.__studioDebug.sampler; + // Start playing at t=0 (begins async decode of pitch 60), immediately seek into rest at t=1.0 + const playPromise = sampler2.play(); + await sampler2.seek(1.0, false); // pause at 1.0 + await playPromise; + await env2.flushAll(100); + assert.equal(env2.sourcesCreated.length, 0, "stale decode from before pause/seek must not start a note during rest"); +}); + +test("Finding 8: held notes longer than 2.5s loop sustain region and release at full event end", async () => { + const heldEvents = () => [{ t: 0.0, dur: 5.0, pitch: 60, vel: 100, guitar: 1, dead: false }]; + const env = await bootWithPiece({ + eventsForState: heldEvents, + audioInitialState: "running", + sampleDuration: 2.5, + }); + + const sampler = env.window.__studioDebug.sampler; + await sampler.play(); + await env.flushAll(15); + + assert.equal(env.sourcesCreated.length, 1); + const src = env.sourcesCreated[0]; + assert.equal(src.loop, true, "5.0s note must enable buffer looping"); + assert.ok(src.loopStart > 0.2 && src.loopStart < src.loopEnd, `invalid loopStart ${src.loopStart}`); + assert.ok(src.loopEnd > src.loopStart + 0.1 && src.loopEnd < 2.5, `invalid loopEnd ${src.loopEnd}`); + const stopDelay = src.stopArgs[0] - src.startArgs[0]; + assert.ok(Math.abs(stopDelay - 5.035) < 0.05, `stop must happen at 5.035s, got ${stopDelay}`); + + // Seeking to t=3.0 of a 5.0s note must wrap buffer offset into [loopStart, loopEnd) and play remaining 2.0s + env.sourcesCreated.length = 0; + await sampler.seek(3.0, true); + await env.flushAll(15); + assert.equal(env.sourcesCreated.length, 1); + const s2 = env.sourcesCreated[0]; + assert.equal(s2.loop, true); + assert.ok(s2.startArgs[1] >= s2.loopStart && s2.startArgs[1] < s2.loopEnd, `offset ${s2.startArgs[1]} must wrap into loop`); + const remDur = s2.stopArgs[0] - s2.startArgs[0]; + assert.ok(Math.abs(remDur - 2.035) < 0.05, `remaining dur+release should be ~2.035s, got ${remDur}`); +}); + +test("Finding 9: playback is gated on sample load, prepares opening notes over >150ms decode, and surfaces decode errors with retry", async () => { + // 1) Play disabled while samples loading + const envLoading = await bootWithPiece({ autoPreloadSamples: false }); + assert.equal(envLoading.document.getElementById("playBtn").disabled, true, "playBtn disabled while loading"); + + // 2) Opening decode > 150ms (220ms) must NOT drop opening note + const envSlow = await bootWithPiece({ + audioInitialState: "running", + decodeDelayMs: 220, + }); + await envSlow.window.__studioDebug.sampler.play(); + await envSlow.flushAll(20); + assert.ok(envSlow.sourcesCreated.length >= 1, "slow >150ms opening decode must still play opening note"); + + // 3) Decode failure must stop playback, show audio error banner + retry button, and recover on retry + const envFail = await bootWithPiece({ + audioInitialState: "running", + failDecode: true, + }); + await envFail.window.__studioDebug.sampler.play(); + await envFail.flushAll(20); + + assert.equal(envFail.window.__studioDebug.sampler.isPlaying(), false); + assert.equal(envFail.document.getElementById("playBtn").textContent, "Играть"); + const audioBanner = envFail.document.getElementById("audioBanner"); + assert.ok(audioBanner && !audioBanner.hidden, "decode failure must show error banner"); + const retryBtn = envFail.document.getElementById("retryAudioBtn"); + assert.ok(retryBtn, "decode failure must expose a retry button"); + + envFail.failDecode = false; + await retryBtn.click(); + await envFail.flushAll(20); + assert.equal(envFail.window.__studioDebug.sampler.isPlaying(), true, "retry should recover playback"); +}); + +test("Finding 10: failed audio resume does not show Пауза over silence and interruption pauses cleanly", async () => { + const env = await bootWithPiece({ + audioInitialState: "suspended", + resumeBehavior: "reject", + }); + + await env.document.getElementById("playBtn").click(); + await env.flushAll(15); + + assert.equal(env.window.__studioDebug.sampler.isPlaying(), false); + assert.equal(env.document.getElementById("playBtn").textContent, "Играть"); + const audioBanner = env.document.getElementById("audioBanner"); + assert.ok(audioBanner && !audioBanner.hidden, "resume rejection must surface an error banner"); + + // Also test resume() resolving without transitioning state to "running" + env.resumeBehavior = "stay-suspended"; + await env.document.getElementById("playBtn").click(); + await env.flushAll(15); + assert.equal(env.window.__studioDebug.sampler.isPlaying(), false); + assert.equal(env.document.getElementById("playBtn").textContent, "Играть"); + + // Now succeed resume, then simulate OS audio interruption via statechange + env.resumeBehavior = "resolve"; + await env.document.getElementById("playBtn").click(); + await env.flushAll(15); + assert.equal(env.window.__studioDebug.sampler.isPlaying(), true); + assert.equal(env.document.getElementById("playBtn").textContent, "Пауза"); + + env.audioContexts[0].emitStateChange("interrupted"); + assert.equal(env.window.__studioDebug.sampler.isPlaying(), false); + assert.equal(env.document.getElementById("playBtn").textContent, "Играть"); +}); + +test("Finding 11: worker.onerror rejects pending calls, clears pending map, and exposes retry", async () => { + const env = createAppHarness({ autoReadyWorker: false }); + await env.flushAll(10); + + const worker1 = env.activeWorker; + let caughtInit = false; + const callPromise = env.window.__studioDebug.callPy("new_piece", { seed: 801000 }).catch(() => { + caughtInit = true; + }); + + // Trigger fatal worker error + worker1.onerror({ message: "Script load failed" }); + await callPromise; + + assert.equal(caughtInit, true, "pending call must reject on worker.onerror"); + const retryPyBtn = env.document.getElementById("retryPyBtn"); + assert.ok(retryPyBtn, "fatal worker error must expose retry button"); + + retryPyBtn.click(); + assert.equal(env.workersCreated, 2, "retry must spawn a new Worker"); + env.activeWorker.onmessage({ data: { type: "ready", version: "v0.27.7", loadMs: 12 } }); + await env.flushAll(10); + assert.equal(env.window.__studioDebug.ready, true, "retry worker ready must mark studio ready"); +}); diff --git a/composer-lab/web/worker.js b/composer-lab/web/worker.js new file mode 100644 index 00000000..49901b79 --- /dev/null +++ b/composer-lab/web/worker.js @@ -0,0 +1,82 @@ +/* Web Worker running Griff Studio Python generator via Pyodide. */ +const PYODIDE_VERSION = "v0.27.7"; +const PYODIDE_BASE = "https://cdn.jsdelivr.net/pyodide/v0.27.7/full/"; +const PY_BASE = "./py/"; +const PY_FILES = [ + "composer.py", + "fretboard.py", + "midiio.py", + "musicxml.py", + "studio/engine.py", + "web_api.py", +]; + +let pyodide = null; +let handleJson = null; + +async function init() { + const t0 = performance.now(); + self.postMessage({ type: "progress", text: `Загрузка Python (Pyodide ${PYODIDE_VERSION})...` }); + importScripts(PYODIDE_BASE + "pyodide.js"); + pyodide = await loadPyodide({ indexURL: PYODIDE_BASE }); + + self.postMessage({ type: "progress", text: "Загрузка модулей генератора..." }); + const fetched = await Promise.all( + PY_FILES.map(async (rel) => { + const res = await fetch(PY_BASE + rel); + if (!res.ok) { + throw new Error(`Failed to fetch ${PY_BASE + rel}: ${res.status}`); + } + return [rel, await res.text()]; + }) + ); + + pyodide.FS.mkdirTree("/app/studio"); + pyodide.FS.writeFile("/app/studio/__init__.py", ""); + for (const [rel, src] of fetched) { + pyodide.FS.writeFile("/app/" + rel, src); + } + + pyodide.runPython( + "import sys\nif '/app' not in sys.path:\n sys.path.insert(0, '/app')\nimport web_api\n" + ); + handleJson = pyodide.globals.get("web_api").handle_json; + + const loadMs = Math.round(performance.now() - t0); + self.postMessage({ type: "ready", version: PYODIDE_VERSION, loadMs }); +} + +self.onmessage = async (ev) => { + const msg = ev.data || {}; + if (msg.type === "init") { + try { + await init(); + } catch (err) { + self.postMessage({ type: "init_error", error: String(err && err.message ? err.message : err) }); + } + return; + } + + if (msg.type === "call") { + const { id, cmd, payload } = msg; + const t0 = performance.now(); + try { + if (!handleJson) { + throw new Error("Python runtime is not initialized"); + } + const raw = handleJson(JSON.stringify({ cmd, payload })); + const result = JSON.parse(raw); + const elapsedMs = Math.round(performance.now() - t0); + self.postMessage({ type: "result", id, ok: true, result, elapsedMs }); + } catch (err) { + const elapsedMs = Math.round(performance.now() - t0); + self.postMessage({ + type: "result", + id, + ok: false, + error: String(err && err.message ? err.message : err), + elapsedMs, + }); + } + } +}; diff --git a/core/src/tonal.rs b/core/src/tonal.rs index 1a2db284..3b88fbe0 100644 --- a/core/src/tonal.rs +++ b/core/src/tonal.rs @@ -265,10 +265,10 @@ impl PitchEvidence { let Some(range) = self.pitch_range else { return Ok(()); }; - for pc in 0..12_usize { + for (pc, &count) in self.onset_counts.iter().enumerate() { #[allow(clippy::cast_possible_truncation)] // pc < 12 let pitch_class = pc as u8; - if self.onset_counts[pc] > 0 && !range_holds_class(range, pitch_class) { + if count > 0 && !range_holds_class(range, pitch_class) { return Err(TonalArtifactError::PitchClassOutsideObservedRange { pitch_class }); } } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 833584bf..dec800be 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "stable" +channel = "1.98.0" components = ["rustfmt", "clippy"]