theme_generator / docs /theme_lab_app.md
pachet's picture
Deploy corrected Theme Lab (d1780324)
1ebc6d4 verified
|
Raw History Blame Contribute Delete
9.07 kB

Theme Lab App

Theme Lab is a FastAPI web app for browsing the theme dictionary, playing theme note events in the browser, and generating new samples from the available theme generation engines.

Analysis and Generation Are Separate

Theme Lab optionally integrates the melody parser from the sibling intention_based_composition checkout. That parser analyzes existing catalog themes and labels spans with explicit melodic intentions. Theme Lab uses the result for JSON analysis endpoints and score overlays.

This analysis is not currently part of web generation. The web engines remain the variable-order Markov model and small transformer; neither receives an intention plan. A separate CLI-only template prototype is documented in review_implementation.md. Its optional --analyze adapter calls the sibling parser as a diagnostic, not as part of web generation. It must not be confused with learned intention-conditioned generation.

The dependency is optional and path-based. By default the app looks for:

../intention_based_composition/src

Set INTENTION_COMPOSITION_SRC to use another location. If the source package is unavailable, the browsing and generation features still work, while the intention-analysis endpoints return unavailable and the score view falls back to an unannotated score.

Local Run

Install runtime dependencies:

python3.12 -m venv .venv
.venv/bin/pip install -r requirements-runtime.lock

Start the app:

.venv/bin/python -m apps.theme_lab.app

Open:

http://127.0.0.1:7860

