Compare commits

..
10 Commits
Author SHA1 Message Date
c0dev0id c7c246c32d Fix endpoint names in url_for() calls; remove fallback URLs from api.js 2026-06-24 18:24:08 +02:00
c0dev0id c4804f0b55 Fix hardcoded API paths: inject URLs via url_for() in template, read from window.NEUSICIAN_URLS in api.js 2026-06-24 18:19:56 +02:00
c0dev0id 097d4488ef Export metadata edits (title, composer, source, encrypter) via patchScore 2026-06-24 17:52:25 +02:00
c0dev0id 720a0b6b25 Add missing tests: AM, patchBarMeta, stressorToString, multi-variation, for_value, DEBUG skipping, serializeModulation edge cases 2026-06-24 16:56:45 +02:00
c0dev0id 89198ec37e Fix serializeModulation field names; add mod:base test assertion 2026-06-24 16:41:12 +02:00
c0dev0id e4b5cf6887 Rename serializeFm to serializeModulation 2026-06-24 16:22:50 +02:00
c0dev0id 923aa5d41a Add AM modulation support to parser and exporter 2026-06-24 16:19:24 +02:00
c0dev0id 1706404b7e Simplify: remove dead code and redundancy across vue app
- Delete ObjectBasic (defined, never imported)
- ObjectShort: remove unused node prop
- exporter: export stressorToString; use in patchBarMeta (removes inline duplicate)
- PaneFO: import stressorToString from exporter; extract H4 style constant,
  shapeSection() helper, instrOnChange() helper; remove apply param from
  makeChangeHandler (was always () => markDirty()); remove unnecessary ?.
  on always-initialized arrays (variations, labelSpecs, subvariations)
- PaneSubObjects: explicit hasChildren on all item kinds; bars at score
  level get hasChildren based on voices; remove stale kind-list fallback
- ast-parser coerce(): remove unreachable s.trim() check ('' handled above)
- PaneCP: fix post-export synthesisStatus reset to use real field names
2026-06-24 16:08:52 +02:00
c0dev0id 9eb4add695 Make bars navigable and editable with _meta export
Navigation:
- SubObjects: bar → voice (with chevron when offsets exist) → offsets
- PaneCP shortView handles voice and offset types

FO pane:
- Bar: editable beats_per_minute, stress_pattern (serialized as
  groups string), upper/lower stress bounds and tempo shape via
  ShapeEditor; sets bar.isDirty on change
- Voice: read-only name, articles, motifs, offset count
- Offset: read-only tick, stem notes and clusters as label strings
  (note re-serialization deferred)

Export:
- exporter.patchScore() now accepts optional bars[] parameter
- Splits rawScoreText by \n---\n; instruments patched in header,
  dirty bar _meta blocks regenerated, voice note lines kept verbatim
