mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a74be6e670 | ||
|
|
28a6af658d | ||
|
|
d6fedd066d |
No files matched your search
@@ -8,7 +8,7 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that show media in the raea app instead of the Mac's viewer and run raea check on the brief's goals as a turn ends (nothing is checked after a save: a render checks its own output)."
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
|
||||
}
|
||||
]
|
||||
}
|
||||
+12
-40
@@ -1,8 +1,7 @@
|
||||
# raea's public CI (docs/public-first.feature PF5), on GitHub's hosted runners only: it runs code from pull requests,
|
||||
# so it never touches a self-hosted machine. What needs this Mac's GPU, VideoToolbox or audio (P26, UI parity, the
|
||||
# sound gates) stays the maintainers' L1/L2 (docs/agents.md); this is the part anyone can read and rerun.
|
||||
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, sdk/cloud's local tests,
|
||||
# cargo check of the engine, the tests of every crate that needs no GPU
|
||||
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, cargo check of the engine
|
||||
name: ci
|
||||
|
||||
on:
|
||||
@@ -69,9 +68,6 @@ jobs:
|
||||
run: bash tools/layers.sh
|
||||
- name: names
|
||||
run: bash tools/names.sh
|
||||
- name: legacy names
|
||||
# nothing names what raea's one loop replaced (docs/goal.feature MK41)
|
||||
run: bash tools/legacy-names.sh
|
||||
- name: size
|
||||
run: bash tools/size.sh
|
||||
- name: one-version
|
||||
@@ -94,24 +90,6 @@ jobs:
|
||||
- name: taxonomy
|
||||
run: bash tools/taxonomy.sh --check
|
||||
|
||||
cloud:
|
||||
# sdk/cloud's tests that need no container or farm (its npm test): the box server's pure parts and memory guard,
|
||||
# what a render sends the farm, and the farm's planner (its encode on ffmpeg), media and volume gate
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
- name: ffmpeg
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg
|
||||
- name: sdk/cloud tests
|
||||
working-directory: sdk/cloud
|
||||
run: npm ci --no-fund --no-audit --loglevel=error && npm test
|
||||
|
||||
engine:
|
||||
# a fresh clone builds as the README says (public #14): the toolchain from rust-toolchain.toml, --locked
|
||||
strategy:
|
||||
@@ -126,41 +104,35 @@ jobs:
|
||||
lfs: false
|
||||
- name: Linux libraries
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm ffmpeg
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
|
||||
- name: macOS tools
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install cmake ninja nasm ffmpeg
|
||||
run: brew install cmake ninja nasm
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: cargo check
|
||||
run: cargo check --locked -p raea-cli --tests
|
||||
- name: unit tests (every crate with no GPU)
|
||||
- name: unit tests (the crates with no GPU or media device)
|
||||
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
# The crates come from the lock file, so a new crate's tests run without anyone naming it: every workspace crate
|
||||
# that links neither wgpu nor Rolldown, then the few that link wgpu and whose tests need no GPU. All of wgpu's
|
||||
# side can't join: its test binaries would fill the runner's disk (#90). Left out, with the reason:
|
||||
# raea-sys-mlx its tests run on MLX's GPU device, and a hosted macOS runner has no Metal device
|
||||
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
|
||||
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
|
||||
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time.
|
||||
# --no-fail-fast: one run names every crate whose tests fail, not only the first
|
||||
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
|
||||
run: |
|
||||
ws=$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.packages[].name' | sort)
|
||||
linked=$(for k in wgpu rolldown; do cargo tree --locked --workspace -i "$k" -e normal,build,dev --prefix none --format '{p}'; done | grep -F "($PWD/" | sed 's/ v[0-9].*//' | sort -u)
|
||||
light=$(comm -23 <(echo "$ws") <(echo "$linked") | grep -vx raea-sys-mlx | sed 's/^/-p /')
|
||||
cargo test --locked --no-fail-fast $light -p raea-runtime-plugins -p raea-runtime-live -p raea-app-check -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
cargo test --locked -p raea-bundle
|
||||
- name: Windows' and Linux's own (#169)
|
||||
# what a Windows or Linux user meets that needs a feature the step above doesn't turn on: openh264 at --quality
|
||||
# master (raea-io-soft's tests/quality.rs, its h264 feature) and raea's Node core under the agent shell
|
||||
# (raea-native's tests/node.rs, its modules feature: Node's names for the system, Windows' paths). QuickJS's
|
||||
# Intl (raea-runtime-jsengine, on Linux) and git found or fetched (raea-io-assets) run in the step above
|
||||
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
|
||||
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
|
||||
# fetched (raea-io-assets), and raea's Node core under the agent shell (raea-native's tests/node.rs: Node's names
|
||||
# for the system, Windows' paths); tests/node.rs needs raea-native's modules feature and tests/quality.rs
|
||||
# raea-io-soft's h264
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: |
|
||||
cargo test --locked -p raea-native --features modules --test node
|
||||
cargo test --locked -p raea-io-soft --features h264
|
||||
cargo test --locked -p raea-runtime-jsengine -p raea-io-assets
|
||||
@@ -107,7 +107,5 @@ sdk/raea/.scratch-*/
|
||||
# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/)
|
||||
/examples/materials/wear/media/
|
||||
/examples/materials/wear/assets/
|
||||
# a playable example's generated sounds, made beside it the first time it's rendered or exported (raea's asset store)
|
||||
/examples/playables/assets/
|
||||
# tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path)
|
||||
/sdk/raea/bench/bevy-parity/**/assets
|
||||
Generated
+65
-189
@@ -8490,15 +8490,6 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intel_tex_2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
|
||||
dependencies = [
|
||||
"ispc_rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
@@ -8582,16 +8573,6 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "ispc_rt"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"num_cpus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
@@ -13820,7 +13801,6 @@ dependencies = [
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
@@ -13863,6 +13843,19 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-ask",
|
||||
"raea-core-facts",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-layers"
|
||||
version = "0.1.0"
|
||||
@@ -13895,9 +13888,15 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-app-judge",
|
||||
"raea-core-ask",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-core-review",
|
||||
"raea-io-home",
|
||||
"raea-runtime-cut-plan",
|
||||
"raea-runtime-goal-plan",
|
||||
"raea-runtime-lod-plan",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -13962,10 +13961,7 @@ dependencies = [
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"raea-core-fonts",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"regex",
|
||||
@@ -13995,11 +13991,8 @@ dependencies = [
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-body",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-motionfaults",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -14009,6 +14002,8 @@ name = "raea-app-solid"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-judge",
|
||||
"raea-app-make",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
@@ -14296,6 +14291,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-capcut",
|
||||
"raea-app-check",
|
||||
"raea-app-ci",
|
||||
@@ -14303,6 +14299,7 @@ dependencies = [
|
||||
"raea-app-engines",
|
||||
"raea-app-fingerprint",
|
||||
"raea-app-game",
|
||||
"raea-app-judge",
|
||||
"raea-app-layers",
|
||||
"raea-app-lightbake",
|
||||
"raea-app-make",
|
||||
@@ -14318,8 +14315,6 @@ dependencies = [
|
||||
"raea-app-voice",
|
||||
"raea-app-workspace",
|
||||
"raea-bevy-plugins",
|
||||
"raea-cli-goal",
|
||||
"raea-cli-refused",
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-brief",
|
||||
@@ -14348,26 +14343,6 @@ dependencies = [
|
||||
"wsx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-cli-goal"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-make",
|
||||
"raea-core-brief",
|
||||
"raea-io-home",
|
||||
"raea-native",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-cli-refused"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-alloc"
|
||||
version = "0.1.0"
|
||||
@@ -14389,6 +14364,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14494,7 +14470,6 @@ version = "0.1.0"
|
||||
name = "raea-core-shape"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"manifold-rust",
|
||||
"raea-core-fonts",
|
||||
"raea-core-grow",
|
||||
@@ -14513,15 +14488,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-wire"
|
||||
version = "0.1.0"
|
||||
@@ -15063,50 +15029,14 @@ dependencies = [
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-render-plugins",
|
||||
"raea-render-raytrace",
|
||||
"raea-runtime-gpuframe",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-memtally",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-post",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-screen",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-splat",
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
@@ -15115,10 +15045,13 @@ dependencies = [
|
||||
"raea-sys-gi",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-lod",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-parity",
|
||||
"raea-sys-phase",
|
||||
"raea-sys-post",
|
||||
@@ -15132,8 +15065,10 @@ dependencies = [
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-viewbox",
|
||||
"raea-sys-volume",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15335,6 +15270,7 @@ name = "raea-runtime-calls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"manifold-rust",
|
||||
"parley",
|
||||
@@ -15345,7 +15281,6 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-ecs",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-wear",
|
||||
"raea-sys-fonts",
|
||||
@@ -15375,6 +15310,15 @@ dependencies = [
|
||||
"raea-io-home",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-cut-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-brief",
|
||||
"raea-io-soft",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-dom"
|
||||
version = "0.1.0"
|
||||
@@ -15411,14 +15355,6 @@ dependencies = [
|
||||
"vello",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-edit"
|
||||
version = "0.1.0"
|
||||
@@ -15460,7 +15396,6 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15490,7 +15425,6 @@ dependencies = [
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-review",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-sound",
|
||||
@@ -15507,6 +15441,14 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-goal-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-brief",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-gpuframe"
|
||||
version = "0.1.0"
|
||||
@@ -15573,17 +15515,6 @@ dependencies = [
|
||||
"rquickjs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-live"
|
||||
version = "0.1.0"
|
||||
@@ -15640,9 +15571,12 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-scene",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
@@ -15651,8 +15585,8 @@ dependencies = [
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-twins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-facetrack",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"raea-sys-screen",
|
||||
@@ -15704,7 +15638,6 @@ dependencies = [
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
@@ -15729,18 +15662,6 @@ dependencies = [
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-review"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-review",
|
||||
"raea-sys-light-meter",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15751,7 +15672,6 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-kinds",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
@@ -15790,7 +15710,6 @@ dependencies = [
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-share",
|
||||
"raea-sys-toon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -16129,17 +16048,6 @@ dependencies = [
|
||||
"parry3d",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-facetrack"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-filters"
|
||||
version = "0.1.0"
|
||||
@@ -16227,6 +16135,17 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-foliage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"parry3d",
|
||||
"raea-core-ease",
|
||||
"raea-sys-glb",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fonts"
|
||||
version = "0.1.0"
|
||||
@@ -16267,7 +16186,6 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-core-tables",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-shots",
|
||||
@@ -16489,11 +16407,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"blake3",
|
||||
"image",
|
||||
"intel_tex_2",
|
||||
"raea-core-program",
|
||||
"raea-io-home",
|
||||
"raea-core-shape",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
@@ -16507,13 +16423,6 @@ dependencies = [
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-memtally"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
@@ -16587,27 +16496,6 @@ dependencies = [
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-core-ease",
|
||||
"raea-sys-body",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -16828,7 +16716,6 @@ name = "raea-sys-splat"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
@@ -16894,17 +16781,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-toon"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-touch"
|
||||
version = "0.1.0"
|
||||
|
||||
+4
-12
@@ -12,7 +12,6 @@ members = [
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
"core/tables",
|
||||
"core/scene",
|
||||
"core/shape",
|
||||
"core/meshcheck",
|
||||
@@ -31,7 +30,6 @@ members = [
|
||||
"systems/phase",
|
||||
"systems/shader/wgsl",
|
||||
"systems/sampler",
|
||||
"systems/memtally",
|
||||
"systems/parity",
|
||||
"systems/shader",
|
||||
"systems/three-shader",
|
||||
@@ -43,8 +41,6 @@ members = [
|
||||
"engine/bevy-world",
|
||||
"engine/bundle",
|
||||
"engine/cli",
|
||||
"engine/cli/goal",
|
||||
"engine/cli/refused",
|
||||
"engine/neural",
|
||||
"engine/light",
|
||||
"engine/modules",
|
||||
@@ -109,8 +105,6 @@ members = [
|
||||
"systems/a11y",
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/notice",
|
||||
"systems/motionfaults",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
@@ -127,7 +121,6 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/facetrack",
|
||||
"systems/engine-shaders",
|
||||
"systems/shots",
|
||||
"systems/hold",
|
||||
@@ -148,6 +141,7 @@ members = [
|
||||
"systems/matchmove",
|
||||
"systems/grid",
|
||||
"systems/lod",
|
||||
"systems/foliage",
|
||||
"systems/viewbox",
|
||||
"systems/rendermap",
|
||||
"systems/meshseq",
|
||||
@@ -155,7 +149,6 @@ members = [
|
||||
"systems/look",
|
||||
"systems/compose",
|
||||
"systems/material",
|
||||
"systems/toon",
|
||||
"systems/mesh",
|
||||
"systems/post",
|
||||
"systems/fog",
|
||||
@@ -177,14 +170,12 @@ members = [
|
||||
"tools/perceive",
|
||||
"engine/render",
|
||||
"engine/render/raytrace",
|
||||
"engine/render/plugins",
|
||||
"engine/render/denoise/bench",
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
"runtime/react",
|
||||
"runtime/track",
|
||||
"runtime/pagestore",
|
||||
"runtime/review",
|
||||
"runtime/cssurls",
|
||||
"runtime/pid",
|
||||
"bench/bridge",
|
||||
@@ -198,20 +189,20 @@ members = [
|
||||
"runtime/bundle/lib",
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/ecs",
|
||||
"runtime/shots",
|
||||
"runtime/wear",
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/endchecks",
|
||||
"runtime/lod-plan",
|
||||
"runtime/cut-plan",
|
||||
"runtime/goal-plan",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
"runtime/kinds",
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/ask",
|
||||
@@ -237,6 +228,7 @@ members = [
|
||||
"apps/motion",
|
||||
"apps/engines",
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/make",
|
||||
"apps/solid",
|
||||
"apps/scene",
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
<p align="center">
|
||||
Tell your AI what to make. Videos, motion graphics, 3D and games, written as React and TypeScript<br>
|
||||
(the code your AI already writes) and rendered on your own GPU.
|
||||
(the code your AI already writes) and rendered on your own GPU, faster than they play.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -130,7 +130,7 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
|
||||
Gaussian splats, and Bevy plugins compiled into the engine. three.js work runs as it's written: a React Three Fiber
|
||||
scene inside `<R3F>`, or a three.js page's script inside `<Three program>`.
|
||||
- **Sound.** One mixer for live play and offline render, instruments and effects, and local models for foley and
|
||||
instrument notes (`raea make sao`, `raea make tokensynth`).
|
||||
instrument notes (`raea sao`, `raea tokensynth`).
|
||||
- **Built for agents.** Everything it draws stays queryable as data, so an agent can render a frame, look at it, and
|
||||
fix what's wrong without a person in the loop.
|
||||
|
||||
@@ -145,10 +145,9 @@ Apache-2.0, to read, render and take apart, and its models, textures and sound f
|
||||
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
|
||||
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
|
||||
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
|
||||
- **Claude plugin.** The raea skill and its hooks: media an agent opens goes to the raea app, and `raea check` holds
|
||||
the brief's goals as a turn ends. Nothing is checked after a save, since a render checks its own output. In Claude
|
||||
Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/` folder of raea-skills, and
|
||||
`/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
|
||||
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
|
||||
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
|
||||
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
|
||||
- **Bug reports.** When an agent finds a bug in raea itself, `raea bug TITLE --text TEXT` sends it to raea's server
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
|
||||
description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
|
||||
|
||||
[dependencies]
|
||||
# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
|
||||
//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
|
||||
//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
|
||||
//! and says which labels it missed, so its words can be fixed. `try_words` asks new words of the labelled clips and
|
||||
//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
|
||||
//! sets both AUCs side by side.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
@@ -135,7 +135,7 @@ fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `calibrate(ID)`: the feed's labels read again, then every labelled version held to them. The ones that
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
|
||||
/// pass are kept as the person's calibration; one that no longer passes loses it.
|
||||
pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
|
||||
let feed = labels::from_feed()?;
|
||||
@@ -159,7 +159,7 @@ fn today() -> String {
|
||||
raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
|
||||
}
|
||||
|
||||
/// The groups `try_words` sends: the new question on each labelled clip set, with the state it was asked with.
|
||||
/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
|
||||
pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
|
||||
let all = labels::all();
|
||||
let standing = labels::standing(&all);
|
||||
@@ -182,7 +182,7 @@ pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Gr
|
||||
groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
|
||||
}
|
||||
if groups.is_empty() {
|
||||
return Err(format!("ask try: none of {like}'s labelled clips are still kept (calibrate() lists its labels)"));
|
||||
return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
|
||||
}
|
||||
Ok((old, new, groups))
|
||||
}
|
||||
@@ -201,7 +201,7 @@ fn media(names: &[&str]) -> Option<Media> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `try_words(LIKE, WORDS)`: the new words asked of the old question's labelled clips, and both versions held to
|
||||
/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
|
||||
/// the same labels.
|
||||
pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
|
||||
let (old, new, groups) = try_groups(like, words)?;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
|
||||
//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
|
||||
//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
|
||||
//! labels, which is what lets `try_words` measure new words.
|
||||
//! labels, which is what lets `raea ask try` measure new words.
|
||||
//!
|
||||
//! Where labels come from:
|
||||
//! - `verdict(ANSWER, WORD)`: the person answers the question themselves, in its own terms (yes or no, an option,
|
||||
//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
|
||||
//! a level). Theirs counts first.
|
||||
//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
|
||||
//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
|
||||
//! with no such note is a no. Read again by every `calibrate()`.
|
||||
//! with no such note is a no. Read again by every `raea ask calibrate`.
|
||||
//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
|
||||
//! fingerprint keeps another eye's readings (FP6d).
|
||||
|
||||
@@ -149,7 +149,7 @@ fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -
|
||||
}
|
||||
}
|
||||
|
||||
/// `verdict(ANSWER, WORD, EYE)`: the person's answer to the question on that answer's clips (or another
|
||||
/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
|
||||
/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
|
||||
pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
|
||||
let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
|
||||
|
||||
+8
-4
@@ -1,13 +1,17 @@
|
||||
//! Questions about a piece's picture and sound (docs/ask.feature AK2-AK3), asked for the fingerprint's double-check
|
||||
//! (`raea fingerprint score --ask`, apps/double). `prepare` reads what raea knows of the piece and keeps the questions
|
||||
//! that apply; `runner` plans the calls, cuts each clip once and asks in parallel; `record` keeps every call and answer;
|
||||
//! `labels` reads the person's notes and approvals into labels, and `calibrate` holds each question to them (AK6-AK7).
|
||||
//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
|
||||
//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
|
||||
//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
|
||||
//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
|
||||
//! fingerprint's double-check go through the same runner.
|
||||
|
||||
pub mod calibrate;
|
||||
pub mod labels;
|
||||
pub mod prepare;
|
||||
pub mod record;
|
||||
pub mod runner;
|
||||
pub mod verbs;
|
||||
|
||||
pub use verbs::{USAGE, cli};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
|
||||
//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
|
||||
//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
|
||||
//! question, so a verdict reads in its terms and `try_words` can reword it.
|
||||
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -49,7 +49,7 @@ fn hex(digest: &[u8]) -> String {
|
||||
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// What a file is, cheaply, and the size an ident names (raea-core-ask's).
|
||||
/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea make status` reads the same).
|
||||
pub use raea_core_ask::ident::{ident, ident_len};
|
||||
|
||||
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
|
||||
//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
|
||||
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
|
||||
//! carry clips kept from an earlier call instead of a file to cut (`try_words`), and every question goes out with the
|
||||
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
|
||||
//! person's own calibration when it has earned one (calibrate.rs).
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
@@ -50,10 +50,10 @@ pub struct Kept {
|
||||
pub sound_seconds: f64,
|
||||
}
|
||||
|
||||
/// One answer, or why a question wasn't asked or still waits: one line of JSON each.
|
||||
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Answer {
|
||||
/// its id in the record (`labels::verdict` takes it)
|
||||
/// its id in the record (`raea ask verdict` takes it)
|
||||
pub answer: Option<String>,
|
||||
pub file: String,
|
||||
pub id: String,
|
||||
@@ -285,7 +285,7 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
|
||||
sum
|
||||
}
|
||||
|
||||
/// The clips a call sent, kept by hash for `try_words`.
|
||||
/// The clips a call sent, kept by hash for `raea ask try`.
|
||||
fn kept(m: &Media) -> Vec<String> {
|
||||
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
|
||||
[each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::prepare::{self, Piece, VOICE};
|
||||
use crate::runner::{self, Answer, Entry, Event, Opts};
|
||||
|
||||
fn rubric() -> String {
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/verbs/critique.md")).expect("the critique guide")
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
|
||||
}
|
||||
|
||||
pub(crate) fn setup() {
|
||||
@@ -166,3 +166,9 @@ fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
|
||||
assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
|
||||
assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_words_keep_their_id() {
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
|
||||
//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
|
||||
//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
|
||||
//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
|
||||
//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
|
||||
//! calibrate.rs; AK6-AK7).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::Read as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use raea_core_ask::{Kind, Question, Window, library};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::labels::{self, span};
|
||||
use crate::prepare::{self, Piece};
|
||||
use crate::runner::{self, Entry, Event, Opts};
|
||||
use crate::{calibrate, record};
|
||||
|
||||
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
|
||||
|
||||
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
|
||||
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
|
||||
|
||||
/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
|
||||
#[derive(Default)]
|
||||
struct Args {
|
||||
words: Vec<String>,
|
||||
flags: BTreeMap<String, Vec<String>>,
|
||||
gate_any: bool,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse(args: &[String]) -> Result<Args, String> {
|
||||
let mut a = Args::default();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let s = args[i].as_str();
|
||||
if VALUED.contains(&s) {
|
||||
let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
|
||||
a.flags.entry(s.into()).or_default().push(v.clone());
|
||||
i += 1;
|
||||
} else if BARE.contains(&s) {
|
||||
a.flags.entry(s.into()).or_default();
|
||||
if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
|
||||
a.gate_any = true;
|
||||
i += 1;
|
||||
}
|
||||
} else if s.starts_with("--") {
|
||||
return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
|
||||
} else {
|
||||
a.words.push(s.into());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
fn has(&self, f: &str) -> bool {
|
||||
self.flags.contains_key(f)
|
||||
}
|
||||
fn one(&self, f: &str) -> Option<&str> {
|
||||
self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
|
||||
}
|
||||
fn num(&self, f: &str) -> Result<Option<f64>, String> {
|
||||
self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
|
||||
}
|
||||
fn list(&self, f: &str) -> Vec<String> {
|
||||
self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The craft rubric's text, where the guides are installed, for the `rubric` set.
|
||||
pub fn rubric_md() -> Option<String> {
|
||||
std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
|
||||
}
|
||||
|
||||
/// A question's id from its words: `own-` and its first words, so the same words keep their id.
|
||||
pub fn own_id(words: &str) -> String {
|
||||
let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
|
||||
let mut id = format!("own-{}", slug.join("-"));
|
||||
id.truncate(raea_core_ask::limits::ID_LEN);
|
||||
id
|
||||
}
|
||||
|
||||
/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
|
||||
fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
|
||||
let mut qs = own.to_vec();
|
||||
for s in sets {
|
||||
qs.extend(library::set(s, rubric)?);
|
||||
}
|
||||
for id in std {
|
||||
qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
|
||||
}
|
||||
Ok(qs)
|
||||
}
|
||||
|
||||
fn shaped(words: &str, a: &Args) -> Result<Question, String> {
|
||||
let mut q = Question::plain(&own_id(words), words);
|
||||
if let Some(c) = a.one("--choose") {
|
||||
q.kind = Kind::Choose;
|
||||
q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
|
||||
} else if let Some(n) = a.one("--rate") {
|
||||
let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
|
||||
q.kind = Kind::Rate;
|
||||
q.options = (1..=n).map(|i| i.to_string()).collect();
|
||||
} else if a.has("--grade") {
|
||||
q.kind = Kind::Grade;
|
||||
}
|
||||
q.flags = a.list("--flag");
|
||||
if let Some(why) = raea_core_ask::limits::check(&q) {
|
||||
return Err(format!("ask: {why}"));
|
||||
}
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
/// The window from --from, --to and --at (three seconds around it).
|
||||
fn window(a: &Args) -> Result<Option<Window>, String> {
|
||||
if let Some(at) = a.num("--at")? {
|
||||
return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
|
||||
}
|
||||
let (from, to) = (a.num("--from")?, a.num("--to")?);
|
||||
Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
|
||||
}
|
||||
|
||||
fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
|
||||
match v {
|
||||
None => Ok(None),
|
||||
Some("yes" | "true") => Ok(Some(true)),
|
||||
Some("no" | "false") => Ok(Some(false)),
|
||||
Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces read once a run, by what they were read with.
|
||||
type Pieces = HashMap<String, Arc<Piece>>;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
|
||||
let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
|
||||
if let Some(p) = pieces.get(&key) {
|
||||
return Ok(p.clone());
|
||||
}
|
||||
let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
|
||||
pieces.insert(key, p.clone());
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
|
||||
let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
|
||||
Entry { piece: p, window, questions, dropped, with }
|
||||
}
|
||||
|
||||
/// The command line's one entry.
|
||||
fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
|
||||
let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
|
||||
let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
|
||||
if qs.is_empty() {
|
||||
return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
|
||||
}
|
||||
let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
|
||||
let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
|
||||
Ok(vec![entry(p, window(a)?, qs, with, rubric)])
|
||||
}
|
||||
|
||||
/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
|
||||
/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
|
||||
fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let text = match path {
|
||||
"-" => {
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
|
||||
s
|
||||
}
|
||||
p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
|
||||
};
|
||||
let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
|
||||
Ok(Value::Array(a)) => a,
|
||||
Ok(v @ Value::Object(_)) => vec![v],
|
||||
_ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
|
||||
};
|
||||
let strs = |v: &Value| -> Vec<String> {
|
||||
match v {
|
||||
Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
|
||||
Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (n, r) in rows.iter().enumerate() {
|
||||
let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
|
||||
let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
|
||||
let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
|
||||
Value::String(w) => Ok(Question::plain(&own_id(w), w)),
|
||||
q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
|
||||
});
|
||||
let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
|
||||
let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
|
||||
let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
|
||||
let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
|
||||
let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
|
||||
out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `raea ask list [SET]`: the standard questions.
|
||||
fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
|
||||
let sets: Vec<String> = match a.words.get(1) {
|
||||
Some(s) => vec![s.clone()],
|
||||
None => library::SETS.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mine = calibrate::local();
|
||||
for s in &sets {
|
||||
let mut qs = library::set(s, rubric)?;
|
||||
qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
|
||||
if a.has("--json") {
|
||||
out.push(json!({"set": s, "questions": qs}).to_string());
|
||||
continue;
|
||||
}
|
||||
out.push(format!("{s}:"));
|
||||
for q in qs {
|
||||
let how = if q.calibrated() { "calibrated" } else { "advice" };
|
||||
out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
|
||||
}
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// An event as a line of text.
|
||||
fn line(e: &Event, files: usize) -> String {
|
||||
match e {
|
||||
Event::Would(v) => {
|
||||
let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
|
||||
let m = &v["media"];
|
||||
let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
format!(
|
||||
"would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
|
||||
qs.len(),
|
||||
span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
|
||||
v["file"].as_str().unwrap_or(""),
|
||||
qs.join(", "),
|
||||
kb("videos"),
|
||||
kb("stills"),
|
||||
kb("sounds"),
|
||||
v["estimate_usd"].as_f64().unwrap_or(0.0),
|
||||
v["state"].as_str().unwrap_or("")
|
||||
)
|
||||
}
|
||||
Event::Answer(a) => {
|
||||
let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
|
||||
let what = match (&a.says, &a.not_asked, &a.waits) {
|
||||
(Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
|
||||
(_, Some(n), _) => format!("not asked: {n}"),
|
||||
(.., Some(w)) => w.clone(),
|
||||
_ => "no answer".into(),
|
||||
};
|
||||
format!("{who}{:<34} {what}", a.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
|
||||
pub fn cli(args: &[String]) -> i32 {
|
||||
match run(args) {
|
||||
Ok(code) => code,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<i32, String> {
|
||||
let a = Args::parse(args)?;
|
||||
let rubric = rubric_md();
|
||||
let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
|
||||
let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
|
||||
match sub {
|
||||
Some("list") => {
|
||||
println!("{}", list(&a, rubric.as_deref())?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("verdict") => {
|
||||
let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
|
||||
println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("calibrate") => return calibrated(&a),
|
||||
Some("try") => return tried(&a, jobs),
|
||||
_ => {}
|
||||
}
|
||||
let mut pieces = Pieces::new();
|
||||
let entries = match a.one("--batch") {
|
||||
Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
|
||||
None => from_args(&a, rubric.as_deref(), &mut pieces)?,
|
||||
};
|
||||
let (json_out, dry) = (a.has("--json"), a.has("--dry"));
|
||||
let files = pieces.len();
|
||||
let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
|
||||
match (&e, json_out) {
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(e, false) => println!("{}", line(e, files)),
|
||||
}
|
||||
});
|
||||
if json_out {
|
||||
println!("{}", json!({"summary": sum}));
|
||||
} else if dry {
|
||||
println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
|
||||
} else if sum.calls > 0 {
|
||||
let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
|
||||
let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
|
||||
let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
|
||||
println!(
|
||||
"asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
|
||||
sum.asked,
|
||||
if sum.asked == 1 { "" } else { "s" },
|
||||
sum.calls,
|
||||
if sum.calls == 1 { "" } else { "s" },
|
||||
routes.join(" and "),
|
||||
sum.cost
|
||||
);
|
||||
}
|
||||
if !dry && sum.calls == 0 {
|
||||
return Err("ask: nothing was asked (each question's line says why)".into());
|
||||
}
|
||||
// a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
|
||||
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
|
||||
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
|
||||
}
|
||||
|
||||
/// A version's standing as a line, with its misses below when it doesn't separate.
|
||||
fn standing_line(s: &calibrate::Standing) -> String {
|
||||
let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
|
||||
let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
|
||||
if s.others > 0 {
|
||||
out += &format!(" ({} from other eyes, not counted)", s.others);
|
||||
}
|
||||
for m in &s.misses {
|
||||
let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
|
||||
out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
|
||||
fn calibrated(a: &Args) -> Result<i32, String> {
|
||||
let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
|
||||
if a.has("--json") {
|
||||
println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
|
||||
all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
|
||||
return Ok(0);
|
||||
}
|
||||
println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
|
||||
if all.is_empty() {
|
||||
println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
|
||||
}
|
||||
all.iter().for_each(|s| println!("{}", standing_line(s)));
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
|
||||
fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
|
||||
let words = a.words[1..].join(" ");
|
||||
let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
|
||||
if words.trim().is_empty() {
|
||||
return Err("ask try WORDS --like ID: the new words".into());
|
||||
}
|
||||
let json_out = a.has("--json");
|
||||
let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(e, false) => println!("{}", line(e, 2)),
|
||||
})?;
|
||||
match (both, json_out) {
|
||||
(None, true) => println!("{}", json!({"summary": sum})),
|
||||
(None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
|
||||
(Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
|
||||
(Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
|
||||
}
|
||||
Ok(i32::from(!a.has("--dry") && sum.calls == 0))
|
||||
}
|
||||
@@ -20,14 +20,14 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
|
||||
raea-sys-measure = { path = "../../systems/measure" }
|
||||
# what it reads of a video, through FFmpeg or raea's own decoders where it isn't installed
|
||||
raea-app-check-read = { path = "read" }
|
||||
# who can fix what it finds: the encode's or the picture's own, carried, a source
|
||||
# who can fix what it finds: the encode's or the picture's own, carried, a source (split out to keep this crate small)
|
||||
raea-app-check-cause = { path = "cause" }
|
||||
# the text rules on a render's manifest (split out: raea render holds its own text to them)
|
||||
raea-app-check-text = { path = "text" }
|
||||
# the flashing screen (WCAG 2.3.1)
|
||||
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
|
||||
raea-app-check-flash = { path = "flash" }
|
||||
# what the person sent from the raea app, handed to the agent
|
||||
# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
|
||||
raea-app-check-inbox = { path = "inbox" }
|
||||
# the Stop gate for a `make` job (docs/goal.feature MK2)
|
||||
# the Stop gate for a `make` job (docs/make.feature MK2; split out to keep this crate small)
|
||||
raea-app-check-make = { path = "make" }
|
||||
serde_json = "1"
|
||||
@@ -53,7 +53,7 @@ pub fn luma(rgba: &[u8], width: usize, w: usize, h: usize) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// `frames` as `comp` draws them, never encoded, as luma `w` x `h` (top-left): `raea render COMP --at F,... -o DIR/`
|
||||
/// (PNG) run by `raea` from the project, kept out of its record (RAEA_RECORD=off)
|
||||
/// (PNG) run by `raea` from the project, kept out of its record as the quick check's stills are
|
||||
pub fn unencoded(raea: &Path, project: &Path, comp: &Path, frames: &[i64], w: usize, h: usize) -> R<Vec<Vec<u8>>> {
|
||||
let mut wanted: Vec<i64> = frames.to_vec();
|
||||
wanted.sort_unstable();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels.
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
|
||||
//! in a crate of its own so the check stays small (tools/size.sh).
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea hook`'s Stop gate for a `make` job (docs/goal.feature MK36): an agent can't end its turn until `raea goal check --at done` passes"
|
||||
description = "`raea hook`'s Stop gate for a `make` job (docs/make.feature MK2): an agent can't end its turn until `raea make status` says the job is done"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
+34
-40
@@ -1,8 +1,8 @@
|
||||
//! raea-app-check-make: the Stop hook's moment of the loop (docs/goal.feature MK36): an agent working in a project with a
|
||||
//! brief.ts can't end its turn until `raea goal check --at done` passes: every goal the brief holds (or, with none, the
|
||||
//! floor) and every raea file reached from the brief (`registered`). Run by `raea goal check`, a child process, so this
|
||||
//! crate carries none of the rules. A session blocked three times with the same open items goes through: it's going in
|
||||
//! circles, and the person is better told than the agent looped.
|
||||
//! raea-app-check-make: the Stop hook's half of `raea make` (docs/make.feature MK2): an agent working in a project whose brief.ts has a
|
||||
//! `make` job can't end its turn until `raea make status` says the job is done. Cheap when there's no job: the brief's
|
||||
//! words are read, and only a brief with `make:` is evaluated (by `raea make status`, a child process, so this crate
|
||||
//! doesn't carry the judge). A session blocked three times with the same open items goes through: it's going in
|
||||
//! circles, and the person is better told than the agent looped (PL7's keeper stops the same way).
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -12,13 +12,13 @@ use serde_json::Value;
|
||||
/// How many times the same open items may block one session before the stop goes through.
|
||||
pub const SAME_BLOCKS: u32 = 3;
|
||||
|
||||
/// The project's brief.ts, at or above `cwd` inside its raea project: every brief is held, none is an outlier.
|
||||
/// The brief.ts with a job, at or above `cwd` inside its raea project.
|
||||
pub fn brief_with_job(cwd: &Path) -> Option<PathBuf> {
|
||||
let project = raea_core_facts::record::up(cwd, ".raea/project");
|
||||
for d in dunce::canonicalize(cwd).ok()?.ancestors() {
|
||||
let p = d.join("brief.ts");
|
||||
if p.is_file() {
|
||||
return Some(p);
|
||||
return std::fs::read_to_string(&p).is_ok_and(|t| t.contains("make:") || t.contains("make :")).then_some(p);
|
||||
}
|
||||
if project.as_deref() == Some(d) {
|
||||
return None;
|
||||
@@ -46,42 +46,37 @@ pub fn may_block(guard: &Path, items: &str) -> bool {
|
||||
next <= SAME_BLOCKS
|
||||
}
|
||||
|
||||
/// What the agent is told when its turn may not end, or None to let it end: no job here, the job passes, the runner
|
||||
/// didn't run (never block on raea's own failure), or the same items have blocked it three times already.
|
||||
/// What the agent is told when its turn may not end, or None to let it end: no job here, the job is done, the job
|
||||
/// didn't load (never block on raea's own failure), or the same items have blocked it three times already.
|
||||
/// Each turn's status also brings the job's task in plan.org up to date (`--plan`, docs/make.feature MK3).
|
||||
pub fn stop(v: &Value) -> Option<String> {
|
||||
let cwd = PathBuf::from(v["cwd"].as_str()?);
|
||||
let brief = brief_with_job(&cwd)?;
|
||||
let exe = std::env::current_exe().ok()?;
|
||||
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
|
||||
let out = std::process::Command::new(exe).args(["make", "status"]).arg(brief.parent()?).args(["--json", "--plan"]).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let s: Value = serde_json::from_slice(&out.stdout).ok()?;
|
||||
let home = raea_io_home::user_home()?;
|
||||
let session = v["session_id"].as_str().unwrap_or("");
|
||||
let guard = home.join(".raea/hooks/goal").join(format!("{:x}", hash(&[session, &brief.display().to_string()])));
|
||||
if r["passed"] == true {
|
||||
let guard = home.join(".raea/hooks/make").join(format!("{:x}", hash(&[session, &brief.display().to_string()])));
|
||||
if s["done"] == true {
|
||||
let _ = std::fs::remove_file(&guard);
|
||||
return None;
|
||||
}
|
||||
let items = open_items(&r);
|
||||
let items = open_items(&s);
|
||||
if !may_block(&guard, &items) {
|
||||
return None;
|
||||
}
|
||||
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
|
||||
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
|
||||
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
|
||||
Some(format!(
|
||||
"Not done ({} job, {}): {items}. Keep going: `raea make status` lists what's open; a defect you judge wrong is answered in NOTES.md by its name.",
|
||||
s["kind"].as_str().unwrap_or("make"),
|
||||
brief.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
|
||||
pub fn open_items(r: &Value) -> String {
|
||||
let mut items: Vec<String> = r["findings"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|x| x["level"] == "error")
|
||||
.map(|x| format!("{}{}: {}", x["check"].as_str().unwrap_or(""), x["file"].as_str().map(|f| format!(" {f}")).unwrap_or_default(), x["says"].as_str().unwrap_or("")))
|
||||
.collect();
|
||||
for b in r["broke"].as_array().into_iter().flatten() {
|
||||
items.push(format!("{} broke: {}", b["check"].as_str().unwrap_or(""), b["says"].as_str().unwrap_or("")));
|
||||
}
|
||||
/// The open items, one line each: what's missing, then each gate that isn't clear.
|
||||
pub fn open_items(s: &Value) -> String {
|
||||
let mut items: Vec<String> = s["missing"].as_array().into_iter().flatten().filter_map(|m| m.as_str().map(String::from)).collect();
|
||||
items.extend(s["gates"].as_array().into_iter().flatten().filter(|g| g["clear"] != true).map(|g| format!("{}{}: {}", g["gate"].as_str().unwrap_or(""), g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default(), g["says"].as_str().unwrap_or(""))));
|
||||
items.join("; ")
|
||||
}
|
||||
|
||||
@@ -91,18 +86,19 @@ mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-goal-gate-{name}-{}", std::process::id()));
|
||||
let d = std::env::temp_dir().join(format!("raea-make-gate-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("compositions")).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_brief_is_held_with_or_without_a_goal() {
|
||||
fn only_a_brief_with_a_job_is_held() {
|
||||
let d = tmp("job");
|
||||
assert_eq!(brief_with_job(&d.join("compositions")), None, "no brief, nothing held");
|
||||
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\" })").unwrap();
|
||||
assert_eq!(brief_with_job(&d.join("compositions")).map(|p| p.file_name().unwrap().to_owned()), Some("brief.ts".into()), "a brief without a goal is held to the floor and registered");
|
||||
assert_eq!(brief_with_job(&d.join("compositions")), None, "a brief without make is never held");
|
||||
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\", make: kit({ objects: [] }) })").unwrap();
|
||||
assert_eq!(brief_with_job(&d.join("compositions")).map(|p| p.file_name().unwrap().to_owned()), Some("brief.ts".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -114,12 +110,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_items_list_each_error_then_each_broken_check() {
|
||||
let r = json!({"findings": [
|
||||
{"check": "deliverables", "level": "error", "file": null, "says": "missing: out/kit/lineup.png"},
|
||||
{"check": "cta", "level": "error", "file": "out/cuts/a_9x16.mp4", "says": "no CTA in its last 8 s"},
|
||||
{"check": "place", "level": "warn", "file": "out/cuts/a_9x16.mp4", "says": "a warning holds nothing"}],
|
||||
"broke": [{"check": "mine", "says": "x is undefined"}]});
|
||||
assert_eq!(open_items(&r), "deliverables: missing: out/kit/lineup.png; cta out/cuts/a_9x16.mp4: no CTA in its last 8 s; mine broke: x is undefined");
|
||||
fn open_items_list_what_is_missing_then_the_gates_that_are_not_clear() {
|
||||
let s = json!({"missing": ["out/kit/lineup.png"], "gates": [
|
||||
{"gate": "checks", "of": "scene.tsx", "clear": false, "says": "never rendered"},
|
||||
{"gate": "critic", "clear": true, "says": "ok"}]});
|
||||
assert_eq!(open_items(&s), "out/kit/lineup.png; checks scene.tsx: never rendered");
|
||||
}
|
||||
}
|
||||
+25
-7
@@ -3,10 +3,9 @@
|
||||
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
|
||||
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
|
||||
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
|
||||
//! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
|
||||
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
|
||||
//! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
|
||||
//! every harness hands its agent; what was sent goes back in the shape each one reads.
|
||||
//! file is saved: the quick check on a composition. After any tool, and as a turn ends: what the person sent from the raea
|
||||
//! app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness
|
||||
//! hands its agent; the quick check's findings go back in the shape each one reads.
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -114,6 +113,17 @@ pub fn steer(files: &[String]) -> String {
|
||||
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
|
||||
}
|
||||
|
||||
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
|
||||
/// adds or updates (Codex).
|
||||
fn saved(v: &Value) -> Vec<String> {
|
||||
let i = &v["tool_input"];
|
||||
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
|
||||
return vec![p.to_string()];
|
||||
}
|
||||
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
|
||||
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
|
||||
}
|
||||
|
||||
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
|
||||
/// plain stdout, Claude Code's and Codex's PostToolUse context.
|
||||
fn after(agent: &str, text: &str) -> String {
|
||||
@@ -146,7 +156,7 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
|
||||
}
|
||||
if event == "Stop" {
|
||||
// what the person sent, and a brief whose goals don't pass at done (docs/goal.feature MK36): either keeps the turn going
|
||||
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
|
||||
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
|
||||
return Ok(if reasons.is_empty() { String::new() } else { json!({"decision": "block", "reason": reasons.join("\n\n")}).to_string() });
|
||||
}
|
||||
@@ -161,8 +171,14 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
}
|
||||
return Ok(String::new());
|
||||
}
|
||||
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
|
||||
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
|
||||
let mut found = Vec::new();
|
||||
for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
|
||||
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
|
||||
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
|
||||
}
|
||||
let quick = (!found.is_empty()).then(|| format!("raea check --quick after this save:\n{}", found.join("\n")));
|
||||
let text = [sent, quick].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
|
||||
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -188,6 +204,8 @@ mod tests {
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
|
||||
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
|
||||
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
|
||||
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
|
||||
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
|
||||
assert_eq!(after("kimi", "x"), "x");
|
||||
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
|
||||
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
|
||||
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
|
||||
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
|
||||
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
|
||||
@@ -28,6 +28,7 @@ use raea_app_check_text::*;
|
||||
use raea_app_check_cause as cause;
|
||||
/// a video read through FFmpeg, or raea's own decoders where it isn't installed
|
||||
use raea_app_check_read::{self as read, Probe};
|
||||
pub mod quick;
|
||||
pub mod hook;
|
||||
pub use raea_app_check_inbox as inbox;
|
||||
#[cfg(test)]
|
||||
@@ -65,7 +66,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
|
||||
|
||||
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -115,7 +116,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
}
|
||||
|
||||
/// the flags `raea check` takes, each with a value
|
||||
const TAKES: [&str; 6] = ["--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
|
||||
|
||||
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
|
||||
@@ -217,7 +218,7 @@ fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<Strin
|
||||
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
|
||||
}
|
||||
let mut s = format!("raea check {video}\n");
|
||||
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea goal next` read
|
||||
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea next` read
|
||||
let kept = raea_core_facts::record::keep("raea check", std::path::Path::new(video), out.map(std::path::Path::new), &found, vec![], &raea_io_trace::utc(std::time::SystemTime::now()).1);
|
||||
let kept = kept.map(|e| format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
|
||||
for line in found.iter().map(Finding::line).chain(passed.iter().map(|p| format!("ok {p}"))).chain(kept) {
|
||||
|
||||
@@ -15,16 +15,6 @@ pub(crate) const MOST: f32 = 4.0;
|
||||
pub(crate) const RUN: usize = 4;
|
||||
pub(crate) const BACK: usize = 4;
|
||||
pub(crate) const BLOTCHY: f64 = 0.009;
|
||||
/// The least blotching an encoder's patches have been measured at (the VideoToolbox exports' 0.012): a score between
|
||||
/// BLOTCHY and this, whose cause can't be told, is a warning, never an error (12-05: a 3D shot rendered at master
|
||||
/// quality read 0.010, from its shadows' own dithered edge, and was an error whose fix, master quality, it already had)
|
||||
pub(crate) const BLOTCHED: f64 = 0.012;
|
||||
|
||||
/// How a finding whose cause can't be told stands: an error when more than a fifth of the samples blotch and the worst
|
||||
/// is past BLOTCHED, else a warning
|
||||
pub(crate) fn untold_level(share: f64, worst: f64) -> u8 {
|
||||
if share > 0.2 && worst >= BLOTCHED { 1 } else { 2 }
|
||||
}
|
||||
|
||||
pub(crate) fn blotch_score(y: &[u8], w: usize, h: usize) -> Option<f64> {
|
||||
let (bw, bh) = (w / 8, h / 8);
|
||||
@@ -200,8 +190,8 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
|
||||
let own = if a.0.before > 0 { format!("; {} of the samples show the footage's own too, which stays", a.0.before) } else { String::new() };
|
||||
(if a.0.worse as f64 / a.0.of.max(1) as f64 > 0.2 { 1 } else { 2 }, first.or(Some(at)), format!("the encode added blocky patches in dark areas: {} of {} samples are blotchier than the composition draws them unencoded; render with --quality master, which gives the darks the bits they need{own}", a.0.worse, a.0.of))
|
||||
}
|
||||
Some(Err(why)) => (untold_level(share, worst), Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
|
||||
None => (untold_level(share, worst), Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
|
||||
Some(Err(why)) => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
|
||||
None => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
|
||||
};
|
||||
issues.push(Issue { rule: "blotching", p, at, says });
|
||||
} else if seen > 0 {
|
||||
@@ -223,15 +213,12 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
continue;
|
||||
}
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
// each colour its words are drawn in (an accent word's beside the line's), held to the lowest
|
||||
let measure = |color: &str| if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
|
||||
let worst = r.middle_inks().into_iter().filter_map(|c| measure(c).map(|v| (v, c))).min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let Some((ratio, color)) = worst else { continue };
|
||||
let word = if color == r.middle_color() { String::new() } else { format!(" (its words in {color})") };
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{}{word} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
|
||||
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
|
||||
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
|
||||
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
|
||||
//! nothing.
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
|
||||
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
|
||||
fn samples(m: &Value) -> Option<[u64; 3]> {
|
||||
let n = m["length"].as_u64()?.max(1);
|
||||
Some([n / 4, n / 2, n - 1])
|
||||
}
|
||||
|
||||
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
|
||||
/// person's, evaluated by the raea CLI when --taste names them.
|
||||
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
|
||||
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
let manifest = tmp.join("render.json");
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
|
||||
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
|
||||
// frame 0 first, for the length (its manifest's), then the three stills
|
||||
let mut out = render("0")?;
|
||||
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
|
||||
if let Some(at) = at {
|
||||
let _ = std::fs::remove_file(&manifest);
|
||||
out = render(&at.map(|f| f.to_string()).join(","))?;
|
||||
}
|
||||
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
|
||||
let result = if let (Some(at), true) = (at, manifest.is_file()) {
|
||||
on_manifest(file, &manifest, args, tastes, at)
|
||||
} else {
|
||||
// a render that fails is the finding: the agent sees why
|
||||
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
|
||||
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
|
||||
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
|
||||
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
|
||||
};
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
result
|
||||
}
|
||||
|
||||
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
|
||||
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
|
||||
/// sound, blotching) waits for the full check on the export.
|
||||
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
|
||||
let at = manifest.display();
|
||||
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
|
||||
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
|
||||
let runs = text_runs(&m);
|
||||
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
|
||||
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
|
||||
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
|
||||
// and what the render of the stills found (the 3D's clipping, DR3)
|
||||
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
|
||||
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
|
||||
#[test]
|
||||
fn frames_come_from_the_render() {
|
||||
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
|
||||
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
|
||||
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
|
||||
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
|
||||
assert_eq!(super::samples(&json!({"width": 640})), None);
|
||||
}
|
||||
}
|
||||
+13
-15
@@ -22,7 +22,7 @@ fn a_placeholder_brand_kit_is_flagged() {
|
||||
brand_kit(&["", video.to_str().unwrap()], &mut issues, &mut passed);
|
||||
(issues.iter().map(|i| i.p).collect::<Vec<_>>(), passed.len())
|
||||
};
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![2], 0));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![1], 0));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["x"],"by_hand":{"palette.accent":"hero button"}}}"#)), (vec![], 1));
|
||||
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":[]}}"#)), (vec![], 1));
|
||||
assert_eq!(rules(None), (vec![2], 0));
|
||||
@@ -51,10 +51,6 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {
|
||||
(20.0 - (x * x + y * y).sqrt() / 24.0).max(6.0) as u8
|
||||
}).collect();
|
||||
assert!(blotch_score(&rings, w, h).unwrap() < BLOTCHY / 2.0);
|
||||
// a cause that can't be told: an error only past an encoder's measured blotching, on more than a fifth of samples
|
||||
assert_eq!(untold_level(1.0, 0.010), 2);
|
||||
assert_eq!(untold_level(1.0, 0.09), 1);
|
||||
assert_eq!(untold_level(0.1, 0.09), 2);
|
||||
assert_eq!(x264_crf(b"..\x05x264 - core 165 r3222 - H.264/MPEG-4 AVC codec - options: cabac=1 rc=crf mbtree=1 crf=12.0 qcomp=0.60"), Some(12.0));
|
||||
assert_eq!(x264_crf(b"Lavf61 VideoToolbox"), None);
|
||||
}
|
||||
@@ -71,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
|
||||
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
|
||||
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
|
||||
]);
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
|
||||
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
|
||||
@@ -189,14 +185,15 @@ fn a_bed_close_under_the_voice_and_a_loud_stretch_without_it_are_found() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placement_states_the_zones_check_measures() {
|
||||
// zones() is where the numbers live; placement.md says them in words, held to it here
|
||||
fn the_floor_and_placement_state_the_zones_check_measures() {
|
||||
// zones() is where the numbers live; floor.md and placement.md say them in words, held to it here
|
||||
let words = |t: &str| t.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let floor = words(include_str!("../../../sdk/guides/craft/floor.md"));
|
||||
let placement = words(include_str!("../../../sdk/guides/craft/motion/placement.md"));
|
||||
let n = |v: f64| format!("{v:.0}");
|
||||
let [t, r, b, l] = zones(1080.0, 1920.0, Some("9:16"), None);
|
||||
let said = [
|
||||
format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l)),
|
||||
format!("keep the top {} px, the bottom {}, the right {} and the left {} clear", n(t), n(b), n(r), n(l)),
|
||||
["tiktok", "reels", "shorts"].map(|p| {
|
||||
let [t, r, b, _] = zones(1080.0, 1920.0, Some("9:16"), Some(p));
|
||||
let name = match p { "tiktok" => "TikTok", "reels" => "Reels", _ => "Shorts" };
|
||||
@@ -207,8 +204,10 @@ fn placement_states_the_zones_check_measures() {
|
||||
{ let [t, r, b, l] = zones(1920.0, 1080.0, Some("16:9"), None); assert!(t == b && r == l); format!("16:9 top and bottom {}, sides {}", n(t), n(r)) },
|
||||
];
|
||||
for s in &said {
|
||||
assert!(placement.contains(s.as_str()), "placement.md doesn't say {s:?}");
|
||||
assert!(floor.contains(s.as_str()), "floor.md doesn't say {s:?}");
|
||||
}
|
||||
let s = format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l));
|
||||
assert!(placement.contains(&s), "placement.md doesn't say {s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -268,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
|
||||
|
||||
#[test]
|
||||
fn a_caption_is_timed_from_the_first_word_it_shows() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
|
||||
@@ -336,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
|
||||
|
||||
#[test]
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
|
||||
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
@@ -426,11 +425,10 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
#[test]
|
||||
fn a_moving_text_is_read_where_it_is() {
|
||||
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: vec![], color: String::new(), size: 40.0 };
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
|
||||
let (t, b) = run.middle(30.0);
|
||||
assert_eq!(t, 4.0);
|
||||
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
|
||||
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
|
||||
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
|
||||
}
|
||||
|
||||
@@ -43,13 +43,6 @@ pub struct Run {
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub boxes: Vec<[f64; 4]>,
|
||||
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
|
||||
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
|
||||
pub colors: Vec<String>,
|
||||
/// the colours its words are drawn in on each of those frames, beside `colors`, when any differs from the line's (the
|
||||
/// manifest's `inks`: a caption's accent word); empty when every word is in the line's colour
|
||||
pub inks: Vec<Vec<String>>,
|
||||
/// its colour on its last frame
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
}
|
||||
@@ -64,36 +57,11 @@ impl Run {
|
||||
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
|
||||
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
|
||||
}
|
||||
|
||||
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
|
||||
pub fn middle_color(&self) -> &str {
|
||||
let n = self.boxes.len();
|
||||
match self.colors.get(n / 2) {
|
||||
Some(c) if n > 1 && self.colors.len() == n => c,
|
||||
_ => &self.color,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every colour its words are drawn in on that frame: the line's, and an accent span's beside it (12-06: a line
|
||||
/// recorded only by its own colour hid a dark word on a dark plate)
|
||||
pub fn middle_inks(&self) -> Vec<&str> {
|
||||
let n = self.boxes.len();
|
||||
let mut all = vec![self.middle_color()];
|
||||
let at = if n > 1 && self.inks.len() == n { self.inks.get(n / 2) } else { self.inks.last() };
|
||||
for i in at.into_iter().flatten() {
|
||||
if !all.contains(&i.as_str()) {
|
||||
all.push(i);
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
}
|
||||
|
||||
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
|
||||
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, and a brand.css
|
||||
/// with no brand.json beside it wasn't read from the brand at all, both P2: where a kit came from is a note for the person
|
||||
/// at sign-off, not a fault in the cut (12-05, run 39: all four of Body Shop's cuts held an error for a fetch of the
|
||||
/// brand's site that read 40 of its 95 colour and face variables)
|
||||
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
|
||||
/// with no brand.json beside it wasn't read from the brand at all, P2
|
||||
pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for start in near.iter().filter(|p| !p.is_empty()) {
|
||||
@@ -114,7 +82,7 @@ pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String
|
||||
let thin: Vec<&str> = kit["source"]["thin"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
let by_hand = kit["source"]["by_hand"].as_object().is_some_and(|o| !o.is_empty());
|
||||
if !thin.is_empty() && !by_hand {
|
||||
issues.push(Issue { rule: "brand", p: 2, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
|
||||
issues.push(Issue { rule: "brand", p: 1, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
|
||||
} else {
|
||||
passed.push(format!("brand: the cut is styled from {}'s kit{}", kit["domain"].as_str().unwrap_or("the brand"), if by_hand { ", checked by hand" } else { "" }));
|
||||
}
|
||||
@@ -146,24 +114,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
});
|
||||
let mut r = match found {
|
||||
Some(i) => open.remove(i),
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), inks: Vec::new(), color: String::new(), size: 0.0 },
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
|
||||
};
|
||||
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
let inks: Vec<String> = x["inks"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
|
||||
if text.len() > r.text.len() {
|
||||
r.boxes.clear();
|
||||
r.colors.clear();
|
||||
r.inks.clear();
|
||||
}
|
||||
if text.len() >= r.text.len() {
|
||||
r.text = text;
|
||||
r.box_ = b;
|
||||
r.boxes.push(ink.unwrap_or(b));
|
||||
r.colors.push(color.clone());
|
||||
r.inks.push(inks);
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = color;
|
||||
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
r.size = x["size"].as_f64().unwrap_or(0.0);
|
||||
next.push(r);
|
||||
}
|
||||
@@ -214,11 +176,7 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
|
||||
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
|
||||
pub const RAIL: f64 = 0.45;
|
||||
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/motion/placement.md)
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
|
||||
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
|
||||
let r = w / h;
|
||||
let shape = shape.unwrap_or(if r < 0.7 { "9:16" } else if r < 0.9 { "4:5" } else if r < 1.2 { "1:1" } else { "16:9" });
|
||||
@@ -250,8 +208,7 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let q = quote(&r.text);
|
||||
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
|
||||
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
|
||||
if r.boxes.iter().all(off) {
|
||||
clipped += 1;
|
||||
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
|
||||
@@ -337,48 +294,3 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
|
||||
passed.push(format!("cues: {checked} texts land on their words"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
|
||||
/// down was an error); the same card over the buttons isn't.
|
||||
#[test]
|
||||
fn the_right_zone_starts_where_the_apps_buttons_do() {
|
||||
let right = |y: f64| {
|
||||
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
|
||||
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
|
||||
};
|
||||
assert_eq!(right(682.0), "");
|
||||
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
|
||||
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
|
||||
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs.len(), 1);
|
||||
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
|
||||
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_with_an_accent_word_is_measured_in_both_colours() {
|
||||
// a white caption with one word in dark red: the manifest's line colour alone hid the red word
|
||||
let m = json!({"fps": 10.0, "frames": (0..4).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "Stay out longer.", "box": [100, 1400, 880, 90], "size": 84, "color": "rgb(255, 255, 255)", "inks": ["rgb(255, 255, 255)", "rgb(120, 0, 0)"]}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs[0].middle_inks(), vec!["rgb(255, 255, 255)", "rgb(120, 0, 0)"]);
|
||||
// a line drawn in its own colour only has no inks, and is measured in that colour alone
|
||||
let plain = json!({"fps": 10.0, "frames": [{"frame": 0, "text": [{"text": "raea", "box": [0, 0, 10, 10], "size": 40, "color": "rgb(1, 2, 3)"}]}]});
|
||||
assert_eq!(text_runs(&plain)[0].middle_inks(), vec!["rgb(1, 2, 3)"]);
|
||||
}
|
||||
}
|
||||
@@ -18,10 +18,10 @@ use crate::ts;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
|
||||
/// The flags raea check takes with a value (its own, and the floor's on a video).
|
||||
const TAKES: [&str; 9] = ["--composition", "--only", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
|
||||
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
|
||||
/// context` reads the person's taste).
|
||||
@@ -410,7 +410,7 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
|
||||
// a note's ask's finding says which ask, as two asks can run one check
|
||||
out.extend(c.found.iter().map(|f| if f.by.starts_with("note ") { format!("{} [{}]", f.line(), f.by) } else { f.line() }));
|
||||
out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));
|
||||
// kept in its project's record (DR3), what raea findings and raea goal next read
|
||||
// kept in its project's record (DR3), what raea findings and raea next read
|
||||
if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {
|
||||
out.push(format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
let _ = std::fs::write(&m, v.to_string());
|
||||
}
|
||||
}
|
||||
// a render that is part of another (a review's tiles) leaves the entry to that one
|
||||
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
|
||||
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
||||
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
|
||||
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
|
||||
|
||||
@@ -35,7 +35,7 @@ pub struct Double {
|
||||
pub problem: Option<f64>,
|
||||
/// clef agrees: past even odds, or past the question's threshold once the person's labels calibrated it
|
||||
pub agrees: Option<bool>,
|
||||
/// its answer's id in the ask record (~/.raea/ask/answers.jsonl)
|
||||
/// its answer's id in raea ask's record, for `raea ask verdict`
|
||||
pub answer: Option<String>,
|
||||
/// why it wasn't asked or still waits
|
||||
pub not_asked: Option<String>,
|
||||
|
||||
@@ -15,8 +15,6 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
||||
raea-app-double = { path = "../double" }
|
||||
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
|
||||
@@ -21,13 +21,13 @@ use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, for a person to look at; --json prints it as JSON)";
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||
|
||||
/// The flags each verb takes, and whether each takes a value
|
||||
pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
pub(crate) const FLAGS: [(&str, bool); 31] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
@@ -51,6 +51,7 @@ pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
("--as", true),
|
||||
("--against", true),
|
||||
("--profile", true),
|
||||
("--by", true),
|
||||
("--ask", true),
|
||||
("--tally", false),
|
||||
("--bad", false),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
|
||||
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
|
||||
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
|
||||
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
|
||||
@@ -99,9 +99,30 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
|
||||
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
|
||||
raea_io_clef::critic::ask(cwd, p)
|
||||
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||
let mut c = std::process::Command::new(by);
|
||||
match by {
|
||||
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
|
||||
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
|
||||
o => return Err(format!("--by {o}: kimi or claude")),
|
||||
};
|
||||
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
|
||||
let mut text = String::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
|
||||
match content {
|
||||
Value::String(s) => text += s,
|
||||
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
|
||||
_ => {}
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
@@ -112,12 +133,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
|
||||
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// `raea fingerprint read PROJECT`
|
||||
/// `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let run = || -> Result<String, String> {
|
||||
let w = words(args)?;
|
||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let by = "agent";
|
||||
let by = flag(args, "--by").unwrap_or("kimi");
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||
let mut notes = pinned(&project);
|
||||
@@ -127,15 +148,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||
}
|
||||
for chunk in notes.chunks_mut(40) {
|
||||
let text = ask(&project, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
|
||||
let text = ask(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
fold(chunk, &fp, &ans, by);
|
||||
eprintln!("read {} notes", chunk.len());
|
||||
}
|
||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
@@ -264,7 +285,7 @@ mod tests {
|
||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
||||
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
|
||||
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
|
||||
fold(&mut n, &fp, &ans, "agent");
|
||||
fold(&mut n, &fp, &ans, "kimi");
|
||||
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
|
||||
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
|
||||
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||
|
||||
@@ -110,7 +110,7 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
|
||||
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
|
||||
// is, with its normals and texture coordinates, since it needn't be a closed solid
|
||||
Some(b) => {
|
||||
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
|
||||
let (t, uv) = raea_core_shape::buffer_tris(b)?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea judge: a review's sheets judged by clef-omni on a frozen rubric, the pass decided in code, calibrated against the person's eye before it gates"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
serde_json = "1"
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
@@ -0,0 +1,194 @@
|
||||
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
|
||||
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
|
||||
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
|
||||
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
|
||||
//! its reading as the eye clef is calibrated against.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{BAR, scores};
|
||||
|
||||
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||
|
||||
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
|
||||
/// own categories and the bar (docs/make.feature MK5); none asks the rubric raea judge has always asked.
|
||||
pub fn prompt(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
|
||||
match kind {
|
||||
None => prompt_default(dir, brief, target),
|
||||
Some(k) => prompt_kind(k, dir, brief, target),
|
||||
}
|
||||
}
|
||||
|
||||
fn brief_words(brief: &Value) -> String {
|
||||
["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ")
|
||||
}
|
||||
|
||||
fn prompt_kind(kind: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
|
||||
let words = brief_words(brief);
|
||||
let target = target.map(|t| format!(" The reference, what it must read as, is {}.", t.display())).unwrap_or_default();
|
||||
let d = dir.display();
|
||||
let sheets = match kind {
|
||||
"shot" => format!("This round's sheet: {d}/framing.png. Each row is one shot: its first, middle and last frame, left to right, each stamped with its name and time. Open it."),
|
||||
_ => format!(
|
||||
"This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both{}.",
|
||||
if kind == "kit" { "; the scene is the kit's lineup, its props side by side with a scale bar" } else { "" }
|
||||
),
|
||||
};
|
||||
let blind = if kind == "shot" {
|
||||
String::new()
|
||||
} else {
|
||||
format!("PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what is this, what era? List five objects you can name. Is it a photograph or a render, and which three tells decided it?\n\n")
|
||||
};
|
||||
let cats: String = scores(Some(kind)).iter().map(|(k, on, ask)| format!("- {k}{}: {}\n", if *on == "clay" { " (judged on CLAY)" } else { "" }, ask.split_once(": ").map(|(_, r)| r).unwrap_or(ask))).collect();
|
||||
let json_scores = scores(Some(kind)).iter().map(|(k, _, _)| format!("\"{k}\": 0")).collect::<Vec<_>>().join(", ");
|
||||
format!(
|
||||
"You review a {kind} from images only, as the person who will use it would. You have never seen how it was built and you never will. \
|
||||
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n{blind}\
|
||||
PART 2, SCORED. The brief: \"{words}\".{target} {sheets}\n\n\
|
||||
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n{cats}\n\
|
||||
{BAR} Each defect field is one short sentence; \"blocking\" means someone using this would notice it where it will be seen. \
|
||||
Name exactly what gives it away (not \"the phone looks fake\" but \"the handset is fused to the cradle with no gap\").\n\n\
|
||||
End your answer with only this JSON, nothing after it:\n\
|
||||
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
|
||||
\"scores\": {{{json_scores}}}, \
|
||||
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
|
||||
\"show_as_is\": \"\"}}"
|
||||
)
|
||||
}
|
||||
|
||||
fn prompt_default(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
|
||||
let words = brief_words(brief);
|
||||
let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();
|
||||
format!(
|
||||
"You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built and you never will. \
|
||||
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n\
|
||||
PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what place is this, what time, what era? List five objects you can name. \
|
||||
Is it a photograph or a render, and which three tells decided it?\n\n\
|
||||
PART 2, SCORED. The brief: \"{words}\".{target} This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: \
|
||||
hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both.\n\n\
|
||||
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n\
|
||||
- composition: camera, framing, layout, the position and scale of every major object.\n\
|
||||
- form, judged on CLAY: silhouettes read at a glance; parts have real thickness; nothing blobby, melted or a primitive standing in for a thing; repeated things vary.\n\
|
||||
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet.\n\
|
||||
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.\n\
|
||||
- light: motivated by the place's own sources; exposure and contrast believable.\n\
|
||||
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads.\n\
|
||||
- world: one coherent real place; nothing off-era or invented beyond the brief.\n\n\
|
||||
Then list the defects, most damaging first: at most 8, each field one short sentence. \"blocking\" means someone using this scene would notice it in the views it will be seen in. \
|
||||
Name exactly what gives it away (not \"the dryer looks fake\" but \"the dryer door is a flat disc with no rim or glass depth\").\n\n\
|
||||
End your answer with only this JSON, nothing after it:\n\
|
||||
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
|
||||
\"scores\": {{\"composition\": 0, \"form\": 0, \"assembly\": 0, \"materials\": 0, \"light\": 0, \"detail\": 0, \"world\": 0}}, \
|
||||
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
|
||||
\"show_as_is\": \"\"}}",
|
||||
d = dir.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// The last JSON object in the text that has scores (an agent may think aloud, or draft the JSON twice).
|
||||
pub fn last_verdict(text: &str) -> Option<Value> {
|
||||
let starts: Vec<usize> = text.match_indices('{').map(|(i, _)| i).collect();
|
||||
for &s in starts.iter().rev() {
|
||||
let mut de = serde_json::Deserializer::from_str(&text[s..]).into_iter::<Value>();
|
||||
if let Some(Ok(v)) = de.next()
|
||||
&& v.get("scores").is_some_and(Value::is_object)
|
||||
{
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The verdict read into the judge's own shape: scores (0-10, the kind's categories), defects (present, level, named
|
||||
/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.
|
||||
pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
|
||||
let mut out = Map::new();
|
||||
for &(k, _, _) in scores(kind) {
|
||||
if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {
|
||||
out.insert(k.into(), json!(x));
|
||||
}
|
||||
}
|
||||
let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {
|
||||
let level = if d["level"].as_str().unwrap_or("").starts_with("block") { "blocking" } else { "detail" };
|
||||
let wrong = d["wrong"].as_str().unwrap_or("");
|
||||
json!({"defect": wrong.chars().take(80).collect::<String>(), "present": true, "level": level, "sheet": d["tile"], "asked": wrong,
|
||||
"where": d["where"], "real": d["real"], "fix": d["fix"]})
|
||||
}).collect();
|
||||
let photo = match v["blind"]["photo"].as_str() {
|
||||
Some(p) if p.starts_with('y') => json!(1.0),
|
||||
Some(p) if p.starts_with('n') => json!(0.0),
|
||||
_ => Value::Null,
|
||||
};
|
||||
(out, defects, photo)
|
||||
}
|
||||
|
||||
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
|
||||
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
|
||||
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
use std::io::BufRead as _;
|
||||
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
let p = prompt(kind, &dir, brief, target);
|
||||
let mut cmd = match by {
|
||||
"kimi" => {
|
||||
let mut c = std::process::Command::new("kimi");
|
||||
c.args(["-p", &p, "--output-format", "stream-json"]);
|
||||
c
|
||||
}
|
||||
"claude" => {
|
||||
let mut c = std::process::Command::new("claude");
|
||||
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
|
||||
c
|
||||
}
|
||||
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
|
||||
};
|
||||
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
|
||||
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
|
||||
let mut said = Vec::new();
|
||||
let mut last = String::new();
|
||||
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
|
||||
said.extend(texts(&v));
|
||||
let step = match (v["role"].as_str(), v["type"].as_str()) {
|
||||
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
|
||||
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
|
||||
_ => continue,
|
||||
};
|
||||
if step != last {
|
||||
eprintln!("judge ({by}): {}", step.replace('\n', " "));
|
||||
last = step;
|
||||
}
|
||||
}
|
||||
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
|
||||
let text = said.join("\n");
|
||||
if !out.status.success() && last_verdict(&text).is_none() {
|
||||
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
|
||||
}
|
||||
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
|
||||
}
|
||||
|
||||
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
|
||||
/// {content: [{type: text, text}]}} and its final {type: result, result}.
|
||||
fn texts(v: &Value) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if v["role"] == "assistant"
|
||||
&& let Some(s) = v["content"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
for c in v["message"]["content"].as_array().into_iter().flatten() {
|
||||
if c["type"] == "text"
|
||||
&& let Some(s) = c["text"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
if v["type"] == "result"
|
||||
&& let Some(s) = v["result"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Shane's eye, the judge's calibration. `raea judge eye DIR form=5 light=7 ... [--pass yes|no]` records his scores for a
|
||||
//! round the judge has already judged (DIR/judge.json), with the judge's raw scores beside them, in
|
||||
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
|
||||
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
|
||||
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
|
||||
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{pass_for, scores};
|
||||
|
||||
fn home() -> PathBuf {
|
||||
raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")
|
||||
}
|
||||
|
||||
/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's
|
||||
/// (docs/make.feature MK6), each fitted on that kind's rounds alone.
|
||||
fn file_of(kind: Option<&str>) -> PathBuf {
|
||||
home().join(kind.map_or_else(|| "calibration.json".to_string(), |k| format!("calibration.{k}.json")))
|
||||
}
|
||||
|
||||
/// The calibration in force for a kind, if one was made.
|
||||
pub fn calibration(kind: Option<&str>) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(file_of(kind)).ok()?).ok()
|
||||
}
|
||||
|
||||
/// A row's or a verdict's kind: none for the default rubric.
|
||||
fn kind_in(v: &Value) -> Option<&str> {
|
||||
v["kind"].as_str()
|
||||
}
|
||||
|
||||
/// The judge's scores mapped through the calibration's lines, kept to 0-10.
|
||||
pub fn apply(c: &Value, scores: &mut Map<String, Value>) {
|
||||
for (k, v) in scores.iter_mut() {
|
||||
if let (Some(x), Some(a), Some(b)) = (v.as_f64(), c["maps"][k]["a"].as_f64(), c["maps"][k]["b"].as_f64()) {
|
||||
*v = json!(((a * x + b).clamp(0.0, 10.0) * 100.0).round() / 100.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record(args: &[String]) -> Result<String, String> {
|
||||
let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;
|
||||
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
|
||||
let kind = kind_in(&verdict);
|
||||
let cats = scores(kind);
|
||||
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
|
||||
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
|
||||
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
|
||||
let (eye, defects, _) = crate::agent::read(kind, &v);
|
||||
if eye.len() < cats.len() {
|
||||
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
|
||||
}
|
||||
let eye_pass = pass_for(kind, &eye, &defects).0;
|
||||
let row = json!({"dir": verdict["dir"], "kind": kind, "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
|
||||
append(&row)?;
|
||||
let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();
|
||||
return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));
|
||||
}
|
||||
let mut eye = Map::new();
|
||||
let mut said_pass = None;
|
||||
let mut i = 3;
|
||||
while i < args.len() {
|
||||
if args[i] == "--pass" {
|
||||
said_pass = Some(matches!(args.get(i + 1).map(String::as_str), Some("yes" | "true" | "y")));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;
|
||||
if !cats.iter().any(|s| s.0 == k) {
|
||||
return Err(format!("judge eye: no category {k}: {}", cats.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;
|
||||
eye.insert(k.into(), json!(x));
|
||||
i += 1;
|
||||
}
|
||||
if eye.is_empty() {
|
||||
return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());
|
||||
}
|
||||
// his pass: as he says it, else the same rule on his scores with the judge's defects
|
||||
let eye_pass = said_pass.unwrap_or_else(|| pass_for(kind, &eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
|
||||
let row = json!({"dir": verdict["dir"], "kind": kind, "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
|
||||
append(&row)?;
|
||||
Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))
|
||||
}
|
||||
|
||||
/// One eye row onto ~/.raea/judge/eye.jsonl; a newer reading of the same round by the same eye replaces the older.
|
||||
fn append(row: &Value) -> Result<(), String> {
|
||||
std::fs::create_dir_all(home()).map_err(|e| e.to_string())?;
|
||||
let path = home().join("eye.jsonl");
|
||||
let mut rows: Vec<Value> = std::fs::read_to_string(&path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| !(r["dir"] == row["dir"] && whose(r) == whose(&row))).collect();
|
||||
rows.push(row.clone());
|
||||
std::fs::write(&path, rows.iter().map(Value::to_string).collect::<Vec<_>>().join("\n") + "\n").map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Least squares y = a x + b; flat x (one value) maps by the mean offset.
|
||||
fn fit(xy: &[(f64, f64)]) -> (f64, f64) {
|
||||
let n = xy.len() as f64;
|
||||
let (mx, my) = (xy.iter().map(|p| p.0).sum::<f64>() / n, xy.iter().map(|p| p.1).sum::<f64>() / n);
|
||||
let sxx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
|
||||
if sxx < 1e-9 {
|
||||
return (1.0, my - mx);
|
||||
}
|
||||
let a = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;
|
||||
(a, my - a * mx)
|
||||
}
|
||||
|
||||
/// The fit over a kind's rows of {judge, eye, defects, eye_pass} (none: the default rubric's): per-category maps and
|
||||
/// errors, and the pass agreement.
|
||||
pub fn fit_rows_for(kind: Option<&str>, rows: &[Value]) -> Value {
|
||||
let mut maps = Map::new();
|
||||
for &(k, _, _) in scores(kind) {
|
||||
let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();
|
||||
if xy.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = fit(&xy);
|
||||
let mae = |f: &dyn Fn(f64) -> f64| xy.iter().map(|(x, y)| (f(*x) - y).abs()).sum::<f64>() / xy.len() as f64;
|
||||
let r2 = |x: f64| (x * 1000.0).round() / 1000.0;
|
||||
maps.insert(k.into(), json!({"a": r2(a), "b": r2(b), "n": xy.len(), "maeRaw": r2(mae(&|x| x)), "maeMapped": r2(mae(&|x| (a * x + b).clamp(0.0, 10.0)))}));
|
||||
}
|
||||
let cal = json!({"maps": maps});
|
||||
let mut agree = 0;
|
||||
for r in rows {
|
||||
let mut s = r["judge"].as_object().cloned().unwrap_or_default();
|
||||
apply(&cal, &mut s);
|
||||
let p = pass_for(kind, &s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
|
||||
if Value::Bool(p) == r["eye_pass"] {
|
||||
agree += 1;
|
||||
}
|
||||
}
|
||||
let n = rows.len();
|
||||
let agreement = if n == 0 { 0.0 } else { agree as f64 / n as f64 };
|
||||
// agreement means something only when the eye passed some rounds and failed others: all fails agree trivially
|
||||
let passes = rows.iter().filter(|r| r["eye_pass"] == true).count();
|
||||
let both = passes > 0 && passes < n;
|
||||
json!({"maps": maps, "rounds": n, "eyePasses": passes, "agreement": (agreement * 1000.0).round() / 1000.0, "gate": n >= 10 && agreement >= 0.8 && both})
|
||||
}
|
||||
|
||||
pub fn calibrate(args: &[String]) -> Result<String, String> {
|
||||
let kind = crate::kind_of(args)?;
|
||||
let kind = kind.as_deref();
|
||||
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| kind_in(r) == kind).collect();
|
||||
if rows.is_empty() {
|
||||
let k = kind.map(|k| format!(" of a {k}")).unwrap_or_default();
|
||||
return Err(format!("judge calibrate: no rounds{k} with your eye yet (raea judge eye DIR form=5 ...)"));
|
||||
}
|
||||
let mut cal = fit_rows_for(kind, &rows);
|
||||
cal["kind"] = json!(kind);
|
||||
let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();
|
||||
eyes.sort();
|
||||
eyes.dedup();
|
||||
cal["eyes"] = json!(eyes);
|
||||
std::fs::write(file_of(kind), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());
|
||||
}
|
||||
let mut t: Vec<String> = cal["maps"].as_object().into_iter().flatten().map(|(k, m)| format!("{k:<12} eye = {} x judge {:+} (off by {} raw, {} mapped, {} rounds)", m["a"], m["b"], m["maeRaw"], m["maeMapped"], m["n"])).collect();
|
||||
t.push(format!("agreement on the pass: {} over {} rounds (eyes: {}); {}", cal["agreement"], cal["rounds"], eyes.join(", "), if cal["gate"] == true { "the judge gates now".to_string() } else if cal["rounds"].as_u64() >= Some(10) && cal["agreement"].as_f64() >= Some(0.8) { format!("advice only: the eye passed {} of {} rounds, and agreement means something only with passes and fails both (judge a scene that is good)", cal["eyePasses"], cal["rounds"]) } else { "advice only until 10 rounds agree 8 in 10, with passes and fails both".to_string() }));
|
||||
Ok(t.join("\n"))
|
||||
}
|
||||
|
||||
/// Whose eye a row records: Shane's when it doesn't say.
|
||||
fn whose(r: &Value) -> &str {
|
||||
r["by"].as_str().unwrap_or("shane")
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! `raea judge`: a review's sheets (`raea render --review DIR`) judged by clef-omni on the frozen rubric (rubric.rs),
|
||||
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
|
||||
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
|
||||
//!
|
||||
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
|
||||
//! raea judge calibrate [--kind scene|kit|shot] [--json]
|
||||
//!
|
||||
//! `--kind` asks a `raea make` job's own rubric (docs/make.feature MK5): a scene's, a kit's or a shot list's categories,
|
||||
//! with the bar AnyKit's critic is given; each kind is calibrated on its own rounds (MK6).
|
||||
//!
|
||||
//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,
|
||||
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
|
||||
|
||||
mod agent;
|
||||
mod eye;
|
||||
|
||||
/// Whether the judge's score gates a `raea make` kind's jobs: its calibration (`raea judge calibrate --kind KIND`)
|
||||
/// agreed with the person's eye (docs/make.feature MK6).
|
||||
pub fn kind_gates(kind: &str) -> bool {
|
||||
eye::calibration(Some(kind)).is_some_and(|c| c["gate"] == true)
|
||||
}
|
||||
pub mod rubric;
|
||||
|
||||
pub use agent::BY;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_bundle::flag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a raea make job's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
|
||||
|
||||
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
|
||||
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
|
||||
match flag(args, "--kind") {
|
||||
None => Ok(None),
|
||||
Some(k) if rubric::KINDS.contains(&k.as_str()) => Ok(Some(k)),
|
||||
Some(k) => Err(format!("judge: --kind {k}: the kinds are {}", rubric::KINDS.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
|
||||
/// with the rubric's questions as written and each sheet as a JPEG still.
|
||||
fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
|
||||
let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;
|
||||
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
|
||||
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
|
||||
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
|
||||
let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
|
||||
Ok((Value::Object(a.answers), a.cost))
|
||||
}
|
||||
|
||||
/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.
|
||||
fn brief_of(path: Option<&str>) -> Result<Value, String> {
|
||||
let Some(p) = path else { return Ok(json!({})) };
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
|
||||
Ok(v.get("brief").cloned().unwrap_or(v))
|
||||
}
|
||||
|
||||
/// The rounds judged so far beside this one (DIR's parent's judge.log.jsonl).
|
||||
fn log_of(dir: &Path) -> PathBuf {
|
||||
dir.parent().unwrap_or(dir).join("judge.log.jsonl")
|
||||
}
|
||||
|
||||
/// Done and stall, from the log's rounds (oldest first), in code.
|
||||
pub fn progress(rounds: &[Value]) -> Value {
|
||||
let passes = rounds.iter().rev().take_while(|r| r["pass"] == true).count();
|
||||
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
|
||||
let stall = means.len() >= 3 && {
|
||||
let best_before = means[..means.len() - 2].iter().cloned().fold(f64::MIN, f64::max);
|
||||
let best_now = means[means.len() - 2..].iter().cloned().fold(f64::MIN, f64::max);
|
||||
best_now - best_before < 1.0
|
||||
};
|
||||
// the same blocking defect present in the last two rounds
|
||||
let named = |r: &Value| -> Vec<String> { rubric::blocking(r["defects"].as_array().map(Vec::as_slice).unwrap_or_default()).into_iter().map(str::to_string).collect() };
|
||||
let again: Vec<String> = match rounds {
|
||||
[.., a, b] => named(a).into_iter().filter(|d| named(b).contains(d)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
json!({"rounds": rounds.len(), "passesInARow": passes, "done": passes >= 2, "stall": stall || !again.is_empty(), "again": again})
|
||||
}
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("eye") => return eye::record(args),
|
||||
Some("calibrate") => return eye::calibrate(args),
|
||||
Some(_) => {}
|
||||
None => return Err(USAGE.into()),
|
||||
}
|
||||
let dir = PathBuf::from(&args[1]);
|
||||
let kind = kind_of(args)?;
|
||||
let kind = kind.as_deref();
|
||||
let hero = dir.join("hero-colour.png");
|
||||
let sheets: Vec<(&str, PathBuf)> = rubric::sheets(kind).iter().map(|(s, f)| (*s, dir.join(f))).collect();
|
||||
for (_, f) in &sheets {
|
||||
if !f.is_file() {
|
||||
let make = if kind == Some("shot") { format!("raea make framing --out {}", dir.display()) } else { format!("raea render EDIT.tsx --review {}", dir.display()) };
|
||||
return Err(format!("judge: no {} (make the sheets with {make})", f.display()));
|
||||
}
|
||||
}
|
||||
let brief = brief_of(flag(args, "--brief").as_deref())?;
|
||||
let target = flag(args, "--target").map(PathBuf::from);
|
||||
let dry = args.iter().any(|a| a == "--dry");
|
||||
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
|
||||
if by != "clef" {
|
||||
if dry {
|
||||
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
|
||||
}
|
||||
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
|
||||
let (scores, defects, photo) = agent::read(kind, &v);
|
||||
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
|
||||
}
|
||||
let mut calls = Vec::new();
|
||||
for (sheet, img) in &sheets {
|
||||
let mut images = vec![img.clone()];
|
||||
if *sheet == "colour" {
|
||||
images.extend(target.clone());
|
||||
}
|
||||
calls.push((*sheet, rubric::state_for(kind, sheet, &brief), rubric::questions_for(kind, sheet), images));
|
||||
}
|
||||
if hero.is_file() && kind != Some("shot") {
|
||||
calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));
|
||||
}
|
||||
if dry {
|
||||
let shown: Vec<Value> = calls.iter().map(|(s, st, q, im)| json!({"sheet": s, "state": st, "questions": q, "images": im.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()})).collect();
|
||||
return Ok(serde_json::to_string_pretty(&json!({"would_ask": shown})).unwrap_or_default());
|
||||
}
|
||||
let mut scores = serde_json::Map::new();
|
||||
let mut defects = Vec::new();
|
||||
let mut photo = Value::Null;
|
||||
let mut cost = 0.0;
|
||||
for (sheet, st, q, images) in &calls {
|
||||
let (answers, c) = ask(st, q, images)?;
|
||||
cost += c;
|
||||
if *sheet == "blind" {
|
||||
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
|
||||
continue;
|
||||
}
|
||||
let (s, d) = rubric::read_for(kind, &answers);
|
||||
scores.extend(s);
|
||||
defects.extend(d.into_iter().map(|mut x| {
|
||||
x["sheet"] = json!(sheet);
|
||||
x
|
||||
}));
|
||||
}
|
||||
let raw = scores.clone();
|
||||
let cal = eye::calibration(kind);
|
||||
if let Some(c) = &cal {
|
||||
eye::apply(c, &mut scores);
|
||||
}
|
||||
let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);
|
||||
finish(args, kind, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
|
||||
}
|
||||
|
||||
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
|
||||
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
|
||||
/// sheet in its words and is about no entity.
|
||||
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
|
||||
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
|
||||
let blocking = d["level"] == "blocking";
|
||||
let level = match (blocking, advice) {
|
||||
(true, false) => Level::Error,
|
||||
(true, true) | (false, false) => Level::Warn,
|
||||
(false, true) => Level::Note,
|
||||
};
|
||||
let sheet = d["sheet"].as_str().unwrap_or("");
|
||||
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
|
||||
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
|
||||
if let Some(p) = d["p"].as_f64() {
|
||||
f = f.measure("p", p, "", Some(0.5));
|
||||
}
|
||||
match d["fix"].as_str() {
|
||||
Some(x) if !x.is_empty() => f.fix(x),
|
||||
_ => f,
|
||||
}
|
||||
});
|
||||
finding::ranked(found.collect())
|
||||
}
|
||||
|
||||
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
|
||||
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
|
||||
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
|
||||
let found = findings(&defects, by, advice);
|
||||
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
|
||||
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
|
||||
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
|
||||
v.extend(e.clone());
|
||||
}
|
||||
let log = log_of(dir);
|
||||
let mut rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| r["dir"] != verdict["dir"]).collect();
|
||||
rounds.push(verdict.clone());
|
||||
verdict["progress"] = progress(&rounds);
|
||||
let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };
|
||||
std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "kind": r["kind"], "by": r["by"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
|
||||
std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;
|
||||
if cost > 0.0 {
|
||||
let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();
|
||||
}
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok(serde_json::to_string_pretty(&verdict).unwrap_or_default());
|
||||
}
|
||||
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
|
||||
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
|
||||
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
|
||||
for f in &found {
|
||||
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
|
||||
t.push(format!(" {}{p}", f.line()));
|
||||
}
|
||||
let p = &verdict["progress"];
|
||||
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
|
||||
t.push(format!("raea judge: {}", finding::count(&found)));
|
||||
Ok(t.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
|
||||
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
|
||||
pub fn why_refused(out: &std::process::Output) -> String {
|
||||
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
|
||||
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! The frozen rubric (the 11-06 prompt pack, section 3, in clef-omni's native question types): a 0-10 score per category
|
||||
//! as an ordered six-level rubric, and every named defect as a yes/no question, so a defect is a probability rather
|
||||
//! than prose. clef-omni answers questions, not essays; the defects it can name are the ones asked. Nothing here says
|
||||
//! where the pass line is (the loop decides, in code: `pass`).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The six levels each category is scored on, lowest first (clef's `score`: the probability-weighted level), read as
|
||||
/// 0, 2, 4, 6, 8, 10.
|
||||
fn levels(what: &str) -> Value {
|
||||
json!([
|
||||
format!("0: no {what} to speak of; broken or missing"),
|
||||
format!("2: {what} is crude: primitives and placeholders"),
|
||||
format!("4: {what} is a rough draft, plainly unfinished"),
|
||||
format!("6: {what} is a believable draft"),
|
||||
format!("8: {what} is a production base an artist would accept"),
|
||||
format!("10: {what} is indistinguishable from the real thing"),
|
||||
])
|
||||
}
|
||||
|
||||
/// A category: (id, the sheet it is judged on, the question).
|
||||
pub type Score = (&'static str, &'static str, &'static str);
|
||||
|
||||
/// (id, the sheet it is judged on, the question): the rubric raea judge has always asked, when no `--kind` is given.
|
||||
pub const SCORES: [Score; 7] = [
|
||||
("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),
|
||||
("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),
|
||||
("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),
|
||||
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
|
||||
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; no surface implausibly dark or bright."),
|
||||
("detail", "colour", "Detail: close surfaces hold real geometry or texture at that distance, not smooth stand-ins; printed matter reads."),
|
||||
("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),
|
||||
];
|
||||
|
||||
/// The job kinds with a rubric of their own (docs/make.feature MK5): `raea judge DIR --kind scene|kit|shot`.
|
||||
pub const KINDS: [&str; 3] = ["scene", "kit", "shot"];
|
||||
|
||||
/// A scene made to a plan (AnyScene's categories): judged on the six-camera sheets.
|
||||
pub const SCENE: [Score; 8] = [
|
||||
("layout", "clay", "Layout, judged on these grey clay tiles: every major object where the plan and the reference put it, at its real size, with room to move between them."),
|
||||
("props", "clay", "Props, judged on these grey clay tiles: each object's form reads at a glance, with real thickness; nothing blobby or a primitive standing in; nothing floats, sinks or pokes through."),
|
||||
("signage", "colour", "Screens and signage: every screen, sign, label and printed thing reads, belongs to one invented world, and shows no real brand."),
|
||||
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
|
||||
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; emissive things glow without lighting the room wrong."),
|
||||
("atmosphere", "colour", "Atmosphere: the air, haze, dust or weather the place would have, matching the plan's dials; not empty and clinical."),
|
||||
("plausibility", "colour", "Plausibility: one coherent real place a person could stand in; nothing off-era, nothing that couldn't be there."),
|
||||
("composition", "colour", "Composition: the hero camera's framing and the place's layout read as the reference's."),
|
||||
];
|
||||
|
||||
/// A kit (AnyKit's categories): judged on the six-camera sheets of its lineup.
|
||||
pub const KIT: [Score; 8] = [
|
||||
("cohesion", "colour", "Cohesion: every prop belongs to one set: the same era, palette, materials, wear and maker; none is an outlier."),
|
||||
("fidelity", "colour", "Reference fidelity: the props read as the style references' world, at normal viewing distance."),
|
||||
("brief", "colour", "Brief: the kit holds the props the brief asked for, each recognisable as what it is meant to be."),
|
||||
("mesh", "clay", "Mesh, judged on these grey clay tiles: crisp silhouettes, real thickness, no melted or blobby forms, no holes or spikes."),
|
||||
("texture", "colour", "Texture: real materials with wear where use puts it; no smeared, stretched or flat default surfaces; glass is glass."),
|
||||
("assembly", "clay", "Assembly, judged on these grey clay tiles: every part of each prop is connected to its body; handles, legs and lids attached."),
|
||||
("scale", "clay", "Scale, judged on these grey clay tiles: each prop's size is right beside the others and the scale bar."),
|
||||
("labels", "colour", "Labels: printed text and logos read, belong to the one invented maker, and no real brand shows."),
|
||||
];
|
||||
|
||||
/// A shot list (AnyShot's categories): judged on the framing sheet, each shot's first, middle and last frame.
|
||||
pub const SHOT: [Score; 6] = [
|
||||
("framing", "colour", "Framing: each shot frames its subject as its description says, at every one of its frames."),
|
||||
("move", "colour", "Move: the camera's change from first to last frame is the move the description names, at a believable size."),
|
||||
("focus", "colour", "Focus: what the description says is sharp is sharp; nothing important lost in blur."),
|
||||
("clearance", "colour", "Clearance: the camera is never inside or against a wall or object; nothing blocks the frame."),
|
||||
("continuity", "colour", "Continuity: the shots read as one place at one time: the same light, weather and dressing across them."),
|
||||
("grade", "colour", "Grade: the look matches the plan's look dial, with believable exposure and colour."),
|
||||
];
|
||||
|
||||
/// The categories asked for a kind: its own rubric, or the default one.
|
||||
pub fn scores(kind: Option<&str>) -> &'static [Score] {
|
||||
match kind {
|
||||
Some("scene") => &SCENE,
|
||||
Some("kit") => &KIT,
|
||||
Some("shot") => &SHOT,
|
||||
_ => &SCORES,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a kind's critic is told the bar is (AnyKit's own words, docs/make.feature MK5).
|
||||
pub const BAR: &str = "The bar is a production base an artist then refines, judged at normal viewing distance: take no points off for choices that differ from the reference, don't nitpick, and name at most five fixes, most damaging first.";
|
||||
|
||||
/// The sheets a kind is judged on: the six-camera colour and clay sheets, or a shot list's framing sheet alone.
|
||||
pub fn sheets(kind: Option<&str>) -> &'static [(&'static str, &'static str)] {
|
||||
match kind {
|
||||
Some("shot") => &[("colour", "framing.png")],
|
||||
_ => &[("colour", "colour.png"), ("clay", "clay.png")],
|
||||
}
|
||||
}
|
||||
|
||||
/// (id, sheet, the yes/no question, blocking when yes)
|
||||
pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
|
||||
("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),
|
||||
("intersecting", "clay", "Does any object pass through another object, a wall or the floor?", true),
|
||||
("blobby", "clay", "Is any object a blobby, melted or lumpy shape where the real thing has crisp form?", true),
|
||||
("stand_in", "clay", "Is any object just a plain box, ball or cylinder standing in for a more detailed real thing?", true),
|
||||
("clones", "clay", "Are several copies of one thing identical and evenly spaced in an obviously artificial way?", false),
|
||||
("flat_colour", "colour", "Is any large surface a flat, uniform default colour with no texture, variation or wear?", true),
|
||||
("plastic", "colour", "Do the surfaces look like shiny uniform plastic or CG rather than their real materials?", true),
|
||||
("garbled_text", "colour", "Is any visible text garbled, tiled or unreadable where it should read?", false),
|
||||
("too_dark", "colour", "Is the scene so dark that important objects are hard to see?", true),
|
||||
("too_bright", "colour", "Is the scene washed out, with large areas blown to white?", true),
|
||||
("brands", "colour", "Is a real brand name or logo visible?", true),
|
||||
("not_doing", "colour", "Does the scene show anything the brief says it must not contain?", true),
|
||||
];
|
||||
|
||||
/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).
|
||||
pub fn state(sheet: &str, brief: &Value) -> String {
|
||||
state_for(None, sheet, brief)
|
||||
}
|
||||
|
||||
/// state, for a kind: a kind's critic also reads what it is looking at in its terms, and the bar.
|
||||
pub fn state_for(kind: Option<&str>, sheet: &str, brief: &Value) -> String {
|
||||
let what = match kind {
|
||||
Some("shot") => "The image is a framing sheet: each row is one shot, its first, middle and last frame left to right, each stamped with the shot's name and time. Judge each shot as its description would.".to_string(),
|
||||
_ => {
|
||||
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
|
||||
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
|
||||
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
|
||||
let kit = if kind == Some("kit") { " The scene is a kit: a lineup of props made to belong together, with a scale bar." } else { "" };
|
||||
format!("{what}{target}{kit}")
|
||||
}
|
||||
};
|
||||
// the default rubric's words stay as calibrated: "the scene"
|
||||
let it = match kind { None | Some("scene") => "the scene", Some("kit") => "the kit", _ => "the shots" };
|
||||
let mut s = format!("{what} Judge only what is in the pixels, as the person who will use {it} would.");
|
||||
let look = brief["look"].as_str().unwrap_or("");
|
||||
let logline = brief["logline"].as_str().unwrap_or("");
|
||||
let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
if !logline.is_empty() || !look.is_empty() {
|
||||
s.push_str(&format!(" The brief: {logline} Look: {look}."));
|
||||
}
|
||||
if !not.is_empty() {
|
||||
let it = it[..1].to_uppercase() + &it[1..];
|
||||
s.push_str(&format!(" {it} must not contain: {}.", not.join("; ")));
|
||||
}
|
||||
if kind.is_some() {
|
||||
s.push(' ');
|
||||
s.push_str(BAR);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The questions for one sheet, by id.
|
||||
pub fn questions(sheet: &str) -> Value {
|
||||
questions_for(None, sheet)
|
||||
}
|
||||
|
||||
/// questions, for a kind's rubric.
|
||||
pub fn questions_for(kind: Option<&str>, sheet: &str) -> Value {
|
||||
let mut q = serde_json::Map::new();
|
||||
for &(id, on, ask) in scores(kind) {
|
||||
if on == sheet {
|
||||
q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));
|
||||
}
|
||||
}
|
||||
for (id, on, ask, _) in DEFECTS {
|
||||
if on == sheet {
|
||||
q.insert(format!("defect_{id}"), json!({"type": "noul", "instructions": ask}));
|
||||
}
|
||||
}
|
||||
Value::Object(q)
|
||||
}
|
||||
|
||||
/// The blind read on the hero tile alone: is this a photograph (reported, never gated, until calibrated).
|
||||
pub fn blind() -> Value {
|
||||
json!({"photo": {"type": "noul", "instructions": "Is this a photograph of a real place, rather than a computer render?"}})
|
||||
}
|
||||
|
||||
/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).
|
||||
pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
|
||||
read_for(None, answers)
|
||||
}
|
||||
|
||||
/// read, for a kind's rubric.
|
||||
pub fn read_for(kind: Option<&str>, answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
|
||||
let mut scores = serde_json::Map::new();
|
||||
let mut defects = Vec::new();
|
||||
for &(id, _, _) in self::scores(kind) {
|
||||
if let Some(a) = answers.get(format!("score_{id}")) {
|
||||
let level = a["score"].as_f64().unwrap_or(0.0);
|
||||
scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));
|
||||
}
|
||||
}
|
||||
for (id, _, ask, blocking) in DEFECTS {
|
||||
if let Some(a) = answers.get(format!("defect_{id}")) {
|
||||
let p = a["noul"].as_f64().unwrap_or(0.0);
|
||||
defects.push(json!({"defect": id, "p": (p * 1000.0).round() / 1000.0, "present": p >= 0.5, "level": if blocking { "blocking" } else { "detail" }, "asked": ask}));
|
||||
}
|
||||
}
|
||||
(scores, defects)
|
||||
}
|
||||
|
||||
/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's
|
||||
/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.
|
||||
pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
|
||||
pass_for(None, scores, defects)
|
||||
}
|
||||
|
||||
/// pass, for a kind's rubric: every one of its categories scored.
|
||||
pub fn pass_for(kind: Option<&str>, scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
|
||||
let want = self::scores(kind).len();
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mut why = Vec::new();
|
||||
let blocking = blocking(defects);
|
||||
if !blocking.is_empty() {
|
||||
why.push(format!("blocking: {}", blocking.join(", ")));
|
||||
}
|
||||
let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };
|
||||
if vals.len() < want {
|
||||
why.push(format!("only {} of {want} categories scored", vals.len()));
|
||||
}
|
||||
if min < 6.0 {
|
||||
let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();
|
||||
why.push(format!("below a draft: {}", low.join(", ")));
|
||||
}
|
||||
if mean < 7.0 {
|
||||
why.push("the whole is under a production base".into());
|
||||
}
|
||||
(why.is_empty(), why)
|
||||
}
|
||||
|
||||
/// The blocking defects present, by name.
|
||||
pub fn blocking(defects: &[Value]) -> Vec<&str> {
|
||||
defects.iter().filter(|d| d["present"] == true && d["level"] == "blocking").filter_map(|d| d["defect"].as_str()).collect()
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn scores(v: f64) -> serde_json::Map<String, Value> {
|
||||
rubric::SCORES.iter().map(|s| (s.0.to_string(), json!(v))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pass_is_code_and_a_blocking_defect_holds_it() {
|
||||
assert!(rubric::pass(&scores(7.5), &[]).0);
|
||||
assert!(!rubric::pass(&scores(6.5), &[]).0, "mean under 7");
|
||||
let mut s = scores(8.0);
|
||||
s.insert("form".into(), json!(5.0));
|
||||
let (ok, why) = rubric::pass(&s, &[]);
|
||||
assert!(!ok && why.iter().any(|w| w.contains("form")));
|
||||
let d = vec![json!({"defect": "floating", "present": true, "level": "blocking"})];
|
||||
assert!(!rubric::pass(&scores(9.0), &d).0);
|
||||
// the questions hold no pass line
|
||||
let q = format!("{}{}", rubric::questions("colour"), rubric::questions("clay"));
|
||||
assert!(!q.contains("mean") && !q.contains(">= 6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_are_read_and_rounds_say_done_and_stall() {
|
||||
let a = json!({"score_form": {"score": 3.5}, "defect_floating": {"noul": 0.8}});
|
||||
let (s, d) = rubric::read(&a);
|
||||
assert_eq!(s["form"], 7.0);
|
||||
assert_eq!(d[0]["present"], true);
|
||||
let r = |p: bool, m: f64| json!({"pass": p, "mean": m, "defects": []});
|
||||
assert_eq!(progress(&[r(false, 5.0), r(true, 7.2), r(true, 7.4)])["done"], true);
|
||||
assert_eq!(progress(&[r(false, 5.0), r(false, 5.3), r(false, 5.6)])["stall"], true);
|
||||
assert_eq!(progress(&[r(false, 4.0), r(false, 5.3), r(false, 6.1)])["stall"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibration_maps_a_lenient_judge_onto_the_eye() {
|
||||
// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8
|
||||
let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});
|
||||
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();
|
||||
let cal = eye::fit_rows_for(None, &rows);
|
||||
assert_eq!(cal["agreement"], 1.0);
|
||||
assert_eq!(cal["gate"], true);
|
||||
assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);
|
||||
let few = eye::fit_rows_for(None, &rows[..4]);
|
||||
assert_eq!(few["gate"], false, "too few rounds to gate");
|
||||
// an eye that failed everything agrees with a judge that fails everything, which proves nothing
|
||||
let fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();
|
||||
let all_fail = eye::fit_rows_for(None, &fails);
|
||||
assert_eq!(all_fail["agreement"], 1.0);
|
||||
assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
|
||||
// an agent thinks aloud, may draft the JSON twice, and ends with the one it means
|
||||
let text = r#"• Looking at the sheets... draft: {"scores": {"form": 1}} then the answer:
|
||||
{"blind": {"place": "office", "objects": [], "photo": "no", "tells": []},
|
||||
"scores": {"composition": 6, "form": 5.5, "assembly": 7, "materials": 4, "light": 6, "detail": 5, "world": 6, "vibes": 9},
|
||||
"defects": [{"tile": "iso", "where": "left", "wrong": "the desks are plain boxes", "real": "a desk has legs", "fix": "model legs", "level": "blocking"},
|
||||
{"tile": "low", "wrong": "", "level": "detail"}],
|
||||
"show_as_is": "no"}"#;
|
||||
let v = crate::agent::last_verdict(text).unwrap();
|
||||
let (scores, defects, photo) = crate::agent::read(None, &v);
|
||||
assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");
|
||||
assert_eq!(scores["form"], serde_json::json!(5.5));
|
||||
assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");
|
||||
assert_eq!(defects[0]["level"], "blocking");
|
||||
assert_eq!(photo, serde_json::json!(0.0));
|
||||
let (pass, why) = crate::rubric::pass(&scores, &defects);
|
||||
assert!(!pass && why[0].starts_with("blocking"));
|
||||
assert!(crate::agent::last_verdict("no json here").is_none());
|
||||
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
|
||||
let f = &crate::findings(&defects, "kimi", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
|
||||
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
|
||||
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {
|
||||
// docs/make.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each
|
||||
let kit = rubric::questions_for(Some("kit"), "clay");
|
||||
for k in ["score_mesh", "score_assembly", "score_scale"] {
|
||||
assert!(kit.get(k).is_some(), "{k} in {kit}");
|
||||
}
|
||||
assert!(kit.get("score_cohesion").is_none(), "cohesion is judged in colour");
|
||||
assert_eq!(rubric::sheets(Some("shot")), &[("colour", "framing.png")]);
|
||||
assert_eq!(rubric::sheets(None).len(), 2);
|
||||
let shot = rubric::questions_for(Some("shot"), "colour");
|
||||
assert!(shot.get("score_clearance").is_some() && shot.get("score_composition").is_none());
|
||||
assert!(rubric::state_for(Some("kit"), "colour", &json!({})).contains(rubric::BAR));
|
||||
assert!(rubric::state_for(Some("shot"), "colour", &json!({})).contains("framing sheet"));
|
||||
// the default's words are what it was calibrated on
|
||||
let d = rubric::state("clay", &json!({"notDoing": ["cats"]}));
|
||||
assert!(d.contains("as the person who will use the scene would") && d.contains("The scene must not contain: cats.") && !d.contains(rubric::BAR), "{d}");
|
||||
// every kind scored in full to pass
|
||||
let all = |k: Option<&str>, v: f64| -> serde_json::Map<String, Value> { rubric::scores(k).iter().map(|s| (s.0.to_string(), json!(v))).collect() };
|
||||
assert!(rubric::pass_for(Some("kit"), &all(Some("kit"), 8.0), &[]).0);
|
||||
let (ok, why) = rubric::pass_for(Some("kit"), &all(None, 8.0), &[]);
|
||||
assert!(!ok && why.iter().any(|w| w.contains("of 8 categories")), "{why:?}");
|
||||
assert!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "film".into()]).is_err());
|
||||
assert_eq!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "shot".into()]).unwrap().as_deref(), Some("shot"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_critic_is_asked_its_kinds_categories() {
|
||||
let p = crate::agent::prompt(Some("shot"), std::path::Path::new("/r/r1"), &json!({"look": "dusk"}), None);
|
||||
assert!(p.contains("/r/r1/framing.png") && p.contains("\"clearance\": 0") && p.contains(rubric::BAR) && !p.contains("PART 1, BLIND"), "{p}");
|
||||
let k = crate::agent::prompt(Some("kit"), std::path::Path::new("/r/r1"), &json!({}), None);
|
||||
assert!(k.contains("\"cohesion\": 0") && k.contains("scale bar") && k.contains("(judged on CLAY)"));
|
||||
let d = crate::agent::prompt(None, std::path::Path::new("/r/r1"), &json!({}), None);
|
||||
assert!(d.contains("\"composition\": 0") && !d.contains(rubric::BAR));
|
||||
let v = json!({"scores": {"cohesion": 7, "fidelity": 8, "composition": 9}});
|
||||
let (s, _, _) = crate::agent::read(Some("kit"), &v);
|
||||
assert_eq!(s.len(), 2, "only the kit's categories");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kind_is_calibrated_on_its_own_categories() {
|
||||
// docs/make.feature MK6
|
||||
let s = |j: f64| -> serde_json::Map<String, Value> { rubric::KIT.iter().map(|c| (c.0.to_string(), json!(j))).collect() };
|
||||
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { json!({"kind": "kit", "judge": s(8.0), "eye": s(5.0), "eye_pass": false, "defects": []}) } else { json!({"kind": "kit", "judge": s(9.0), "eye": s(8.0), "eye_pass": true, "defects": []}) }).collect();
|
||||
let cal = eye::fit_rows_for(Some("kit"), &rows);
|
||||
assert_eq!(cal["gate"], true);
|
||||
assert!(cal["maps"]["cohesion"].is_object() && cal["maps"]["form"].is_null());
|
||||
}
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea make bake light: bounce light baked into lightmaps on raea's own ray tracer, and the bar it is held to against Cycles (docs/bake.feature)"
|
||||
description = "raea bake light: bounce light baked into lightmaps on raea's own ray tracer, and the bar it is held to against Cycles (docs/bake.feature)"
|
||||
|
||||
[dependencies]
|
||||
# the frames' distance in stops, as raea light check measures it (LT1)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"about": "the bake's test set (docs/bake.feature BK0), for `raea make bake light --compare DIR`: each set's Cycles still (blender/look.py, given the composition's own sky, tone and lens) and Cycles bake (blender/lightbake.py), and raea's frames beside them",
|
||||
"about": "the bake's test set (docs/bake.feature BK0), for `raea bake light --compare DIR`: each set's Cycles still (blender/look.py, given the composition's own sky, tone and lens) and Cycles bake (blender/lightbake.py), and raea's frames beside them",
|
||||
"sets": [
|
||||
{ "name": "table", "dir": "bench/bake", "file": "table.tsx", "composition": "table", "cycles": ["table-cycles.tsx", "table-cycles"], "bar": true, "texels": 128,
|
||||
"look": ["--hdri", "media/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "--strength", "0.25", "--rotation", "0.6", "--tone", "agx", "--exposure", "-0.8", "--focus", "2.5", "--fstop", "2.8", "--size", "1280x720"] },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea make bake light EDIT.tsx [--composition ID] [--samples N] [--compare DIR]` (docs/bake.feature): raea's own bake of a
|
||||
//! `raea bake light EDIT.tsx [--composition ID] [--samples N] [--compare DIR]` (docs/bake.feature): raea's own bake of a
|
||||
//! composition's static parts (BK1-BK5), and the bar it is held to (BK0). `--compare DIR` runs the test set (sets.json)
|
||||
//! through Cycles (blender/look.py's still and blender/lightbake.py's bake, both at --samples, 1024 by default) and
|
||||
//! through raea, then writes DIR/report.json and a table: each frame's RMSE and stops against the Cycles still, each
|
||||
@@ -16,7 +16,7 @@ use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const USAGE: &str = "raea make bake light EDIT.tsx [--composition ID] [--samples N] | raea make bake light --compare DIR [--sets FILE] [--set NAME] [--samples N] [--fresh] (bounce light baked into lightmaps on raea's ray tracer; --compare measures the test set against Cycles' bake and still, docs/bake.feature)";
|
||||
pub const USAGE: &str = "raea bake light EDIT.tsx [--composition ID] [--samples N] | raea bake light --compare DIR [--sets FILE] [--set NAME] [--samples N] [--fresh] (bounce light baked into lightmaps on raea's ray tracer; --compare measures the test set against Cycles' bake and still, docs/bake.feature)";
|
||||
|
||||
/// One set of the test set, as sets.json lists it.
|
||||
pub struct Set {
|
||||
@@ -136,8 +136,8 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
}
|
||||
let samples: u32 = flag(args, "--samples").map(|v| v.parse().map_err(|_| format!("--samples {v}: a count of samples a texel"))).transpose()?.unwrap_or(1024);
|
||||
let Some(out) = flag(args, "--compare").map(PathBuf::from) else {
|
||||
// rask: BK5 `raea make bake light EDIT.tsx` bakes a composition's <LightBake> ahead of a render and says what it baked
|
||||
return Err("raea's own bake isn't built yet (docs/bake.feature BK1-BK5); `raea make bake light --compare DIR` measures the test set against Cycles".into());
|
||||
// rask: BK5 `raea bake light EDIT.tsx` bakes a composition's <LightBake> ahead of a render and says what it baked
|
||||
return Err("raea's own bake isn't built yet (docs/bake.feature BK1-BK5); `raea bake light --compare DIR` measures the test set against Cycles".into());
|
||||
};
|
||||
let list = sets(&flag(args, "--sets").map_or_else(|| raea_io_home::home().join("apps/lightbake/sets.json"), PathBuf::from))?;
|
||||
let only = flag(args, "--set");
|
||||
@@ -145,7 +145,7 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut reports = Vec::new();
|
||||
for s in list.iter().filter(|s| only.is_none() || only.as_deref() == Some(s.name.as_str())) {
|
||||
eprintln!("raea make bake light: {} ...", s.name);
|
||||
eprintln!("raea bake light: {} ...", s.name);
|
||||
reports.push(compare::set(s, samples, &out.join(&s.name), fresh)?);
|
||||
}
|
||||
if reports.is_empty() {
|
||||
@@ -154,5 +154,5 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
let report = json!({ "samples": samples, "sets": reports });
|
||||
let path = out.join("report.json");
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&report).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{}raea make bake light: wrote {}", compare::table(&reports), path.display()))
|
||||
Ok(format!("{}raea bake light: wrote {}", compare::table(&reports), path.display()))
|
||||
}
|
||||
+14
-2
@@ -4,15 +4,27 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea make's Rust: a scene, kit or shot goal's asset steps (docs/goal.feature)"
|
||||
description = "raea make: a scene, kit or shot held to its frozen plan; what's missing and whether it's done, decided in code (docs/make.feature)"
|
||||
|
||||
[dependencies]
|
||||
# the plan: `make` on brief.ts
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# the folder a project lives in
|
||||
# the project's record of renders and checks, and the folder it lives in
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# the parts a render showed closer than their planned detail (MK24)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# a cut job's gates: its client's brief as rules, held over the delivered files (MK25-MK27)
|
||||
raea-runtime-cut-plan = { path = "../../runtime/cut-plan" }
|
||||
# a goal job's gates: its commands and a fresh critic's verdict on its words (/goal)
|
||||
raea-runtime-goal-plan = { path = "../../runtime/goal-plan" }
|
||||
# the judge's rounds, passes and blocking defects, read as it keeps them
|
||||
raea-app-judge = { path = "../judge" }
|
||||
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
# a lens's field of view (MK15's lens chart), as the review sheets work it out
|
||||
raea-core-review = { path = "../../core/review" }
|
||||
# raea ask's ledger folder
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# the contact sheets: tiles composited, labels drawn in the system's fonts
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! The second tier of the gate (docs/make.feature MK4): the `make` set of `raea ask` questions (core/ask
|
||||
//! library/make.json), asked of the job's newest sheets. A question gates once it is calibrated on the person's labels
|
||||
//! (`raea ask calibrate`: 16 problem, 16 clean, an AUC of 0.8); until then what it says is advice in the status. An
|
||||
//! answer counts for a sheet only when its call was about exactly that sheet's bytes (the ledger's `ident`), so a sheet
|
||||
//! rendered again must be asked again.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_ask::{Calibration, Question};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The ledger as status reads it: every call's ident by id, every answer, and the person's calibrations.
|
||||
#[derive(Default)]
|
||||
pub struct Ledger {
|
||||
pub idents: HashMap<String, String>,
|
||||
pub answers: Vec<Value>,
|
||||
pub calibrations: BTreeMap<String, Calibration>,
|
||||
}
|
||||
|
||||
impl Ledger {
|
||||
/// `raea ask`'s record (RAEA_ASK_DIR, else ~/.raea/ask), read once.
|
||||
pub fn read() -> Ledger {
|
||||
let dir = raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask");
|
||||
let rows = |f: &str| -> Vec<Value> { std::fs::read_to_string(dir.join(f)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect() };
|
||||
let idents = rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c["ident"].as_str()?.to_string()))).collect();
|
||||
let answers = rows("answers.jsonl").into_iter().filter(|a| a["question"].as_str().is_some_and(|q| q.starts_with("make."))).collect();
|
||||
let calibrations = std::fs::read_to_string(dir.join("calibration.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
|
||||
Ledger { idents, answers, calibrations }
|
||||
}
|
||||
}
|
||||
|
||||
/// The `make` set's questions with the person's calibrations in place of raea's (as `raea ask` applies them).
|
||||
pub fn questions(ledger: &Ledger) -> Vec<Question> {
|
||||
let mut qs = raea_core_ask::library::set("make", None).unwrap_or_default();
|
||||
for q in &mut qs {
|
||||
if let Some(c) = ledger.calibrations.get(&q.version()) {
|
||||
q.calibration = Some(c.clone());
|
||||
}
|
||||
}
|
||||
qs
|
||||
}
|
||||
|
||||
/// The sheet a question is asked of: its id's second word (make.clay.floating is asked of a clay sheet).
|
||||
pub fn sheet_of(q: &Question) -> &str {
|
||||
match q.id.split('.').nth(1) {
|
||||
Some(sheet) => sheet,
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The command that asks a sheet its questions.
|
||||
pub fn command(sheet: &Path, qs: &[&Question]) -> String {
|
||||
let std: Vec<String> = qs.iter().map(|q| format!("--std {}", q.id)).collect();
|
||||
format!("raea ask {} {}", sheet.display(), std.join(" "))
|
||||
}
|
||||
|
||||
/// Each sheet's gate, and the advice: what uncalibrated questions flagged. `sheets` are (kind, file): clay, colour,
|
||||
/// refs, framing. `notes` is NOTES.md: a flagged question answered there by its id holds nothing.
|
||||
pub fn gates(sheets: &[(&str, PathBuf)], ledger: &Ledger, notes: &str) -> (Vec<Value>, Vec<String>) {
|
||||
let qs = questions(ledger);
|
||||
let mut gates = Vec::new();
|
||||
let mut advice = Vec::new();
|
||||
for (kind, file) in sheets {
|
||||
let mine: Vec<&Question> = qs.iter().filter(|q| sheet_of(q) == *kind).collect();
|
||||
if mine.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let Some(ident) = raea_core_ask::ident::ident(file) else { continue };
|
||||
// the newest answer to each question about these exact bytes
|
||||
let mut latest: BTreeMap<&str, &Value> = BTreeMap::new();
|
||||
for a in &ledger.answers {
|
||||
let about = a["call"].as_str().and_then(|c| ledger.idents.get(c)).is_some_and(|i| *i == ident);
|
||||
let Some(q) = a["question"].as_str() else { continue };
|
||||
if about && latest.get(q).is_none_or(|b| at(a) >= at(b)) {
|
||||
latest.insert(q, a);
|
||||
}
|
||||
}
|
||||
let mut open = Vec::new();
|
||||
let mut unasked = Vec::new();
|
||||
for q in &mine {
|
||||
let a = latest.get(q.id.as_str());
|
||||
let flagged = a.is_some_and(|a| a["flagged"] == true);
|
||||
let p = a.and_then(|a| a["problem"].as_f64()).map(|p| format!(" (p {p:.2})")).unwrap_or_default();
|
||||
if q.calibrated() {
|
||||
match a {
|
||||
None => unasked.push(*q),
|
||||
Some(_) if flagged && !notes.contains(&q.id) => open.push(format!("{} flagged{p}: {}", q.id, q.fix.as_deref().unwrap_or("fix it, or answer it in NOTES.md by its id"))),
|
||||
_ => {}
|
||||
}
|
||||
} else if flagged {
|
||||
advice.push(format!("{rel}: {} says yes{p}, advice until calibrated: {}", q.id, q.fix.as_deref().unwrap_or("")));
|
||||
}
|
||||
}
|
||||
if !unasked.is_empty() {
|
||||
open.push(format!("not asked of this {kind} sheet yet: {}", command(file, &unasked)));
|
||||
}
|
||||
let calibrated = mine.iter().filter(|q| q.calibrated()).count();
|
||||
let says = match (open.is_empty(), calibrated) {
|
||||
(true, 0) => format!("advice only: none of its {} questions is calibrated yet (raea ask calibrate)", mine.len()),
|
||||
(true, n) => format!("{n} calibrated question{} clear", if n == 1 { "" } else { "s" }),
|
||||
(false, _) => open.join("; "),
|
||||
};
|
||||
let mut g = json!({"gate": "ask", "of": rel, "clear": open.is_empty(), "says": says});
|
||||
g["ask"] = json!(command(file, &mine));
|
||||
gates.push(g);
|
||||
}
|
||||
(gates, advice)
|
||||
}
|
||||
|
||||
fn at(a: &Value) -> u64 {
|
||||
a["at"].as_str().and_then(|s| s.parse().ok()).or_else(|| a["at"].as_u64()).unwrap_or(0)
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
//! The plan stop (docs/goal.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,
|
||||
//! The plan stop (docs/make.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,
|
||||
//! the plan drawn so a person can approve it. A floor plan from above (every object's footprint at its `at`, turned by
|
||||
//! its `rot`, labelled; invented ones dashed, so what came from the reference and what was added are told apart), a
|
||||
//! grey-box blockout of the same plan rendered from the entrance and through `raea render --review`, and the
|
||||
//! reference beside the blockout on one comparison sheet.
|
||||
//!
|
||||
//! raea make blockout [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets
|
||||
//! raea make plan [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object, Origin};
|
||||
use raea_core_brief::make::{Make, Object, Origin};
|
||||
|
||||
use crate::sheet::{Tile, esc, sheet, svg_png};
|
||||
use crate::shots::raea;
|
||||
@@ -27,7 +27,7 @@ fn height(o: &Object) -> f64 {
|
||||
}
|
||||
|
||||
/// The placed objects and the floor they span: (objects with an `at`, [x0, z0, x1, z1] with half a metre around).
|
||||
pub fn extent(m: &Goal) -> (Vec<&Object>, [f64; 4]) {
|
||||
pub fn extent(m: &Make) -> (Vec<&Object>, [f64; 4]) {
|
||||
let placed: Vec<&Object> = m.objects.iter().filter(|o| o.at.is_some()).collect();
|
||||
let mut b = [0.0f64, 0.0, 1.0, 1.0];
|
||||
for o in &placed {
|
||||
@@ -40,10 +40,10 @@ pub fn extent(m: &Goal) -> (Vec<&Object>, [f64; 4]) {
|
||||
}
|
||||
|
||||
/// The floor plan as SVG: the entrance (z = 0) at the bottom, a metre grid, each footprint turned and labelled.
|
||||
pub fn floor_svg(m: &Goal) -> Result<String, String> {
|
||||
pub fn floor_svg(m: &Make) -> Result<String, String> {
|
||||
let (placed, [x0, z0, x1, z1]) = extent(m);
|
||||
if placed.is_empty() {
|
||||
return Err("raea make blockout: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());
|
||||
return Err("raea make plan: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());
|
||||
}
|
||||
let px = (1400.0 / (x1 - x0).max(z1 - z0)).min(260.0);
|
||||
let (w, h) = (((x1 - x0) * px).ceil() as u32 + 40, ((z1 - z0) * px).ceil() as u32 + 130);
|
||||
@@ -93,7 +93,7 @@ pub fn floor_svg(m: &Goal) -> Result<String, String> {
|
||||
}
|
||||
|
||||
/// The blockout: a grey box for each placed object at its place and turn on a floor, seen from the entrance.
|
||||
pub fn blockout_tsx(m: &Goal) -> String {
|
||||
pub fn blockout_tsx(m: &Make) -> String {
|
||||
let (placed, [x0, z0, x1, z1]) = extent(m);
|
||||
let mut boxes = String::new();
|
||||
for o in &placed {
|
||||
@@ -119,7 +119,7 @@ pub fn blockout_tsx(m: &Goal) -> String {
|
||||
let (cx, cz) = ((x0 + x1) / 2.0, (z0 + z1) / 2.0);
|
||||
let (fw, fd) = ((x1 - x0) / 2.0, (z1 - z0) / 2.0);
|
||||
format!(
|
||||
"// written by raea make blockout: the plan as grey boxes, seen from the entrance (approve it before anything is made)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n\nfunction Blockout() {{\n return (\n <AbsoluteFill style={{{{ background: \"#cfd3d6\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, 1.6, {ez:.3}).lookingAt([{cx:.3}, 0.9, {cz:.3}])}} projection={{{{ Perspective: {{ fov: (50 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{350}} />\n <DirectionalLight transform={{Transform.fromXyz({lx:.3}, 6, -2).lookingAt([{cx:.3}, 0, {cz:.3}])}} illuminance={{8000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, -0.01, {cz:.3})}}>\n <Cuboid half_size={{[{fw:.3}, 0.01, {fd:.3}]}} />\n <StandardMaterial base_color=\"#e6e3dc\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n{boxes} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"blockout\" component={{Blockout}} width={{1280}} height={{720}} fps={{30}} durationInFrames={{1}} />);\n",
|
||||
"// written by raea make plan: the plan as grey boxes, seen from the entrance (approve it before anything is made)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n\nfunction Blockout() {{\n return (\n <AbsoluteFill style={{{{ background: \"#cfd3d6\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, 1.6, {ez:.3}).lookingAt([{cx:.3}, 0.9, {cz:.3}])}} projection={{{{ Perspective: {{ fov: (50 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{350}} />\n <DirectionalLight transform={{Transform.fromXyz({lx:.3}, 6, -2).lookingAt([{cx:.3}, 0, {cz:.3}])}} illuminance={{8000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, -0.01, {cz:.3})}}>\n <Cuboid half_size={{[{fw:.3}, 0.01, {fd:.3}]}} />\n <StandardMaterial base_color=\"#e6e3dc\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n{boxes} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"blockout\" component={{Blockout}} width={{1280}} height={{720}} fps={{30}} durationInFrames={{1}} />);\n",
|
||||
ez = z0 - 0.4,
|
||||
lx = cx + 2.0,
|
||||
)
|
||||
@@ -130,7 +130,7 @@ pub fn plan_dir(dir: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
/// The plan stop's pictures: floor plan, blockout (and its review sheets), and the comparison with reference 0.
|
||||
pub fn draw_plan(dir: &Path, m: &Goal, review: bool) -> Result<String, String> {
|
||||
pub fn draw_plan(dir: &Path, m: &Make, review: bool) -> Result<String, String> {
|
||||
let out = plan_dir(dir);
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let floor = out.join("floor-plan.png");
|
||||
|
||||
+12
-12
@@ -1,4 +1,4 @@
|
||||
//! A kit's steps (docs/goal.feature MK10-MK12, from AnyKit): every object's reference made in one style from the
|
||||
//! A kit's steps (docs/make.feature MK10-MK12, from AnyKit): every object's reference made in one style from the
|
||||
//! style images, checked on one sheet before any 3D; each reference to both generators (Tripo H3.1 and Meshy, on fal)
|
||||
//! and the pick made on clay renders (kitout.rs draws the pick sheets); the pick fitted to its real size with a
|
||||
//! quarter-triangle LOD beside it, each with a sidecar saying how it was made.
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object};
|
||||
use raea_core_brief::make::{Make, Object};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
@@ -27,12 +27,12 @@ const HERO_FACES: u32 = 150_000;
|
||||
const PROP_FACES: u32 = 60_000;
|
||||
|
||||
/// The objects named in `--only` (all when it's empty).
|
||||
pub fn objects<'a>(m: &'a Goal, only: &[String]) -> Vec<&'a Object> {
|
||||
pub fn objects<'a>(m: &'a Make, only: &[String]) -> Vec<&'a Object> {
|
||||
crate::only(&m.objects, only, |o| o.id.as_str())
|
||||
}
|
||||
|
||||
/// The prompt a reference is made from: the plan's style paragraph, the object's own words, the scan template.
|
||||
pub fn ref_prompt(m: &Goal, o: &Object) -> String {
|
||||
pub fn ref_prompt(m: &Make, o: &Object) -> String {
|
||||
let style = m.style.as_deref().unwrap_or("").trim().trim_end_matches('.');
|
||||
let what = o.prompt.as_deref().unwrap_or(&o.label).trim().trim_end_matches('.');
|
||||
format!("{style}. {what}. {SCAN}")
|
||||
@@ -105,7 +105,7 @@ pub fn refs_dir(dir: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
/// Every object's reference, made from the style images (`references`) in the plan's style; then the sheet.
|
||||
pub fn refs(dir: &Path, m: &Goal, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {
|
||||
pub fn refs(dir: &Path, m: &Make, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {
|
||||
if m.references.is_empty() {
|
||||
return Err("raea make refs: the plan has no `references` (the style images every reference is made from)".into());
|
||||
}
|
||||
@@ -144,7 +144,7 @@ pub fn refs(dir: &Path, m: &Goal, only: &[String], model: Option<&str>, dry: boo
|
||||
}
|
||||
|
||||
/// The reference sheet: the style images first, then every object's reference, labelled with its id and size.
|
||||
pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
|
||||
pub fn sheet_refs(dir: &Path, m: &Make) -> Result<String, String> {
|
||||
let style: Vec<Tile> = m.references.iter().enumerate().map(|(i, r)| Tile { img: dir.join(r), label: format!("style {}", i + 1) }).collect();
|
||||
let refs: Vec<Tile> = m
|
||||
.objects
|
||||
@@ -158,11 +158,11 @@ pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
|
||||
rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));
|
||||
let file = dir.join("review/refs.png");
|
||||
sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;
|
||||
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID)", file.display()))
|
||||
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID); ask it: raea ask {} --std make.refs.outlier --std make.refs.two_objects --std make.refs.brands", file.display(), file.display()))
|
||||
}
|
||||
|
||||
/// The flow that sends one reference to both generators, each at its face limit.
|
||||
pub fn gen_flow(m: &Goal, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {
|
||||
pub fn gen_flow(m: &Make, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {
|
||||
let faces = if o.hero == Some(true) { HERO_FACES } else { PROP_FACES };
|
||||
let prompt = o.prompt.clone().unwrap_or_else(|| o.label.clone());
|
||||
let _ = m;
|
||||
@@ -178,7 +178,7 @@ pub fn gen_dir(dir: &Path, id: &str) -> PathBuf {
|
||||
}
|
||||
|
||||
/// Every reference to both generators: out/kit/gen/ID/tripo.glb and meshy.glb.
|
||||
pub fn generate(dir: &Path, m: &Goal, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {
|
||||
pub fn generate(dir: &Path, m: &Make, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {
|
||||
let mut said = Vec::new();
|
||||
let mut spent = 0.0;
|
||||
for o in objects(m, only) {
|
||||
@@ -229,7 +229,7 @@ pub fn picks(dir: &Path) -> serde_json::Map<String, Value> {
|
||||
}
|
||||
|
||||
/// One object's pick and why, recorded (MK11).
|
||||
pub fn choose(dir: &Path, m: &Goal, id: &str, generator: &str, why: &str) -> Result<String, String> {
|
||||
pub fn choose(dir: &Path, m: &Make, id: &str, generator: &str, why: &str) -> Result<String, String> {
|
||||
if !m.objects.iter().any(|o| o.id == id) {
|
||||
return Err(format!("raea make pick: no object `{id}` in the plan"));
|
||||
}
|
||||
@@ -256,7 +256,7 @@ fn triangles(glb: &Path) -> Result<u64, String> {
|
||||
|
||||
/// Each pick fitted to its real size (front -Y, bottom-centre, metres) and a quarter-triangle LOD1 beside it, each
|
||||
/// with a sidecar saying how it was made (MK12).
|
||||
pub fn prep(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
|
||||
pub fn prep(dir: &Path, m: &Make, only: &[String]) -> Result<String, String> {
|
||||
let p = picks(dir);
|
||||
let mut said = Vec::new();
|
||||
for o in objects(m, only) {
|
||||
@@ -284,7 +284,7 @@ pub fn prep(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
|
||||
// the sidecar the Blender scripts carry along (source, licence, credit) and how it was made: ours, generated
|
||||
let made = |what: &str, tris: u64| {
|
||||
json!({"source": format!("generated by raea make: {model} from out/kit/refs/{}.png", o.id), "license": "ours (generated for this project)", "credit": "",
|
||||
"made": {"by": "raea make (docs/goal.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),
|
||||
"made": {"by": "raea make (docs/make.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),
|
||||
"style": m.style, "what": what, "triangles": tris, "source": if o.source.is_some() { json!(o.source) } else { Value::Null }}})
|
||||
};
|
||||
std::fs::write(full.with_extension("glb.json"), serde_json::to_string_pretty(&made("fitted to its real size", tris)).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The kit's sheets and its landing (docs/goal.feature MK11, MK13): the pick sheet (each object's reference beside
|
||||
//! The kit's sheets and its landing (docs/make.feature MK11, MK13): the pick sheet (each object's reference beside
|
||||
//! both generators' models, each in colour and in clay, drawn in raea), and the kit landed as a component set (one
|
||||
//! component per object, its model and LOD imported beside it, so it travels as one folder), a `<Lineup>` of them all
|
||||
//! with a scale bar, a thumb each, and kit.json.
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Object};
|
||||
use raea_core_brief::make::{Make, Object};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::kit::{gen_dir, objects, picks};
|
||||
@@ -53,7 +53,7 @@ pub fn draw(model: &Path, h: f64) -> Result<(PathBuf, PathBuf), String> {
|
||||
}
|
||||
|
||||
/// The pick sheet: a row an object, its reference, then each generator's model fitted to size, in colour and in clay.
|
||||
pub fn pick_sheet(dir: &Path, m: &Goal, only: &[String]) -> Result<String, String> {
|
||||
pub fn pick_sheet(dir: &Path, m: &Make, only: &[String]) -> Result<String, String> {
|
||||
let mut rows = Vec::new();
|
||||
for o in objects(m, only) {
|
||||
let g = gen_dir(dir, &o.id);
|
||||
@@ -99,7 +99,7 @@ pub fn component_name(id: &str) -> String {
|
||||
pub fn component(o: &Object, why: &str) -> String {
|
||||
let n = component_name(&o.id);
|
||||
format!(
|
||||
"// raea make component add: {label}, {h} m, from the kit's style (raea make kit; {why})\nimport {{ Model }} from \"raea/3d\";\nimport full from \"./{id}.glb\";\nimport far from \"./{id}_lod1.glb\";\n\ntype Props = {{\n position?: [number, number, number];\n rotation?: [number, number, number];\n /** the quarter-triangle model, for when it's small on screen */\n lod?: boolean;\n}};\n\n/** {label}: fitted to its real size, its bottom at the origin, its front toward +z. */\nexport default function {n}({{ position = [0, 0, 0], rotation = [0, 0, 0], lod = false }}: Props) {{\n return <Model src={{lod ? far : full}} position={{position}} rotation={{rotation}} />;\n}}\n",
|
||||
"// raea component add: {label}, {h} m, from the kit's style (raea make kit; {why})\nimport {{ Model }} from \"raea/3d\";\nimport full from \"./{id}.glb\";\nimport far from \"./{id}_lod1.glb\";\n\ntype Props = {{\n position?: [number, number, number];\n rotation?: [number, number, number];\n /** the quarter-triangle model, for when it's small on screen */\n lod?: boolean;\n}};\n\n/** {label}: fitted to its real size, its bottom at the origin, its front toward +z. */\nexport default function {n}({{ position = [0, 0, 0], rotation = [0, 0, 0], lod = false }}: Props) {{\n return <Model src={{lod ? far : full}} position={{position}} rotation={{rotation}} />;\n}}\n",
|
||||
label = o.label,
|
||||
h = tall(o),
|
||||
id = o.id,
|
||||
@@ -109,7 +109,7 @@ pub fn component(o: &Object, why: &str) -> String {
|
||||
|
||||
/// The lineup: every component side by side in the plan's order, gaps between, a label each lying in front of the pieces and a
|
||||
/// scale bar (the longest round length the set covers), seen from a little right of centre and above.
|
||||
pub fn lineup(m: &Goal, kit: &str) -> String {
|
||||
pub fn lineup(m: &Make, kit: &str) -> String {
|
||||
let mut imports = String::new();
|
||||
let mut parts = String::new();
|
||||
let mut x = 0.0;
|
||||
@@ -176,7 +176,7 @@ fn copy(a: &Path, b: &Path) -> Result<(), String> {
|
||||
|
||||
/// The kit landed: each prepped object's model, LOD and sidecars, its component and thumb; the lineup and its cover
|
||||
/// render; kit.json. Objects not prepped yet are named, not skipped silently.
|
||||
pub fn land(dir: &Path, m: &Goal, name: Option<&str>, to: Option<&str>) -> Result<String, String> {
|
||||
pub fn land(dir: &Path, m: &Make, name: Option<&str>, to: Option<&str>) -> Result<String, String> {
|
||||
let kit = name.map(str::to_string).unwrap_or_else(|| dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or("kit".into()));
|
||||
let dest = kit_dir(dir, &kit, to);
|
||||
std::fs::create_dir_all(dest.join("thumbs")).map_err(|e| format!("{}: {e}", dest.display()))?;
|
||||
@@ -214,10 +214,10 @@ pub fn land(dir: &Path, m: &Goal, name: Option<&str>, to: Option<&str>) -> Resul
|
||||
std::fs::write(&lineup_tsx, lineup(m, &kit)).map_err(|e| e.to_string())?;
|
||||
let cover = dest.join("cover.png");
|
||||
raea(&["render".into(), lineup_tsx.display().to_string(), "-o".into(), cover.display().to_string(), "--frame".into(), "0".into()], &[])?;
|
||||
let doc = json!({"kit": kit, "style": m.style, "references": m.references, "items": items, "lineup": "lineup.tsx", "cover": "cover.png", "landed": dest.display().to_string(), "made": {"by": "raea make kit (docs/goal.feature MK13)"}});
|
||||
let doc = json!({"kit": kit, "style": m.style, "references": m.references, "items": items, "lineup": "lineup.tsx", "cover": "cover.png", "landed": dest.display().to_string(), "made": {"by": "raea make kit (docs/make.feature MK13)"}});
|
||||
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
|
||||
std::fs::write(dest.join("kit.json"), &text).map_err(|e| e.to_string())?;
|
||||
// the job's own record of it, what raea/goal's deliverables pack counts
|
||||
// the job's own record of it, what `raea make status` counts (core/brief deliverables)
|
||||
std::fs::write(dir.join("out/kit/kit.json"), &text).map_err(|e| e.to_string())?;
|
||||
copy(&cover, &dir.join("out/kit/lineup.png"))?;
|
||||
Ok(format!("landed the {kit} kit ({} pieces) in {}: components, lineup.tsx, cover.png, thumbs/, kit.json", items.len(), dest.display()))
|
||||
|
||||
+81
-47
@@ -1,22 +1,27 @@
|
||||
//! The asset tools for a scene, kit or shot goal (docs/goal.feature): `raea make blockout|refs|...` build to the goal's
|
||||
//! frozen plan (`goal` on brief.ts, core/brief goal.rs). The loop itself, every rule at its moments, is TypeScript:
|
||||
//! `raea check` and `raea goal tasks` run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
|
||||
//! `raea make`: a scene, kit or shot made to its frozen plan (`make` on brief.ts, core/brief make.rs) and held to the
|
||||
//! review loop (docs/make.feature). `status` decides, in code, what's missing and whether the agent may stop; the Stop
|
||||
//! hook (apps/check hook.rs) asks it at the end of every turn.
|
||||
//!
|
||||
//! raea make blockout|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
|
||||
//! raea make status [DIR] [--json] [--plan] (--plan: the gates as check lines in plan.org, MK3)
|
||||
//! raea make plan|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
|
||||
|
||||
pub mod asked;
|
||||
pub mod floor;
|
||||
pub mod kit;
|
||||
pub mod kitout;
|
||||
pub mod plan;
|
||||
pub mod sheet;
|
||||
pub mod shots;
|
||||
pub mod status;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::Goal;
|
||||
use raea_core_brief::make::Make;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const USAGE: &str = "raea make place FILE [--at S[,S...]] [--box WxH] (the clearest places in a shot for a text box that size, in a 1080-wide frame)
|
||||
raea make blockout [DIR] [--no-review] (a scene's blockout stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
|
||||
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
|
||||
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
|
||||
raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry] (each reference to both generators, Tripo H3.1 and Meshy on fal: out/kit/gen/ID/)
|
||||
@@ -43,56 +48,62 @@ pub fn brief_path(dir: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a brief.ts has a goal at all, read from its words: cheap enough for a hook at every turn's end, so the
|
||||
/// Whether a brief.ts has a job at all, read from its words: cheap enough for a hook at every turn's end, so the
|
||||
/// module is only evaluated when it can matter.
|
||||
pub fn has_goal(brief: &Path) -> bool {
|
||||
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("goal:") || t.contains("goal :"))
|
||||
pub fn has_make(brief: &Path) -> bool {
|
||||
std::fs::read_to_string(brief).is_ok_and(|t| t.contains("make:") || t.contains("make :"))
|
||||
}
|
||||
|
||||
/// The goals of brief.ts, evaluated by `raea spec FILE --as brief` (the module runs; Rust checks it against core/brief).
|
||||
pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
|
||||
/// The plan from brief.ts, evaluated by `raea spec FILE --as brief` (the module runs; Rust checks it against core/brief).
|
||||
pub fn read_make(brief: &Path) -> Result<Option<Make>, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), why_refused(&out)))?;
|
||||
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
|
||||
let b = v.get("brief").cloned().unwrap_or(v);
|
||||
match b.get("goal") {
|
||||
None | Some(Value::Null) => Ok(vec![]),
|
||||
Some(g) => {
|
||||
let gs: raea_core_brief::goal::Goals = serde_json::from_value(g.clone()).map_err(|e| format!("{}: goal: {e}", brief.display()))?;
|
||||
Ok(gs.all().into_iter().cloned().collect())
|
||||
}
|
||||
match b.get("make") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(m) => serde_json::from_value(m.clone()).map(Some).map_err(|e| format!("{}: make: {e}", brief.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a raea that ran printed no answer: its last line said (a refusal's word taken off), else that it printed nothing.
|
||||
fn why_refused(out: &std::process::Output) -> String {
|
||||
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
|
||||
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
|
||||
/// The judge's rounds beside the brief (review/judge.log.jsonl, as `raea judge` keeps them), the newest round's
|
||||
/// verdict (judge.json, or judge.BY.json for an agent critic), and when the log was last written.
|
||||
fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTime>) {
|
||||
let log = dir.join("review").join("judge.log.jsonl");
|
||||
let rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
|
||||
let verdict = rounds.last().and_then(|r| {
|
||||
let d = status::round_dir(dir, r)?;
|
||||
let file = r["by"].as_str().filter(|b| *b != "clef").map_or_else(|| "judge.json".to_string(), |b| format!("judge.{b}.json"));
|
||||
serde_json::from_str(&std::fs::read_to_string(d.join(file)).ok()?).ok()
|
||||
});
|
||||
let at = std::fs::metadata(&log).and_then(|m| m.modified()).ok();
|
||||
(rounds, verdict, at)
|
||||
}
|
||||
|
||||
/// The scene, kit or shot goal the asset tools build to: the one named, else the only one of those kinds.
|
||||
pub fn read_goal(brief: &Path) -> Result<Option<Goal>, String> {
|
||||
read_goal_named(brief, None)
|
||||
/// The status of the job whose brief is at `brief`, with its plan already read.
|
||||
pub fn status_of(brief: &Path, make: &Make) -> Value {
|
||||
let dir = brief.parent().unwrap_or(Path::new("."));
|
||||
let project = raea_core_facts::record::up(dir, ".raea/project");
|
||||
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
|
||||
let (rounds, verdict, judged_at) = judged(dir);
|
||||
let ledger = asked::Ledger::read();
|
||||
let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
|
||||
let mut s = status::status(&job);
|
||||
s["brief"] = Value::String(brief.display().to_string());
|
||||
s
|
||||
}
|
||||
|
||||
pub fn read_goal_named(brief: &Path, name: Option<&str>) -> Result<Option<Goal>, String> {
|
||||
use raea_core_brief::goal::{name_of, Kind};
|
||||
let all = read_goals(brief)?;
|
||||
if let Some(n) = name {
|
||||
return all.into_iter().find(|g| name_of(g) == n).map(Some).ok_or_else(|| format!("{}: no goal is named {n}", brief.display()));
|
||||
}
|
||||
let mut built: Vec<Goal> = all.into_iter().filter(|g| matches!(g.kind, Kind::Scene | Kind::Kit | Kind::Shot)).collect();
|
||||
match built.len() {
|
||||
0 => Ok(None),
|
||||
1 => Ok(built.pop()),
|
||||
_ => Err(format!("{}: several scene, kit or shot goals ({}): name one with --goal", brief.display(), built.iter().map(name_of).collect::<Vec<_>>().join(", "))),
|
||||
}
|
||||
/// For the hook: the job's status from a folder, None when there's no job there (no brief.ts, or no `make` on it).
|
||||
pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {
|
||||
let Some(brief) = brief_path(dir).filter(|b| has_make(b)) else { return Ok(None) };
|
||||
let Some(make) = read_make(&brief)? else { return Ok(None) };
|
||||
Ok(Some(status_of(&brief, &make)))
|
||||
}
|
||||
|
||||
/// The flags that take a value: what follows them isn't a positional argument.
|
||||
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--goal"];
|
||||
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
|
||||
|
||||
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
@@ -127,10 +138,10 @@ pub(crate) fn only<'a, T>(all: &'a [T], only: &[String], name: impl Fn(&T) -> &s
|
||||
}
|
||||
|
||||
/// The job's brief and plan from a folder.
|
||||
fn job(dir: &Path, name: Option<&str>) -> Result<(PathBuf, Goal), String> {
|
||||
let brief = brief_path(dir).ok_or_else(|| format!("no brief.ts at or above {} in its project", dir.display()))?;
|
||||
let goal = read_goal_named(&brief, name)?.ok_or_else(|| format!("{} has no scene, kit or shot goal (`goal: scene({{...}})`, kit() or shot() from raea/brief)", brief.display()))?;
|
||||
Ok((brief, goal))
|
||||
fn job(dir: &Path) -> Result<(PathBuf, Make), String> {
|
||||
let brief = brief_path(dir).ok_or_else(|| format!("raea make: no brief.ts at or above {} in its project", dir.display()))?;
|
||||
let make = read_make(&brief)?.ok_or_else(|| format!("raea make: {} has no `make` (scene(), kit() or shot() from raea/brief)", brief.display()))?;
|
||||
Ok((brief, make))
|
||||
}
|
||||
|
||||
/// The steps: each reads the plan from DIR's brief.ts and works beside it.
|
||||
@@ -146,13 +157,13 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
|
||||
return Err(USAGE.into());
|
||||
}
|
||||
let dir = pos.get(dir_at).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
|
||||
let (brief, m) = job(&dir, flag(args, "--goal"))?;
|
||||
let (brief, m) = job(&dir)?;
|
||||
let here = brief.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
let only = list(args, "--only");
|
||||
let dry = args.iter().any(|a| a == "--dry");
|
||||
let out_or = |d: PathBuf| flag(args, "--out").map(PathBuf::from).unwrap_or(d);
|
||||
match verb {
|
||||
"blockout" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),
|
||||
"plan" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),
|
||||
"refs" => kit::refs(&here, &m, &only, flag(args, "--model"), dry),
|
||||
"sheet" => match args.get(2).map(String::as_str) {
|
||||
Some("refs") => kit::sheet_refs(&here, &m),
|
||||
@@ -173,10 +184,33 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some(v @ ("blockout" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => step(v, args),
|
||||
_ => Err(USAGE.into()),
|
||||
Some("status") => {}
|
||||
Some("judge") => return job(&PathBuf::from(positional(args, 2).first().map_or(".", String::as_str))).and_then(|(b, m)| raea_runtime_goal_plan::judge(m.goal.as_ref().ok_or("raea make judge: the job isn't a goal({...})")?, b.parent().unwrap_or(Path::new(".")), flag(args, "--by").unwrap_or("claude")).map(|v| serde_json::to_string_pretty(&v).unwrap_or_default())),
|
||||
Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),
|
||||
_ => return Err(USAGE.into()),
|
||||
}
|
||||
let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
|
||||
let (brief, make) = job(&dir)?;
|
||||
let mut s = status_of(&brief, &make);
|
||||
if args.iter().any(|a| a == "--plan") {
|
||||
let dir = brief.parent().unwrap_or(Path::new("."));
|
||||
let root = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());
|
||||
let kind = s["kind"].as_str().unwrap_or("make").to_string();
|
||||
let (file, task) = plan::write(&root, &brief, &kind, &s)?;
|
||||
s["planOrg"] = Value::String(file.display().to_string());
|
||||
s["planTask"] = Value::String(task);
|
||||
}
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return Ok(serde_json::to_string_pretty(&s).unwrap_or_default());
|
||||
}
|
||||
let mut t = status::text(&s);
|
||||
if let (Some(p), Some(task)) = (s["planOrg"].as_str(), s["planTask"].as_str()) {
|
||||
t.push_str(&format!("\nplan.org: the gates are check lines under task {task} in {p}"));
|
||||
}
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_steps;
|
||||
@@ -0,0 +1,95 @@
|
||||
//! The job's gates in the project's plan.org (docs/make.feature MK3; docs/plan.feature PL1): one task, its :ID: from the
|
||||
//! brief's path, each gate and each missing thing a check line under it with a progress cookie, so the person, the app
|
||||
//! and raea cloud read the same list the Stop hook holds the agent to. MAKING while it isn't done, REVIEW once it is
|
||||
//! (the person closes it); a task the person marked DONE or DROPPED keeps their mark, and their own lines under it stay.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The task's id: t- and eight letters and digits (PL1b), the same for the same brief.
|
||||
pub fn task_id(brief_rel: &str) -> String {
|
||||
let h = brief_rel.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
|
||||
format!("t-mk{:06x}", h & 0xff_ffff)
|
||||
}
|
||||
|
||||
fn is_check(line: &str) -> bool {
|
||||
let t = line.trim_start();
|
||||
let rest = t.strip_prefix("- ").or_else(|| t.strip_prefix("+ "));
|
||||
rest.is_some_and(|r| r.starts_with("[ ]") || r.starts_with("[X]") || r.starts_with("[x]") || r.starts_with("[-]"))
|
||||
}
|
||||
|
||||
fn short(s: &str) -> String {
|
||||
let s = s.replace('\n', " ");
|
||||
if s.chars().count() > 140 { format!("{}…", s.chars().take(139).collect::<String>()) } else { s }
|
||||
}
|
||||
|
||||
/// The check lines for a status: what's missing, then each gate.
|
||||
pub fn checks(status: &Value) -> Vec<(bool, String)> {
|
||||
let mut out: Vec<(bool, String)> = Vec::new();
|
||||
for m in status["missing"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
out.push((false, format!("missing: {}", short(m))));
|
||||
}
|
||||
for g in status["gates"].as_array().into_iter().flatten() {
|
||||
let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();
|
||||
out.push((g["clear"] == true, format!("{}{of}: {}", g["gate"].as_str().unwrap_or("gate"), short(g["says"].as_str().unwrap_or("")))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// plan.org's text with the job's task brought up to date (made at the end when it isn't there).
|
||||
pub fn update(text: &str, title: &str, brief_rel: &str, kind: &str, status: &Value) -> String {
|
||||
let id = task_id(brief_rel);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let done = status["done"] == true;
|
||||
let cs = checks(status);
|
||||
let cookie = format!("[{}/{}]", cs.iter().filter(|c| c.0).count(), cs.len());
|
||||
let check_lines: Vec<String> = cs.iter().map(|(d, t)| format!("- [{}] {t}", if *d { "X" } else { " " })).collect();
|
||||
let id_line = lines.iter().position(|l| l.trim() == format!(":ID: {id}") || l.trim() == format!(":ID: {id}"));
|
||||
let Some(id_at) = id_line else {
|
||||
let mut out = if text.trim().is_empty() { format!("#+TITLE: {title}\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n") } else { text.trim_end().to_string() + "\n" };
|
||||
out.push_str(&format!("\n* {} make: {kind} ({brief_rel}) {cookie}\n:PROPERTIES:\n:ID: {id}\n:KIND: make\n:VERB: {kind}\n:END:\n", if done { "REVIEW" } else { "MAKING" }));
|
||||
out.push_str(&(check_lines.join("\n") + "\n"));
|
||||
return out;
|
||||
};
|
||||
let head = (0..id_at).rev().find(|&i| lines[i].starts_with('*')).unwrap_or(0);
|
||||
let stars = lines[head].chars().take_while(|c| *c == '*').count();
|
||||
let end = (id_at + 1..lines.len()).find(|&i| lines[i].starts_with('*') && lines[i].chars().take_while(|c| *c == '*').count() <= stars).unwrap_or(lines.len());
|
||||
let drawer_end = (id_at..end).find(|&i| lines[i].trim() == ":END:").unwrap_or(id_at);
|
||||
// the headline: its keyword brought up to date unless the person closed it, its cookie replaced
|
||||
let words: Vec<&str> = lines[head][stars..].split_whitespace().collect();
|
||||
let kw = words.first().copied().unwrap_or("");
|
||||
let closed = kw == "DONE" || kw == "DROPPED";
|
||||
let rest: Vec<&str> = words.iter().skip(if ["TODO", "MAKING", "REVIEW", "DONE", "DROPPED"].contains(&kw) { 1 } else { 0 }).copied().filter(|w| !(w.starts_with('[') && w.ends_with(']') && w.contains('/'))).collect();
|
||||
let kw = if closed { kw } else if done { "REVIEW" } else { "MAKING" };
|
||||
let headline = format!("{} {kw} {} {cookie}", "*".repeat(stars), rest.join(" "));
|
||||
let theirs: Vec<&str> = lines[drawer_end + 1..end].iter().copied().filter(|l| !is_check(l)).collect();
|
||||
let mut out: Vec<String> = lines[..head].iter().map(|l| l.to_string()).collect();
|
||||
out.push(headline);
|
||||
out.extend(lines[head + 1..=drawer_end].iter().map(|l| l.to_string()));
|
||||
out.extend(check_lines);
|
||||
out.extend(theirs.iter().map(|l| l.to_string()));
|
||||
out.extend(lines[end..].iter().map(|l| l.to_string()));
|
||||
out.join("\n") + "\n"
|
||||
}
|
||||
|
||||
/// Writes the job's task into plan.org at the top of `root` (the project's folder, else the brief's): the file and the
|
||||
/// task's id.
|
||||
pub fn write(root: &Path, brief: &Path, kind: &str, status: &Value) -> Result<(std::path::PathBuf, String), String> {
|
||||
let file = root.join("plan.org");
|
||||
let rel = brief.strip_prefix(root).unwrap_or(brief).to_string_lossy().replace('\\', "/");
|
||||
let title = root.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "plan".into());
|
||||
let text = std::fs::read_to_string(&file).unwrap_or_default();
|
||||
let next = update(&text, &title, &rel, kind, status);
|
||||
if next != text {
|
||||
replace(&file, &next).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
}
|
||||
Ok((file, task_id(&rel)))
|
||||
}
|
||||
|
||||
/// A file's text replaced: written beside it, then moved over it, so a reader never sees half a plan.
|
||||
fn replace(file: &Path, text: &str) -> std::io::Result<()> {
|
||||
let tmp = file.with_extension("org.tmp");
|
||||
std::fs::write(&tmp, text)?;
|
||||
std::fs::rename(&tmp, file)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The contact sheets a person looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
|
||||
//! a title over them, on one PNG read at once. Labels are drawn by resvg in the system's own fonts; an SVG drawn whole
|
||||
//! (the floor plan, MK18) goes through `svg_png`.
|
||||
//! The contact sheets a gate looks at (docs/make.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
|
||||
//! a title over them, on one PNG a person, `raea ask` and the critic read at once. Labels are drawn by resvg in the
|
||||
//! system's own fonts; an SVG drawn whole (the floor plan, MK18) goes through `svg_png`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Blocking a shot list (docs/goal.feature MK15): `raea make framing` renders each shot's first, middle and last
|
||||
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person sees every shot's
|
||||
//! start and end at once; `raea make lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm
|
||||
//! (RAEA_LENS, core/review) to choose its lens before it's moved.
|
||||
//! Blocking a shot list (docs/make.feature MK15): `raea make framing` renders each shot's first, middle and last
|
||||
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person, `raea ask`
|
||||
//! (make.framing.*) and the critic (`raea judge --kind shot`) see every shot's start and end at once; `raea make
|
||||
//! lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS, core/review) to choose its
|
||||
//! lens before it's moved.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::goal::{Goal, Shot};
|
||||
use raea_core_brief::make::{Make, Shot};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
@@ -61,7 +62,7 @@ fn composition(dir: &Path, s: &Shot) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// The framing sheet of the plan's shots (or those named in `only`), written to `out` (OUT/framing.png).
|
||||
pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<String, String> {
|
||||
pub fn framing(dir: &Path, m: &Make, only: &[String], out: &Path) -> Result<String, String> {
|
||||
let shots: Vec<&Shot> = crate::only(&m.shots, only, |s| s.name.as_str());
|
||||
if shots.is_empty() {
|
||||
return Err("raea make framing: no shots in the plan (or none named)".into());
|
||||
@@ -81,11 +82,11 @@ pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<Stri
|
||||
}
|
||||
let file = out.join("framing.png");
|
||||
sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;
|
||||
Ok(format!("wrote {} ({} shot{})", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }))
|
||||
Ok(format!("wrote {} ({} shot{}); ask it: raea ask {} --set make (the framing questions apply); judge it: raea judge {} --kind shot", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }, file.display(), out.display()))
|
||||
}
|
||||
|
||||
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
|
||||
pub fn lenschart(dir: &Path, m: &Goal, name: &str, out: &Path) -> Result<String, String> {
|
||||
pub fn lenschart(dir: &Path, m: &Make, name: &str, out: &Path) -> Result<String, String> {
|
||||
let s = m.shots.iter().find(|s| s.name == name).ok_or_else(|| format!("raea make lenschart: no shot `{name}` in the plan"))?;
|
||||
let tsx = composition(dir, s)?;
|
||||
let work = out.join("lens-frames").join(name);
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
|
||||
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
|
||||
|
||||
use std::{path::{Path, PathBuf}, time::SystemTime};
|
||||
|
||||
use raea_core_brief::make::{self, Make};
|
||||
use raea_core_facts::{Level, record::Entry};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The heading the notes end with, so the next job (and the skill) learns from this one.
|
||||
pub const SKILL_HEADING: &str = "What the skill got wrong";
|
||||
|
||||
/// Everything status reads, gathered by `lib.rs` (or a test).
|
||||
pub struct Job<'a> {
|
||||
pub make: &'a Make,
|
||||
/// the brief's folder: deliverables, NOTES.md and review/ are relative to it
|
||||
pub dir: &'a Path,
|
||||
/// the project's folder (record paths are relative to it), when it is a raea project
|
||||
pub project: Option<&'a Path>,
|
||||
pub record: &'a [Entry],
|
||||
/// review/judge.log.jsonl's rounds, oldest first
|
||||
pub rounds: &'a [Value],
|
||||
/// the latest round's judge.json, when there is one
|
||||
pub verdict: Option<&'a Value>,
|
||||
/// when the judge last wrote its log
|
||||
pub judged_at: Option<SystemTime>,
|
||||
/// `raea ask`'s ledger, for the make questions' gate (asked.rs)
|
||||
pub ledger: &'a crate::asked::Ledger,
|
||||
/// `raea judge calibrate --kind KIND` agreed with the person's eye for this kind: its score gates too (MK6)
|
||||
pub score_gates: bool,
|
||||
}
|
||||
|
||||
/// A round's folder: as the judge wrote it when absolute, else the folder of that name beside the log (review/), since
|
||||
/// `raea judge DIR` keeps its log in DIR's parent and DIR was written relative to wherever it ran.
|
||||
pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {
|
||||
let d = Path::new(round["dir"].as_str()?);
|
||||
if d.is_absolute() {
|
||||
return Some(d.to_path_buf());
|
||||
}
|
||||
Some(dir.join("review").join(d.file_name()?))
|
||||
}
|
||||
|
||||
/// The sheets the make questions are asked of: the newest round's (its framing sheet for a shot list, its colour and
|
||||
/// clay sheets otherwise) and a kit's reference sheet.
|
||||
pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(r) = job.rounds.last().and_then(|r| round_dir(job.dir, r)) {
|
||||
if job.make.kind == make::Kind::Shot {
|
||||
out.push(("framing", r.join("framing.png")));
|
||||
} else {
|
||||
out.push(("clay", r.join("clay.png")));
|
||||
out.push(("colour", r.join("colour.png")));
|
||||
}
|
||||
}
|
||||
if job.make.kind == make::Kind::Kit {
|
||||
out.push(("refs", job.dir.join("review/refs.png")));
|
||||
}
|
||||
out.into_iter().filter(|(_, f)| f.is_file()).collect()
|
||||
}
|
||||
|
||||
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
|
||||
fn mtime(p: &Path) -> Option<SystemTime> {
|
||||
std::fs::metadata(p).ok()?.modified().ok()
|
||||
}
|
||||
fn mtime_secs(p: &Path) -> Option<u64> {
|
||||
Some(mtime(p)?.duration_since(SystemTime::UNIX_EPOCH).ok()?.as_secs())
|
||||
}
|
||||
|
||||
fn is_picture(p: &Path) -> bool {
|
||||
matches!(p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("png" | "jpg" | "jpeg" | "exr"))
|
||||
}
|
||||
|
||||
/// One deliverable: a file, `a|b` (either), or `dir/` (three or more pictures in it). Returns the files that answer it.
|
||||
fn answered(dir: &Path, want: &str) -> Result<Vec<PathBuf>, String> {
|
||||
if let Some(folder) = want.strip_suffix('/') {
|
||||
let pics: Vec<PathBuf> = std::fs::read_dir(dir.join(folder)).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| is_picture(p)).collect();
|
||||
return if pics.len() >= 3 { Ok(pics) } else { Err(format!("{want} holds {} picture{}; three or more", pics.len(), if pics.len() == 1 { "" } else { "s" })) };
|
||||
}
|
||||
let found: Vec<PathBuf> = want.split('|').map(|w| dir.join(w)).filter(|p| p.is_file()).collect();
|
||||
if found.is_empty() { Err(want.replace('|', " or ")) } else { Ok(found) }
|
||||
}
|
||||
|
||||
fn notes_text(dir: &Path) -> Option<String> {
|
||||
std::fs::read_to_string(dir.join("NOTES.md")).ok()
|
||||
}
|
||||
|
||||
/// AnyKit's stall: three rounds in a row without beating the best mean before them. Not the judge's own `stall`
|
||||
/// (the same defect twice: change the approach), which is advice to the agent, not a reason to let it stop.
|
||||
pub fn stalled(rounds: &[Value]) -> bool {
|
||||
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
|
||||
means.len() >= 4 && {
|
||||
let (before, last) = means.split_at(means.len() - 3);
|
||||
last.iter().cloned().fold(f64::MIN, f64::max) <= before.iter().cloned().fold(f64::MIN, f64::max)
|
||||
}
|
||||
}
|
||||
|
||||
fn gate(name: &str, of: Option<&str>, clear: bool, says: String) -> Value {
|
||||
let mut g = json!({"gate": name, "clear": clear, "says": says});
|
||||
if let Some(of) = of {
|
||||
g["of"] = json!(of);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// Tier 1: each composition the plan names has a render or check newer than it that found no error.
|
||||
fn checks(job: &Job) -> Vec<Value> {
|
||||
job.make
|
||||
.compositions
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let file = job.dir.join(c);
|
||||
let rel = job.project.map(|p| raea_core_facts::record::rel(p, &file)).unwrap_or_else(|| c.clone());
|
||||
let Some(last) = job.record.iter().rev().find(|e| e.of == rel) else {
|
||||
return gate("checks", Some(c), false, format!("never rendered or checked: raea render {c} (or raea scene lint {c})"));
|
||||
};
|
||||
let changed = mtime_secs(&file);
|
||||
if changed.is_some_and(|t| t > last.at) {
|
||||
return gate("checks", Some(c), false, format!("changed since its last {} ({}): run it again", last.by, last.id));
|
||||
}
|
||||
let errors: Vec<&str> = last.findings.iter().filter(|f| f.level == Level::Error).map(|f| f.says.as_str()).collect();
|
||||
match errors.as_slice() {
|
||||
[] => gate("checks", Some(c), true, format!("clean at {} ({})", last.id, last.by)),
|
||||
[one] => gate("checks", Some(c), false, format!("{} found: {one}", last.id)),
|
||||
many => gate("checks", Some(c), false, format!("{} found {} errors, first: {}", last.id, many.len(), many[0])),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
|
||||
fn lods(job: &Job, notes: &str) -> Vec<Value> {
|
||||
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
|
||||
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
|
||||
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
|
||||
}
|
||||
|
||||
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
|
||||
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
|
||||
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
let Some(last) = job.rounds.last() else {
|
||||
let kind = job.make.kind.name();
|
||||
let what = match job.make.kind {
|
||||
make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
|
||||
make::Kind::Shot => "raea make framing --out review/r1",
|
||||
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "raea render EDIT.tsx --review review/r1",
|
||||
};
|
||||
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let fresh = match (job.judged_at, newest) {
|
||||
(Some(j), Some(n)) => j >= n,
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
};
|
||||
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
|
||||
// the kind's own rubric (MK5): a round judged on another's doesn't count
|
||||
let kind = job.make.kind.name();
|
||||
if last["kind"].as_str() != Some(kind) {
|
||||
let dir = last["dir"].as_str().unwrap_or("review/rN");
|
||||
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
|
||||
}
|
||||
let blocking: Vec<&str> = raea_app_judge::rubric::blocking(last["defects"].as_array().map(Vec::as_slice).unwrap_or_default());
|
||||
let open: Vec<&str> = if last["pass"] == true { Vec::new() } else { blocking.into_iter().filter(|d| !notes.contains(d)).collect() };
|
||||
out.push(gate("defects", None, open.is_empty(), if open.is_empty() { "no blocking defect left unanswered".into() } else { format!("blocking, neither fixed nor answered in NOTES.md: {}", open.join(", ")) }));
|
||||
// the score gates once the judge is calibrated for this kind; before that, fixed-or-answered is enough (MK6)
|
||||
if job.score_gates {
|
||||
let p = raea_app_judge::progress(job.rounds);
|
||||
let done = p["done"] == true;
|
||||
out.push(gate("score", None, done, format!("the calibrated judge: {} passes in a row, two needed", p["passesInARow"])));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The job's status: what's missing, each gate, the judge's rounds, and whether the agent may stop.
|
||||
pub fn status(job: &Job) -> Value {
|
||||
let mut missing = Vec::new();
|
||||
let mut newest: Option<SystemTime> = None;
|
||||
for want in make::deliverables(job.make) {
|
||||
match answered(job.dir, &want) {
|
||||
Ok(files) => newest = files.iter().filter_map(|f| mtime(f)).chain(newest).max(),
|
||||
Err(why) => missing.push(why),
|
||||
}
|
||||
}
|
||||
let notes = notes_text(job.dir).unwrap_or_default();
|
||||
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
|
||||
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
|
||||
}
|
||||
let mut gates = checks(job);
|
||||
gates.extend(lods(job, ¬es));
|
||||
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
|
||||
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
|
||||
match (&job.make.cut, job.make.kind) {
|
||||
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
|
||||
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
|
||||
_ => gates.extend(critic(job, newest, ¬es)),
|
||||
}
|
||||
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, ¬es);
|
||||
gates.extend(asks);
|
||||
let cap = job.make.rounds.unwrap_or(make::ROUNDS) as usize;
|
||||
let capped = job.rounds.len() >= cap;
|
||||
let stalled = stalled(job.rounds);
|
||||
let clear = missing.is_empty() && gates.iter().all(|g| g["clear"] == true);
|
||||
let mut why = Vec::new();
|
||||
if capped && !clear {
|
||||
why.push(format!("capped: {} critic rounds, the most this job gets; delivered with what's still missing", job.rounds.len()));
|
||||
}
|
||||
if stalled && !clear {
|
||||
why.push("stalled: three rounds without beating the best before them; delivered with what's still missing".into());
|
||||
}
|
||||
let advice = raea_app_judge::progress(job.rounds);
|
||||
json!({
|
||||
"kind": job.make.kind,
|
||||
"done": clear || capped || stalled,
|
||||
"short": !clear && (capped || stalled),
|
||||
"missing": missing,
|
||||
"gates": gates,
|
||||
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
|
||||
"plan": make::doctor(job.make),
|
||||
"files": {"deliverables": make::deliverables(job.make), "previews": make::previews(job.make)},
|
||||
"advice": said,
|
||||
"why": why,
|
||||
})
|
||||
}
|
||||
|
||||
/// The status for a person or an agent to read.
|
||||
pub fn text(s: &Value) -> String {
|
||||
let mut t = vec![format!("make: {} {}", s["kind"].as_str().unwrap_or("?"), if s["done"] == true { if s["short"] == true { "delivered short" } else { "done" } } else { "not done" })];
|
||||
for w in s["why"].as_array().into_iter().flatten() {
|
||||
t.push(format!(" {}", w.as_str().unwrap_or("")));
|
||||
}
|
||||
for (key, head) in [("plan", "plan:"), ("missing", "missing:"), ("advice", "advice (raea ask, not calibrated yet):")] {
|
||||
let items: Vec<&str> = s[key].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
if !items.is_empty() {
|
||||
t.push(head.into());
|
||||
t.extend(items.iter().map(|i| format!(" {i}")));
|
||||
}
|
||||
}
|
||||
t.push("gates:".into());
|
||||
for g in s["gates"].as_array().into_iter().flatten() {
|
||||
let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();
|
||||
t.push(format!(" {} {}{of}: {}", if g["clear"] == true { "ok " } else { "open" }, g["gate"].as_str().unwrap_or(""), g["says"].as_str().unwrap_or("")));
|
||||
}
|
||||
let j = &s["judge"];
|
||||
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
|
||||
t.join("\n")
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use raea_core_brief::{make::Make, read};
|
||||
use raea_core_facts::record::Entry;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::asked::Ledger;
|
||||
use crate::status::{Job, status, stalled};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-make-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn put(d: &PathBuf, rel: &str, text: &str) {
|
||||
let p = d.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
}
|
||||
|
||||
fn kit() -> Make {
|
||||
read("make", r#"{"kind": "kit", "style": "1970s desk, maker Aurora", "objects": [{"id": "phone", "label": "Phone", "h": 0.12, "prompt": "a rotary phone"}]}"#).unwrap()
|
||||
}
|
||||
|
||||
fn delivered(d: &PathBuf) {
|
||||
for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"] {
|
||||
put(d, f, "x");
|
||||
}
|
||||
put(d, "NOTES.md", "# Notes\n\n## What the skill got wrong\n- nothing yet\n");
|
||||
}
|
||||
|
||||
fn round(pass: bool, mean: f64, defects: Value) -> Value {
|
||||
json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})
|
||||
}
|
||||
|
||||
fn run(make: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {
|
||||
run_with(make, d, record, rounds, judged_at, &Ledger::default())
|
||||
}
|
||||
|
||||
fn run_with(make: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {
|
||||
status(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })
|
||||
}
|
||||
|
||||
fn later() -> Option<SystemTime> {
|
||||
Some(SystemTime::now() + Duration::from_secs(5))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_made_is_not_done_and_says_what_is_missing() {
|
||||
let d = dir("empty");
|
||||
let s = run(&kit(), &d, &[], &[], None);
|
||||
assert_eq!(s["done"], false);
|
||||
let missing = s["missing"].to_string();
|
||||
assert!(missing.contains("out/kit/phone/phone_lod1.glb") && missing.contains("NOTES.md"), "{missing}");
|
||||
assert!(s["gates"].as_array().unwrap().iter().any(|g| g["gate"] == "critic" && g["clear"] == false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivered_and_judged_after_is_done() {
|
||||
let d = dir("done");
|
||||
delivered(&d);
|
||||
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], later());
|
||||
assert_eq!(s["done"], true, "{s:#}");
|
||||
assert_eq!(s["short"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_round_older_than_the_newest_deliverable_is_stale() {
|
||||
let d = dir("stale");
|
||||
delivered(&d);
|
||||
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], Some(SystemTime::UNIX_EPOCH));
|
||||
assert_eq!(s["done"], false);
|
||||
assert!(s["gates"].to_string().contains("came after the last round"), "{s:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {
|
||||
let d = dir("defect");
|
||||
delivered(&d);
|
||||
let defects = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
|
||||
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
|
||||
assert_eq!(s["done"], false);
|
||||
assert!(s["gates"].to_string().contains("floating"));
|
||||
put(&d, "NOTES.md", "## What the skill got wrong\n- floating: the handset rests in its cradle; the judge read its shadow as a gap\n");
|
||||
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
|
||||
assert_eq!(s["done"], true, "{s:#}");
|
||||
// once the judge is calibrated for kits, its score gates too: two passes in a row (MK6)
|
||||
let (rounds, ledger) = ([round(false, 6.0, defects)], Ledger::default());
|
||||
let s = status(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });
|
||||
assert_eq!(s["done"], false, "{s:#}");
|
||||
assert!(s["gates"].to_string().contains("two needed"), "{s:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_the_cap_it_is_delivered_short() {
|
||||
let d = dir("cap");
|
||||
let rounds: Vec<Value> = (0..8).map(|i| round(false, 5.0 + i as f64 * 0.5, json!([]))).collect();
|
||||
let s = run(&kit(), &d, &[], &rounds, later());
|
||||
assert_eq!((s["done"].clone(), s["short"].clone()), (json!(true), json!(true)), "{s:#}");
|
||||
assert!(s["why"].to_string().contains("capped"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_rounds_without_beating_the_best_is_a_stall() {
|
||||
let r = |m: f64| json!({"mean": m});
|
||||
assert!(stalled(&[r(5.0), r(6.5), r(6.0), r(6.4), r(6.5)]));
|
||||
assert!(!stalled(&[r(5.0), r(6.0), r(6.2), r(6.4), r(6.6)]));
|
||||
assert!(!stalled(&[r(5.0), r(5.0), r(5.0)]), "too few rounds to call it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composition_needs_a_clean_check_newer_than_it() {
|
||||
let d = dir("checks");
|
||||
delivered(&d);
|
||||
put(&d, "scene.tsx", "x");
|
||||
let mut make = kit();
|
||||
make.compositions = vec!["scene.tsx".into()];
|
||||
let rounds = [round(true, 7.5, json!([]))];
|
||||
let s = run(&make, &d, &[], &rounds, later());
|
||||
assert!(s["gates"].to_string().contains("never rendered"), "{s:#}");
|
||||
let entry = |at: u64, level: &str| -> Entry {
|
||||
serde_json::from_value(json!({"id": "20261123-x", "at": at, "by": "raea render", "of": "scene.tsx",
|
||||
"findings": [{"check": "float", "level": level, "says": "the mug floats 2 cm", "by": "raea scene lint"}]})).unwrap()
|
||||
};
|
||||
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
|
||||
let s = run(&make, &d, &[entry(future, "error")], &rounds, later());
|
||||
assert!(s["gates"].to_string().contains("the mug floats"), "{s:#}");
|
||||
let s = run(&make, &d, &[entry(future, "warn")], &rounds, later());
|
||||
assert_eq!(s["done"], true, "a warn doesn't block: {s:#}");
|
||||
let s = run(&make, &d, &[entry(1, "warn")], &rounds, later());
|
||||
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
|
||||
}
|
||||
|
||||
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
|
||||
#[test]
|
||||
fn a_part_seen_closer_than_planned_holds_the_job() {
|
||||
let d = dir("lod");
|
||||
delivered(&d);
|
||||
put(&d, "scene.tsx", "x");
|
||||
let mut make = kit();
|
||||
make.compositions = vec!["scene.tsx".into()];
|
||||
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
|
||||
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
|
||||
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
|
||||
assert!(s["done"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
|
||||
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
|
||||
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["done"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scene_wants_three_stills() {
|
||||
let d = dir("scene");
|
||||
let make: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "stool", "label": "Stool", "h": 0.45, "route": "gen", "prompt": "a red stool"}]}"#).unwrap();
|
||||
put(&d, "out/stills/a.png", "x");
|
||||
let s = run(&make, &d, &[], &[], None);
|
||||
assert!(s["missing"].to_string().contains("holds 1 picture"), "{s:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_round_judged_on_another_kinds_rubric_does_not_count() {
|
||||
// docs/make.feature MK5: a kit is judged on the kit's rubric
|
||||
let d = dir("rubric");
|
||||
delivered(&d);
|
||||
let old = json!({"dir": "review/r1", "pass": true, "mean": 8.0, "defects": []});
|
||||
let s = run(&kit(), &d, &[], &[old], later());
|
||||
assert_eq!(s["done"], false);
|
||||
assert!(s["gates"].to_string().contains("--kind kit"), "{s:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
|
||||
// docs/make.feature MK4
|
||||
let d = dir("ask");
|
||||
delivered(&d);
|
||||
put(&d, "review/r1/clay.png", "clay sheet bytes");
|
||||
put(&d, "review/r1/colour.png", "colour sheet bytes");
|
||||
let rounds = [round(true, 7.5, json!([]))];
|
||||
let floating = raea_core_ask::library::find("make.clay.floating", None).unwrap();
|
||||
let mut ledger = Ledger::default();
|
||||
// nothing calibrated: every question is advice, and the job is done
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert_eq!(s["done"], true, "{s:#}");
|
||||
assert!(s["gates"].to_string().contains("advice only"), "{s:#}");
|
||||
// floating calibrated on the person's labels: it must be asked of this exact clay sheet
|
||||
ledger.calibrations.insert(floating.version(), serde_json::from_value(json!({"auc": 0.9, "n": 40, "positives": 16, "threshold": 0.4, "date": "2026-11-23", "by": "you"})).unwrap());
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert_eq!(s["done"], false);
|
||||
let gates = s["gates"].to_string();
|
||||
assert!(gates.contains("not asked of this clay sheet") && gates.contains("--std make.clay.floating"), "{gates}");
|
||||
// asked, and it flagged: open until fixed or answered by its id in NOTES.md
|
||||
let ident = raea_core_ask::ident::ident(&d.join("review/r1/clay.png")).unwrap();
|
||||
ledger.idents.insert("c-1".into(), ident);
|
||||
ledger.answers.push(json!({"id": "a-1", "at": "100", "call": "c-1", "question": "make.clay.floating", "flagged": true, "problem": 0.8}));
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert_eq!(s["done"], false);
|
||||
assert!(s["gates"].to_string().contains("make.clay.floating flagged (p 0.80)"), "{s:#}");
|
||||
put(&d, "NOTES.md", "## What the skill got wrong\n- make.clay.floating: the handset's shadow, not a gap; checked on the low tile\n");
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert_eq!(s["done"], true, "{s:#}");
|
||||
// the sheet rendered again: the old answer was about other bytes, so it's asked again
|
||||
put(&d, "review/r1/clay.png", "a new clay sheet");
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert!(s["gates"].to_string().contains("not asked of this clay sheet"), "{s:#}");
|
||||
// an uncalibrated question that flags is said as advice, holding nothing
|
||||
let ident = raea_core_ask::ident::ident(&d.join("review/r1/colour.png")).unwrap();
|
||||
ledger.idents.insert("c-2".into(), ident);
|
||||
ledger.answers.push(json!({"id": "a-2", "at": "101", "call": "c-2", "question": "make.colour.plastic", "flagged": true, "problem": 0.7}));
|
||||
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
|
||||
assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gates_are_check_lines_under_the_jobs_task_in_plan_org() {
|
||||
// docs/make.feature MK3
|
||||
let not_done = json!({"done": false, "missing": ["out/kit/lineup.png"], "gates": [{"gate": "critic", "clear": false, "says": "no round yet"}, {"gate": "checks", "of": "kit.tsx", "clear": true, "says": "clean"}]});
|
||||
let t = crate::plan::update("", "desk", "brief.ts", "kit", ¬_done);
|
||||
let id = crate::plan::task_id("brief.ts");
|
||||
assert!(id.len() == 10 && id.starts_with("t-") && id[2..].chars().all(|c| c.is_ascii_alphanumeric()), "{id}");
|
||||
assert!(t.starts_with("#+TITLE: desk\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n"), "{t}");
|
||||
assert!(t.contains("* MAKING make: kit (brief.ts) [1/3]") && t.contains(&format!(":ID: {id}")), "{t}");
|
||||
assert!(t.contains("- [ ] missing: out/kit/lineup.png") && t.contains("- [X] checks kit.tsx: clean"), "{t}");
|
||||
// the person's own line under it stays; the checks are brought up to date; done is REVIEW
|
||||
let mut mine = t.replace("- [X] checks kit.tsx: clean\n", "- [X] checks kit.tsx: clean\nShane: keep the phone's cord\n");
|
||||
mine = format!("{mine}* TODO another task\n");
|
||||
let done = json!({"done": true, "missing": [], "gates": [{"gate": "critic", "clear": true, "says": "round 2 judged"}]});
|
||||
let t2 = crate::plan::update(&mine, "desk", "brief.ts", "kit", &done);
|
||||
assert!(t2.contains("* REVIEW make: kit (brief.ts) [1/1]") && t2.contains("Shane: keep the phone's cord") && t2.contains("* TODO another task"), "{t2}");
|
||||
assert!(!t2.contains("missing:"), "{t2}");
|
||||
assert_eq!(t2.matches(":ID: ").count(), 1);
|
||||
// a task the person closed keeps their mark
|
||||
let closed = t2.replace("* REVIEW make", "* DONE make");
|
||||
assert!(crate::plan::update(&closed, "desk", "brief.ts", "kit", ¬_done).contains("* DONE make: kit (brief.ts) [1/3]"));
|
||||
// once written, writing the same again changes nothing
|
||||
assert_eq!(crate::plan::update(&t2, "desk", "brief.ts", "kit", &done), t2);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use image::{Rgba, RgbaImage};
|
||||
use raea_core_brief::{goal::Goal as Make, read};
|
||||
use raea_core_brief::{make::Make, read};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
@@ -109,7 +109,7 @@ fn the_kit_lands_as_components_and_a_lineup() {
|
||||
let m = kit();
|
||||
assert_eq!(crate::kitout::component_name("rotary_phone"), "RotaryPhone");
|
||||
let c = crate::kitout::component(&m.objects[0], "sharper numerals");
|
||||
assert!(c.starts_with("// raea make component add: Rotary phone, 0.12 m"), "{c}");
|
||||
assert!(c.starts_with("// raea component add: Rotary phone, 0.12 m"), "{c}");
|
||||
assert!(c.contains("import full from \"./rotary_phone.glb\";") && c.contains("import far from \"./rotary_phone_lod1.glb\";"));
|
||||
assert!(c.contains("export default function RotaryPhone("));
|
||||
let l = crate::kitout::lineup(&m, "desk");
|
||||
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
|
||||
// a shot with no composition can't be framed, and says what's needed
|
||||
let d = dir("framing");
|
||||
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
|
||||
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
}
|
||||
|
||||
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
|
||||
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
|
||||
|
||||
#[test]
|
||||
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
|
||||
use raea_core_brief::goal::Object;
|
||||
use raea_core_brief::make::Object;
|
||||
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
|
||||
// long across (x) where the plan's is front to back (z): a quarter turn
|
||||
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
|
||||
|
||||
@@ -40,29 +40,6 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
|
||||
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
|
||||
}
|
||||
|
||||
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
|
||||
/// interview: 7 s one after another, 4 s so).
|
||||
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
|
||||
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
|
||||
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
|
||||
let next = AtomicUsize::new(0);
|
||||
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..workers {
|
||||
s.spawn(|| {
|
||||
loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
if i >= n {
|
||||
break;
|
||||
}
|
||||
*out[i].lock().unwrap() = Some(f(i));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
|
||||
}
|
||||
|
||||
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
if files.is_empty() {
|
||||
return Err("raea media sheet FILE... -o OUT: which files?".into());
|
||||
@@ -70,9 +47,10 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
let mut tiles = Vec::new();
|
||||
if files.len() == 1 {
|
||||
let p = probe_of(&files[0])?;
|
||||
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
|
||||
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
|
||||
tiles.extend(at.into_iter().zip(read));
|
||||
for i in 0..n.max(1) {
|
||||
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
|
||||
tiles.push((t, frame(&files[0], t)?));
|
||||
}
|
||||
} else {
|
||||
for f in files {
|
||||
let p = probe_of(f)?;
|
||||
|
||||
+63
-70
@@ -1,7 +1,6 @@
|
||||
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
|
||||
|
||||
use super::*;
|
||||
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
|
||||
|
||||
pub(crate) fn round3(x: f64) -> f64 {
|
||||
(x * 1000.0).round() / 1000.0
|
||||
@@ -39,11 +38,7 @@ pub fn probe_of(path: &Path) -> R<Probe> {
|
||||
}
|
||||
i
|
||||
});
|
||||
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
|
||||
let audio = match audio_track(path) {
|
||||
Some(a) => Some(a),
|
||||
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
|
||||
};
|
||||
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
|
||||
if video.is_none() && audio.is_none() {
|
||||
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
|
||||
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
|
||||
@@ -129,37 +124,74 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
|
||||
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
|
||||
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
|
||||
audio_in(&moov_of(path)?)
|
||||
/// The boxes inside `b` (a box's payload): (type, payload).
|
||||
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 8 <= b.len() {
|
||||
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
|
||||
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
|
||||
let mut hdr = 8;
|
||||
if size == 1 && i + 16 <= b.len() {
|
||||
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = b.len() - i;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
let Some(mdia) = child(trak, b"mdia") else { continue };
|
||||
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
|
||||
continue;
|
||||
}
|
||||
let mdhd = child(mdia, b"mdhd")?;
|
||||
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
|
||||
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
|
||||
// them again as a double at 48 and a count at 56
|
||||
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
|
||||
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
|
||||
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
|
||||
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
|
||||
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
|
||||
}
|
||||
None
|
||||
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The first video track's timing, for MP4 and QuickTime files.
|
||||
pub fn video_track(path: &Path) -> Option<Track> {
|
||||
let moov = moov_of(path)?;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
|
||||
let mut at = 0u64;
|
||||
let moov = loop {
|
||||
if at + 8 > len {
|
||||
return None;
|
||||
}
|
||||
let mut h = [0u8; 16];
|
||||
f.seek(SeekFrom::Start(at)).ok()?;
|
||||
f.read_exact(&mut h[..8]).ok()?;
|
||||
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
|
||||
let mut hdr = 8u64;
|
||||
if size == 1 {
|
||||
f.read_exact(&mut h[8..]).ok()?;
|
||||
size = u64::from_be_bytes(h[8..].try_into().ok()?);
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = len - at;
|
||||
}
|
||||
if size < hdr {
|
||||
return None;
|
||||
}
|
||||
if &h[4..8] == b"moov" {
|
||||
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
|
||||
f.read_exact(&mut m).ok()?;
|
||||
break m;
|
||||
}
|
||||
at += size;
|
||||
};
|
||||
for (k, trak) in boxes(&moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
@@ -263,42 +295,3 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
|
||||
}
|
||||
|
||||
// ---- pictures
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
v.extend_from_slice(kind);
|
||||
v.extend_from_slice(body);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sound_track_is_read_from_the_file_s_own_tables() {
|
||||
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
|
||||
let mut mdhd = vec![0u8; 24];
|
||||
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
|
||||
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
|
||||
let mut hdlr = vec![0u8; 24];
|
||||
hdlr[8..12].copy_from_slice(b"soun");
|
||||
let mut stsd = vec![0u8; 44];
|
||||
stsd[7] = 1;
|
||||
stsd[12..16].copy_from_slice(b"mp4a");
|
||||
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
|
||||
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
|
||||
// a picture track ahead of it is passed over
|
||||
let mut vh = vec![0u8; 24];
|
||||
vh[8..12].copy_from_slice(b"vide");
|
||||
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
|
||||
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
|
||||
// no sound track, or one that states no rate: nothing (the track is decoded instead)
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
|
||||
let mut silent = stsd.clone();
|
||||
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea make motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
|
||||
description = "`raea motion` and `raea setup motion`: body motion made by Kimodo on this machine, on MLX on a Mac, on PyTorch elsewhere"
|
||||
|
||||
[dependencies]
|
||||
# a take's joints as vectors (score.rs)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea make motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
|
||||
//! `raea motion` without the rest of the CLI, for working on this crate while the workspace's other crates are mid-change:
|
||||
//! `lane build -- cargo run --release -p raea-app-motion --example motion -- "LINE" --seeds 4 -o CLIP.json`
|
||||
fn main() {
|
||||
let args: Vec<String> = std::iter::once("motion".to_string()).chain(std::env::args().skip(1)).collect();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea make motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
|
||||
//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip
|
||||
//! from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path:
|
||||
//! what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the same one the
|
||||
//! cloud runner wrote (docs/character.feature CH15b, CH15c).
|
||||
@@ -15,11 +15,11 @@ use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea make motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--seeds 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. --seeds N makes N takes (seeds SEED to SEED+N-1) and keeps the one with the fewest faults: a foot sliding while planted, the shoulders shrugging, the hips sinking, a hand or forearm into the torso or head (a skeletal check; each take's score is printed and the kept one's written into the clip). Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";
|
||||
|
||||
pub const SETUP_USAGE: &str = "raea setup motion [--check]";
|
||||
pub const SETUP_ABOUT: &str = "what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";
|
||||
|
||||
fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
match flag(args, name) {
|
||||
@@ -131,7 +131,7 @@ fn make(ask: Ask) -> R<String> {
|
||||
let missing = t.missing();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"raea make motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
|
||||
"raea motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",
|
||||
missing.join(", the "),
|
||||
t.dir.display()
|
||||
));
|
||||
@@ -233,7 +233,7 @@ fn disk(dir: &std::path::Path) -> String {
|
||||
raea_io_home::disk_use(dir, true)
|
||||
}
|
||||
|
||||
/// `raea setup motion [--check]`: what raea make motion runs on here, made where missing (--check only says), and where it is.
|
||||
/// `raea setup motion [--check]`: what raea motion runs on here, made where missing (--check only says), and where it is.
|
||||
pub fn setup(args: &[String]) -> R<String> {
|
||||
let check = args.iter().any(|a| a == "--check");
|
||||
if let Some(a) = args.iter().find(|a| *a != "--check") {
|
||||
@@ -257,7 +257,7 @@ fn setup_here(check: bool) -> R<String> {
|
||||
let state = match (had, has) {
|
||||
(true, _) => "installed",
|
||||
(false, true) => "installed now",
|
||||
(false, false) => "not installed: raea setup motion fetches it (raea make motion does too, the first time it needs it)",
|
||||
(false, false) => "not installed: raea setup motion fetches it (raea motion does too, the first time it needs it)",
|
||||
};
|
||||
lines.push(format!(" {name:<12} {state}; {what}\n {} ({})", dir.display(), if *has { disk(dir) } else { "-".into() }));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea make motion --seeds N` can keep the best of N:
|
||||
//! A take scored for the faults a body shows (sheet3d plan E3), so `raea motion --seeds N` can keep the best of N:
|
||||
//! a foot sliding while it's planted, the shoulders shrugging up, the hips sinking, and a hand or forearm inside the
|
||||
//! torso or head. Read from the take's own joints (Kimodo's SOMA skeleton, metres, Y up) and its foot contacts.
|
||||
//! Collision is a skeletal proxy: capsules round the spine and a sphere for the head, sized for SOMA's average adult;
|
||||
|
||||
@@ -14,9 +14,4 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "1"
|
||||
serde_json = "1"
|
||||
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
|
||||
raea-core-fonts = { path = "../../core/fonts" }
|
||||
# a game's generated sounds made at export, as a render makes them, and FFmpeg to compress them (PA6)
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
base64 = "0.22"
|
||||
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
|
||||
@@ -1,127 +0,0 @@
|
||||
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
|
||||
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
|
||||
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
|
||||
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
|
||||
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
|
||||
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
|
||||
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
|
||||
//! own default family is Inter, the native page's.
|
||||
|
||||
use base64::Engine;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The family a page with no family of its own draws in
|
||||
const DEFAULT: &str = "Inter";
|
||||
|
||||
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
|
||||
/// bundled family raea draws it as; the default first
|
||||
pub fn families(script: &str) -> Vec<(String, &'static str)> {
|
||||
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
|
||||
let res = [
|
||||
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
|
||||
r#"font-family\s*:\s*([^;"'`}]+)"#,
|
||||
];
|
||||
for re in res {
|
||||
let re = regex::Regex::new(re).expect("a valid pattern");
|
||||
for cap in re.captures_iter(script) {
|
||||
for name in cap[1].split(',') {
|
||||
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
|
||||
if let Some(c) = raea_core_fonts::canonical(name) {
|
||||
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
|
||||
out.push((name.to_string(), c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
|
||||
/// the halfway weight to the lighter face
|
||||
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
|
||||
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
|
||||
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
|
||||
if *f == canonical {
|
||||
by_style
|
||||
.entry(st)
|
||||
.or_default()
|
||||
.push((w.parse().unwrap_or(400), bytes));
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (st, mut ws) in by_style {
|
||||
ws.sort_by_key(|(w, _)| *w);
|
||||
let mut lo = 1u16;
|
||||
for (i, (w, bytes)) in ws.iter().enumerate() {
|
||||
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
|
||||
out.push(((lo, hi), st, *bytes));
|
||||
lo = hi + 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
|
||||
/// page's default family
|
||||
pub fn style(script: &str) -> String {
|
||||
let b64 = base64::engine::general_purpose::STANDARD;
|
||||
let mut css = String::from("<style>\n");
|
||||
for (name, canonical) in families(script) {
|
||||
for ((lo, hi), st, bytes) in faces(canonical) {
|
||||
css.push_str(&format!(
|
||||
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
|
||||
name.replace('"', ""),
|
||||
b64.encode(bytes)
|
||||
));
|
||||
}
|
||||
}
|
||||
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
|
||||
css
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
|
||||
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
|
||||
let f = families(script);
|
||||
assert_eq!(
|
||||
f,
|
||||
[
|
||||
("Inter".to_string(), "inter"),
|
||||
("Helvetica Neue".into(), "inter"),
|
||||
("Georgia".into(), "eb-garamond")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_weight_takes_the_face_the_native_page_takes() {
|
||||
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
|
||||
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
|
||||
// the native pick for each weight is the face whose range holds it
|
||||
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
|
||||
let native = raea_core_fonts::face("Inter", w, false).unwrap();
|
||||
let ours = faces("inter")
|
||||
.into_iter()
|
||||
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
|
||||
.unwrap()
|
||||
.2;
|
||||
assert!(native == ours, "weight {w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_style_holds_inter_and_sets_the_default() {
|
||||
let css = style("var x=1;");
|
||||
assert_eq!(css.matches("@font-face").count(), 3);
|
||||
assert!(
|
||||
css.contains("font-weight:801 1000")
|
||||
&& css.contains("html,body{font-family:\"Inter\"}")
|
||||
);
|
||||
assert!(css.len() < 110_000, "{} bytes", css.len());
|
||||
}
|
||||
}
|
||||
+18
-170
@@ -1,19 +1,15 @@
|
||||
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
|
||||
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
|
||||
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
|
||||
//! in the script; three.js only when the lint found a 3D kind, PA15; a sound player only for a game with sound, Tone.js
|
||||
//! only for a raea/tone graph, and its generated sounds made and carried in the page, PA6), and written as each
|
||||
//! network's page or ZIP (pages.rs), each checked against its cap.
|
||||
mod fonts;
|
||||
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
|
||||
mod lint;
|
||||
mod pages;
|
||||
mod sound;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
|
||||
|
||||
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
|
||||
@@ -23,13 +19,12 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone
|
||||
/// graph): the project's own (`raea add [email protected]`), else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<PathBuf> {
|
||||
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
|
||||
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
|
||||
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
let mut d = game.parent();
|
||||
while let Some(dir) = d {
|
||||
if has(dir) {
|
||||
if dir.join("node_modules/three/package.json").is_file() {
|
||||
return Ok(dir.to_path_buf());
|
||||
}
|
||||
d = dir.parent();
|
||||
@@ -37,80 +32,21 @@ fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<
|
||||
["sdk/playable", "sdk/r3f"]
|
||||
.iter()
|
||||
.map(|p| home.join(p))
|
||||
.find(|d| has(d))
|
||||
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
|
||||
}
|
||||
|
||||
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
|
||||
fn ecs_wasm(home: &Path) -> R<String> {
|
||||
use base64::Engine;
|
||||
let f = home.join("sdk/playable/src/host/ecs.wasm");
|
||||
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(b))
|
||||
}
|
||||
|
||||
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Sounds {
|
||||
None,
|
||||
Media,
|
||||
Tone,
|
||||
}
|
||||
|
||||
/// What a page carries beside the game and the host, as the lint found the game needs it
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
struct Carry {
|
||||
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
|
||||
with_3d: bool,
|
||||
sounds: Sounds,
|
||||
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
|
||||
ecs: bool,
|
||||
}
|
||||
|
||||
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
|
||||
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
|
||||
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
|
||||
/// raea/tone graph (PA6)
|
||||
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
|
||||
let Carry { with_3d, sounds, ecs } = carry;
|
||||
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
|
||||
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
|
||||
if with_3d {
|
||||
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
|
||||
}
|
||||
if sounds != Sounds::None {
|
||||
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
|
||||
}
|
||||
if sounds == Sounds::Tone {
|
||||
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
|
||||
}
|
||||
let d3 = if with_3d { "bevy3d" } else { "undefined" };
|
||||
e.push_str(&match sounds {
|
||||
Sounds::None if with_3d => "start(bevy3d);\n".into(),
|
||||
Sounds::None => "start();\n".into(),
|
||||
Sounds::Media => format!("start({d3}, sound());\n"),
|
||||
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
|
||||
});
|
||||
e
|
||||
.find(|d| d.join("node_modules/three/package.json").is_file())
|
||||
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
|
||||
let Carry { with_3d, sounds, .. } = carry;
|
||||
let host = home.join("sdk/playable/src/host");
|
||||
if !host.join("main.tsx").is_file() {
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host/main.tsx");
|
||||
if !host.is_file() {
|
||||
return Err(format!("{}: raea's playable host isn't there", host.display()));
|
||||
}
|
||||
let three = three_dir(game, home)?;
|
||||
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
|
||||
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
|
||||
if with_3d {
|
||||
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]);
|
||||
}
|
||||
if sounds == Sounds::Tone {
|
||||
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
|
||||
}
|
||||
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
|
||||
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
|
||||
let alias = format!("three/={}", three.display());
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
|
||||
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
|
||||
let _ = std::fs::remove_file(&out);
|
||||
js
|
||||
@@ -130,12 +66,7 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
}
|
||||
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
|
||||
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
|
||||
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
|
||||
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
|
||||
if name.is_empty() || name.contains(['/', '\\']) {
|
||||
return Err(format!("--name {name:?}: a file name, no folders"));
|
||||
}
|
||||
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
|
||||
|
||||
let mut report = Vec::new();
|
||||
let found = lint::lint(&game)?;
|
||||
@@ -152,45 +83,16 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let is = |k: &str| found.sound[k].as_bool() == Some(true);
|
||||
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
|
||||
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
|
||||
let home = raea_io_home::home();
|
||||
let js = bundle(&game, &home, carry)?;
|
||||
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
|
||||
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
|
||||
let made = sound::make(&game, &assets)?;
|
||||
report.push(match sounds {
|
||||
Sounds::None => "sound: none".into(),
|
||||
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
|
||||
});
|
||||
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
|
||||
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
|
||||
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
|
||||
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
|
||||
let js = format!("{ecs}{}{js}", made.script);
|
||||
// the faces the native page draws with, for the families the game names (PA8)
|
||||
let style = fonts::style(&js);
|
||||
let js = bundle(&game, &raea_io_home::home())?;
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut over = false;
|
||||
let mut written = Vec::new();
|
||||
for net in networks {
|
||||
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
|
||||
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
|
||||
let w = pages::write(net, &name, &script, &out, orientation)?;
|
||||
let ok = w.bytes <= pages::CAP;
|
||||
over |= !ok;
|
||||
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
|
||||
written.push(w);
|
||||
}
|
||||
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
|
||||
let manifest = serde_json::json!({
|
||||
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
|
||||
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
|
||||
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
|
||||
"cap": pages::CAP,
|
||||
});
|
||||
let mf = out.join(format!("{name}.playable.json"));
|
||||
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
|
||||
if over {
|
||||
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
|
||||
return Err(report.join("\n"));
|
||||
@@ -198,57 +100,3 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
|
||||
Ok(report.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Carry, Sounds, entry};
|
||||
use std::path::Path;
|
||||
|
||||
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
|
||||
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_game_starts_with_no_drawer() {
|
||||
let e = e(false, Sounds::None, false);
|
||||
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_game_starts_with_three() {
|
||||
let e = e(true, Sounds::None, false);
|
||||
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
|
||||
let media = e(false, Sounds::Media, false);
|
||||
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
|
||||
let tone = e(true, Sounds::Tone, false);
|
||||
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
|
||||
let e = e(false, Sounds::None, true);
|
||||
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
|
||||
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
|
||||
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,6 @@ pub struct Found {
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
pub refusals: Vec<String>,
|
||||
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
|
||||
pub sound: Value,
|
||||
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
|
||||
pub ecs: bool,
|
||||
}
|
||||
|
||||
const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
@@ -31,7 +27,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
|
||||
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
|
||||
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
|
||||
(r"<(Video|OffthreadVideo)\b", "<Video> plays footage through the native media stack, which a playable doesn't carry: render the clip as frames or an image sequence"),
|
||||
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
|
||||
];
|
||||
|
||||
/// The game's source and its compositions, judged
|
||||
@@ -52,7 +48,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
let walked = match walk(game) {
|
||||
Ok(w) => w,
|
||||
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
@@ -77,7 +73,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
|
||||
}
|
||||
|
||||
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
|
||||
|
||||
@@ -43,10 +43,9 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
|
||||
/// `style` (the fonts, fonts.rs) first in the head
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, head, body, script);
|
||||
let file = match network {
|
||||
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
|
||||
"google" => {
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
//! A playable's generated sounds (docs/playables.feature PA6). A game's `sao(...)` effects and TokenSynth notes are
|
||||
//! made by the native renderer the first time a render meets them (runtime/sound: raea's asset store, beside the edit).
|
||||
//! A playable makes no requests, so the export makes each one the game describes (sdk/playable walk.ts lists them,
|
||||
//! each with its model, prompt, seed and params as the renderer passes them, so the store's cache is shared with
|
||||
//! renders) and carries it in the page as a data URL under its src (`asset:sao/...`), AAC at 64 kb/s mono when FFmpeg
|
||||
//! is there (a two-second effect is about 16 KB), else the file as made. The host plays it after the first touch.
|
||||
|
||||
use super::R;
|
||||
use base64::Engine;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// The page's sounds: a script that sets `__raeaSounds` (src -> data URL), how many and their bytes
|
||||
pub struct Made {
|
||||
pub script: String,
|
||||
pub count: usize,
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
/// Each generated sound the game describes, made (or found made) beside the game and inlined
|
||||
pub fn make(game: &Path, assets: &[Value]) -> R<Made> {
|
||||
let store = raea_io_assets::Store::beside(game);
|
||||
let ffmpeg = raea_io_assets::ffmpeg_tool("ffmpeg", false).ok();
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut bytes = 0;
|
||||
for a in assets {
|
||||
let (Some(src), Some(model), Some(prompt)) =
|
||||
(a["src"].as_str(), a["model"].as_str(), a["prompt"].as_str())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let seed = a["seed"].as_u64().unwrap_or(1);
|
||||
let made = store
|
||||
.make(model, prompt, seed, &a["params"])
|
||||
.map_err(|e| format!("the sound {model} \"{prompt}\" couldn't be made: {e}"))?;
|
||||
let file = store.path(&made);
|
||||
let (mime, data) = match ffmpeg.as_deref().and_then(|f| aac(f, &file)) {
|
||||
Some(d) => ("audio/mp4", d),
|
||||
None => (
|
||||
mime(&made.ext),
|
||||
std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?,
|
||||
),
|
||||
};
|
||||
bytes += data.len();
|
||||
out.insert(
|
||||
src.into(),
|
||||
Value::from(format!(
|
||||
"data:{mime};base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(&data)
|
||||
)),
|
||||
);
|
||||
}
|
||||
let count = out.len();
|
||||
let script = if count == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
format!("globalThis.__raeaSounds={};", Value::Object(out))
|
||||
};
|
||||
Ok(Made {
|
||||
script,
|
||||
count,
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// The file as AAC in an MP4 (what WebKit and every other browser decode), mono at 64 kb/s
|
||||
fn aac(ffmpeg: &Path, file: &Path) -> Option<Vec<u8>> {
|
||||
let to = std::env::temp_dir().join(format!("raea-playable-sound-{}.m4a", std::process::id()));
|
||||
let ok = std::process::Command::new(ffmpeg)
|
||||
.args(["-v", "error", "-y", "-i"])
|
||||
.arg(file)
|
||||
.args(["-vn", "-ac", "1", "-c:a", "aac", "-b:a", "64k", "-f", "mp4"])
|
||||
.arg(&to)
|
||||
.status()
|
||||
.is_ok_and(|s| s.success());
|
||||
let data = if ok { std::fs::read(&to).ok() } else { None };
|
||||
let _ = std::fs::remove_file(&to);
|
||||
data
|
||||
}
|
||||
|
||||
fn mime(ext: &str) -> &'static str {
|
||||
match ext {
|
||||
"mp3" => "audio/mpeg",
|
||||
"ogg" => "audio/ogg",
|
||||
"flac" => "audio/flac",
|
||||
"m4a" | "mp4" | "aac" => "audio/mp4",
|
||||
_ => "audio/wav",
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|faults|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
description = "raea scene lint|explain|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
@@ -12,11 +12,6 @@ raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# raea scene faults: whether a viewer would notice each lint finding, and the judge learning from verdicts
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# raea scene faults --clip: a character's motion held to what a body does
|
||||
raea-sys-motionfaults = { path = "../../systems/motionfaults" }
|
||||
raea-sys-body = { path = "../../systems/body" }
|
||||
# each part's planned detail beside how large the frames show it (MK21, MK23)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters held to what a body does
|
||||
//! (raea-sys-motionfaults), read from the scene itself, with no clip written out. raea/character's `<Character>` draws
|
||||
//! each joint as a marker part named `<name>-<joint>` (its joint.glb) at the joint's place and turn, and every joint's
|
||||
//! rest frame is the world's, so a joint's turn from rest against its parent is its parent's world turn undone from its
|
||||
//! own: each frame's pose comes back exactly. The skeleton is the body's skeleton.json beside its joint.glb.
|
||||
//!
|
||||
//! And the hands against the scene: each finger bone, the thumb's too, as a segment from its joint toward its tip,
|
||||
//! tested against every other part's real triangles (raea-sys-notice's BVH). A bone that crosses a surface has gone in
|
||||
//! at least a finger's half thickness: a thumb through a grip, fingers through a mug's wall. And the other way: while
|
||||
//! two or more fingertips rest on a surface (the hand holds something), a tip left 3 cm or more off it hasn't closed:
|
||||
//! the thumb not wrapping round a post.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::math::{Quat, Vec3};
|
||||
use raea_core_scene::Item;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton};
|
||||
use raea_sys_motionfaults::{Clip, Fault, Hit, grip, stretches};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A distal bone is tested this far toward its tip (its tip is the skin's end, which rests on what it touches).
|
||||
const ALONG: f32 = 0.85;
|
||||
|
||||
fn name(it: &Item) -> Option<&str> {
|
||||
it.props.get("name").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// The characters on a frame: each one's name and the folder its joint.glb is in.
|
||||
fn characters(its: &[Item]) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for it in its {
|
||||
let (Some(n), Some(src)) = (name(it), it.props.get("src").and_then(Value::as_str)) else { continue };
|
||||
if let (Some(body), true) = (n.strip_suffix("-body"), src.ends_with("/body.glb")) {
|
||||
let folder = src.trim_end_matches("/body.glb").to_string();
|
||||
if !out.iter().any(|o| o.0 == body) {
|
||||
out.push((body.to_string(), folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body's skeleton.json, its folder as the scene names it found from the composition's folder up.
|
||||
fn skeleton(dir: &Path, folder: &str) -> Option<(PathBuf, Skeleton)> {
|
||||
let rel = folder.trim_start_matches('/');
|
||||
for up in dir.ancestors().take(4) {
|
||||
for sub in ["", "media", "assets", "public", "compositions/media"] {
|
||||
let p = up.join(sub).join(rel).join("skeleton.json");
|
||||
if let Ok(t) = std::fs::read_to_string(&p) {
|
||||
return Skeleton::from_json(&t).ok().map(|s| (p, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A part's place and turn (its scale taken out).
|
||||
fn placed(it: &Item) -> (Vec3, Quat) {
|
||||
let (_, r, t) = it.world.to_scale_rotation_translation();
|
||||
(t, r)
|
||||
}
|
||||
|
||||
/// One character's frames as a clip, and each frame's joint places in the scene (for the hands against it).
|
||||
fn clip_of(skel: &Skeleton, who: &str, frames: &[Vec<Item>], fps: f32) -> (Clip, Vec<Vec<Option<(Vec3, Quat)>>>) {
|
||||
let (mut poses, mut places) = (Vec::new(), Vec::new());
|
||||
for its in frames {
|
||||
let at: Vec<Option<(Vec3, Quat)>> = skel.joints.iter().map(|j| its.iter().find(|it| name(it) == Some(&format!("{who}-{}", j.name))).map(placed)).collect();
|
||||
let mut p: Pose = skel.rest();
|
||||
for (i, j) in skel.joints.iter().enumerate() {
|
||||
let Some((pos, rot)) = at[i] else { continue };
|
||||
match j.parent.and_then(|q| at[q]) {
|
||||
Some((_, prot)) => p.turns[i] = (prot.inverse() * rot).normalize(),
|
||||
None if j.parent.is_none() => {
|
||||
p.turns[i] = rot;
|
||||
p.root = pos;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
poses.push(p);
|
||||
places.push(at);
|
||||
}
|
||||
(Clip { skel: skel.clone(), fps, poses, held: None }, places)
|
||||
}
|
||||
|
||||
/// The hands against the scene's other parts, frame by frame: finger bones through a surface (`through`), and tips
|
||||
/// left off what the hand holds (`grip`), as faults over the stretches they last.
|
||||
fn hands(skel: &Skeleton, who: &str, frames: &[Vec<Item>], places: &[Vec<Option<(Vec3, Quat)>>], numbers: &[i64]) -> Vec<Fault> {
|
||||
let mut hits: Vec<Hit> = Vec::new();
|
||||
let bones: Vec<usize> = Side::BOTH.iter().flat_map(|&s| FINGERS.iter().filter_map(move |f| skel.finger(f, s))).flatten().collect();
|
||||
let tips: Vec<Vec<usize>> = Side::BOTH.iter().map(|&s| FINGERS.iter().filter_map(|f| skel.finger(f, s).map(|b| b[2])).collect()).collect();
|
||||
for (k, its) in frames.iter().enumerate() {
|
||||
// the scene but the character itself (its skin is drawn at its bind pose in the parts, its markers are specks)
|
||||
let mine = format!("{who}-");
|
||||
let others: Vec<Item> = its.iter().filter(|it| !name(it).is_some_and(|n| n.starts_with(&mine))).cloned().collect();
|
||||
// every part: a mesh's place is often in its own vertices, its transform the world's origin (gambit's ladder lab),
|
||||
// so nothing can be left out by where its transform sits
|
||||
if bones.iter().all(|&i| places[k][i].is_none()) {
|
||||
continue;
|
||||
}
|
||||
let near: Vec<Item> = others.into_iter().filter(|it| it.kind != "camera").collect();
|
||||
let scene = raea_sys_notice::Scene::of(&near);
|
||||
let bone = |i: usize, along: f32| places[k][i].map(|(a, rot)| (a, a + rot * ((skel.joints[i].tail - skel.joints[i].head) * along)));
|
||||
for &i in &bones {
|
||||
if let Some((a, b)) = bone(i, ALONG)
|
||||
&& scene.blocked(a, b, 0.0)
|
||||
{
|
||||
hits.push(Hit { check: "through", joint: skel.joints[i].name.clone(), f: k, value: 0.0, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
for side in &tips {
|
||||
let off: Vec<(usize, f32)> = side.iter().filter_map(|&i| bone(i, 1.0).map(|(_, tip)| (i, scene.reach(tip, grip::LOOK)))).collect();
|
||||
for o in grip::open(&off.iter().map(|o| o.1).collect::<Vec<_>>()) {
|
||||
hits.push(Hit { check: "grip", joint: skel.joints[off[o].0].name.clone(), f: k, value: off[o].1, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// one fault per check and joint while the frames run on, as a clip's are (motionfaults' stretches)
|
||||
let mut out = stretches(hits);
|
||||
for f in &mut out {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to] as usize, numbers[f.peak] as usize);
|
||||
f.says = match f.check {
|
||||
"grip" => format!("{} is {:.0} mm off what the hand holds (it hasn't closed on it), frames {}-{}", f.joint, f.value * 1000.0, f.from, f.to),
|
||||
_ => format!("{} passes through a part of the scene, frames {}-{}", f.joint, f.from, f.to),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One character's findings over the composition's frames.
|
||||
pub struct Found {
|
||||
pub who: String,
|
||||
pub skeleton: PathBuf,
|
||||
pub frames: usize,
|
||||
pub faults: Vec<Fault>,
|
||||
}
|
||||
|
||||
/// Every character's motion faults over the frames given (their numbers alongside); a character whose skeleton.json
|
||||
/// can't be found is said in the second list.
|
||||
pub fn run(dir: &Path, frames: &[(i64, Vec<Item>)], fps: f32) -> Result<(Vec<Found>, Vec<String>), String> {
|
||||
let Some((_, first)) = frames.first() else { return Err("no frames".into()) };
|
||||
let found = characters(first);
|
||||
if found.is_empty() {
|
||||
return Err("no characters in the composition (a <Character> draws <name>-body and <name>-<joint> parts)".into());
|
||||
}
|
||||
let numbers: Vec<i64> = frames.iter().map(|f| f.0).collect();
|
||||
let items: Vec<Vec<Item>> = frames.iter().map(|f| f.1.clone()).collect();
|
||||
let (mut out, mut missing) = (Vec::new(), Vec::new());
|
||||
for (who, folder) in found {
|
||||
let Some((path, skel)) = skeleton(dir, &folder) else {
|
||||
missing.push(format!("{who}: no skeleton.json for {folder}, not checked"));
|
||||
continue;
|
||||
};
|
||||
let (clip, places) = clip_of(&skel, &who, &items, fps);
|
||||
let mut faults = raea_sys_motionfaults::check(&clip);
|
||||
// the clip's frames are the composition's from its first
|
||||
for f in &mut faults {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to.min(numbers.len() - 1)] as usize, numbers[f.peak] as usize);
|
||||
}
|
||||
faults.extend(hands(&skel, &who, &items, &places, &numbers));
|
||||
out.push(Found { who, skeleton: path, frames: clip.poses.len(), faults });
|
||||
}
|
||||
Ok((out, missing))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Camera clearance (docs/goal.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to
|
||||
//! Camera clearance (docs/make.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to
|
||||
//! each solid part, and where it comes closer than a person carrying it could (0.45 m by default). A camera that
|
||||
//! grazes a door frame or pushes into a desk draws the inside of the part, or a wall filling the frame; the boxes the
|
||||
//! stage keeps say it without drawing. Only solids count: volumes, decals, footage, 2D, see-through parts (glass) and
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx`: the lint's findings judged as a viewer of the shot would see them (raea-sys-notice):
|
||||
//! every frame's camera asked where each one shows and how large, a small model saying how likely it is to read as a
|
||||
//! fault, the likeliest first. Hidden ones (walls meeting the ceiling inside the slab) are counted, not listed.
|
||||
//!
|
||||
//! It learns: `--real KEY` and `--fine KEY` keep a verdict on a finding beside the project (review/
|
||||
//! faults.labels.jsonl), and a finding the last run said that's gone while both its parts remain is kept as fixed,
|
||||
//! so real. `raea scene faults train [FOLDER]` fits the model to every project's verdicts under FOLDER.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
use raea_sys_notice::{FAULT, Judged, Model, labels};
|
||||
|
||||
/// The most frames whose cameras are asked (evenly over the shot).
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(crate::USAGE.into()) };
|
||||
if edit == "train" {
|
||||
return train(args.get(3).map(String::as_str));
|
||||
}
|
||||
if edit == "--clip" {
|
||||
return crate::motion::cli(args);
|
||||
}
|
||||
let tsx = dunce::canonicalize(std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = frame_of(args)?;
|
||||
let opts = comp_opts(args)?;
|
||||
let shot = opts.composition.clone().unwrap_or_default();
|
||||
let js = std::env::temp_dir().join(format!("raea-faults-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &opts, None)?;
|
||||
let got = raea_runtime_export::scene_frames(&js, &dir, 0, true, &[]);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
// the composition's characters held to what a body does, read from the scene (chars.rs)
|
||||
if args.iter().any(|a| a == "--motion") {
|
||||
let all: Vec<(i64, Vec<raea_core_scene::Item>)> = frames.iter().map(|fr| (fr.0, items(&fr.1))).collect();
|
||||
let (text, v, n) = crate::motion::composition(&tsx, &shot, &dir, &all, fps as f32, args)?;
|
||||
return finish(if args.iter().any(|a| a == "--json") { serde_json::to_string_pretty(&v).unwrap_or_default() } else { text }, n);
|
||||
}
|
||||
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
|
||||
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
|
||||
let (now, next) = (items(&frames[k].1), items(&frames[other].1));
|
||||
let (found, _) = raea_sys_contact::lint(&now, &next);
|
||||
// the cameras: the frame's own and evenly over the rest of the shot
|
||||
let step = frames.len().div_ceil(CAMERAS).max(1);
|
||||
let mut views = vec![now.clone()];
|
||||
for (i, (_, fr)) in frames.iter().enumerate() {
|
||||
if i != k && i % step == 0 {
|
||||
views.push(items(fr));
|
||||
}
|
||||
}
|
||||
let model = Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, w, h, &model);
|
||||
// faults of known size planted and judged: the judge measured, nothing kept (seed.rs)
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--seed") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults to plant")?;
|
||||
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
|
||||
}
|
||||
|
||||
// what it learns from: this run against the last, and any verdict given now
|
||||
let project = labels::project_of(&tsx);
|
||||
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
|
||||
let parts: Vec<String> = found.iter().flat_map(|v| ["part", "on", "into"].into_iter().filter_map(move |n| v[n].as_str())).map(String::from).collect();
|
||||
let mut rows = labels::fixed(&labels::last(&project, &shot), &keys, &parts);
|
||||
let fixed = rows.len();
|
||||
for (name, real) in [("--real", true), ("--fine", false)] {
|
||||
for key in raea_runtime_bundle::flags(args, name) {
|
||||
let j = judged.iter().find(|j| j.fault.key == key).ok_or_else(|| format!("{name} {key}: no finding by that key on this shot (keys are listed with --json, or after each line)"))?;
|
||||
rows.push(labels::row(&key, real, "marked", &shot, &j.x, &j.toks));
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
let last: Vec<Value> = judged.iter().map(|j| json!({"key": j.fault.key, "part": j.fault.part, "into": j.fault.into, "x": j.x, "toks": j.toks, "shot": shot})).collect();
|
||||
labels::keep_last(&project, &shot, last)?;
|
||||
|
||||
let faults: Vec<&Judged> = judged.iter().filter(|j| j.p >= FAULT).collect();
|
||||
let hidden = judged.iter().filter(|j| j.seen.shown == 0).count();
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
let rows: Vec<Value> = judged
|
||||
.iter()
|
||||
.map(|j| json!({"key": j.fault.key, "check": j.fault.check, "part": j.fault.part, "into": j.fault.into, "p": (j.p * 1e3).round() / 1e3, "fault": j.p >= FAULT,
|
||||
"seen": {"frames": j.seen.frames, "shown": j.seen.shown, "px": (j.seen.px * 10.0).round() / 10.0, "near": (j.seen.near * 1e3).round() / 1e3}, "says": j.fault.says}))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&json!({"frame": frame, "model": model.from, "labels": model.labels, "findings": rows, "faults": faults.len(), "hidden": hidden, "fixed": fixed})).unwrap_or_default();
|
||||
return finish(text, faults.len());
|
||||
}
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for j in &judged {
|
||||
if j.seen.shown == 0 && j.p < FAULT {
|
||||
continue;
|
||||
}
|
||||
let tag = if j.p >= FAULT { "FAULT" } else { "maybe" };
|
||||
out.push(format!("{:.2} {tag} {} (seen on {}/{} frames, {:.1} px, {:.2} m off) key: {}", j.p, j.fault.says, j.seen.shown, j.seen.frames, j.seen.px, j.seen.near, j.fault.key));
|
||||
}
|
||||
out.push(format!(
|
||||
"frame {frame}: {} findings, {} likely faults, {} seen but likely fine, {hidden} no camera sees; judged by {} ({} labels){}",
|
||||
judged.len(),
|
||||
faults.len(),
|
||||
judged.len() - faults.len() - judged.iter().filter(|j| j.seen.shown == 0 && j.p < FAULT).count(),
|
||||
model.from,
|
||||
model.labels,
|
||||
if fixed > 0 { format!("; {fixed} fixed since the last run, kept as real") } else { String::new() }
|
||||
));
|
||||
finish(out.join("\n"), faults.len())
|
||||
}
|
||||
|
||||
/// Faults fail it, as the lint's errors do.
|
||||
fn finish(text: String, faults: usize) -> Result<String, String> {
|
||||
if faults > 0 {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// `raea scene faults train [FOLDER]`: every project's verdicts under FOLDER (default: here) fitted, the model kept in
|
||||
/// raea's models folder for every run after.
|
||||
fn train(root: Option<&str>) -> Result<String, String> {
|
||||
let root = std::path::PathBuf::from(root.unwrap_or("."));
|
||||
let files = labels::files(&root, 4);
|
||||
let ex: Vec<_> = files.iter().flat_map(|f| labels::examples(f)).collect();
|
||||
if ex.is_empty() {
|
||||
return Err(format!("no verdicts under {} (review/faults.labels.jsonl: --real KEY, --fine KEY, and fixes)", root.display()));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let right = ex.iter().filter(|(x, t, y)| (m.score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let before = ex.iter().filter(|(x, t, y)| (Model::prior().score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let p = raea_sys_notice::model::path();
|
||||
std::fs::create_dir_all(p.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&p, serde_json::to_string_pretty(&m.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
// held out: each finding (one finding judged on two shots shares its words) fitted without, then asked
|
||||
let (held, finds) = held_out(&ex.iter().map(|e| (e.1.clone(), e.0.clone(), e.1.clone(), e.2)).collect::<Vec<_>>());
|
||||
// and a shot at a time (each project's own shot names, so a shot is a project's view): a scene it has never seen
|
||||
let by_shot: Vec<_> = files.iter().enumerate().flat_map(|(n, f)| labels::shots(f).into_iter().map(move |(s, x, t, y)| (format!("{n}/{s}"), x, t, y))).collect();
|
||||
let (unseen, names) = held_out(&by_shot);
|
||||
Ok(format!(
|
||||
"{} verdicts on {} findings from {} projects ({real} real, {} fine): the prior agreed with {before}, the fitted judge with {right}, with {held} each fitted without its own finding (held out), and with {unseen} each fitted without its whole shot ({} shots, a scene it hasn't seen); kept in {}\n{}",
|
||||
ex.len(),
|
||||
finds,
|
||||
files.len(),
|
||||
ex.len() - real,
|
||||
names,
|
||||
p.display(),
|
||||
crate::motion::train()?
|
||||
))
|
||||
}
|
||||
|
||||
/// Verdicts a judge gets right fitted without their own group (a finding's words, a shot): each group left out in
|
||||
/// turn, fitted on the rest, then asked. With how many groups there were.
|
||||
fn held_out<K: Ord>(rows: &[(K, Vec<f32>, Vec<String>, f32)]) -> (usize, usize) {
|
||||
let mut groups: Vec<&K> = rows.iter().map(|r| &r.0).collect();
|
||||
groups.sort();
|
||||
groups.dedup();
|
||||
let (mut right, n) = (0, groups.len());
|
||||
for g in groups {
|
||||
let rest: Vec<_> = rows.iter().filter(|r| &r.0 != g).map(|r| (r.1.clone(), r.2.clone(), r.3)).collect();
|
||||
let m = Model::fit(&rest);
|
||||
right += rows.iter().filter(|r| &r.0 == g && (m.score(&r.1, &r.2) >= FAULT) == (r.3 >= 0.5)).count();
|
||||
}
|
||||
(right, n)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `raea scene lint|explain|light|stage|lod`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature). `lod` is
|
||||
//! each part's planned detail beside how large the frames show it (docs/goal.feature MK23).
|
||||
//! each part's planned detail beside how large the frames show it (docs/make.feature MK23).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -10,18 +10,12 @@ use raea_runtime_export::{frame_of, items};
|
||||
|
||||
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
|
||||
pub mod clearance;
|
||||
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
|
||||
mod chars;
|
||||
mod faults;
|
||||
mod motion;
|
||||
// faults of known size planted, to measure the judge (`faults --seed N`)
|
||||
mod seed;
|
||||
mod light;
|
||||
// each part's planned detail beside how large the frames show it (MK23)
|
||||
pub mod lod;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
@@ -34,7 +28,6 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lod" => return lod::cli(args),
|
||||
"faults" => return faults::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/goal.feature MK23): every part's
|
||||
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/make.feature MK23): every part's
|
||||
//! planned detail beside how large the frames show it. A part's plan is its own `lod` (0 the hero to 4 far), else its
|
||||
//! name's on the job's plan (`lod` on brief.ts's make objects); what a frame shows is how much of it the part's box
|
||||
//! spans (raea-runtime-lod-plan). The table lists the planned parts first, the ones seen closer than planned on top,
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
//! `raea scene faults --clip CLIP.json|FOLDER [--clip ...]`: a character's motion held to what a body does, frame by frame
|
||||
//! (raea-sys-motionfaults): knees that buckle while the foot stands, feet that skate, joints past their range, fingers
|
||||
//! twisted or bent back, jolts, and fingers through what the hand holds. A clip is the skeleton's `joints` (and its
|
||||
//! `surface`, for the palm), `fps`, and `frames` of `{ root, turns }` (with `thing` for what the hand holds).
|
||||
//!
|
||||
//! It learns: `--fine KEY` and `--real KEY` on a clip's finding (each line ends with its key: check and joint role)
|
||||
//! move that key's line for every run after (raea-sys-motionfaults' verdicts, kept beside the scene judge's model).
|
||||
|
||||
use raea_sys_motionfaults::critic;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
// each --clip a clip's JSON, or a folder of them
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
for given in args.windows(2).filter(|w| w[0] == "--clip").map(|w| &w[1]) {
|
||||
match std::fs::read_dir(given) {
|
||||
Ok(dir) => {
|
||||
let mut v: Vec<String> = dir.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).map(|p| p.to_string_lossy().into()).collect();
|
||||
v.sort();
|
||||
files.extend(v);
|
||||
}
|
||||
Err(_) => files.push(given.clone()),
|
||||
}
|
||||
}
|
||||
if let Some(n) = args.windows(2).find(|w| w[0] == "--seed").map(|w| &w[1]) {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults of each kind to plant in each clip")?;
|
||||
return seed(&files, n);
|
||||
}
|
||||
let as_json = args.iter().any(|a| a == "--json");
|
||||
let (mut text, mut out, mut faults) = (String::new(), Vec::new(), 0);
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let (mut given, mut held) = (0usize, 0usize);
|
||||
for file in &files {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let mut found = raea_sys_motionfaults::check(&clip);
|
||||
// verdicts given now, on this clip's findings by key, then every verdict's lines applied
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let hit: Vec<_> = found.iter().filter(|f| raea_sys_motionfaults::verdicts::key(f) == *k).collect();
|
||||
if hit.is_empty() {
|
||||
return Err(format!("{file}: no finding has the key {k} (each line ends with its key)"));
|
||||
}
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in hit {
|
||||
if f.value < from || f.value > upto {
|
||||
continue;
|
||||
}
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let before = found.len();
|
||||
found.retain(|f| stands(f, &verdicts, &judge));
|
||||
held += before - found.len();
|
||||
faults += found.len();
|
||||
let name = std::path::Path::new(file).file_stem().map_or(file.to_string(), |s| s.to_string_lossy().into());
|
||||
text += &format!("{name}: {} frames, {} fault{}\n", clip.poses.len(), found.len(), if found.len() == 1 { "" } else { "s" });
|
||||
for f in &found {
|
||||
text += &format!(" {:<8} {} key: {}\n", f.check, f.says, raea_sys_motionfaults::verdicts::key(f));
|
||||
}
|
||||
out.push(json!({"clip": file, "frames": clip.poses.len(), "faults": found.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("--clip takes a clip's JSON (joints, fps, frames of root and turns)".into());
|
||||
}
|
||||
if given > 0 {
|
||||
if let Some(dir) = store.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
critic::append(&epath, &examples)?;
|
||||
text += &format!("{given} verdict{} kept in {}\n", if given == 1 { "" } else { "s" }, store.display());
|
||||
}
|
||||
if held > 0 {
|
||||
text += &format!("{held} finding{} held back by earlier verdicts (fine at that size)\n", if held == 1 { " is" } else { "s are" });
|
||||
}
|
||||
if as_json {
|
||||
return Ok(serde_json::to_string_pretty(&json!({"clips": out, "faults": faults, "held": held})).unwrap());
|
||||
}
|
||||
if faults > 0 {
|
||||
eprint!("{text}");
|
||||
return Err(format!("{faults} motion fault{} in {} clip{}", if faults == 1 { "" } else { "s" }, out.len(), if out.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Faults of each kind planted in every clip (raea-sys-motionfaults' plant), and how many `check` finds: one that is
|
||||
/// new against the clip's own faults, of its kind, on its joint (any joint for a grip), over its frame.
|
||||
fn seed(files: &[String], n: usize) -> Result<String, String> {
|
||||
use raea_sys_motionfaults::plant::{KINDS, Rng, plant};
|
||||
use std::collections::BTreeMap;
|
||||
let mut tally: BTreeMap<&str, (usize, usize, Vec<f32>, Vec<f32>)> = BTreeMap::new();
|
||||
let mut text = String::new();
|
||||
for (k, file) in files.iter().enumerate() {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let own = raea_sys_motionfaults::check(&clip);
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15 ^ (k as u64 + 1) * 0x1000_0001);
|
||||
for kind in KINDS {
|
||||
for _ in 0..n {
|
||||
let Some((moved, p)) = plant(&clip, kind, &mut rng) else { continue };
|
||||
let near = |f: &raea_sys_motionfaults::Fault| f.check == p.check && (p.check == "through" || p.check == "skate" || f.joint == p.joint) && f.from <= p.frame + 2 && p.frame <= f.to + 2;
|
||||
let found = raea_sys_motionfaults::check(&moved);
|
||||
let caught = found.iter().any(|f| near(f) && !own.iter().any(|o| o.check == f.check && o.joint == f.joint && o.from <= f.to && f.from <= o.to));
|
||||
let t = tally.entry(p.check).or_default();
|
||||
t.0 += 1;
|
||||
if caught {
|
||||
t.1 += 1;
|
||||
t.2.push(p.size);
|
||||
} else {
|
||||
t.3.push(p.size);
|
||||
let name = std::path::Path::new(file).file_stem().map_or(String::new(), |s| s.to_string_lossy().into());
|
||||
text += &format!(" missed in {name}: {}\n", p.says);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!("planted in {} clips:\n", files.len());
|
||||
for (kind, (planted, caught, got, missed)) in &tally {
|
||||
out += &format!(" {kind:<8} {caught}/{planted} caught{}{}\n", if got.is_empty() { String::new() } else { format!(", smallest caught {:.3}", raea_sys_motionfaults::bounds(got).0) }, if missed.is_empty() { String::new() } else { format!(", smallest missed {:.3}", raea_sys_motionfaults::bounds(missed).0) });
|
||||
}
|
||||
Ok(out + text.as_str())
|
||||
}
|
||||
|
||||
/// Where the motion verdicts are kept: beside the scene judge's model (notice/motion.json), or RAEA_NOTICE_MOTION.
|
||||
/// `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters (chars.rs) held to the motion
|
||||
/// checks, verdicts given (`--real`/`--fine KEY`) and applied as `--clip`'s are. And what a change shows: each run's
|
||||
/// findings are kept (review/motion.last/<shot>.json), and one the last run reported that's gone now, the character
|
||||
/// and its frames the same, was fixed, so it's kept as a real verdict at its size (raea-sys-motionfaults `fixed`).
|
||||
pub fn composition(tsx: &std::path::Path, shot: &str, dir: &std::path::Path, frames: &[(i64, Vec<raea_core_scene::Item>)], fps: f32, args: &[String]) -> Result<(String, Value, usize), String> {
|
||||
use raea_sys_motionfaults::verdicts::{fixed, key, record};
|
||||
let (found, missing) = crate::chars::run(dir, frames, fps)?;
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let lastp = raea_sys_notice::labels::project_of(tsx).join("review").join("motion.last").join(format!("{shot}.json"));
|
||||
let last: Value = std::fs::read_to_string(&lastp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
|
||||
let (mut text, mut rows, mut total, mut given, mut fixes, mut held) = (missing.join("\n"), Vec::new(), 0, 0, 0, 0);
|
||||
let mut keep = serde_json::Map::new();
|
||||
for c in &found {
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in c.faults.iter().filter(|f| key(f) == *k && f.value >= from && f.value <= upto) {
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines = String::new();
|
||||
let was = &last["characters"][&c.who];
|
||||
if was["frames"].as_u64() == Some(c.frames as u64) && last["checks"] == raea_sys_motionfaults::CHECKS {
|
||||
for (k, v, n) in fixed(was["faults"].as_array().map(Vec::as_slice).unwrap_or(&[]), &c.faults) {
|
||||
verdicts.give_at(&k, v, true);
|
||||
let (check, joint) = k.split_once(':').unwrap_or((&k, ""));
|
||||
examples.push(critic::row_of(check, joint, v, n, true, "fixed"));
|
||||
fixes += 1;
|
||||
lines += &format!(" fixed {k} at {v:.3}: gone since the last run, kept as real\n");
|
||||
}
|
||||
}
|
||||
keep.insert(c.who.clone(), json!({"frames": c.frames, "faults": c.faults.iter().map(record).collect::<Vec<_>>()}));
|
||||
let mut stand: Vec<&raea_sys_motionfaults::Fault> = Vec::new();
|
||||
for f in &c.faults {
|
||||
if stands(f, &verdicts, &judge) {
|
||||
stand.push(f);
|
||||
}
|
||||
}
|
||||
held += c.faults.len() - stand.len();
|
||||
total += stand.len();
|
||||
for f in &stand {
|
||||
lines += &format!(" {:<8} {} key: {}\n", f.check, f.says, key(f));
|
||||
}
|
||||
text += &format!("{} ({}): {} frames, {} fault{}\n{lines}", c.who, c.skeleton.display(), c.frames, stand.len(), if stand.len() == 1 { "" } else { "s" });
|
||||
rows.push(json!({"character": c.who, "skeleton": c.skeleton, "frames": c.frames, "faults": stand.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if given + fixes > 0 {
|
||||
std::fs::create_dir_all(store.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
}
|
||||
critic::append(&epath, &examples)?;
|
||||
if let Some(dir) = lastp.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::write(&lastp, serde_json::to_string_pretty(&json!({"checks": raea_sys_motionfaults::CHECKS, "characters": keep})).unwrap_or_default()).map_err(|e| format!("{}: {e}", lastp.display()))?;
|
||||
text += &format!("{held} held back by verdicts and the critic ({} labels), {given} verdicts given, {fixes} fixed since the last run (kept as real) in {}", judge.labels, store.display());
|
||||
Ok((text, json!({"characters": rows, "faults": total, "held": held, "fixed": fixes}), total))
|
||||
}
|
||||
|
||||
/// `--fine-upto N` / `--fine-from N` (`--real-upto`, `--real-from`): that call's verdicts only on findings of the key
|
||||
/// within those sizes, in the finding's own units (degrees past the range for a finger or a limit): a pinky's small
|
||||
/// bends fine, its big one real.
|
||||
/// A fault that stands: marked real, or not marked fine and scored a fault by the judge.
|
||||
fn stands(f: &raea_sys_motionfaults::Fault, verdicts: &raea_sys_motionfaults::verdicts::Verdicts, judge: &critic::Critic) -> bool {
|
||||
verdicts.real_at(f) || (verdicts.stands(f) && judge.score(f) >= critic::SAY)
|
||||
}
|
||||
|
||||
fn sizes(args: &[String], real: bool) -> (f32, f32) {
|
||||
let (a, b) = if real { ("--real-from", "--real-upto") } else { ("--fine-from", "--fine-upto") };
|
||||
let get = |flag: &str, or: f32| args.windows(2).find(|w| w[0] == flag).and_then(|w| w[1].parse().ok()).unwrap_or(or);
|
||||
(get(a, f32::NEG_INFINITY), get(b, f32::INFINITY))
|
||||
}
|
||||
|
||||
/// Who a verdict is by: `--by NAME` (an agent that looked: claude), else a person (marked).
|
||||
fn by(args: &[String]) -> &str {
|
||||
args.windows(2).find(|w| w[0] == "--by").map_or("marked", |w| w[1].as_str())
|
||||
}
|
||||
|
||||
/// The motion critic fitted to every example kept, held out by key, written beside the verdicts.
|
||||
pub fn train() -> Result<String, String> {
|
||||
let (cpath, epath) = critic::paths(&verdicts_path());
|
||||
let ex = critic::examples(&std::fs::read_to_string(&epath).unwrap_or_default());
|
||||
if ex.is_empty() {
|
||||
return Ok(format!("motion critic: no examples yet ({})", epath.display()));
|
||||
}
|
||||
let c = critic::Critic::fit(&ex);
|
||||
let right = ex.iter().filter(|e| (c.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let prior = ex.iter().filter(|e| (critic::Critic::prior().score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let mut keys: Vec<&String> = ex.iter().map(|e| &e.1[2]).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
let held = keys.iter().map(|k| {
|
||||
let m = critic::Critic::fit(&ex.iter().filter(|e| &e.1[2] != *k).cloned().collect::<Vec<_>>());
|
||||
ex.iter().filter(|e| &e.1[2] == *k && (m.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count()
|
||||
}).sum::<usize>();
|
||||
std::fs::write(&cpath, serde_json::to_string_pretty(&c.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", cpath.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
Ok(format!("motion critic: {} examples on {} keys ({real} real, {} fine): the prior agreed with {prior}, the fitted critic with {right}, and with {held} each fitted without its own key (held out); kept in {}", ex.len(), keys.len(), ex.len() - real, cpath.display()))
|
||||
}
|
||||
|
||||
fn verdicts_path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MOTION").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_sys_notice::model::path().with_file_name("motion.json"),
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx --seed N`: the judge measured on faults of known size. N props that rest as they should
|
||||
//! are each moved once (sunk into what they stand on, lifted a few millimetres off it, or lifted into the air), the
|
||||
//! lint run again, and the planted fault's finding judged. What it says: how many the lint found, and of those a camera
|
||||
//! sees at two pixels or more, how many the judge calls faults; of those no camera sees, how many it still calls one.
|
||||
//! Nothing is written: a planted fault's truth is its size, which the judge's own features already carry, so it
|
||||
//! measures the judge rather than teaching it.
|
||||
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_core_scene::{Item, label};
|
||||
use raea_sys_motionfaults::plant::Rng;
|
||||
use raea_sys_notice::{Cam, FAULT, Model, Scene, camera};
|
||||
|
||||
/// Props this big across or smaller are moved.
|
||||
const PROP: f32 = 1.2;
|
||||
/// Pixels a planted fault covers at the least to count as plain to see.
|
||||
const PLAIN: f32 = 2.0;
|
||||
|
||||
|
||||
fn moved(its: &[Item], name: &str, by: Vec3) -> Vec<Item> {
|
||||
its.iter().cloned().map(|mut it| {
|
||||
if (it.kind == "mesh" || it.kind == "model") && label(&it, "") == name {
|
||||
it.world = Mat4::from_translation(by) * it.world;
|
||||
}
|
||||
it
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(now: &[Item], next: &[Item], views: &[Vec<Item>], found: &[Value], w: u32, h: u32, model: &Model, n: usize) -> String {
|
||||
let count = |name: &str| now.iter().filter(|it| (it.kind == "mesh" || it.kind == "model") && label(it, "") == name).count();
|
||||
let props: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|v| v["check"] == "rests")
|
||||
.filter(|v| {
|
||||
let (lo, hi) = (&v["box"]["min"], &v["box"]["max"]);
|
||||
(0..3).all(|k| hi[k].as_f64().unwrap_or(9.0) - lo[k].as_f64().unwrap_or(0.0) <= PROP as f64)
|
||||
})
|
||||
.filter_map(|v| v["part"].as_str())
|
||||
.filter(|p| count(p) == 1)
|
||||
.collect();
|
||||
let cams: Vec<Cam> = views.iter().filter_map(|f| camera(f)).collect();
|
||||
// only props some camera of the shot sees (the middle of the box's top): a fault planted out of view tells
|
||||
// nothing of how the judge weighs one in it
|
||||
let scene = Scene::of(now);
|
||||
let in_view = |p: &str| {
|
||||
let Some(v) = found.iter().find(|v| v["part"] == p) else { return false };
|
||||
let at = |k: usize, e: &str| v["box"][e][k].as_f64().unwrap_or(0.0) as f32;
|
||||
let top = Vec3::new((at(0, "min") + at(0, "max")) / 2.0, at(1, "max") + 0.01, (at(2, "min") + at(2, "max")) / 2.0);
|
||||
raea_sys_notice::seen(&[raea_sys_notice::sight::Spot { at: top, facing: None, size: 0.0 }], false, &cams, &scene, w as f32, h as f32).shown > 0
|
||||
};
|
||||
let props: Vec<&str> = props.into_iter().filter(|p| in_view(p)).collect();
|
||||
if props.is_empty() {
|
||||
return "no prop the shot sees rests on anything to plant a fault in".into();
|
||||
}
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let (mut lines, mut lint_found, mut plain, mut plain_flagged, mut hidden, mut hidden_flagged, mut small, mut small_flagged) = (Vec::new(), 0, 0, 0, 0, 0, 0, 0);
|
||||
for i in 0..n {
|
||||
let part = props[(rng.next() * props.len() as f32) as usize % props.len()];
|
||||
let r = rng.next();
|
||||
let (kind, d) = if r < 0.4 { ("floats", 0.002 + rng.next() * 0.028) } else if r < 0.8 { ("sunk", 0.005 + rng.next() * 0.035) } else { ("air", 0.08 + rng.next() * 0.22) };
|
||||
let by = Vec3::new(0.0, if kind == "sunk" { -d } else { d }, 0.0);
|
||||
let (a, b) = (moved(now, part, by), moved(next, part, by));
|
||||
let (again, _) = raea_sys_contact::lint(&a, &b);
|
||||
let want = |c: &str| c == kind || (kind == "sunk" && c == "seated") || (kind == "air" && c == "floats") || (kind != "sunk" && c == "mounted");
|
||||
let Some(f) = again.iter().find(|v| v["part"] == part && v["check"].as_str().is_some_and(want)) else {
|
||||
// what it said of the part instead (a prop lifted against a wall reads as mounted on it)
|
||||
let said: Vec<&str> = again.iter().filter(|v| v["part"] == part).filter_map(|v| v["check"].as_str()).collect();
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: not found as {kind} (the lint said {})", d * 1000.0, said.join(", ")));
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
continue;
|
||||
};
|
||||
lint_found += 1;
|
||||
let scene = Scene::of(&a);
|
||||
let j = raea_sys_notice::judge_in(std::slice::from_ref(f), &scene, &cams, w, h, model);
|
||||
let Some(j) = j.first() else { continue };
|
||||
let flagged = j.p >= FAULT;
|
||||
if j.seen.shown == 0 {
|
||||
hidden += 1;
|
||||
hidden_flagged += flagged as usize;
|
||||
} else if j.seen.px >= PLAIN {
|
||||
plain += 1;
|
||||
plain_flagged += flagged as usize;
|
||||
} else {
|
||||
small += 1;
|
||||
small_flagged += flagged as usize;
|
||||
}
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: seen {}/{} frames, {:.1} px -> {:.2}{}", d * 1000.0, j.seen.shown, j.seen.frames, j.seen.px, j.p, if flagged { " FAULT" } else { "" }));
|
||||
// each trial lints the scene again (half a minute on a furnished room): said as it goes
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
}
|
||||
lines.push(format!(
|
||||
"planted {n} in {} props: the lint found {lint_found}; plain to see (>= {PLAIN} px) {plain}, judged faults {plain_flagged}; seen under {PLAIN} px {small}, judged faults {small_flagged}; no camera sees {hidden}, judged faults {hidden_flagged}",
|
||||
props.len()
|
||||
));
|
||||
lines.join("\n")
|
||||
}
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea make solid info and raea make solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
|
||||
description = "raea solid info and raea solid view: a solid file run, its parts measured (raea-core-solidinfo), and its review sheets in colour and clay"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
@@ -14,8 +14,11 @@ raea-core-facts = { path = "../../core/facts" }
|
||||
serde_json = "1"
|
||||
# --set's and the CLI's flags, read as the bundler reads them
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# a scene, kit or shot held to its plan (docs/goal.feature)
|
||||
# `raea judge`, dispatched with `raea solid` (verb())
|
||||
raea-app-judge = { path = "../judge" }
|
||||
raea-app-ask = { path = "../ask" }
|
||||
# a scene, kit or shot held to its plan (docs/make.feature)
|
||||
raea-app-make = { path = "../make" }
|
||||
# `raea make solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
|
||||
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
raea-core-meshcheck = { path = "../../core/meshcheck" }
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea make solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB]` (docs/blender.feature BL1):
|
||||
//! `raea solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB]` (docs/blender.feature BL1):
|
||||
//! a solid written as one .glb, metres, y up, so a Blender step can take it (bake.py for real UVs and baked maps, a
|
||||
//! cloth to fall on). The solid stays the source: the .glb is made again from it whenever it changes. An empty solid,
|
||||
//! or one solid info finds an error in, is refused with the findings. The file is read back and measured against the
|
||||
@@ -52,7 +52,7 @@ fn said(info: &Value, level: &str, part: Option<&str>) -> Vec<String> {
|
||||
}
|
||||
|
||||
pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[String]) -> Result<String, String> {
|
||||
let out = flag(args, "-o").filter(|o| o.ends_with(".glb")).ok_or("raea make solid export FILE.ts -o OUT.glb: give the .glb to write")?;
|
||||
let out = flag(args, "-o").filter(|o| o.ends_with(".glb")).ok_or("raea solid export FILE.ts -o OUT.glb: give the .glb to write")?;
|
||||
let part = flag(args, "--part");
|
||||
let chosen: Vec<&(String, String)> = parts.iter().filter(|(n, _)| part.as_deref().is_none_or(|p| p == n)).collect();
|
||||
if chosen.is_empty() {
|
||||
@@ -79,7 +79,7 @@ pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[Str
|
||||
let name = part.clone().unwrap_or_else(|| file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid").to_string());
|
||||
j["nodes"][0]["name"] = json!(name);
|
||||
j["meshes"][0]["name"] = json!(name);
|
||||
j["asset"]["generator"] = json!("raea make solid export");
|
||||
j["asset"]["generator"] = json!("raea solid export");
|
||||
if let Some(c) = flag(args, "--colour") {
|
||||
j["materials"] = json!([{"name": name, "pbrMetallicRoughness": {"baseColorFactor": linear(&c)?, "metallicFactor": 0.0, "roughnessFactor": 0.8}}]);
|
||||
j["meshes"][0]["primitives"][0]["material"] = json!(0);
|
||||
@@ -92,7 +92,7 @@ pub fn export(file: &Path, parts: &[(String, String)], info: &Value, args: &[Str
|
||||
if !diff.is_empty() {
|
||||
return Err(format!("solid export: {out} doesn't read back as the solid: {}", diff.join("; ")));
|
||||
}
|
||||
let side = json!({"source": format!("raea make solid export {}{}", file.display(), part.as_ref().map(|p| format!(" --part {p}")).unwrap_or_default()), "license": "built in code for this project", "credit": ""});
|
||||
let side = json!({"source": format!("raea solid export {}{}", file.display(), part.as_ref().map(|p| format!(" --part {p}")).unwrap_or_default()), "license": "built in code for this project", "credit": ""});
|
||||
std::fs::write(format!("{out}.json"), serde_json::to_string_pretty(&side).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
let r = |x: f64| (x * 1e5).round() / 1e5;
|
||||
let mut t = vec![format!(
|
||||
|
||||
+11
-9
@@ -1,11 +1,11 @@
|
||||
//! `raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
|
||||
//! `raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk]`: the file's solid measured
|
||||
//! (raea-core-solidinfo). FILE.ts exports `default`: a Solid, an object of named Solids (the parts), or a function
|
||||
//! of the params returning either; and optionally `params`, each a number, a boolean, or `[low, high, default]`. The
|
||||
//! file is run by `raea run` (a wrapper that prints each part's shape expression), then measured natively. --set
|
||||
//! builds it at other params and says what moved from the defaults; --walk moves each ranged param alone to each end
|
||||
//! and says which break it (more pieces, empty) and which reach no geometry. FILE.expect.json beside it is read when
|
||||
//! --expect isn't given. Errors exit 1, as scene lint. A part's `role` comes from the file's `roles` export ({body:
|
||||
//! "contain"}), its `at` from the line that names it. `raea make solid view` takes its pictures (view.rs); `raea make solid export`
|
||||
//! "contain"}), its `at` from the line that names it. `raea solid view` takes its pictures (view.rs); `raea solid export`
|
||||
//! writes it as a .glb for a Blender step (export.rs). Its `needs` export ({textured: true}) asks for what solids can't
|
||||
//! give yet: real UVs and baked maps name bake.py (docs/blender.feature BL14).
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde_json::{Map, Value, json};
|
||||
mod export;
|
||||
mod view;
|
||||
|
||||
pub const USAGE: &str = "raea make solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea make solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea make solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
|
||||
pub const USAGE: &str = "raea solid info FILE.ts [--json] [--set k=v,...] [--expect E.json] [--walk] (volume, box, pieces, genus per part; joints; predictions and mutants)\n raea solid view FILE.ts -o DIR [--set k=v,...] [--json] (the solid's parts in colour and clay from fixed cameras)\n raea solid export FILE.ts -o OUT.glb [--set k=v,...] [--part NAME] [--colour #RRGGBB] (the solid as one .glb for a Blender step, read back and checked)";
|
||||
|
||||
thread_local! {
|
||||
/// the last run file's `roles` and `needs` exports
|
||||
@@ -68,7 +68,7 @@ print("RAEA_SOLID_INFO " + JSON.stringify({{ params: p, spec, parts: exprs, role
|
||||
fn textured(out: &mut Value, file: &Path) {
|
||||
let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid");
|
||||
let f = raea_core_meshcheck::blender::fix("bake.py", &format!("media/{stem}.glb media/{stem}-baked.glb --into-colour"));
|
||||
let run = format!("raea make solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
|
||||
let run = format!("raea solid export {} -o media/{stem}.glb --colour #RRGGBB && {}", file.display(), f["run"].as_str().unwrap_or(""));
|
||||
let says = format!("its file asks for textures (needs.textured), and a solid's UVs are box projections: export it and bake real UVs and maps; fix: {run}");
|
||||
if let Some(a) = out["found"].as_array_mut() {
|
||||
a.push(json!({"check": "textures", "level": "warning", "says": says, "fix": {"blender": "bake.py", "run": run}}));
|
||||
@@ -91,11 +91,13 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// `raea make solid ...` and `raea make ...` (docs/goal.feature), the verbs that build a piece (engine/cli hands them
|
||||
/// over), or None for another verb.
|
||||
/// `raea solid ...`, `raea judge ...`, `raea make ...` (docs/make.feature) and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
|
||||
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
|
||||
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("solid") => Some(cli(args)),
|
||||
Some("judge") => Some(raea_app_judge::cli(args)),
|
||||
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
|
||||
Some("make") => Some(raea_app_make::cli(args)),
|
||||
_ => None,
|
||||
}
|
||||
@@ -132,7 +134,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
return export::export(&file, &parts, &out, args);
|
||||
}
|
||||
if verb == "view" {
|
||||
let dir = crate::view::out_dir(args).ok_or("raea make solid view FILE.ts -o DIR: give the folder for the sheets")?;
|
||||
let dir = crate::view::out_dir(args).ok_or("raea solid view FILE.ts -o DIR: give the folder for the sheets")?;
|
||||
return crate::view::view(&file, &set, &out, &dir, json_out);
|
||||
}
|
||||
out["params"] = params;
|
||||
@@ -177,7 +179,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
}
|
||||
// what it found as raea's one Finding (docs/direction.feature DR3), about the part, or the solid's file
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea make solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
|
||||
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
|
||||
let errors = found.iter().any(|f| f.level == Level::Error);
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
for k in ["found", "errors", "warnings"] {
|
||||
@@ -198,7 +200,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
t.push(format!("walk {} = {}: {}{}", w["param"].as_str().unwrap_or(""), w["value"], w["verdict"].as_str().unwrap_or(""), w["says"].as_str().map(|s| format!(" ({s})")).unwrap_or_default()));
|
||||
}
|
||||
t.push(format!("solid: {} m³, size {} m, {} pieces, genus {}, {} triangles", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"]));
|
||||
t.push(format!("raea make solid info: {}", finding::count(&found)));
|
||||
t.push(format!("raea solid info: {}", finding::count(&found)));
|
||||
t.join("\n")
|
||||
};
|
||||
if errors {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea make solid view FILE.ts -o DIR [--set k=v,...]`: one solid's review sheets (research note agent-tool-surface.md's
|
||||
//! `raea solid view FILE.ts -o DIR [--set k=v,...]`: one solid's review sheets (research note agent-tool-surface.md's
|
||||
//! `solid view`). The file's parts are put in a small scene, each on its own clay-friendly colour, on a slab under
|
||||
//! a key and fill light, with a hero camera from the front-right corner, and `raea render --review` takes the fixed
|
||||
//! views of it in colour and clay. It prints a sidecar: the sheets, the solid's box, whether it is in more than one
|
||||
|
||||
@@ -17,5 +17,5 @@ serde_json = "1"
|
||||
# the verbs' flags read as a render reads its own
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-runtime-export = { path = "../../runtime/export" }
|
||||
# `raea make motion` and `raea setup motion` (apps/motion), still reached as tools::motion
|
||||
# `raea motion` and `raea setup motion` (apps/motion), still reached as tools::motion
|
||||
raea-app-motion = { path = "../motion" }
|
||||
@@ -55,7 +55,7 @@ pub fn with_preface(text: &str, dir: &Path) -> String {
|
||||
return text.to_string();
|
||||
}
|
||||
let p = format!(
|
||||
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: a render checks its own output at its end (`raea check OUT.mp4`\n> checks one again), and `raea show FILE` puts media in front of the person.\n",
|
||||
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
|
||||
dir.join("raea").display()
|
||||
);
|
||||
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
|
||||
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
|
||||
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it checks nothing (a render checks its
|
||||
//! own output, docs/check.feature CK1) and only hands the session what the person sent from the raea app
|
||||
//! (apps/check/src/inbox.rs). Claude Code's run after every tool, and Claude Code's and Codex's as a turn ends too, where
|
||||
//! `raea check --at done` holds the brief's goals. An event that already has a `raea hook` entry keeps it, its matcher widened
|
||||
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
|
||||
//! composition. Claude Code's run after every tool and as a turn ends too, to hand the session what the person sent from
|
||||
//! the raea app (apps/check/src/inbox.rs). An event that already has a `raea hook` entry keeps it, its matcher widened
|
||||
//! to this raea's when an older raea wrote a narrower one.
|
||||
use crate::agent_mcp::user_home;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The verbs that run raea's local tools: sound (`raea make sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an
|
||||
//! instrument's notes made by local models, and the open sample libraries), `raea make splat` (footage trained into a
|
||||
//! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an
|
||||
//! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a
|
||||
//! Gaussian splat), `raea song` (a song's energy map, apps/tools/src/song.rs) and `raea gen` (generation flows on
|
||||
//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).
|
||||
|
||||
pub mod generate;
|
||||
/// `raea make motion` and `raea setup motion`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (apps/motion)
|
||||
/// `raea motion` and `raea setup motion`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (apps/motion)
|
||||
pub use raea_app_motion as motion;
|
||||
pub mod song;
|
||||
pub mod sound;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! raea's sound tools from the command line: the two local models (SAO for foley, TokenSynth for an instrument's notes)
|
||||
//! and the open sample libraries a Tone.js Sampler can play.
|
||||
//!
|
||||
//! raea make sao "PROMPT" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]
|
||||
//! raea make tokensynth "TIMBRE" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16]
|
||||
//! raea sao "PROMPT" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]
|
||||
//! raea tokensynth "TIMBRE" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16]
|
||||
//! [--dir EDIT_DIR] [-o OUT_DIR]
|
||||
//! raea setup-audio [--check] [sao|tokensynth]
|
||||
//! raea make sounds [WORDS...]
|
||||
//! raea make sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR]
|
||||
//! raea sounds [WORDS...]
|
||||
//! raea sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR]
|
||||
//!
|
||||
//! sao and tokensynth make through the same asset store a composition's render does (raea_io_assets::Store beside
|
||||
//! EDIT_DIR/edit.tsx, default the working folder), with the same parameters, so a sound made here is the one
|
||||
@@ -126,9 +126,9 @@ fn deliver(from: &Path, to: &Path) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const SAO_USAGE: &str = "raea make sao \"PROMPT\" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]";
|
||||
pub const SAO_USAGE: &str = "raea sao \"PROMPT\" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav]";
|
||||
|
||||
/// `raea make sao "PROMPT" [--seconds 2] [--seed 1] [--dir D] [-o OUT.wav]`: one foley sound, made once.
|
||||
/// `raea sao "PROMPT" [--seconds 2] [--seed 1] [--dir D] [-o OUT.wav]`: one foley sound, made once.
|
||||
pub fn sao(args: &[String]) -> R<String> {
|
||||
const USAGE: &str = SAO_USAGE;
|
||||
let prompt = positional(&args[1..], &["--seconds", "--seed", "--dir", "-o"]).join(" ");
|
||||
@@ -159,9 +159,9 @@ pub fn sao(args: &[String]) -> R<String> {
|
||||
Ok(format!("APPLIED sao {prompt:?}, {} s, seed {seed} -> {at} ({how}; asset {}){reuse}", js_num(seconds), &a.hash[..12]))
|
||||
}
|
||||
|
||||
pub const TOKENSYNTH_USAGE: &str = "raea make tokensynth \"TIMBRE\" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16] [--dir EDIT_DIR] [-o OUT_DIR]";
|
||||
pub const TOKENSYNTH_USAGE: &str = "raea tokensynth \"TIMBRE\" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16] [--dir EDIT_DIR] [-o OUT_DIR]";
|
||||
|
||||
/// `raea make tokensynth "TIMBRE" [--notes C2,C3,C4] ... [-o OUT_DIR]`: an instrument's root notes, one WAV each.
|
||||
/// `raea tokensynth "TIMBRE" [--notes C2,C3,C4] ... [-o OUT_DIR]`: an instrument's root notes, one WAV each.
|
||||
pub fn tokensynth(args: &[String]) -> R<String> {
|
||||
const USAGE: &str = TOKENSYNTH_USAGE;
|
||||
let timbre = positional(&args[1..], &["--notes", "--seconds", "--velocity", "--seed", "--precision", "--dir", "-o"]).join(" ");
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) fn synonyms(word: &str) -> Vec<&str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea make sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
|
||||
/// `raea sounds [WORDS...]`: the instruments whose names hold every word (all of them with no words, by pack).
|
||||
pub fn sounds(args: &[String]) -> R<String> {
|
||||
if args.get(1).map(String::as_str) == Some("get") {
|
||||
return sounds_get(args);
|
||||
@@ -70,7 +70,7 @@ pub fn sounds(args: &[String]) -> R<String> {
|
||||
if out.is_empty() {
|
||||
return Ok(format!("no instrument in the sample libraries matches {:?}: try one word (piano, snare, strings, marimba)", words.join(" ")));
|
||||
}
|
||||
Ok(format!("{}\n\nraea make sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
|
||||
Ok(format!("{}\n\nraea sounds get PACK/INSTRUMENT [--notes C2,C4] copies one into media/sounds/ and prints the Sampler for it", out.join("\n\n")))
|
||||
}
|
||||
|
||||
/// Percent-encode a URL path (spaces, commas and `#` in VCSL's names), keeping its slashes.
|
||||
@@ -106,16 +106,16 @@ pub(crate) fn static_path(p: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea make sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
|
||||
/// `raea sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR]`: an instrument's samples into the edit's
|
||||
/// media (default media/sounds/PACK-INSTRUMENT/), its licence beside them, and the TSX that plays them.
|
||||
pub(crate) fn sounds_get(args: &[String]) -> R<String> {
|
||||
const USAGE: &str = "raea make sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea make sounds WORDS finds one)";
|
||||
const USAGE: &str = "raea sounds get PACK/INSTRUMENT [--notes C2,C4 | --all] [--dir EDIT_DIR] [-o OUT_DIR] (raea sounds WORDS finds one)";
|
||||
let id = *positional(&args[2..], &["--notes", "--dir", "-o"]).first().ok_or(USAGE)?;
|
||||
let (pid, iid) = id.split_once('/').ok_or(USAGE)?;
|
||||
let c = catalog()?;
|
||||
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea make sounds lists them"))?;
|
||||
let pack = c["packs"].as_array().into_iter().flatten().find(|p| p["id"] == pid).ok_or(format!("no sample library `{pid}`: raea sounds lists them"))?;
|
||||
let inst = pack["instruments"].as_array().into_iter().flatten().find(|i| i["id"] == iid)
|
||||
.ok_or(format!("{pid} has no instrument `{iid}`: raea make sounds {iid} searches for it"))?;
|
||||
.ok_or(format!("{pid} has no instrument `{iid}`: raea sounds {iid} searches for it"))?;
|
||||
let files = files_of(pack, inst);
|
||||
let pitched_files: Vec<_> = files.iter().filter(|f| f.0.is_some()).cloned().collect();
|
||||
let pitched = pitched_files.iter().map(|f| f.0).collect::<std::collections::BTreeSet<_>>().len() >= 3;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Splats from footage: a video (or a folder of pictures) of a real place or thing trained into a 3D Gaussian splat for
|
||||
//! `<Splat src>` (raea_io_assets::Store::splat; tools/splat: frames, COLMAP, Brush on Metal).
|
||||
//!
|
||||
//! raea make splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames N] [--steps N] [--max-res PX] [--from S]
|
||||
//! raea splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames N] [--steps N] [--max-res PX] [--from S]
|
||||
//! [--seconds N] [--max-splats N] [--matte black] [--match sequential|exhaustive]
|
||||
//! [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]
|
||||
//! raea make splat setup
|
||||
//! raea splat setup
|
||||
//!
|
||||
//! Goes through the asset store beside EDIT_DIR/edit.tsx (default the working folder), so the same footage and params
|
||||
//! train once; OUT.ply is a copy of the store's `<hash>.ply` and OUT.ply.json of its sidecar (with --credit and
|
||||
@@ -17,7 +17,7 @@ use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea make splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames 150] [--steps 20000] [--max-res 1600] [--from S] [--seconds N] [--max-splats 2000000] [--matte none|black] [--match sequential|exhaustive] [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]\n raea make splat setup";
|
||||
pub const USAGE: &str = "raea splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames 150] [--steps 20000] [--max-res 1600] [--from S] [--seconds N] [--max-splats 2000000] [--matte none|black] [--match sequential|exhaustive] [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]\n raea splat setup";
|
||||
const WITH_VALUE: [&str; 13] = ["--frames", "--steps", "--max-res", "--from", "--seconds", "--max-splats", "--matte", "--match", "--credit", "--license", "--dir", "-o", "--o"];
|
||||
|
||||
/// The CLI's input and params (what Store::splat is asked), checked: (input, params JSON).
|
||||
@@ -57,7 +57,7 @@ pub fn parse(args: &[String]) -> R<(PathBuf, Value)> {
|
||||
Ok((input, raea_io_assets::splat_params(&Value::Object(p))?))
|
||||
}
|
||||
|
||||
/// `raea make splat ...`
|
||||
/// `raea splat ...`
|
||||
pub fn splat(args: &[String]) -> R<String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("setup") => {
|
||||
|
||||
@@ -14,7 +14,7 @@ raea-io-assets = { path = "../../io/assets" }
|
||||
serde_json = "1"
|
||||
# a project's compositions and components read from their source (docs/projects.feature PJ8)
|
||||
raea-app-registry = { path = "registry" }
|
||||
# the project's record of what renders and checks found, which raea goal next reads (docs/direction.feature DR3)
|
||||
# the project's record of what renders and checks found, which raea next reads (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a command's words (its arguments that aren't flags or their values), read as raea check reads them
|
||||
raea-app-check = { path = "../check" }
|
||||
@@ -1,11 +1,11 @@
|
||||
//! A project's compositions and components, registered by reading its files (docs/projects.feature PJ8),
|
||||
//! so the raea app, `raea project scan`, `raea doctor` and `raea goal next` agree on what each file is:
|
||||
//! so the raea app, `raea project scan`, `raea doctor` and `raea next` agree on what each file is:
|
||||
//! - a composition is each <Composition> a registerRoot registers (its props read from the source, not rendered), or a
|
||||
//! .tsx's default export with none that no other file imports, registered for it under its file's name (versions
|
||||
//! NAME-vN.tsx are one composition), sized from its newest render's manifest when it has one;
|
||||
//! - a component is a .tsx a composition imports, directly or through another.
|
||||
//! What isn't connected is linted (lint.rs), each with its file and line and the fix. raea-app-workspace runs `scan`
|
||||
//! for `raea project scan`, `raea doctor`, `raea goal next` and `raea context`.
|
||||
//! for `raea project scan`, `raea doctor`, `raea next` and `raea context`.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
format!("imports {} from outside the project", tilde(&to)),
|
||||
&match in_shared {
|
||||
Some(r) => format!("import it by the workspace's name for it: \"@shared/{}\"", r.with_extension("").to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/")),
|
||||
None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea make component add, for raea's sets)".into(),
|
||||
None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea component add, for raea's sets)".into(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
@@ -86,12 +86,12 @@ fn old_controllers(base: &Path, ws: Option<&Path>, out: &mut Vec<Finding>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A brief.ts that still keeps tasks in `stages` (docs/plan.feature PL8a): they read, unread, and belong in plan.ts.
|
||||
/// A brief.ts that still keeps tasks in `stages` (docs/plan.feature PL8a): they read, unread, and belong in plan.org.
|
||||
fn briefs_with_tasks(base: &Path, out: &mut Vec<Finding>) {
|
||||
let f = base.join("brief.ts");
|
||||
let Ok(text) = std::fs::read_to_string(&f) else { return };
|
||||
if text.lines().any(|l| l.trim_start().starts_with("stages:") || l.trim_start().starts_with("\"stages\":")) {
|
||||
let says = format!("{}: keeps tasks in `stages`, which raea no longer reads; move each to the project's plan.ts (a task under its stage, its mark as its keyword: TODO, DONE or DROPPED), then delete `stages`", f.display());
|
||||
let says = format!("{}: keeps tasks in `stages`, which raea no longer reads; move each to the project's plan.org (an Org heading under its stage, its mark as TODO, DONE or DROPPED), then delete `stages`", f.display());
|
||||
out.push(Finding { says, fix: Fix::No });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `raea goal next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
|
||||
//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
|
||||
//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, and
|
||||
//! from the project's record (docs/direction.feature DR3) its renders and their checks and what each found. A menu for
|
||||
//! the agent or the person to pick from; nothing runs.
|
||||
@@ -97,10 +97,10 @@ pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea goal next`'s text.
|
||||
/// `raea next`'s text.
|
||||
pub fn text(dir: &Path, brief: &Brief, stale: usize) -> String {
|
||||
let s = steps(dir, brief, stale);
|
||||
let mut t = format!("raea goal next: {}\n", dir.display());
|
||||
let mut t = format!("raea next: {}\n", dir.display());
|
||||
for (i, line) in s.iter().enumerate() {
|
||||
t.push_str(&format!("{}. {line}\n", i + 1));
|
||||
}
|
||||
|
||||
@@ -91,8 +91,8 @@ fn doctor_connects_a_projects_files() {
|
||||
// a controller from before 11-20 is told where its parts go, and kept
|
||||
let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &[], "0.0.1", &|_| Ok(String::new())).unwrap();
|
||||
assert!(out.starts_with("APPLIED 2 of 5 fixed") && out.contains("controllers/pace.ts: a controller, which raea no longer reads") && out.contains("taste.ts"), "{out}");
|
||||
// a brief's old tasks are said to belong in plan.ts (docs/plan.feature PL8a), and kept
|
||||
assert!(out.contains("brief.ts: keeps tasks in `stages`") && out.contains("plan.ts"), "{out}");
|
||||
// a brief's old tasks are said to belong in plan.org (docs/plan.feature PL8a), and kept
|
||||
assert!(out.contains("brief.ts: keeps tasks in `stages`") && out.contains("plan.org"), "{out}");
|
||||
assert!(d.join("controllers/pace.ts").is_file() && std::fs::read_to_string(d.join("brief.ts")).unwrap().contains("stages"), "nothing of the person's is deleted");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// A set as blender/lightbake.py left it (docs/bake.feature BK0): one <Model> of its meshes, each with its Cycles
|
||||
// lightmap and the exposure that puts the bake at raea's brightness, from the .lightmaps.json lightbake.py wrote. A
|
||||
// mesh lightbake.py left unbaked (a metal) is drawn as raea draws it. `raea make bake light --compare` makes media/baked/.
|
||||
// mesh lightbake.py left unbaked (a metal) is drawn as raea draws it. `raea bake light --compare` makes media/baked/.
|
||||
import { staticFile } from "raea";
|
||||
import { Model } from "raea/3d";
|
||||
import { Lightmap, StandardMaterial } from "raea/pbr";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The cornell set with Cycles' bounce light baked into its lightmaps by blender/lightbake.py, any sun left live: what raea's
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/cornell/.
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea bake light --compare` makes media/baked/cornell/.
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
import { Baked } from "./baked";
|
||||
import { Look } from "./parts/cornell";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The table set with Cycles' bounce light baked into its lightmaps by blender/lightbake.py, any sun left live: what raea's
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/table/.
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea bake light --compare` makes media/baked/table/.
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
import { Baked } from "./baked";
|
||||
import { Look } from "./parts/table";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The window set with Cycles' bounce light baked into its lightmaps by blender/lightbake.py, any sun left live: what raea's
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea make bake light --compare` makes media/baked/window/.
|
||||
// own bake is measured against (docs/bake.feature BK0). `raea bake light --compare` makes media/baked/window/.
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
import { Baked } from "./baked";
|
||||
import { Look } from "./parts/window";
|
||||
|
||||
+6
-6
@@ -17,7 +17,6 @@
|
||||
set -uo pipefail
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
cd "$ROOT"
|
||||
. bench/lib/compare.sh
|
||||
# renders compared by their pixels are no exports: unsigned and unwatermarked (a TrustMark id differs per render; CI sets it too)
|
||||
export RAEA_SIGN=0
|
||||
PIXELS=0
|
||||
@@ -76,7 +75,8 @@ if [ $PIXELS = 1 ]; then
|
||||
case "$out" in *PASS*) line S2d PASS "a typed query on the host's World (HostWorld) in a plain App, a reflected component never shared: ${out#host_query: PASS }" ;; *) line S2d FAIL "a typed query on the host's World: ${out:-no result}" ;; esac
|
||||
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render edit.tsx --at 30 -o "$WORK/ref/") > "$WORK/render.log" 2>&1
|
||||
target/release/examples/plain_page "$WORK/edit.js" "$WORK/plain.png" 1280 720 30 30 > "$WORK/plain.log" 2>&1
|
||||
whole=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png") title=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png" crop=400:120:40:30)
|
||||
ssim() { ffmpeg -hide_banner -nostats -i "${REF:-$WORK/ref/frame-00000.png}" -i "${GOT:-$WORK/plain.png}" -lavfi "[0:v]format=rgb24${1}[a];[1:v]format=rgb24${1}[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2; }
|
||||
whole=$(ssim "") title=$(ssim ",crop=400:120:40:30")
|
||||
if [ -z "$whole" ]; then line H5 FAIL "the page over a plain App's scene: no frame (see plain_page, raea render)"
|
||||
else
|
||||
awk -v s="$whole" 'BEGIN { exit !(s >= 0.998) }' && line H5 PASS "the page over a plain App's scene (classbg frame 30, SSIM $whole against raea)" || line H5 FAIL "the page over a plain App's scene (classbg frame 30, SSIM $whole < 0.998)"
|
||||
@@ -101,14 +101,14 @@ if [ $PIXELS = 1 ]; then
|
||||
# would match too)
|
||||
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render video.tsx --at 30 -o "$WORK/vref/") > "$WORK/vrender.log" 2>&1
|
||||
target/release/examples/plain_page "$WORK/video.js" "$WORK/video.png" 1280 720 30 30 > "$WORK/video.log" 2>&1
|
||||
v=$(ssim "$WORK/vref/frame-00000.png" "$WORK/video.png" crop=320:568:80:60)
|
||||
v=$(REF=$WORK/vref/frame-00000.png GOT=$WORK/video.png ssim ",crop=320:568:80:60")
|
||||
mean=$(ffmpeg -v error -i "$WORK/video.png" -vf "crop=320:568:80:60,scale=1:1" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p)
|
||||
if [ -n "$v" ] && [ "$mean" != 1b2230 ] && awk -v s="$v" 'BEGIN { exit !(s >= 0.999) }'; then line H11 PASS "a video playing inside a page in a plain App (its area SSIM $v against raea)"
|
||||
else line H11 FAIL "a video playing inside a page in a plain App (SSIM ${v:-none}, mean ${mean:-none})"; fi
|
||||
# a <Screen>: the frame against raea's, and its page on it: red at its middle, the card blue, black around
|
||||
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render screen.tsx --at 30 -o "$WORK/sref/") > "$WORK/srender.log" 2>&1
|
||||
target/release/examples/plain_page "$WORK/screen.js" "$WORK/screen.png" 1280 720 30 30 > "$WORK/screen.log" 2>&1
|
||||
sc=$(ssim "$WORK/sref/frame-00000.png" "$WORK/screen.png")
|
||||
sc=$(REF=$WORK/sref/frame-00000.png GOT=$WORK/screen.png ssim "")
|
||||
at() { ffmpeg -v error -i "$WORK/screen.png" -vf "crop=1:1:$1:$2" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p; }
|
||||
if [ -n "$sc" ] && awk -v s="$sc" 'BEGIN { exit !(s >= 0.995) }' && [ "$(at 640 360)" = ff3030 ] && [ "$(at 794 424)" = 2040ff ] && [ "$(at 100 100)" = 000000 ]; then
|
||||
line H5 PASS "a <Screen>'s nested composition on its screen in a plain App (SSIM $sc against raea)"
|
||||
@@ -117,8 +117,8 @@ if [ $PIXELS = 1 ]; then
|
||||
# the page under the sphere and over it
|
||||
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render layers.tsx --at 30 -o "$WORK/lref/") > "$WORK/lrender.log" 2>&1
|
||||
target/release/examples/plain_page "$WORK/layers.js" "$WORK/layers.png" 960 540 30 30 > "$WORK/layers.log" 2>&1
|
||||
L() { ssim "$WORK/lref/frame-00000.png" "$WORK/layers.png" "$@"; }
|
||||
lw=$(L) lu=$(L crop=240:80:20:20) lo=$(L crop=900:40:0:250)
|
||||
L() { REF=$WORK/lref/frame-00000.png GOT=$WORK/layers.png ssim "$1"; }
|
||||
lw=$(L "") lu=$(L ",crop=240:80:20:20") lo=$(L ",crop=900:40:0:250")
|
||||
if [ "$lw" = 1.000000 ] && [ "$lu" = 1.000000 ] && [ "$lo" = 1.000000 ]; then
|
||||
line H5 PASS "a layered Canvas3D in a plain App: the page under and over its 3D as raea's (SSIM $lw; under $lu, over $lo)"
|
||||
else line H5 FAIL "a layered Canvas3D in a plain App (SSIM ${lw:-none}; under ${lu:-none}, over ${lo:-none})"; fi
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# The bench checks L2 runs on every release candidate (tools/l2.sh), each with that commit's raea as RAEA_BIN; each
|
||||
# must exit 0. They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault
|
||||
# carries the fault. These say what is right.
|
||||
#
|
||||
# A frame drawn alone or out of order (--at, --frame) agrees with the render of every frame (docs/stage-guards.feature
|
||||
# SG17). 0.1.9 drew a CSS animation in a frame alone from the earliest <Sequence>'s start, or from the frame itself.
|
||||
bench/at-0/check.sh
|
||||
bench/at-time/check.sh
|
||||
bench/at-3d/check.sh
|
||||
bench/compute-frames/check.sh
|
||||
sdk/react/bench/css/check.sh
|
||||
@@ -1,8 +0,0 @@
|
||||
# The bench checks L2 (tools/l2.sh) does not run. L2 runs every bench/**/check.sh and sdk/**/check.sh, and
|
||||
# tools/settle-nudge.sh and tools/frame-pure-3d.sh, each with the release candidate's raea as RAEA_BIN; each must
|
||||
# exit 0.
|
||||
# They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault carries the fault.
|
||||
# These say what is right.
|
||||
#
|
||||
# A check is left out only with its reason, one per line: PATH WHY (what it needs that L2 can't give, or the issue
|
||||
# that tracks its failure). A check whose subject is gone is deleted, not listed here.
|
||||
@@ -1,27 +0,0 @@
|
||||
# shellcheck shell=sh disable=SC3043 # local: every shell that sources this has it
|
||||
# The bench checks' frame comparison, sourced by every script that scores two frames by SSIM so that all of them
|
||||
# measure the same thing. POSIX sh: sh, bash and zsh scripts source it alike.
|
||||
#
|
||||
# . "$ROOT/bench/lib/compare.sh"
|
||||
# s=$(ssim A B [FILTER_A [FILTER_B]])
|
||||
#
|
||||
# ssim prints ffmpeg's SSIM of two images, both read as 8-bit RGB (an alpha channel is dropped, not blended): the
|
||||
# "All" value to six decimals, 1.000000 for identical pixels. FILTER_A is an ffmpeg filter chain applied to A before
|
||||
# the conversion (crop=400:120:40:30), FILTER_B the same for B (default: FILTER_A). It prints nothing when ffmpeg
|
||||
# can't compare them (a file missing or unreadable, or the two sizes differ), so a caller's ${s:-none} or ${s:-0}
|
||||
# says which.
|
||||
#
|
||||
# What the number can and can't see. The same binary rendering a frame twice repeats at 0.99998 or more
|
||||
# (bench/p26-baseline), and a deband dither keyed to screen position, 2/255 at most, keeps 0.999 (sdk/raea/bench/bevy/
|
||||
# view). But whole-frame SSIM forgives a small subject and a small slip: a sequence's frame 28 against frame 29 alone
|
||||
# scored 0.986 (docs/stage-guards.feature SG0), a cut glyph 0.9996, a sprite on the wrong cell 0.989 (tools/
|
||||
# bevy-parity). A bar under 0.999 passes a one-frame slip; a check that must catch a small subject measures it apart
|
||||
# (a crop, a tile, a box).
|
||||
ssim() {
|
||||
local fa fb
|
||||
fa=${3:+$3,}
|
||||
fb=${4:-${3:-}}
|
||||
fb=${fb:+$fb,}
|
||||
ffmpeg -nostdin -hide_banner -nostats -i "$1" -i "$2" -lavfi "[0:v]${fa}format=rgb24[a];[1:v]${fb}format=rgb24[b];[a][b]ssim" \
|
||||
-f null - 2>&1 | grep -o 'All:[0-9.]*' | tail -1 | cut -d: -f2
|
||||
}
|
||||
@@ -16,6 +16,7 @@ mkdir -p "$OUT"
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
expected() { case $1 in
|
||||
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
|
||||
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
|
||||
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
#!/bin/bash
|
||||
# P26's baseline (docs/ts-native.feature P26a): frames of every composition in list.txt rendered by the published raea
|
||||
# 0.1.9, the reference every later page must match (SSIM >= 0.999 per frame, compare.sh's bar, fonts and brand styles
|
||||
# included). It was the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9
|
||||
# on 11-22.
|
||||
# 0.1.9, the reference every later page must match (SSIM >= 0.98 per frame, fonts and brand styles included). It was
|
||||
# the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9 on 11-22.
|
||||
#
|
||||
# bench/p26-baseline/capture.sh [RAEA_BIN] (default: 0.1.9's raea, unpacked at
|
||||
# ~/Library/Caches/raea/p26-baseline/bin-v0.1.9, P26_STORE to move it)
|
||||
|
||||
Loaded 100 of 2055 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user