The app serves corpus MIDI and ABC files directly from this repository. Catalog score previews are rendered on demand from SQLite note events through MusicXML/Verovio and cached under outputs/web_app_runs/catalog_scores_v*/; existing svgs/*.svg files remain the fallback when dynamic rendering is not available. Generated files are written under outputs/web_app_runs/.

When the sibling intention_based_composition checkout is available, Theme Lab also requests a melody-intention parse for the selected theme and serves an augmented score at /api/themes/{theme_id}/score-analysis.svg. This SVG keeps the normal Verovio score and injects translucent span overlays plus short labels such as enclosed ascent, idem. enclosure, retrograde, and dominant close. If Verovio rendering fails for a catalog theme, the same route falls back to the committed svgs/*.svg score and injects overlays using the static ABC/abcm2ps notehead positions.

Current Features

  • Search the SQLite full-text index with AND-combined token prefixes; filter by composer and key. Free text is not arbitrary infix substring matching.
  • View catalog metadata and dynamically rendered SVG score previews.
  • View melody-intention analysis directly on the score when the sibling intention_based_composition parser is available. The current overlay is meant for inspection/debugging, not as a final notation design.
  • Play catalog themes through browser Web Audio using note events from SQLite.
  • Generate new samples with the variable-order Markov engine. The web UI defaults to max order 3 and caps Markov max order at 3; order 4+ can take tens of seconds on CPU and is better run from the offline scripts. Docker builds precompute the default order-3 backend under models/theme_lab_markov_cache/ so the deployed app can load and warm it at startup.
  • Run the transformer engine from the same UI. The committed models/theme_transformer_default.pt checkpoint is loaded at startup so normal generation samples from a pretrained model instead of retraining.
  • Export generated samples as MIDI, ABC, and MusicXML.
  • MusicXML score exports are rendered as complete excerpts: final measures are padded when needed and end with a final barline.
  • Render generated MusicXML to SVG using the Python verovio package first, with the command-line tool as fallback.

Intention Analysis Cache Notes

Theme Lab uses several generated-score caches:

  • catalog_scores_v*: plain Verovio catalog scores.
  • catalog_scores_with_analysis-v*: catalog scores with injected intention overlays.
  • intention_analysis_svgs_v*: compact parser diagnostic SVGs.

Catalog score filenames include the database content fingerprint. Analysis filenames also include a parser-source fingerprint and maximum-span setting. Restart the app after changing sibling parser code (Python modules are imported once per process). Bump the explicit overlay version when changing this app's overlay rendering. Use a stable, non-WAL database snapshot while serving. The frontend also uses cache: "no-store" for API calls and appends a fresh query parameter to selected score image URLs. The server sends Cache-Control: no-store, no-cache for /, /api/*, and /static/*. These redundant cache guards are intentional: otherwise browsers can keep displaying stale SVG overlays after the parser has changed.

Generated Register

Both statistical generation engines emit key-relative pitch classes and duration labels, not fully specified MIDI pitches:

symbol = (relative_pitch_class, duration_value)

relative_pitch_class=null is an explicit rest. Requested length counts events, including rests; web playback omits rest note-ons but preserves their time gaps. Enharmonic output-key aliases are normalized to MIDI-supported major keys. --no-triplets prohibits triplets even on a triplet-compatible grid. The corpus loader keeps source initial/inter-note gaps, with a 0.01-beat timing tolerance; it does not infer silence after the last source note. Endpoint pitch priors are neutral when a boundary event is a rest.

The shared export/playback layer realizes those pitch classes into concrete octaves. Generated Markov and transformer samples are currently constrained to the readable treble range C4-C6 during this realization step, so MIDI playback, ABC, MusicXML, and Verovio score previews all use the same register policy. This is an output-realization choice, not a learned register model.

Docker / Hugging Face Spaces

Build locally:

docker build -t theme-lab .
docker run --rm -p 7860:7860 theme-lab

For a Hugging Face Docker Space, push this repository with the Dockerfile at the root. The container listens on PORT, defaulting to 7860.

Deployment Notes

The Docker build installs:

  • muses from the committed vendor/muses source tree
  • vo-regular-bp from commit 842d56ba824e64af34fa2a8f50957afedbc0d3c1
  • torch for the transformer engine

requirements-runtime.lock pins the CPU-only Linux Torch wheel and excludes test tools and CUDA packages. CI installs requirements-tests.lock, which adds test tools to the same runtime versions. Local pilot outputs and regenerated Markov caches are excluded from the Docker context. Markov misses coordinate per cache key, so an expensive cold build no longer holds the global warm-cache lock. Transformer sampling reuses a lazy acceptor across samples/retries.

Verovio SVG rendering is optional. If verovio is missing, generated MusicXML downloads still work and the UI shows the export links without an SVG preview.

Transformer Checkpoint

The repository includes a compact default checkpoint trained with 200 CPU steps. Train and save a replacement checkpoint with:

.venv/bin/python scripts/run_theme_generation.py transformer \
  --samples 2 \
  --length 24 \
  --steps 300 \
  --output-dir outputs/transformer_checkpoint_smoke \
  --save-checkpoint models/theme_transformer_default.pt \
  --write-musicxml

Generate from the checkpoint without retraining:

.venv/bin/python scripts/run_theme_generation.py transformer \
  --samples 4 \
  --length 24 \
  --load-checkpoint models/theme_transformer_default.pt \
  --output-dir outputs/transformer_checkpoint_generation \
  --write-musicxml

The web app never trains on demand. Missing, loading, or failed checkpoints return HTTP 503; /api/health exposes the state and load error. Training is an explicit CLI operation. The committed legacy checkpoint remains available for demonstration, labeled as having unverified training provenance. CLI checkpoint sampling requires matching corpus/training IDs: retrain it before using the command above for experiments.

Resource Limits

The service admits two concurrent generation requests; additional requests receive HTTP 503. Transformer inference is serialized. Four constrained Markov backends and a two-entry model cache use least-recently-used eviction; sampling locks are per backend. Precomputed caches include the database hash and preprocessing version, so older caches are ignored automatically.

Failed generation directories are deleted. On subsequent generation requests, completed UUID run directories older than THEME_LAB_RUN_TTL_HOURS (default 24) are removed; active runs and catalog-score caches are preserved. This is lazy retention, not a background scheduler or a fixed disk quota. Download results you want to keep.