- ast-parser buildBar() adds isDirty:false
- PaneCP passes scoreModel.bars to patchScore
2026-06-24 13:25:23 +02:00
c0dev0id 338ea5be49 Fix result display: audio player, error message, correct field names
- Use file_accomplished (not frozen+!error) to gate audio player
- Use errors field (was .error — wrong name, always falsy)
- Render <audio controls> instead of bare download link
- Add audiowidget.tmpl.stub for server-side customization
2026-06-24 13:16:28 +02:00
11 changed files with 487 additions and 99 deletions
+25
View File
@@ -0,0 +1,25 @@
{# audiowidget.tmpl.stub
Copy to neusician/templates/ and rename to audiowidget.tmpl.
Include from base.tmpl or any score page with:
{% include 'audiowidget.tmpl' %}
Variables expected in context (all provided by /sompyle/status.json
via the sompyler_status_json route):
result_url – URL to the rendered audio file (e.g. /sompyle/result.mp3)
errors – non-empty string on synthesis failure, else empty/absent
The default JS audio widget in PaneCP renders a plain <audio> element.
Replace or extend this stub to match your site's look and feel.
#}
{% if errors %}
<div class="se-error">{{ errors }}</div>
{% elif result_url %}
<figure class="audio-result">
<figcaption>Rendered result</figcaption>
<audio controls preload="metadata">
<source src="{{ result_url }}" type="audio/mpeg">
<a href="{{ result_url }}">Download MP3</a>
</audio>
</figure>
{% endif %}
+8 -4
View File
@@ -1,3 +1,7 @@
const U = window.NEUSICIAN_URLS;
export const URLS = U;
function authHeader(credentials) {
if (!credentials) return {};
const b64 = btoa(`${credentials.username}:${credentials.password}`);
@@ -5,7 +9,7 @@ function authHeader(credentials) {
}
export async function fetchAstLog(credentials) {
const res = await fetch('/sompyle/astlog', {
const res = await fetch(U.astlog, {
headers: authHeader(credentials),
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
@@ -13,7 +17,7 @@ export async function fetchAstLog(credentials) {
}
export async function fetchScoreText(credentials) {
const res = await fetch('/sompyle/score.spls', {
const res = await fetch(U.score, {
headers: authHeader(credentials),
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
@@ -21,7 +25,7 @@ export async function fetchScoreText(credentials) {
}
export async function putScoreText(text, credentials) {
const res = await fetch('/sompyle/score.spls', {
const res = await fetch(U.score, {
method: 'PUT',
headers: {
...authHeader(credentials),
@@ -34,7 +38,7 @@ export async function putScoreText(text, credentials) {
}
export async function fetchStatus(credentials) {
const res = await fetch('/sompyle/status.json', {
const res = await fetch(U.status, {
headers: authHeader(credentials),
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
+12 -1
View File
@@ -7,7 +7,7 @@ function coerce(s) {
if (s === 'False' || s === 'N' || s === 'off' || s === 'false') return false;
if (s === '') return s;
const n = Number(s);
if (!isNaN(n) && s.trim() !== '') return n;
if (!isNaN(n)) return n;
return s;
}
@@ -181,6 +181,7 @@ function buildInstrument(node) {
volumes: null,
timbre: null,
fmModulations: [],
amModulations: [],
rawChildren: [],
};
@@ -201,6 +202,9 @@ function buildInstrument(node) {
case 'FM.modulation':
instr.fmModulations.push({ ...child.props });
break;
case 'AM.modulation':
instr.amModulations.push({ ...child.props });
break;
default:
instr.rawChildren.push(buildGeneric(child));
}
@@ -253,6 +257,7 @@ function buildBasicProperties(node) {
A: null, S: null, R: null,
oscillator: null,
fmModulations: [],
amModulations: [],
rawChildren: [],
};
@@ -271,6 +276,11 @@ function buildBasicProperties(node) {
const envChild = child.children.find(c => c.slot === 'shape');
if (envChild) fm.shape = buildShape(envChild);
bp.fmModulations.push(fm);
} else if (child.parentSlot === 'AM' && child.slot === 'modulation') {
const am = { ...child.props };
const envChild = child.children.find(c => c.slot === 'shape');
if (envChild) am.shape = buildShape(envChild);
bp.amModulations.push(am);
} else {
bp.rawChildren.push(buildGeneric(child));
}
@@ -328,6 +338,7 @@ function buildBar(node) {
const bar = {
type: 'bar',
id: node.positionals[0] ?? '',
isDirty: false,
stressor: null,
tempoShape: null,
tempoLevels: null,
-15
View File
@@ -1,15 +0,0 @@
import { h } from 'vue';
// Inline identifier + a few key props — used for list rows.
export const ObjectBasic = {
props: ['label', 'meta'], // meta: array of {key, value} pairs
setup(props) {
return () => h('div', { class: 'se-object-label' }, [
h('strong', null, props.label),
...(props.meta ?? []).map(({ key, value }) =>
h('span', { style: 'color:#888;margin-left:0.5rem;font-size:0.8em' },
`${key}=${value}`)
),
]);
},
};
+1 -1
View File
@@ -2,7 +2,7 @@ import { h } from 'vue';
// One-line summary row with a drill-down chevron.
export const ObjectShort = {
props: ['node', 'label', 'typeTag', 'focused', 'hasChildren'],
props: ['label', 'typeTag', 'focused', 'hasChildren'],
emits: ['focus', 'drillDown'],
setup(props, { emit }) {
return () => h('li', {
+20 -8
View File
@@ -1,5 +1,5 @@
import { h, ref } from 'vue';
import { fetchScoreText, putScoreText } from '../api.js';
import { fetchScoreText, putScoreText, URLS } from '../api.js';
import { patchScore } from '../exporter.js';
import { StatusPoller } from './StatusPoller.js';
@@ -26,6 +26,10 @@ function shortView(node) {
return { typeTag: 'label', label: node.label ?? '(no label)', meta: [] };
case 'bar':
return { typeTag: 'bar', label: node.id, meta: [] };
case 'voice':
return { typeTag: 'voice', label: node.name, meta: [] };
case 'offset':
return { typeTag: 'tick', label: String(node.tick ?? '?'), meta: [] };
default:
return { typeTag: node.type, label: node.type, meta: [] };
}
@@ -43,9 +47,9 @@ export const PaneCP = {
try {
const raw = await fetchScoreText(props.store.credentials);
props.store.rawScoreText = raw;
const patched = patchScore(raw, props.store.scoreModel.instruments);
const patched = patchScore(raw, props.store.scoreModel.instruments, props.store.scoreModel.bars, props.store.scoreModel.info);
await putScoreText(patched, props.store.credentials);
props.store.synthesisStatus = { frozen: false, progress: 0 };
props.store.synthesisStatus = { frozen: false, currently_rendered_notes: 0, notes_in_total: 0 };
} catch (e) {
exportError.value = e.message;
} finally {
@@ -110,14 +114,22 @@ export const PaneCP = {
// Export error
exportError.value ? h('div', { class: 'se-error' }, exportError.value) : null,
// Status poller
// Status poller (while running)
store.synthesisStatus && !store.synthesisStatus.frozen
? h(StatusPoller, { store }) : null,
// Result link
store.synthesisStatus?.frozen && !store.synthesisStatus?.error
? h('a', { href: '/sompyle/result.mp3', style: 'display:block;margin-top:0.5rem' },
'Download result') : null,
// Synthesis error
store.synthesisStatus?.frozen && store.synthesisStatus?.errors
? h('div', { class: 'se-error', style: 'margin-top:0.5rem' },
store.synthesisStatus.errors) : null,
// Audio result
store.synthesisStatus?.file_accomplished
? h('audio', {
controls: true,
src: URLS.result,
style: 'display:block;width:100%;margin-top:0.5rem',
}) : null,
]);
};
},
+101 -40
View File
@@ -1,7 +1,18 @@
import { h, ref } from 'vue';
import { ObjectExtended } from './ObjectExtended.js';
import { EnvelopeEditor } from './EnvelopeEditor.js';
import { ShapeEditor } from './ShapeEditor.js';
import { LinkedInstrumentModal } from './LinkedInstrumentModal.js';
import { stressorToString } from '../exporter.js';
const H4 = { style: 'margin:0 0 0.5rem' };
function parseStressor(str) {
const groups = str.split(';').map(seg =>
seg.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n))
).filter(g => g.length > 0);
return groups.length ? { type: 'stressor', groups } : null;
}
function scoreInfoFields(info) {
return [
@@ -14,38 +25,42 @@ function scoreInfoFields(info) {
function instrFields(instr) {
return [
{ key: 'name', value: instr.name, editable: false },
{ key: 'linked', value: instr.isLinked, editable: false, type: 'boolean' },
{ key: 'name', value: instr.name, editable: false },
{ key: 'linked', value: instr.isLinked, editable: false, type: 'boolean' },
{ key: 'NOT_CHANGED_SINCE', value: instr.notChangedSince ?? '—', editable: false },
];
}
function variationFields(v) {
return [
{ key: 'depends_on', value: v.dependsOn ?? '—', editable: true },
];
return [{ key: 'depends_on', value: v.dependsOn ?? '—', editable: true }];
}
function shapeSection(label, shape, onChange) {
if (!shape) return null;
return h('div', { style: 'margin-top:0.5rem' }, [
h('strong', null, label),
h(ShapeEditor, { shape, onChange }),
]);
}
export const PaneFO = {
props: ['store'],
setup(props) {
// Pending edit held while the linked-instrument modal is shown.
const pendingEdit = ref(null); // { instr, apply: fn }
const pendingEdit = ref(null); // { instr, undo? }
function focused() {
const fp = props.store.focusPath;
return fp.length ? fp[fp.length - 1] : null;
}
// Returns a change handler that intercepts the first edit to a linked
// instrument and shows the embed-or-discard modal before applying it.
// `info` may carry { undo } forwarded from ShapeEditor / EnvelopeEditor.
function makeChangeHandler(instr, apply) {
// Intercepts the first edit to a linked instrument:
// shows embed-or-discard modal before committing. `info.undo`
// (forwarded from ShapeEditor/EnvelopeEditor) reverts the mutation on discard.
function makeChangeHandler(instr) {
return (info) => {
if (instr.isLinked && !instr.isDirty) {
pendingEdit.value = { instr, apply, undo: info?.undo };
pendingEdit.value = { instr, undo: info?.undo };
} else {
apply();
instr.isDirty = true;
props.store.markDirty();
}
@@ -56,7 +71,6 @@ export const PaneFO = {
instr.name = instr.name.split('/').pop();
instr.isLinked = false;
instr.isDirty = true;
pendingEdit.value.apply();
pendingEdit.value = null;
props.store.markDirty();
}
@@ -66,6 +80,12 @@ export const PaneFO = {
pendingEdit.value = null;
}
function instrOnChange(instr) {
return instr
? makeChangeHandler(instr)
: () => props.store.markDirty();
}
return () => {
const node = focused();
const children = [];
@@ -74,7 +94,7 @@ export const PaneFO = {
const model = props.store.scoreModel;
if (!model) return h('div', { class: 'se-fo-pane' }, 'No score loaded');
return h('div', { class: 'se-fo-pane' }, [
h('h4', { style: 'margin:0 0 0.5rem' }, 'Score'),
h('h4', H4, 'Score'),
h(ObjectExtended, {
fields: scoreInfoFields(model.info),
onChange: ({ key, value }) => {
@@ -88,22 +108,18 @@ export const PaneFO = {
if (node.type === 'instrument') {
children.push(
h('h4', { style: 'margin:0 0 0.5rem' }, `Instrument: ${node.name}`),
h('h4', H4, `Instrument: ${node.name}`),
h(ObjectExtended, { fields: instrFields(node), onChange: null }),
);
} else if (node.type === 'variation') {
// Find the ancestor instrument for linked-instrument gating.
const instr = props.store.scoreModel?.instruments.find(
i => i.variations?.includes(node) ||
i.variations?.some(v => v.subvariations?.includes(node))
const instr = props.store.scoreModel.instruments.find(
i => i.variations.includes(node) ||
i.variations.some(v => v.subvariations.includes(node))
) ?? null;
const onChange = instr
? makeChangeHandler(instr, () => { props.store.markDirty(); })
: () => props.store.markDirty();
const onChange = instrOnChange(instr);
children.push(
h('h4', { style: 'margin:0 0 0.5rem' }, 'Variation'),
h('h4', H4, 'Variation'),
h(ObjectExtended, { fields: variationFields(node), onChange: ({ key, value }) => {
if (key === 'depends_on') {
const old = node.dependsOn;
@@ -118,29 +134,74 @@ export const PaneFO = {
: null,
);
} else if (node.type === 'label_spec') {
const instr = props.store.scoreModel?.instruments.find(
i => i.variations?.some(v =>
v.labelSpecs?.includes(node) ||
v.subvariations?.some(sv => sv.labelSpecs?.includes(node))
const instr = props.store.scoreModel.instruments.find(
i => i.variations.some(v =>
v.labelSpecs.includes(node) ||
v.subvariations.some(sv => sv.labelSpecs.includes(node))
)
) ?? null;
const onChange = instr
? makeChangeHandler(instr, () => { props.store.markDirty(); })
: () => props.store.markDirty();
const onChange = instrOnChange(instr);
children.push(
h('h4', { style: 'margin:0 0 0.5rem' }, `Label: ${node.label}`),
h('h4', H4, `Label: ${node.label}`),
node.basicProperties
? h(EnvelopeEditor, { basicProperties: node.basicProperties, onChange })
: null,
);
} else if (node.type === 'bar') {
const markBarDirty = () => { node.isDirty = true; props.store.markDirty(); };
children.push(
h('h4', { style: 'margin:0 0 0.5rem' }, `Bar: ${node.id}`),
h(ObjectExtended, { fields: [
{ key: 'id', value: node.id, editable: false },
], onChange: null }),
h('h4', H4, `Bar: ${node.id}`),
h(ObjectExtended, {
fields: [
{ key: 'id', value: node.id, editable: false },
{ key: 'beats_per_minute', value: node.tempoLevels ?? '', editable: true, type: 'number' },
{ key: 'stress_pattern', value: stressorToString(node.stressor), editable: true },
],
onChange: ({ key, value }) => {
if (key === 'beats_per_minute') node.tempoLevels = isNaN(value) ? null : value;
if (key === 'stress_pattern') node.stressor = parseStressor(value);
markBarDirty();
},
}),
shapeSection('Upper stress bound', node.upperStressBound, markBarDirty),
shapeSection('Lower stress bound', node.lowerStressBound, markBarDirty),
shapeSection('Tempo shape', node.tempoShape, markBarDirty),
);
} else if (node.type === 'voice') {
children.push(
h('h4', H4, `Voice: ${node.name}`),
h(ObjectExtended, {
fields: [
{ key: 'articles', value: node.articles.join(', ') || '—', editable: false },
{ key: 'motifs', value: node.motifs.join(', ') || '—', editable: false },
{ key: 'offsets', value: String(node.offsets.length), editable: false },
],
onChange: null,
}),
);
} else if (node.type === 'offset') {
const noteStr = n => `${n.pitch}${n.effLength != null ? ' ' + n.effLength : ''}`;
const clusterStr = c => c.notes.length
? c.notes.map(n => `${n.letter ?? ''}${n.shift != null ? n.shift : ''}${n.length != null ? ' ' + n.length : ''}`).join(', ')
: `cluster[${c.index}]`;
const noteItem = (text, i) => h('li', { class: 'se-object-item', key: i },
h('span', { class: 'se-object-label' }, text));
children.push(
h('h4', H4, `Tick: ${node.tick}`),
h(ObjectExtended, {
fields: [{ key: 'tick', value: node.tick, editable: false }],
onChange: null,
}),
node.stemNotes.length ? h('div', { style: 'margin-top:0.5rem' }, [
h('strong', null, 'Stem notes'),
h('ul', { class: 'se-object-list' }, node.stemNotes.map((n, i) => noteItem(noteStr(n), i))),
]) : null,
node.clusters.length ? h('div', { style: 'margin-top:0.5rem' }, [
h('strong', null, 'Clusters'),
h('ul', { class: 'se-object-list' }, node.clusters.map((c, i) => noteItem(clusterStr(c), i))),
]) : null,
);
} else {
children.push(h('pre', { style: 'font-size:0.75rem;white-space:pre-wrap' },
@@ -152,8 +213,8 @@ export const PaneFO = {
pendingEdit.value
? h(LinkedInstrumentModal, {
instrumentName: pendingEdit.value.instr.name,
onEmbed: () => embedInstrument(pendingEdit.value.instr),
onDiscard: discardEdit,
onEmbed: () => embedInstrument(pendingEdit.value.instr),
onDiscard: discardEdit,
})
: null,
]);
+19 -15
View File
@@ -1,7 +1,6 @@
import { h } from 'vue';
import { ObjectShort } from './ObjectShort.js';
// Shows sub-objects of the currently focused node — variations, bars, voices, etc.
export const PaneSubObjects = {
props: ['store', 'onFocusFO'],
setup(props) {
@@ -15,17 +14,17 @@ export const PaneSubObjects = {
if (node.type === 'score') {
const items = [];
if (node.info)
items.push({ kind: 'info', node: node.info, label: node.info.title ?? '(no title)', hasChildren: false });
items.push({ kind: 'info', node: node.info, label: node.info.title ?? '(no title)', hasChildren: false });
if (node.tuning)
items.push({ kind: 'tuning', node: node.tuning, label: `base ${node.tuning.base ?? '?'}`, hasChildren: false });
items.push({ kind: 'tuning', node: node.tuning, label: `base ${node.tuning.base ?? '?'}`, hasChildren: false });
for (const a of (node.articles ?? []))
items.push({ kind: 'article', node: a, label: a.name, hasChildren: false });
items.push({ kind: 'article', node: a, label: a.name, hasChildren: false });
for (const sv of (node.stageVoices ?? []))
items.push({ kind: 'stage', node: sv, label: sv.name, hasChildren: false });
items.push({ kind: 'stage', node: sv, label: sv.name, hasChildren: false });
for (const i of node.instruments)
items.push({ kind: 'instrument', node: i, label: i.name, hasChildren: true });
items.push({ kind: 'instrument', node: i, label: i.name, hasChildren: true });
for (const b of node.bars)
items.push({ kind: 'bar', node: b, label: b.id, hasChildren: false });
items.push({ kind: 'bar', node: b, label: b.id, hasChildren: Object.keys(b.voices).length > 0 });
return items;
}
if (node.type === 'instrument') {
@@ -33,12 +32,13 @@ export const PaneSubObjects = {
kind: 'variation',
node: v,
label: `variation ${idx + 1}${v.dependsOn ? ` (${v.dependsOn})` : ''}`,
hasChildren: true,
}));
}
if (node.type === 'variation') {
return [
...node.labelSpecs.map(ls => ({
kind: 'label_spec', node: ls, label: ls.label ?? '(no label)',
kind: 'label_spec', node: ls, label: ls.label ?? '(no label)', hasChildren: false,
})),
...node.subvariations.map((sv, idx) => {
const dep = sv.dependsOn;
@@ -51,7 +51,12 @@ export const PaneSubObjects = {
}
if (node.type === 'bar') {
return Object.entries(node.voices).map(([name, v]) => ({
kind: 'voice', node: v, label: name,
kind: 'voice', node: v, label: name, hasChildren: v.offsets.length > 0,
}));
}
if (node.type === 'voice') {
return node.offsets.map((o, idx) => ({
kind: 'offset', node: o, label: `tick ${o.tick ?? idx}`, hasChildren: false,
}));
}
return [];
@@ -62,20 +67,19 @@ export const PaneSubObjects = {
const items = subItems(node);
if (!items.length) return h('div', null, h('em', null, 'No sub-objects'));
return h('div', null, [
return h('div', null,
h('ul', { class: 'se-object-list' }, items.map((item, idx) =>
h(ObjectShort, {
key: idx,
node: item.node,
label: item.label,
typeTag: item.kind,
focused: props.store.focusPath.includes(item.node),
hasChildren: item.hasChildren ?? (item.kind !== 'bar' && item.kind !== 'voice'),
onFocus: () => { props.store.pushFocus(item.node); props.onFocusFO?.(); },
hasChildren: item.hasChildren,
onFocus: () => { props.store.pushFocus(item.node); props.onFocusFO?.(); },
onDrillDown: () => { props.store.pushFocus(item.node); props.onFocusFO?.(); },
})
)),
]);
))
);
};
},
};
+106 -14
View File
@@ -23,12 +23,12 @@ function serializeShape(shape) {
// ── FM / AM modulation ─────────────────────────────────────────────────────
// RFC §3.2.1.1.6-7: FM = FREQUENCY ["f"/"F"] ["@" OSC] ["[" SHAPE "]"] ";" MOD ":" BASE
function serializeFm(fm) {
let s = String(fm.frequency ?? '');
if (fm.factor) s += fm.factor;
if (fm.osc) s += `@${fm.osc}`;
if (fm.shape) s += `[${serializeShape(fm.shape)}]`;
s += `;${fm.mod ?? ''}:${fm.base ?? ''}`;
function serializeModulation(m) {
let s = String(m.frequency ?? '');
if (m.oscillator) s += `@${m.oscillator}`;
if (m.shape) s += `[${serializeShape(m.shape)}]`;
s += `;${m.mod_share ?? ''}:${m.base_share ?? ''}`;
if (m.init_phase != null) s += m.init_phase >= 0 ? `+${m.init_phase}` : String(m.init_phase);
return s;
}
@@ -46,7 +46,8 @@ function basicPropLines(bp) {
if (s) lines.push(`S: "${s}"`);
const r = serializeShape(bp.R);
if (r) lines.push(`R: "${r}"`);
for (const fm of (bp.fmModulations ?? [])) lines.push(`FM: "${serializeFm(fm)}"`);
for (const fm of (bp.fmModulations ?? [])) lines.push(`FM: "${serializeModulation(fm)}"`);
for (const am of (bp.amModulations ?? [])) lines.push(`AM: "${serializeModulation(am)}"`);
return lines;
}
@@ -75,7 +76,8 @@ function variationLines(v) {
if (vol) lines.push(`VOLUMES: "${vol}"`);
const timbre = serializeShape(v.timbre);
if (timbre) lines.push(`TIMBRE: "${timbre}"`);
for (const fm of (v.fmModulations ?? [])) lines.push(`FM: "${serializeFm(fm)}"`);
for (const fm of (v.fmModulations ?? [])) lines.push(`FM: "${serializeModulation(fm)}"`);
for (const am of (v.amModulations ?? [])) lines.push(`AM: "${serializeModulation(am)}"`);
for (const sv of (v.subvariations ?? [])) lines.push(...variationLines(sv));
return lines;
}
@@ -89,7 +91,8 @@ function variationLines(v) {
function instrCharacterLines(instr) {
const variations = instr.variations ?? [];
const hasRootProps = instr.basicProperties || instr.volumes || instr.timbre ||
(instr.fmModulations ?? []).length > 0;
(instr.fmModulations ?? []).length > 0 ||
(instr.amModulations ?? []).length > 0;
const syntheticRoot = hasRootProps
? {
basicProperties: instr.basicProperties,
@@ -98,6 +101,7 @@ function instrCharacterLines(instr) {
volumes: instr.volumes,
timbre: instr.timbre,
fmModulations: instr.fmModulations ?? [],
amModulations: instr.amModulations ?? [],
}
: null;
@@ -134,11 +138,36 @@ export function exportInstrument(instr) {
}
// ── Score patch ────────────────────────────────────────────────────────────
// Replace dirty instrument blocks in rawScoreText with RFC-serialized output.
// Non-dirty instruments are left verbatim.
// Replace dirty instrument blocks and dirty bar _meta blocks.
// Voice note content in bar documents is left verbatim.
export function patchScore(rawScoreText, instruments) {
const lines = rawScoreText.split('\n');
const META_KEYS = ['title', 'composer', 'source', 'encrypter'];
function patchMetadata(text, info) {
if (!info) return text;
const lines = text.split('\n');
const replaced = new Set();
const out = lines.map(line => {
for (const key of META_KEYS) {
if (line.startsWith(key + ':') && info[key] != null && info[key] !== '') {
replaced.add(key);
return `${key}: ${info[key]}`;
}
}
return line;
});
const prepend = META_KEYS
.filter(k => !replaced.has(k) && info[k] != null && info[k] !== '')
.map(k => `${k}: ${info[k]}`);
if (prepend.length) out.unshift(...prepend);
return out.join('\n');
}
function patchInstrumentHeader(text, instruments) {
const lines = text.split('\n');
const result = [];
const instrMap = {};
for (const instr of instruments) {
@@ -149,7 +178,6 @@ export function patchScore(rawScoreText, instruments) {
let i = 0;
while (i < lines.length) {
const line = lines[i];
// RFC §4.4: "instrument NAME:" — strip optional quotes around name
const m = line.match(/^instrument\s+(.+?)\s*:/);
if (m) {
const rawName = m[1].replace(/^'|'$/g, '');
@@ -171,3 +199,67 @@ export function patchScore(rawScoreText, instruments) {
return result.join('\n');
}
export function stressorToString(s) {
if (!s?.groups?.length) return '';
return s.groups.map(g => g.join(',')).join(';');
}
function patchBarMeta(doc, bar) {
const props = [];
const sp = stressorToString(bar.stressor);
if (sp) props.push(` stress_pattern: ${sp}`);
if (bar.tempoLevels != null)
props.push(` beats_per_minute: ${bar.tempoLevels}`);
const ub = serializeShape(bar.upperStressBound);
if (ub) props.push(` upper_stress_bound: ${ub}`);
const lb = serializeShape(bar.lowerStressBound);
if (lb) props.push(` lower_stress_bound: ${lb}`);
if (bar.tempoShape) { const ts = serializeShape(bar.tempoShape); if (ts) props.push(` tempo_shape: "${ts}"`); }
const lines = doc.split('\n');
const out = [];
let i = 0;
let replaced = false;
while (i < lines.length) {
if (lines[i] === '_meta:') {
replaced = true;
i++;
while (i < lines.length && lines[i].startsWith(' ')) i++;
if (props.length) { out.push('_meta:'); out.push(...props); }
} else {
out.push(lines[i]);
i++;
}
}
if (!replaced && props.length) {
const idIdx = out.findIndex(l => /^_id:/.test(l));
if (idIdx !== -1) out.splice(idIdx + 1, 0, '_meta:', ...props);
}
return out.join('\n');
}
export function patchScore(rawScoreText, instruments, bars = [], info = null) {
const SEP = '\n---\n';
const [header, ...barDocs] = rawScoreText.split(SEP);
const patchedHeader = patchInstrumentHeader(patchMetadata(header, info), instruments);
if (!barDocs.length) return patchedHeader;
const barMap = {};
for (const bar of bars) barMap[bar.id] = bar;
const patchedBarDocs = barDocs.map(doc => {
const m = doc.match(/^_id:\s*(\S+)/m);
if (!m) return doc;
const bar = barMap[m[1]];
if (!bar?.isDirty) return doc;
return patchBarMeta(doc, bar);
});
return [patchedHeader, ...patchedBarDocs].join(SEP);
}
+9
View File
@@ -9,6 +9,15 @@
<div id="score-editor-app"
data-import-on-load="{{ import_on_load }}">
</div>
<script>
window.NEUSICIAN_URLS = {
astlog: "{{ url_for('astlog') }}",
score: "{{ url_for('score') }}",
status: "{{ url_for('statusjson') }}",
result: "{{ url_for('send_audio_generated') }}",
submit: "{{ url_for('public-yaml-acceptor') }}"
};
</script>
<script type="importmap">
{
"imports": {
+186 -1
View File
@@ -4,7 +4,7 @@
import { readFileSync } from 'fs';
import { parseAstLog, buildModel } from './static/ast-parser.js';
import { exportInstrument, patchScore } from './static/exporter.js';
import { exportInstrument, patchScore, stressorToString } from './static/exporter.js';
const FIXTURE = new URL('./fixtures/ast.log', import.meta.url);
const text = readFileSync(FIXTURE, 'utf8');
@@ -243,6 +243,191 @@ ok('FM shape start', fm?.shape?.start === '6' || fm?.shape?.start === 6);
fmInstr.isDirty = true;
const fmOut = exportInstrument(fmInstr);
ok('FM exported with [shape]', /FM:.*\[.*\]/.test(fmOut));
ok('FM exported with mod:base', /FM:.*;\d+:\d+/.test(fmOut));
// ── DEBUG line skipping ────────────────────────────────────────────────────
section('DEBUG line skipping');
const DEBUG_FIXTURE = `00 instrument 'dbg'
01 # DEBUG missing level: [('character', [])]
01 character.basic_properties
02 A.shape length=1
03 shape.coords x='1' y='10' z=1 is_sharp=False
03 shape.coords x='2' y='0' z=1 is_sharp=False
`;
const dbgModel = buildModel(parseAstLog(DEBUG_FIXTURE));
const dbgInstr = dbgModel.instruments[0];
ok('DEBUG line skipped — instrument parsed', !!dbgInstr);
ok('DEBUG line skipped — A shape present', !!dbgInstr?.basicProperties?.A);
ok('DEBUG line skipped — A shape has 2 coords', dbgInstr?.basicProperties?.A?.coords?.length === 2);
// ── parseRest edge cases ───────────────────────────────────────────────────
section('parseRest edge cases');
const PARSE_FIXTURE = `00 instrument 'pi'
01 character.variation depends_on='pitch'
02 variation.label_spec 'myLabel' foo=True bar='hello world'
`;
const parseModel = buildModel(parseAstLog(PARSE_FIXTURE));
const parseInstr = parseModel.instruments[0];
const parseLs = parseInstr?.variations[0]?.labelSpecs[0];
ok('quoted positional parsed', parseLs?.label === 'myLabel');
ok('bool prop coerced', parseInstr?.variations[0]?.props?.depends_on === 'pitch' || parseInstr?.variations[0]?.dependsOn === 'pitch');
// ── Sub-variation for_value ────────────────────────────────────────────────
section('Sub-variation for_value');
const SV_FIXTURE = `00 instrument 'piano'
01 character.variation depends_on='pitch'
02 variation.subvariation for_value='440.0'
02 variation.subvariation for_value='880.0'
`;
const svModel = buildModel(parseAstLog(SV_FIXTURE));
const svInstr = svModel.instruments[0];
const svs = svInstr?.variations[0]?.subvariations;
ok('two subvariations parsed', svs?.length === 2);
ok('first subvariation dependsOn=440', svs?.[0]?.dependsOn == 440);
ok('second subvariation dependsOn=880', svs?.[1]?.dependsOn == 880);
// ── AM modulation ─────────────────────────────────────────────────────────
section('AM modulation (synthetic)');
const AM_FIXTURE = `00 instrument 'test'
01 character.basic_properties
02 AM.modulation frequency='3' mod_share='2' base_share='5' overdrive=True oscillator='sawtooth'
03 envelope.shape length=2 start='0' z=1
04 shape.coords x='1' y='1' z=1 is_sharp=False
04 shape.coords x='2' y='0' z=1 is_sharp=False
`;
const amRaw = parseAstLog(AM_FIXTURE);
const amModel = buildModel(amRaw);
const amInstr = amModel.instruments[0];
ok('synthetic AM instrument parsed', !!amInstr);
const amBp = amInstr?.basicProperties;
ok('AM in basicProperties', amBp?.amModulations?.length === 1);
const am = amBp?.amModulations?.[0];
ok('AM frequency', am?.frequency == 3);
ok('AM oscillator', am?.oscillator === 'sawtooth');
ok('AM mod_share', am?.mod_share == 2);
ok('AM base_share', am?.base_share == 5);
ok('AM has shape', !!am?.shape);
ok('AM shape coords', am?.shape?.coords?.length === 2);
amInstr.isDirty = true;
const amOut = exportInstrument(amInstr);
ok('AM exported', amOut.includes('AM:'));
ok('AM exported with @sawtooth', /AM:.*@sawtooth/.test(amOut));
ok('AM exported with mod:base', /AM:.*;\d+:\d+/.test(amOut));
ok('AM exported with [shape]', /AM:.*\[.*\]/.test(amOut));
// ── serializeModulation edge cases ─────────────────────────────────────────
section('serializeModulation edge cases');
const MOD_INIT_FIXTURE = `00 instrument 'test'
01 character.basic_properties
02 FM.modulation frequency='5' mod_share='1' base_share='2' overdrive=True oscillator='square' init_phase='+3'
`;
const modModel = buildModel(parseAstLog(MOD_INIT_FIXTURE));
const modInstr = modModel.instruments[0];
modInstr.isDirty = true;
const modOut = exportInstrument(modInstr);
ok('FM with non-sine oscillator exported', /FM:.*@square/.test(modOut));
ok('FM with init_phase exported', /FM:.*;.*[+-]\d+/.test(modOut));
// ── stressorToString ───────────────────────────────────────────────────────
section('stressorToString');
ok('null stressor → empty string', stressorToString(null) === '');
ok('empty groups → empty string', stressorToString({ groups: [] }) === '');
ok('single group', stressorToString({ groups: [[1, 2, 3]] }) === '1,2,3');
ok('multiple groups', stressorToString({ groups: [[1, 2], [3]] }) === '1,2;3');
ok('single-element groups', stressorToString({ groups: [[4], [2], [1]] }) === '4;2;1');
// ── multiple-variation export (YAML sequence) ──────────────────────────────
section('Multiple-variation export');
const MV_FIXTURE = `00 instrument 'mv'
01 character.variation
02 A.shape length=1
03 shape.coords x='1' y='10' z=1 is_sharp=False
03 shape.coords x='2' y='0' z=1 is_sharp=False
01 character.variation depends_on='stress'
02 A.shape length=2
03 shape.coords x='1' y='5' z=1 is_sharp=False
03 shape.coords x='2' y='0' z=1 is_sharp=False
`;
const mvModel = buildModel(parseAstLog(MV_FIXTURE));
const mvInstr = mvModel.instruments[0];
ok('two variations parsed', mvInstr?.variations?.length === 2);
mvInstr.isDirty = true;
const mvOut = exportInstrument(mvInstr);
ok('multi-variation: has character:', mvOut.includes('character:'));
ok('multi-variation: YAML sequence (- )', /^\s+- /m.test(mvOut));
ok('multi-variation: second variation has ATTR:', mvOut.includes('ATTR: stress'));
// ── patchBarMeta ───────────────────────────────────────────────────────────
section('patchBarMeta (via patchScore)');
const RAW_SCORE_WITH_BARS = `instrument alpha:
character:
A: "1:0,10;1,0"
---
_id: 001P1L1M1
_meta:
stress_pattern: 1,2;3
beats_per_minute: 120
voice soprano:
- C4 4
---
_id: 001P1L1M2
_meta:
beats_per_minute: 100
voice soprano:
- D4 4
`;
const dirtyBar = {
id: '001P1L1M1',
isDirty: true,
stressor: { groups: [[2, 3], [1]] },
tempoLevels: 140,
upperStressBound: null,
lowerStressBound: null,
tempoShape: null,
};
const cleanBar = {
id: '001P1L1M2',
isDirty: false,
stressor: null, tempoLevels: null,
upperStressBound: null, lowerStressBound: null, tempoShape: null,
};
const barPatched = patchScore(RAW_SCORE_WITH_BARS, [], [dirtyBar, cleanBar]);
const barPatchedLines = barPatched.split('\n');
ok('dirty bar _meta updated with new BPM', barPatched.includes('beats_per_minute: 140'));
ok('dirty bar stress_pattern updated', barPatched.includes('stress_pattern: 2,3;1'));
ok('dirty bar voice content preserved', barPatched.includes('- C4 4'));
ok('clean bar unchanged', barPatched.includes('beats_per_minute: 100'));
ok('clean bar voice preserved', barPatched.includes('- D4 4'));
ok('document separators preserved', (barPatched.match(/\n---\n/g) ?? []).length === 2);
// ── patchScore metadata ────────────────────────────────────────────────────
section('patchScore metadata');
const META_SCORE = `title: Old Title
composer: Old Composer
source: Some Book
instrument alpha:
character:
A: "1:0,10;1,0"
`;
const updatedInfo = { title: 'New Title', composer: 'New Composer', source: '', encrypter: 'Me' };
const metaPatched = patchScore(META_SCORE, [], [], updatedInfo);
ok('existing title replaced', metaPatched.includes('title: New Title'));
ok('existing composer replaced', metaPatched.includes('composer: New Composer'));
ok('empty value leaves existing line', metaPatched.includes('source: Some Book'));
ok('new key prepended', metaPatched.includes('encrypter: Me'));
ok('instrument block untouched', metaPatched.includes('instrument alpha:'));
const META_SCORE_NO_TITLE = `composer: Bach\n\ninstrument ki:\n character:\n`;
const noTitlePatched = patchScore(META_SCORE_NO_TITLE, [], [], { title: 'Fugue', composer: 'Bach' });
ok('missing title prepended', noTitlePatched.includes('title: Fugue'));
ok('existing composer not duplicated', (noTitlePatched.match(/^composer:/mg) ?? []).length === 1);
const nullInfoPatched = patchScore(META_SCORE, [], [], null);
ok('null info leaves metadata unchanged', nullInfoPatched.includes('title: Old Title'));
// ── Summary ────────────────────────────────────────────────────────────────
console.log(`\n══ ${pass} passed, ${fail} failed ══\n`);