vizmatic 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scene-cli.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{SCENE_LIMITS,renderSceneFrame,renderSceneVideo}from"./chunk-WUDZYTV6.js";import"./chunk-PSBF4TEK.js";import{readFile,stat}from"fs/promises";import{extname}from"path";async function main(){const args=process.argv.slice(2);if(args.length===1&&["--help","-h"].includes(args[0])){process.stdout.write("Usage: vizmatic-scene --input request.json --output scene.png|scene.mp4\nAll request time values are in seconds. Source is bare TSX, never a Node module.\nOptional JSON outputScale (0.25 to 1) reduces raster resolution; previewFps (MP4 only) reduces output fps while preserving logical scene globals. Metadata reports effective output dimensions and fps.\n");return}if(args.length!==4||args[0]!=="--input"||args[2]!=="--output"){throw new Error("Usage: vizmatic-scene --input request.json --output scene.png|scene.mp4")}const input=args[1],outputPath=args[3];const extension=extname(outputPath).toLowerCase();if(extension!==".png"&&extension!==".mp4")throw new Error("Scene output must be a PNG or MP4 file.");if((await stat(input)).size>SCENE_LIMITS.sourceBytes*6+32768)throw new Error("Scene request file exceeds its size limit.");const request=JSON.parse(await readFile(input,"utf8"));if(!request||typeof request!=="object"||Array.isArray(request))throw new Error("Scene request must be a JSON object.");const allowed=new Set(["source","width","height","duration","time","fps","theme","cues","seed","outputScale",...extension===".mp4"?["previewFps"]:[]]);if(Object.keys(request).some(name=>!allowed.has(name)))throw new Error("Scene request contains an unsupported field.");const options={...request,outputPath};const metadata=extension===".png"?await renderSceneFrame(options):await renderSceneVideo(options);process.stdout.write(`${JSON.stringify(metadata)}
2
+ import{SCENE_LIMITS,renderSceneFrame,renderSceneVideo}from"./chunk-MAHT32CE.js";import"./chunk-PSBF4TEK.js";import{readFile,stat}from"fs/promises";import{extname}from"path";async function main(){const args=process.argv.slice(2);if(args.length===1&&["--help","-h"].includes(args[0])){process.stdout.write("Usage: vizmatic-scene --input request.json --output scene.png|scene.mp4\nAll request time values are in seconds. Source is bare TSX, never a Node module.\nOptional JSON outputScale (0.25 to 1) reduces raster resolution; previewFps (MP4 only) reduces output fps while preserving logical scene globals. Metadata reports effective output dimensions and fps.\n");return}if(args.length!==4||args[0]!=="--input"||args[2]!=="--output"){throw new Error("Usage: vizmatic-scene --input request.json --output scene.png|scene.mp4")}const input=args[1],outputPath=args[3];const extension=extname(outputPath).toLowerCase();if(extension!==".png"&&extension!==".mp4")throw new Error("Scene output must be a PNG or MP4 file.");if((await stat(input)).size>SCENE_LIMITS.sourceBytes*6+32768)throw new Error("Scene request file exceeds its size limit.");const request=JSON.parse(await readFile(input,"utf8"));if(!request||typeof request!=="object"||Array.isArray(request))throw new Error("Scene request must be a JSON object.");const allowed=new Set(["source","width","height","duration","time","fps","theme","cues","seed","outputScale",...extension===".mp4"?["previewFps"]:[]]);if(Object.keys(request).some(name=>!allowed.has(name)))throw new Error("Scene request contains an unsupported field.");const options={...request,outputPath};const metadata=extension===".png"?await renderSceneFrame(options):await renderSceneVideo(options);process.stdout.write(`${JSON.stringify(metadata)}
3
3
  `)}main().catch(error=>{process.stderr.write(`${error instanceof Error?error.message:"Scene rendering failed."}
4
4
  `.slice(0,4096));process.exitCode=1});
@@ -0,0 +1,25 @@
1
+ import { createTeachingCategoricalSampling, categoricalSampling } from '../../src/teaching-categorical-sampling'
2
+ import type { TeachingPainter } from '../../src/teaching-canvas'
3
+ import type { CanvasBounds } from '../../src/canvas-components'
4
+
5
+ /** Supplied deterministic draws illustrate one possible sample, not a randomly executed experiment. */
6
+ export const tailLossFixture = {
7
+ normalization: 'probabilities' as const,
8
+ categories: [{ id: 'common', label: 'Common', mass: .95 }, { id: 'rare', label: 'Rare', mass: .05 }],
9
+ draws: [.1, .3, .5, .7, .9, .2, .4, .8].map((uniform, index) => ({ id: `S${index + 1}`, uniform })),
10
+ }
11
+
12
+ /** The caller binds progress and reveal to its narration; a prediction starts at zero with reveal=false. */
13
+ export function drawCategoricalTailLoss<Shape extends CanvasBounds>(painter: TeachingPainter<Shape>, progress: number, reveal: boolean, theme: 'dark' | 'light' = 'dark') {
14
+ if (!Number.isFinite(progress) || progress < 0 || progress > 1) throw new Error('Example progress must be in [0,1]')
15
+ const cursor = progress * tailLossFixture.draws.length, visibleDraws = Math.floor(cursor)
16
+ return createTeachingCategoricalSampling(painter)({
17
+ ...tailLossFixture, categories: tailLossFixture.categories.map((category, index) => ({ ...category, color: (theme === 'dark' ? ['#79A6FF', '#FF8DC3'] : ['#2459AD', '#9D2467'])[index] })),
18
+ color: theme === 'dark' ? '#DEE7F5' : '#172033', trackColor: theme === 'dark' ? '#18283B' : '#E5EAF0', x: 180, y: 260, width: 1560, height: 690,
19
+ visibleDraws, drawProgress: cursor - visibleDraws,
20
+ showEmpirical: reveal,
21
+ })
22
+ }
23
+
24
+ export const replacementDistribution = categoricalSampling(tailLossFixture).categories.map(category => ({ id: category.id, label: category.label, mass: category.empiricalProbability! }))
25
+ export const omissionProbability = .95 ** 8
@@ -0,0 +1,48 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { createTeachingByteDifference } from '../../src/teaching-byte-diff'
4
+ import type { CanvasBounds, CanvasPainter } from '../../src/canvas-components'
5
+
6
+ const xml = (value: string) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
7
+ const bytes = (value: string) => new TextEncoder().encode(value)
8
+ const digest = (value: Uint8Array) => createHash('sha256').update(value).digest('hex').slice(0, 12)
9
+
10
+ /** Run: pnpm exec tsx examples/teaching-byte-diff.ts [--reveal] > /tmp/byte-diff.svg */
11
+ export function renderByteDifferenceExample(revealVerdict = false, scanProgress = 1): string {
12
+ const content: string[] = []
13
+ const painter: CanvasPainter<CanvasBounds> = {
14
+ rect(x, y, width, height, fill = 'none', stroke = 'none', radius = 0) {
15
+ content.push(`<rect x="${x}" y="${y}" width="${width}" height="${height}" rx="${radius}" fill="${fill}" stroke="${stroke}"/>`)
16
+ return { x, y, width, height }
17
+ },
18
+ text(value, x, y, size, color = '#E9EFFF', align = 'left', font = 'sans') {
19
+ const anchor = align === 'center' ? 'middle' : align === 'right' ? 'end' : 'start'
20
+ content.push(`<text x="${x}" y="${y}" font-size="${size}" fill="${color}" text-anchor="${anchor}" font-family="${font === 'mono' ? 'JetBrains Mono, monospace' : 'Inter, sans-serif'}">${xml(value)}</text>`)
21
+ },
22
+ container(_bounds, draw) { draw() },
23
+ labelScope(bounds, draw) {
24
+ if (bounds.width <= 0 || bounds.height <= 0) throw new Error('Invalid example label bounds')
25
+ draw()
26
+ },
27
+ opacity(alpha, draw) { content.push(`<g opacity="${alpha}">`); draw(); content.push('</g>') },
28
+ circle(x, y, radius, fill = 'none') { content.push(`<circle cx="${x}" cy="${y}" r="${radius}" fill="${fill}"/>`) },
29
+ }
30
+ painter.rect(0, 0, 1920, 1080, '#0A1018')
31
+ painter.text('The filename stays. The bytes change.', 960, 65, 42, '#E9EFFF', 'center')
32
+ const draw = createTeachingByteDifference(painter)
33
+ for (const [index, [name, before, after]] of [
34
+ ['EOF deletion', '4,0,82\n', '4,0,'],
35
+ ['Replacement', 'ID=7\n', 'ID=9\n'],
36
+ ['Insertion', 'ab\n', 'abX\n'],
37
+ ].entries()) {
38
+ const original = bytes(before), current = bytes(after), top = 95 + index * 325
39
+ painter.text(`${name} · SHA-256 ${digest(original)}… → ${digest(current)}…`, 110, top + 25, 25, '#63DEEC')
40
+ draw({ x: 110, y: top + 40, width: 1700, height: 270, fontSize: 25, maxColumns: 10,
41
+ before: original, after: current, scanProgress, revealVerdict })
42
+ }
43
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">${content.join('')}</svg>`
44
+ }
45
+
46
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
47
+ process.stdout.write(renderByteDifferenceExample(process.argv.includes('--reveal')))
48
+ }
@@ -0,0 +1,35 @@
1
+ import type { CanvasBounds } from '../../src/canvas-components'
2
+ import type { TeachingPainter } from '../../src/teaching-canvas'
3
+ import { createTeachingRoutedTransfer } from '../../src/teaching-routed-transfer'
4
+
5
+ /** A new parameter copy passes around three completed rank replicas. */
6
+ export function drawRoutedParameterBroadcast<Shape extends CanvasBounds>(painter: TeachingPainter<Shape>, progress: number) {
7
+ const cyan = '#63DEEC', blue = '#7FA8FF', ink = '#F2EFE6', panel = '#15171D'
8
+ painter.text('Share B′ while completed replicas stay readable', 450, 45, 26, ink, 'center')
9
+ const source = painter.rect(170, 90, 80, 70, panel, blue, 8)
10
+ painter.text('B′', 210, 135, 28, blue, 'center')
11
+ painter.text('Owner', 100, 135, 22, blue, 'center')
12
+ const obstacles = [260, 370, 480].map((y, rank) => {
13
+ const shape = painter.rect(170, y, 80, 70, panel, cyan, 8)
14
+ painter.text('B′', 210, y + 45, 28, cyan, 'center')
15
+ painter.text('Rank ' + rank, 95, y + 44, 22, ink, 'center')
16
+ return { id: `settled-rank-${rank}-B`, bounds: shape }
17
+ })
18
+ const target = painter.rect(170, 600, 80, 70, panel, cyan, 8)
19
+ painter.text('B′', 210, 645, 28, cyan, 'center')
20
+ painter.text('Rank 3', 95, 645, 22, ink, 'center')
21
+ const transfer = createTeachingRoutedTransfer(painter)({
22
+ id: 'owner-B-to-rank-3', source: { id: 'owner-B', shape: source, opacity: 1, side: 'right' },
23
+ target: { id: 'rank-3-B', shape: target, opacity: 1, side: 'right' },
24
+ corridor: { x: 130, y: 65, width: 500, height: 630 }, obstacles,
25
+ color: cyan, width: 4, margin: 6, progress,
26
+ marker: { radius: 15, fill: blue, stroke: ink, strokeWidth: 2 },
27
+ })
28
+ painter.text('The complete marker clears each settled replica.', 460, 735, 23, ink, 'center')
29
+ return transfer
30
+ }
31
+
32
+ export const routedParameterBroadcastExample = {
33
+ width: 900, height: 780, durationSeconds: 4,
34
+ draw: drawRoutedParameterBroadcast,
35
+ }
@@ -0,0 +1,29 @@
1
+ import type { CanvasPainter } from '../../src/canvas-components'
2
+ import { createTeachingTokenHistory, type TokenHistoryPhase } from '../../src/teaching-token-history'
3
+
4
+ // Vocabulary IDs can repeat; these IDs identify their immutable occurrences.
5
+ const prompt = [101, 102, 103].map((token, i) => ({ id: `prompt-${i}`, token }))
6
+ const accepted = [201, 202].map((token, i) => ({ id: `answer-${i}`, token }))
7
+ const retained = { prompt, accepted, processed: [...prompt, accepted[0]], emitted: accepted }
8
+
9
+ export function tokenHistoryExampleState(seconds: number) {
10
+ if (!Number.isFinite(seconds)) throw new Error('Example time must be finite')
11
+ const phase: TokenHistoryPhase = seconds < 3 ? 'resident' : seconds < 4 ? 'dropped' : seconds < 8 ? 'replay' : 'resident'
12
+ return { phase, replayProgress: Math.max(0, Math.min(1, (seconds - 4) / 4)) }
13
+ }
14
+
15
+ /** Retire KV, rebuild four processed positions, and preserve both already delivered outputs. */
16
+ export function drawTokenHistoryExample<Shape>(painter: CanvasPainter<Shape>, seconds: number) {
17
+ const state = tokenHistoryExampleState(seconds)
18
+ painter.text('What survives when this request loses its KV cache?', 100, 135, 42, '#F2EFE6')
19
+ painter.text('Outputs 201 and 202 were accepted and delivered; 202 has not yet been consumed.', 100, 230, 29, '#8D9CB9')
20
+ const result = createTeachingTokenHistory(painter)({ ...retained, ...state,
21
+ x: 100, y: 310, width: 1700, height: 620, fontSize: 30, focusPrefix: 'request-B' })
22
+ painter.text(seconds >= 8
23
+ ? 'Next ordinary input is 202. Replaying does not resample or resend 201 or 202.'
24
+ : state.phase === 'replay' ? 'Rebuild 101, 102, 103, 201 in order; keep accepted history fixed.'
25
+ : state.phase === 'dropped' ? 'The KV row is empty. The answer history is still present.'
26
+ : 'Predict which ledger may be discarded, and which ones must be retained.',
27
+ 100, 1040, 30, '#FFD75E')
28
+ return result
29
+ }
@@ -0,0 +1,55 @@
1
+ import { createTeachingCanvas, type TeachingPainter } from '../../src/teaching-canvas'
2
+ import { createTeachingVectorAccumulation, type WeightedVectorTerm } from '../../src/teaching-vector'
3
+ import type { CanvasBounds } from '../../src/canvas-components'
4
+
5
+ // A supplied two-coordinate EMA example, with beta=0.75.
6
+ const terms: readonly WeightedVectorTerm[] = [
7
+ { id: 'retained-memory', label: 'Previous buffer', weight: 0.75,
8
+ values: [8, 4], color: '#FFD75E' },
9
+ { id: 'opposing-gradient', label: 'Current gradient', weight: 0.25,
10
+ values: [-8, 8], color: '#FF8FC0' },
11
+ ]
12
+
13
+ export function momentumAccumulationExampleState(seconds: number) {
14
+ if (!Number.isFinite(seconds)) throw new Error('Example time must be finite')
15
+ const phase = (start: number, end: number) => Math.max(0, Math.min(1, (seconds - start) / (end - start)))
16
+ return {
17
+ progress: 0.5 * phase(3, 6) + 0.5 * phase(8, 10),
18
+ revealTotal: seconds >= 11,
19
+ prediction: seconds < 8,
20
+ }
21
+ }
22
+
23
+ /** Twelve seconds: predict, retain memory, hold, add the opposing gradient, then reveal. */
24
+ export function drawMomentumAccumulationExample<Shape extends CanvasBounds>(painter: TeachingPainter<Shape>, seconds: number) {
25
+ const state = momentumAccumulationExampleState(seconds)
26
+ const teaching = createTeachingCanvas(painter)
27
+ painter.text('Will a leftward gradient reverse the stored horizontal direction?', 100, 135, 40, '#F2EFE6')
28
+ painter.text('A supplied EMA update: retain three quarters, then add one quarter of the new input.', 100, 225, 29, '#8D9CB9')
29
+ const plot = teaching.axes({ x: 120, y: 315, width: 650, height: 650,
30
+ xDomain: [-1, 9], yDomain: [-1, 9], equalUnits: true,
31
+ xTicks: [0, 2, 4, 6, 8], yTicks: [0, 2, 4, 6, 8],
32
+ xLabel: 'horizontal component', yLabel: 'vertical component',
33
+ color: '#8D9CB9', fontSize: 24 })
34
+ const accumulation = createTeachingVectorAccumulation(painter)({ terms, progress: state.progress, plot,
35
+ ledger: { x: 970, y: 355, width: 820, height: 300 }, fontSize: 28,
36
+ totalLabel: 'New EMA buffer', totalTarget: 'buffer-result', revealTotal: state.revealTotal,
37
+ format: value => Number(value.toFixed(2)).toString() })
38
+ const [retainedX, retainedY] = accumulation.state.terms[0].currentEnd
39
+ const [incomingX, incomingY] = accumulation.state.terms[1].currentEnd
40
+ const retainedTip = plot.point(retainedX, retainedY)
41
+ const incomingTip = plot.point(incomingX, incomingY)
42
+ if (state.progress > 0) painter.text('0.75 × (8, 4)', retainedTip.x + 25, retainedTip.y + 45, 30, '#FFD75E')
43
+ if (seconds >= 8) painter.text('0.25 × (−8, 8)', incomingTip.x + 25, incomingTip.y - 45, 30, '#FF8FC0')
44
+ if (state.revealTotal) {
45
+ const origin = plot.point(0, 0)
46
+ painter.arrow(origin.x, origin.y, accumulation.endpoint.x, accumulation.endpoint.y, '#63DEEC', 3)
47
+ painter.text('The new horizontal component is +4.', 970, 750, 32, '#63DEEC')
48
+ painter.text('The leftward input reduced +6 to +4.', 970, 815, 28, '#FF8FC0')
49
+ painter.text('Stored direction persists while the path turns upward.', 970, 905, 28, '#F2EFE6')
50
+ } else {
51
+ painter.text(state.prediction ? 'Predict the sign before adding the incoming contribution.' : 'Check your predicted sign before we reveal the new buffer.',
52
+ 970, 800, 28, '#FFD75E')
53
+ }
54
+ return accumulation
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vizmatic",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Code-driven animation, diagrams, and charts: vector films that play live in a browser and export to MP4, with typed components for dense technical figures.",
5
5
  "type": "module",
6
6
  "license": "MIT",