SPB Git

Repository Public

gen-examples-catalog.py 7.5 KB 141 lines python

1#!/usr/bin/env python32# ORIX Sonata3# File: Scripts/gen-examples-catalog.py4# Description: Writes Examples/catalog.json from the examples themselves: category, title and "teaches" come from the header comments of each file (or from the table below for the files that predate those comments), duration, tracks and notes from `sonata check --json`. Usage: Scripts/gen-examples-catalog.py [--check]5#6# Author: Simon-Pierre Boucher7# Contact: contact@spboucher.ai8"""Generates Examples/catalog.json. Nothing in the catalogue is typed by hand except the table of9overrides for the examples written before the `// category:` header lines existed (three of10them are golden files that must stay byte-identical)."""11import glob12import json13import os14import subprocess15import sys1617REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))18CATEGORIES = ["Getting started", "Rhythm", "Harmony", "Algorithmic", "Instruments", "Effects and mixing", "Pieces", "Studies", "Language"]1920# file stem -> (category, teaches)21OVERRIDES = {22    "first_note": ("Getting started", "composition, instrument track, play"),23    "aurora": ("Getting started", "tempo, key, signature, chords, rests, effects, master"),24    "chords_and_rhythm": ("Harmony", "functions, chord(), patterns, swing, walking bass"),25    "tempo_and_meter": ("Rhythm", "tempo changes, ritardando ramp, changing metres, markers"),26    "accelerando_study": ("Rhythm", "tempo ramps, accelerando, ritardando"),27    "polyrhythm_3_4_5": ("Rhythm", "tuplets, polyrhythm, layered percussion"),28    "woodwind_trio_odd_metre": ("Rhythm", "5/8 and 7/8, metre changes at composition level, grouping"),29    "just_intonation": ("Harmony", "cents, just intervals, comparing tunings"),30    "microtonal": ("Harmony", "quarter tones, 19-EDO, tuning reference"),31    "algorithmic_canon": ("Algorithmic", "seeded random walk, canon, augmentation, tuplets"),32    "euclidean_bells": ("Algorithmic", "euclid(), cycles of different lengths"),33    "mallet_phasing": ("Algorithmic", "rotate(), phasing process"),34    "recursive_fractal": ("Algorithmic", "recursion, lists of intervals, self-similarity"),35    "crystal_harp": ("Instruments", "instrument definition, slots, plucked string model"),36    "fm_bells": ("Instruments", "fm engine, custom partials, modal percussion"),37    "physical_models": ("Instruments", "instrument definitions, physical-model parameters"),38    "subtractive_patch": ("Instruments", "graph blocks, oscillators, filters, feedback through a delay"),39    "patch_drum_machine": ("Instruments", "patch graphs for drums, pitch envelope, filtered noise"),40    "choir_vowels": ("Instruments", "voice engine, automating a vowel"),41    "bends_and_glides": ("Instruments", "bend curves, glissando, quarter-tone inflection"),42    "guitar_fingerstyle": ("Instruments", "plucked strings, picking patterns from chord tones"),43    "automation_sweep": ("Effects and mixing", "automate gain, pan, instrument and effect parameters, curves"),44    "dub_delay": ("Effects and mixing", "delay on a bus, send automation, phaser"),45    "multitrack_band": ("Effects and mixing", "buses, sends, compression, a full mix"),46    "lofi_keys": ("Effects and mixing", "saturation, bitcrusher, stereo width, sixteenth swing"),47    "acid_line": ("Pieces", "acid bass, automation of resonance, four-on-the-floor"),48    "ambient_drift": ("Pieces", "long forms, seeded choices, convolution reverb"),49    "baroque_invention": ("Pieces", "two-part counterpoint, imitation, sequence"),50    "brass_fanfare": ("Pieces", "brass section, marcato and accents, triplets"),51    "jazz_trio_swing": ("Pieces", "12-bar blues, swing, walking bass from a function"),52    "organ_chorale": ("Pieces", "four voices on one track, ties as suspensions"),53    "string_quartet": ("Pieces", "independent voices, articulations, dynamics"),54    "waltz_strings": ("Pieces", "3/4, pizzicato, legato melody, string orchestra"),55    "sonification": ("Studies", "mapping data to pitch, loudness and pan"),56    "tide_sonification": ("Studies", "a data series as melody, local maxima, automation"),57    "uses_modules": ("Language", "import of a project module, patterns and functions from another file"),58}596061def sonata_binary():62    for candidate in ("target/release/sonata", "target/debug/sonata"):63        path = os.path.join(REPO, candidate)64        if os.path.exists(path):65            return [path]66    return ["cargo", "run", "-q", "-p", "sonata-cli", "--"]676869def header_fields(path):70    """The `// key: value` lines of the header comment block, and the Description line."""71    fields = {}72    with open(path, encoding="utf-8") as f:73        for line in f:74            if not line.startswith("//"):75                break76            text = line[2:].strip()77            for key in ("Description", "category", "title", "teaches"):78                if text.startswith(key + ":"):79                    fields[key.lower()] = text[len(key) + 1:].strip()80    return fields818283def build():84    binary = sonata_binary()85    examples = []86    for path in sorted(glob.glob(os.path.join(REPO, "Examples", "*.sonata"))):87        stem = os.path.basename(path)[:-len(".sonata")]88        fields = header_fields(path)89        out = subprocess.run(binary + ["check", path, "--json"], capture_output=True, text=True, cwd=REPO)90        try:91            doc = json.loads(out.stdout)92        except json.JSONDecodeError:93            sys.exit(f"{stem}: `sonata check` did not answer JSON: {out.stderr.strip()[:200]}")94        if not doc.get("ok") or "summary" not in doc:95            sys.exit(f"{stem}: does not compile to a composition")96        summary = doc["summary"]97        category, teaches = fields.get("category"), fields.get("teaches")98        if stem in OVERRIDES:99            category, teaches = OVERRIDES[stem]100        if category not in CATEGORIES:101            sys.exit(f"{stem}: category {category!r} is not one of {CATEGORIES}")102        if not teaches or "description" not in fields:103            sys.exit(f"{stem}: missing `// teaches:` or `// Description:`")104        examples.append({105            "file": os.path.basename(path),106            "title": fields.get("title") or summary["title"],107            "category": category,108            "description": fields["description"],109            "teaches": [t.strip() for t in teaches.split(",") if t.strip()],110            "duration_sec": round(summary["duration_sec"], 4),111            "tracks": summary["tracks"],112            "notes": summary["notes"],113        })114    titles = [e["title"] for e in examples]115    duplicates = sorted({t for t in titles if titles.count(t) > 1})116    if duplicates:117        sys.exit(f"duplicate titles: {duplicates}")118    examples.sort(key=lambda e: (CATEGORIES.index(e["category"]), e["title"].lower()))119    return json.dumps({"format": 1, "categories": CATEGORIES, "examples": examples}, indent=2, ensure_ascii=False) + "\n"120121122def main():123    target = os.path.join(REPO, "Examples", "catalog.json")124    text = build()125    if "--check" in sys.argv:126        current = open(target, encoding="utf-8").read() if os.path.exists(target) else ""127        if current != text:128            sys.exit("Examples/catalog.json is stale: run Scripts/gen-examples-catalog.py")129        print("Examples/catalog.json is up to date")130        return131    with open(target + ".tmp", "w", encoding="utf-8") as f:132        f.write(text)133    os.replace(target + ".tmp", target)134    doc = json.loads(text)135    counts = {c: sum(1 for e in doc["examples"] if e["category"] == c) for c in CATEGORIES}136    print(f"wrote Examples/catalog.json: {len(doc['examples'])} examples — " + ", ".join(f"{c} {n}" for c, n in counts.items()))137138139if __name__ == "__main__":140    main()141
Files main
Menu

Theme