Metadata-Version: 2.5
Name: rupaka
Version: 0.0.8
Summary: Interactive SVG demos from JSON specs, made of small reusable blocks, that make the learner predict first
Project-URL: Repository, https://github.com/vedicreader/rupaka
Project-URL: Documentation, https://vedicreader.github.io/rupaka/
Author-email: Karthik <karthik.rajgopal@hotmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: demos,interactive,learning,nbdev,svg,teaching
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Education
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.10
Requires-Dist: fastcore>=1.8
Provides-Extra: check
Requires-Dist: playwright>=1.40; extra == 'check'
Provides-Extra: dev
Requires-Dist: ipykernel>=7.3.0; extra == 'dev'
Requires-Dist: nbdev>=3.3.26; extra == 'dev'
Requires-Dist: notebook>=7.6.3; extra == 'dev'
Requires-Dist: playwright>=1.40; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# rupaka


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

rupaka (रूपक) means a form, a play that the audience sees, and the figure of speech that shows one thing through another.
A rupaka demo is one interactive figure that teaches one idea. The learner changes the inputs and sees the result change.

A demo never shows the answer first. Each demo follows one loop:

1.  Predict. The demo shows the inputs and asks one question. The result is hidden.
2.  Reveal. The learner locks in with ⌘↩. The demo shows the result and says if the prediction was right.
3.  Manipulate. Now the controls are live. The result changes when the inputs change.
4.  Explain. The caption ends with a new question that the learner answers with the controls.

The validator enforces step 1: a block that shows a value which the answer depends on must wait for the gate.
An explainer is the one exception. It has `"mode": "learn"` and no gate, so it shows a thing at once (see Explainers below).

## What a demo is

A demo is a JSON spec, not code. It has a small state, derived values from named functions (fns), and a list of blocks.
A model can write a spec safely, because a spec cannot run code.

| part | what it is |
|----|----|
| block | a reusable UI part in `rupaka/blocks/<name>/`: its JS, its CSS, a `block.json` manifest and an example |
| fn | a pure function that computes a derived value: [`rules`](https://vedicreader.github.io/rupaka/spec.html#rules), [`rrf`](https://vedicreader.github.io/rupaka/spec.html#rrf), [`softmax`](https://vedicreader.github.io/rupaka/spec.html#softmax), [`lookup`](https://vedicreader.github.io/rupaka/spec.html#lookup), [`expr`](https://vedicreader.github.io/rupaka/spec.html#expr), [`field`](https://vedicreader.github.io/rupaka/spec.html#field), `ids`, `pick`, `sort`, [`fmt`](https://vedicreader.github.io/rupaka/spec.html#fmt) |
| gate | the block that asks for the prediction and hides the result until the lock in |
| spec | the JSON object: `state`, `derive`, `blocks` and `tables`, and a `mode` that is `predict` (the default) or `learn` |

The blocks are [`gate`](https://vedicreader.github.io/rupaka/spec.html#gate), [`readout`](https://vedicreader.github.io/rupaka/spec.html#readout), [`caption`](https://vedicreader.github.io/rupaka/spec.html#caption), [`row`](https://vedicreader.github.io/rupaka/spec.html#row), [`stack`](https://vedicreader.github.io/rupaka/spec.html#stack), [`slider`](https://vedicreader.github.io/rupaka/spec.html#slider), [`toggle`](https://vedicreader.github.io/rupaka/spec.html#toggle), [`choice`](https://vedicreader.github.io/rupaka/spec.html#choice), [`wheel`](https://vedicreader.github.io/rupaka/spec.html#wheel), [`ranklist`](https://vedicreader.github.io/rupaka/spec.html#ranklist), [`bars`](https://vedicreader.github.io/rupaka/spec.html#bars), [`axis`](https://vedicreader.github.io/rupaka/spec.html#axis), [`point`](https://vedicreader.github.io/rupaka/spec.html#point), [`plot`](https://vedicreader.github.io/rupaka/spec.html#plot), [`grid`](https://vedicreader.github.io/rupaka/spec.html#grid) and [`pixels`](https://vedicreader.github.io/rupaka/spec.html#pixels).
For 3D, a [`scene`](https://vedicreader.github.io/rupaka/spec.html#scene) holds [`body`](https://vedicreader.github.io/rupaka/spec.html#body), [`force`](https://vedicreader.github.io/rupaka/spec.html#force), [`label3d`](https://vedicreader.github.io/rupaka/spec.html#label3d) and [`shot`](https://vedicreader.github.io/rupaka/spec.html#shot) blocks (see the section on 3D scenes below).

## Install

``` sh
pip install rupaka
```

The headless check needs playwright: `pip install "rupaka[check]"`. It uses the Chromium that `playwright install chromium` gives, or the browser in `$FASTCDP_CHROME`. It never runs your everyday Chrome.

## How to use

Build a spec with the builders, or write the JSON.

``` python
from rupaka.spec import *
```

``` python
d = demo('sum', 'A sum', ask='Predict the sum before you see it.', state=dict(a=2, b=3), derive=[expr('a + b', 'sum')],
         blocks=[gate('s', 'What is {a} + {b}?', [4, 5, 6], 'sum', why='Say why, in one line.'),
                 readout('{a} + {b} = {sum}', after='s')])
```

[`validate`](https://vedicreader.github.io/rupaka/spec.html#validate) returns the errors. An empty list means the spec is good.

``` python
assert validate(d) == []
```

A readout that shows the sum before the gate breaks the think rule:

``` python
bad = {**d, 'blocks': [d['blocks'][0], readout('{a} + {b} = {sum}')]}
validate(bad)
```

Then put the demo where the learner is:

| where | how |
|----|----|
| a notebook (leela, Jupyter) | `show(spec)`: an HTML output in a sandboxed frame, and the `application/vnd.rupaka+json` mime |
| Markdown | `md(spec)` writes a ```` ```rupaka ```` fence; `md(spec, frame=True)` writes a frame that leela draws today |
| a FastHTML page | `Demo(spec)` and `Assets('/rupaka')`; serve `bundle('js')` and `bundle('css')` at that prefix |
| a file | `save(spec, 'demo.html')` writes one page that works from `file://` with no network |

`check(spec)` draws the demo in headless Chrome and plays it. `author(concept, ask)` asks a model for a demo, and checks and repairs it.

## The host API

A host page can read and change a demo that it mounted. In these calls, `el` is the element that holds the demo: the `[data-rupaka]` element, or the element that you gave to `Rupaka.mount`.

| call | what it does |
|----|----|
| `Rupaka.state(el)` | gives a copy of the input keys (the keys of `spec.state`) and their values |
| `Rupaka.set(el, state)` | sets the input keys that `state` has, then runs `derive` one time and draws one time. It ignores other keys. |
| `Rupaka.options(el, gate)` | gives the option values of the gate [`gate`](https://vedicreader.github.io/rupaka/spec.html#gate), in the order that the gate shows them. Each value is the value itself, not the text that the gate shows. The gate reads options from the state after `derive`, and this call does the same. An unknown gate gives `null`. |
| `Rupaka.settle(el, gate, pick, {answer})` | closes the gate [`gate`](https://vedicreader.github.io/rupaka/spec.html#gate) as if the learner picked `pick`. It draws the verdict and shows the blocks that wait for the gate. With `pick` null, the gate closes with no verdict. An unknown gate does nothing and gives `false`. The options object is optional. |
| `Rupaka.open(el, gate)` | opens the closed gate [`gate`](https://vedicreader.github.io/rupaka/spec.html#gate) again, as the Try another button of the gate does. It removes the pick, the reason and the verdict, and hides the blocks that wait for the gate. It draws one time. It does not move the focus. A gate that is open does not change, and the call gives `true`. A gate that waits for the host to save a prediction does not open, and the call gives `false`. An unknown gate does nothing and gives `false`. |
| `Rupaka.mount(el, spec, {save})` | calls `save(state)` after each change of an input key. `state` is the value that `Rupaka.state(el)` gives. |

`Rupaka.set`, `Rupaka.settle` and `Rupaka.open` never send `rk-predict`, never add to `st.log` and never call [`save`](https://vedicreader.github.io/rupaka/render.html#save). `Rupaka.options` only reads. A `lock` does not stop `Rupaka.set`. Each call throws an error when no demo is mounted in `el`.

To show one demo in two windows, mount the spec in each window. Send `Rupaka.state` of the first copy to the second window, and call `Rupaka.set` there. To send a pick, send its index in `Rupaka.options` of the first copy. In the second window, find the value at that index in `Rupaka.options`, and call `Rupaka.settle` with it. When the learner in the first window clicks Try another, call `Rupaka.open` in the second window.

A host can remove the gate answers from the spec of a copy that a room sees, so that the room cannot read them early. Then give the answer to `Rupaka.settle` in `answer`. The gate uses it to draw the verdict. `answer` is `{is: value}` or a path in the state, as in a gate. When the spec has an answer, the gate uses the answer in the spec. Rupaka does not write `answer` into the spec or the state. When the spec has no answer and you give no `answer`, the gate closes with no verdict.

`rupaka.poll` makes a question for a room from a gate. `of_gate(spec, gate)` gives the question and the index of the answer. `public(p)` gives the part that the room sees.

## 3D scenes

A [`scene`](https://vedicreader.github.io/rupaka/spec.html#scene) block draws a physical thing in 3D: a jet that hovers, a gearbox, a molecule. It holds four kinds of part:

| block | what it is |
|----|----|
| [`body`](https://vedicreader.github.io/rupaka/spec.html#body) | a primitive (`box`, `cylinder`, `cone`, `sphere`, `capsule`, `torus`) or a `group`. `in` puts a body in another body, so a compound part moves as one. A state key in `rot` turns it |
| [`force`](https://vedicreader.github.io/rupaka/spec.html#force) | an arrow on a body. Its length is `mag` times the scene scale, so arrows compare. `mag` can be a state key or a derived key |
| [`label3d`](https://vedicreader.github.io/rupaka/spec.html#label3d) | a chip on a point, with a leader line. Chips never overlap: each chip goes to a free place around its point |
| [`shot`](https://vedicreader.github.io/rupaka/spec.html#shot) | a named camera: `wide`, `side`, `front`, `top` or `close:<body id>`. The scene finds the framing from the bounds of what shows |

The scene has a toon look: flat colours in three soft bands, ink outlines, a soft floor and a contact shadow. The colours come from the page theme, in light and dark.
With `bind`, a scene builds one step at a time: a part with `step: n` shows from step n, and the camera moves to the newest shot. With `prefers-reduced-motion`, the camera cuts and parts show at once.
The think rule holds: a force or a label that shows the answer of a gate must wait for the gate.

``` python
s = demo('lift', state=dict(step=1, cam='wide', w=4), derive=[expr('w * 2', 'up')],
         blocks=[gate('g', 'What is twice {w}?', [6, 8], 'up'),
                 scene(body('base', 'box', [2, 1, 2]), force([0, 1, 0], 'up', on='base', at=[0, 1.5, 0], label='lift, {up}', after='g'),
                       shot(bind='cam'), shot('close:base', step=2), bind='step', steps=['A box.', 'Look closer.'])])
```

rupaka keeps a copy of three.js (0.185.0, MIT) in `rupaka/static/vendor/three/`. It loads only for a spec that has a scene, and never from a CDN:

- [`page`](https://vedicreader.github.io/rupaka/render.html#page), [`save`](https://vedicreader.github.io/rupaka/render.html#save), [`show`](https://vedicreader.github.io/rupaka/render.html#show) and `md(frame=True)` put three.js in the page when a spec has a scene, so the page works offline and from `file://`.
- A server that serves the runtime at a prefix also serves `bundle('three')` as `three.js` at that prefix, beside `rupaka.js`. The runtime loads it from there the first time that a scene mounts. A host that serves it at another place sets `Rupaka.base` before the first scene mounts.

### Scenes and the board

The board of the screen guide speaks one line for each step. It drives a scene with the host API, so “again”, “slower” and “next” need no new code:

| board operation | host call |
|----|----|
| `{"op": "step", "n": 3}` with a scene spec | `Rupaka.set(el, {step: 3})`, where `step` is the `bind` of the scene |
| `{"op": "demo", "set": {...}}` | `Rupaka.set(el, {...})`, for example a slider value or a step |
| `{"op": "cam", "shot": "side"}` | `Rupaka.cam(el, 'side')`. It sets the key that a [`shot`](https://vedicreader.github.io/rupaka/spec.html#shot) block binds. It gives `false` for a bad name, or when the scene has no bound shot |

`shots(spec)` gives the shot names that a spec knows, so a host can check a `cam` operation before it draws. Each scene element also tells its state: `data-rk-shot` is the shot now, and `data-rk-still` is `1` when nothing moves.

### Explainers

Sometimes the learner must see a thing before there is a good question, for example how a jet hovers. An explainer shows a scene at once, with no prediction step.
Set `"mode": "learn"` on the spec. Then [`validate`](https://vedicreader.github.io/rupaka/spec.html#validate) lets the spec have no gate. All the other checks still run.

- An explainer cannot have a gate, and no block can wait for a gate or lock to a gate. [`validate`](https://vedicreader.github.io/rupaka/spec.html#validate) refuses each one and says what to remove.
- With no `mode`, or with `"mode": "predict"`, a spec with no gate is refused as before. A `mode` that is not `predict` or `learn` is refused.
- The runtime shows a small “Explainer” label above the title, so the learner knows that there is no prediction step. The `.rk` element has `data-rk-mode="learn"`.

``` python
ex = demo('box', 'A box', mode='learn', state=dict(step=1), blocks=[scene(body('b', 'box', [1, 1, 1]), bind='step', steps=['A box.'])])
```

## The gallery

`rupaka/demos/` holds hand-made demos: vowel sandhi, reciprocal rank fusion, softmax and temperature, nakṣatra and pāda, and a parabola.

## Develop

The notebooks in `nbs/` are the source of the Python. The JS and CSS are hand-written files under `rupaka/static/`, `rupaka/blocks/` and `rupaka/fns/`.

``` sh
uv sync
uv run nbdev-prepare
uv run pytest
```
