mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f86933383b |
No files matched your search
@@ -83,7 +83,7 @@ pub struct CutPlan {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "CutBeat")]
|
||||
#[ts(rename = "Beat")]
|
||||
pub struct Beat {
|
||||
/// where it starts, in seconds from the cut's start (0 for the first)
|
||||
pub at: f64,
|
||||
|
||||
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
|
||||
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
|
||||
pub fn goal_declarations() -> String {
|
||||
let cfg = Config::new();
|
||||
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
|
||||
// a cut's beats are a script's (script.rs Beat)
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
|
||||
out.extend(decls!(cfg;
|
||||
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
|
||||
@@ -103,20 +103,6 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
|
||||
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
|
||||
And every other raea command runs on the box
|
||||
|
||||
Scenario: CL16. raea cloud's boxes are Fly Machines
|
||||
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
|
||||
read and stopped at 8 cores and 16 GB (12-03)
|
||||
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
|
||||
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
|
||||
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
|
||||
project's folders and paths are the same
|
||||
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
|
||||
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
|
||||
proxy starts it again at the next request
|
||||
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
|
||||
straight to the new box's file API), and puts every box on a release (latest)
|
||||
And a file PUT to a box streams to disk and lands whole, never held in memory
|
||||
|
||||
Rule: it is proven end to end
|
||||
Scenario: CL12. A stand-in agent, then a real one
|
||||
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
|
||||
|
||||
@@ -2,6 +2,3 @@ node_modules
|
||||
deploy
|
||||
test
|
||||
README.md
|
||||
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
|
||||
!deploy/git
|
||||
!deploy/fly/start.sh
|
||||
@@ -1,71 +0,0 @@
|
||||
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
|
||||
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
|
||||
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
|
||||
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
|
||||
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
|
||||
# deploy/fly/box.sh builds it from sdk/cloud:
|
||||
#
|
||||
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
|
||||
FROM ubuntu:26.04
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
|
||||
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
|
||||
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
|
||||
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
|
||||
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
|
||||
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
|
||||
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
|
||||
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
|
||||
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
|
||||
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG NODE=24.22.0
|
||||
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
|
||||
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
|
||||
|
||||
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
|
||||
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
|
||||
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
|
||||
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
|
||||
&& ln -s /home/raea /home/sprite
|
||||
|
||||
# raea, checked against its release's .sha256
|
||||
ARG RAEA_VERSION
|
||||
ARG RAEA_REPO=shinyobjectz/raea
|
||||
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
|
||||
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
|
||||
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
|
||||
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
|
||||
&& /opt/raea/bin/raea --version
|
||||
|
||||
WORKDIR /opt/raea-cloud
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
|
||||
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
|
||||
COPY server server
|
||||
ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
COPY deploy/git deploy/git
|
||||
COPY deploy/fly/start.sh image/fly-start.sh
|
||||
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
|
||||
# the entrypoint 711, and it re-runs itself as raea)
|
||||
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
|
||||
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
|
||||
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
|
||||
&& git lfs install --system --skip-repo > /dev/null
|
||||
|
||||
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
|
||||
ARG COMMIT=unknown
|
||||
ARG DIRTY=false
|
||||
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
|
||||
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
|
||||
|
||||
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
|
||||
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/bin/bash
|
||||
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
|
||||
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
|
||||
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
|
||||
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
|
||||
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
|
||||
#
|
||||
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
|
||||
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
|
||||
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
|
||||
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
|
||||
# settings and Machine, then its health
|
||||
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
|
||||
# changes address) and its home folder copied, then listed in raea cloud
|
||||
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
|
||||
# deploy/fly/box.sh status NAME its address, Machine and health
|
||||
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
|
||||
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
|
||||
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
|
||||
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
|
||||
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
|
||||
#
|
||||
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
|
||||
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
|
||||
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
|
||||
set -euo pipefail
|
||||
REPO=shinyobjectz/raea
|
||||
HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
CONF=$HOME/.config/raea-cloud
|
||||
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
|
||||
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
|
||||
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
|
||||
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
|
||||
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
|
||||
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
|
||||
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
|
||||
fi
|
||||
REGION=${RAEA_FLY_REGION:-iad}
|
||||
SIZE=${RAEA_BOX_SIZE:-performance-8x}
|
||||
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
|
||||
IMAGE_APP=raea-box-image
|
||||
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
|
||||
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
|
||||
NAME=${2:-}
|
||||
app() { echo "raea-box-${1#raea-}"; }
|
||||
url() { echo "https://$(app "$1").fly.dev"; }
|
||||
envfile() { echo "$CONF/boxes/$1.env"; }
|
||||
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
|
||||
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
|
||||
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
|
||||
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
|
||||
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
|
||||
print(m[0]["id"] if m else "")'; }
|
||||
healthy() {
|
||||
local u t
|
||||
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
|
||||
for _ in $(seq 1 60); do
|
||||
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
|
||||
sleep 5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
image)
|
||||
version=${2:-${RAEA_VERSION:-$(newest)}}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
src=$HERE
|
||||
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
|
||||
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
|
||||
src=$(mktemp -d)
|
||||
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
|
||||
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
|
||||
src=$src/sdk/cloud
|
||||
commit=$RAEA_CLOUD_REF dirty=false
|
||||
else
|
||||
commit=$(git -C "$HERE" rev-parse HEAD)
|
||||
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
|
||||
fi
|
||||
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
|
||||
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
|
||||
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
|
||||
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
|
||||
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
|
||||
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
|
||||
;;
|
||||
up)
|
||||
need_name
|
||||
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
|
||||
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
|
||||
a=$(app "$NAME") f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
if [ ! -s "$f" ]; then
|
||||
# a new box: its own token, and the farm's settings
|
||||
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
|
||||
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
|
||||
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
|
||||
fi
|
||||
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
|
||||
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
|
||||
fly ips allocate-v4 --shared -a "$a" > /dev/null
|
||||
fly ips allocate-v6 -a "$a" > /dev/null
|
||||
}
|
||||
# the box's settings as Fly secrets, from the file (never on a command line)
|
||||
fly secrets import --stage -a "$a" < "$f" > /dev/null
|
||||
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
|
||||
id=$(machine "$NAME")
|
||||
if [ -z "$id" ]; then
|
||||
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
|
||||
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
|
||||
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
|
||||
# ~/.raea-cloud.env on its volume (start.sh)
|
||||
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
|
||||
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
|
||||
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
|
||||
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
|
||||
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
|
||||
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
|
||||
fi
|
||||
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
|
||||
"$0" status "$NAME"
|
||||
;;
|
||||
move)
|
||||
need_name
|
||||
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
|
||||
. "$(dirname "$0")/../sprites/org.sh"
|
||||
f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
|
||||
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
|
||||
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
|
||||
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
|
||||
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
|
||||
# sprite exec it came at about 4 MB/s), then unpacked there
|
||||
a=$(app "$NAME")
|
||||
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
|
||||
healthy "$NAME" > /dev/null || true
|
||||
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
|
||||
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
|
||||
else
|
||||
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
|
||||
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
|
||||
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
|
||||
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
|
||||
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
|
||||
sending=$!
|
||||
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
|
||||
# out (12-03, Shane: fail fast at every step)
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
|
||||
got=-1 since=$SECONDS
|
||||
while kill -0 "$sending" 2> /dev/null; do
|
||||
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
|
||||
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
|
||||
except Exception: print(-1)')
|
||||
if [ "${n:--1}" -gt "$got" ]; then
|
||||
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
|
||||
got=$n since=$SECONDS
|
||||
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
|
||||
kill "$sending" 2> /dev/null
|
||||
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
|
||||
exit 1
|
||||
fi
|
||||
sleep 15
|
||||
done
|
||||
wait "$sending"
|
||||
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
|
||||
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
|
||||
fi
|
||||
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
|
||||
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
|
||||
# first, as fly ssh doesn't start a stopped Machine
|
||||
healthy "$NAME" > /dev/null || true
|
||||
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
|
||||
# real-path match
|
||||
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
|
||||
# its own settings on its disk too, as a Sprite kept them
|
||||
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
|
||||
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
|
||||
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
|
||||
;;
|
||||
register)
|
||||
need_name
|
||||
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
|
||||
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
|
||||
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
|
||||
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
|
||||
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
|
||||
;;
|
||||
status)
|
||||
need_name
|
||||
echo "$(url "$NAME") machine $(machine "$NAME")"
|
||||
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
|
||||
echo
|
||||
;;
|
||||
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
|
||||
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
|
||||
latest)
|
||||
version=${2:-$(newest)}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
linux=raea-$version-linux-x86_64.tar.gz
|
||||
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
|
||||
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
|
||||
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
|
||||
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
|
||||
failed=""
|
||||
for b in $names; do
|
||||
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
|
||||
echo "fly box: $b onto raea $version (${ref:0:10})"
|
||||
"$0" up "$b" > /dev/null || failed+=" $b"
|
||||
done
|
||||
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
|
||||
echo "fly box: every Fly box is on raea $version"
|
||||
;;
|
||||
key)
|
||||
need_name
|
||||
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
|
||||
k=$(printf %s "$k" | tr -d '[:space:]')
|
||||
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
|
||||
f=$(envfile "$NAME")
|
||||
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
|
||||
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
|
||||
;;
|
||||
sh)
|
||||
need_name
|
||||
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
|
||||
;;
|
||||
*)
|
||||
sed -n '2,25p' "$0"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -1,7 +0,0 @@
|
||||
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
|
||||
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
|
||||
app = "raea-box-image"
|
||||
primary_region = "iad"
|
||||
|
||||
[build]
|
||||
dockerfile = "Dockerfile"
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/bin/bash
|
||||
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
|
||||
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
|
||||
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
|
||||
# stopped until Fly's proxy starts it for the next request.
|
||||
set -uo pipefail
|
||||
H=/home/raea
|
||||
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
|
||||
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
|
||||
BOX=${BOX/raea-box-/raea-}
|
||||
mkdir -p "$H/work"
|
||||
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
|
||||
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
|
||||
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
|
||||
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
|
||||
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
|
||||
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
|
||||
if [ -s "$H/.raea-cloud.env" ]; then
|
||||
while IFS='=' read -r k v; do
|
||||
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
|
||||
[ -n "${!k:-}" ] || export "$k=$v"
|
||||
done < "$H/.raea-cloud.env"
|
||||
fi
|
||||
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
|
||||
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
|
||||
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
|
||||
[ -n "${!k:-}" ] && echo "$k=${!k}"
|
||||
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
|
||||
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
|
||||
# the folders and paths of projects made on a Sprite are the same here
|
||||
export RAEA_CLOUD_WORK=/home/sprite/work
|
||||
# the box's commits say which box made them
|
||||
[ -s "$H/.gitconfig" ] || {
|
||||
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
|
||||
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
|
||||
sudo -u raea HOME=$H git config --global init.defaultBranch main
|
||||
}
|
||||
python3 - "$BOX" << 'PY'
|
||||
import json, sys
|
||||
p = "/opt/raea-cloud/BUILD.json"
|
||||
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
|
||||
PY
|
||||
exec /opt/raea-cloud/image/entrypoint.sh
|
||||
@@ -247,10 +247,8 @@ class Log:
|
||||
SCALEDOWN = 2
|
||||
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
|
||||
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 180 since
|
||||
# 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
|
||||
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
|
||||
CPU_SCALEDOWN = 180
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
|
||||
CPU_SCALEDOWN = 60
|
||||
|
||||
|
||||
def on(gpus, job):
|
||||
|
||||
@@ -94,19 +94,6 @@ PARTS = 4
|
||||
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
|
||||
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
|
||||
CPU_PARTS = 2
|
||||
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
|
||||
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
|
||||
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
|
||||
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
|
||||
# the bill by.
|
||||
FLAT_PART = 24
|
||||
FLAT_FRAME_S = 0.6
|
||||
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
|
||||
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
|
||||
# 81 s where the others took 11-15, and the whole render waited on it)
|
||||
HEDGE_SHARE = 0.7
|
||||
HEDGE_AFTER = 1.5
|
||||
HEDGE_MIN_S = 8.0
|
||||
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
|
||||
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
|
||||
PART_START = 5.0
|
||||
@@ -267,81 +254,6 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
|
||||
return code
|
||||
|
||||
|
||||
def _ready(h):
|
||||
"""a spawned run's answer, the exception it raised, or None while it's still running"""
|
||||
try:
|
||||
return h.get(timeout=0)
|
||||
except Exception as e:
|
||||
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
|
||||
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
|
||||
return None
|
||||
return e
|
||||
|
||||
|
||||
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
|
||||
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
|
||||
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
|
||||
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
|
||||
to the same files wherever it runs, so either answer is the run's."""
|
||||
if not calls:
|
||||
return 0
|
||||
pause = pause or time.sleep
|
||||
if most and len(calls) > most:
|
||||
fn = fn.with_options(max_containers=most)
|
||||
code = 0
|
||||
t0 = clock()
|
||||
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
|
||||
took = []
|
||||
while out:
|
||||
for first in list(out):
|
||||
o = out[first]
|
||||
r = None
|
||||
for h in o["h"]:
|
||||
r = _ready(h)
|
||||
if r is not None:
|
||||
break
|
||||
if r is None:
|
||||
continue
|
||||
for h in o["h"]:
|
||||
try:
|
||||
h.cancel()
|
||||
except Exception:
|
||||
pass
|
||||
del out[first]
|
||||
took.append(clock() - o["at"])
|
||||
if isinstance(r, Exception):
|
||||
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
|
||||
if again is not None:
|
||||
again.append(o["call"])
|
||||
else:
|
||||
code = code or 1
|
||||
continue
|
||||
if bill:
|
||||
bill.add(r)
|
||||
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
|
||||
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
|
||||
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
|
||||
again.append(o["call"])
|
||||
continue
|
||||
if got is not None:
|
||||
got.append(r)
|
||||
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
|
||||
if r["code"]:
|
||||
log(r["out"], err=True)
|
||||
code = code or r["code"]
|
||||
if not out:
|
||||
break
|
||||
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
|
||||
slow = max(took)
|
||||
for first, o in out.items():
|
||||
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
|
||||
o["again"] = True
|
||||
o["h"].append(fn.spawn(*o["call"]))
|
||||
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
|
||||
pause(wait_s)
|
||||
return code
|
||||
|
||||
|
||||
def timed(r, n):
|
||||
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
|
||||
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
|
||||
@@ -412,10 +324,6 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
nv = bool((p.get("manifest") or {}).get("has3d"))
|
||||
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
|
||||
r0 = None
|
||||
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
|
||||
quick = bool(flat and p.get("keys"))
|
||||
if quick:
|
||||
n0 = 0
|
||||
first = list(range(at0, at0 + n0))
|
||||
if flat and n0:
|
||||
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
|
||||
@@ -436,22 +344,17 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
if r0 and r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
|
||||
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
|
||||
left = todo - n0
|
||||
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
|
||||
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
|
||||
if quick:
|
||||
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
|
||||
else:
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
|
||||
parts = f" in {k * m} parts" if m > 1 else ""
|
||||
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
|
||||
if r0:
|
||||
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
|
||||
elif quick and left:
|
||||
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
|
||||
else:
|
||||
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
|
||||
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
|
||||
@@ -462,38 +365,24 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
got = [r0] if r0 else []
|
||||
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
|
||||
again = [] if flat else None
|
||||
code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
if again:
|
||||
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
|
||||
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
|
||||
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
|
||||
if code:
|
||||
return code
|
||||
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
|
||||
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
|
||||
def took(what, t0):
|
||||
if time.time() - t0 >= 1:
|
||||
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
|
||||
|
||||
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
|
||||
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
|
||||
if video:
|
||||
t0 = time.time()
|
||||
t.join()
|
||||
took("the sound", t0)
|
||||
t0 = time.time()
|
||||
reload() # the other containers' frames
|
||||
took("reloading the volume", t0)
|
||||
frames = f"{os.path.dirname(work)}/frames"
|
||||
dest = os.path.join(work, out)
|
||||
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
|
||||
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
|
||||
t0 = time.time()
|
||||
farm_keys.put(store, keyed["keys"], got, frames)
|
||||
took("keeping the runs drawn", t0)
|
||||
t0 = time.time()
|
||||
got += farm_keys.take(hits, frames)
|
||||
took(f"bringing {len(hits)} kept runs", t0)
|
||||
if manifest and p.get("manifest"):
|
||||
path = os.path.join(work, manifest)
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
|
||||
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
|
||||
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
|
||||
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
|
||||
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
|
||||
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
|
||||
// idle, went on an hour running goal checks on raea-5).
|
||||
import type { WebSocket } from "ws"
|
||||
|
||||
export const CALLER_GONE_MS = 3 * 60_000
|
||||
const EVERY_MS = 20_000
|
||||
|
||||
/** the keepalive's timer: clear it when the socket closes */
|
||||
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
|
||||
let pong = Date.now()
|
||||
ws.on("pong", () => (pong = Date.now()))
|
||||
return setInterval(() => {
|
||||
if (ws.readyState !== ws.OPEN) return
|
||||
if (Date.now() - pong > goneMs) {
|
||||
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
|
||||
ws.terminate()
|
||||
return
|
||||
}
|
||||
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
|
||||
ws.ping()
|
||||
}, everyMs)
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
|
||||
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
|
||||
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { pipeline } from "node:stream/promises"
|
||||
|
||||
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
|
||||
|
||||
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
|
||||
const { json } = o
|
||||
const p = o.resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT") {
|
||||
// to disk as it comes, beside the file, then put in its place whole
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
const part = `${p}.part-${process.pid}-${Date.now()}`
|
||||
return pipeline(req, createWriteStream(part)).then(
|
||||
() => {
|
||||
renameSync(part, p)
|
||||
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
|
||||
},
|
||||
(e) => {
|
||||
rmSync(part, { force: true })
|
||||
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
|
||||
},
|
||||
)
|
||||
}
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
|
||||
return pipeline(createReadStream(p), res).catch(() => res.destroy())
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
|
||||
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
|
||||
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
|
||||
// the Machine (restart policy on-failure) stays stopped.
|
||||
//
|
||||
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
|
||||
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
|
||||
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
|
||||
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
|
||||
//
|
||||
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
|
||||
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
|
||||
import type { Server } from "node:http"
|
||||
import path from "node:path"
|
||||
|
||||
export const HOLD_FILE = ".raea-hold"
|
||||
|
||||
/** a process other than this one (and its parents) whose working folder is under `work` */
|
||||
export function workingIn(work: string, self = process.pid): number[] {
|
||||
const mine = new Set<number>()
|
||||
for (let p = self; p > 1; ) {
|
||||
mine.add(p)
|
||||
try {
|
||||
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
|
||||
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
|
||||
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
|
||||
} catch {
|
||||
break
|
||||
}
|
||||
}
|
||||
const out: number[] = []
|
||||
let pids: string[] = []
|
||||
try {
|
||||
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
|
||||
} catch {
|
||||
return out
|
||||
}
|
||||
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
|
||||
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
|
||||
// idle and the box stopped under it)
|
||||
const roots = [path.resolve(work) + "/"]
|
||||
try {
|
||||
roots.push(realpathSync(work) + "/")
|
||||
} catch {}
|
||||
for (const d of pids) {
|
||||
const pid = Number(d)
|
||||
if (mine.has(pid)) continue
|
||||
try {
|
||||
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
|
||||
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
|
||||
} catch {}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface IdleOptions {
|
||||
server: Server
|
||||
work: string
|
||||
home: string
|
||||
/** whether the server itself has something running (an agent, a shell, a job) */
|
||||
busy: () => boolean
|
||||
quietMs: number
|
||||
holdMs?: number
|
||||
everyMs?: number
|
||||
log?: (line: string) => void
|
||||
exit?: () => void
|
||||
}
|
||||
|
||||
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
|
||||
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
|
||||
let last = Date.now()
|
||||
const holdMs = o.holdMs ?? 10 * 60_000
|
||||
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
|
||||
const exit = o.exit ?? (() => process.exit(0))
|
||||
const why = (): string | null => {
|
||||
if (Date.now() - last < o.quietMs) return "a request came lately"
|
||||
if (o.busy()) return "the server runs something"
|
||||
try {
|
||||
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
|
||||
if (Date.now() - held < holdMs) return "a project holds it"
|
||||
} catch {}
|
||||
const w = workingIn(o.work)
|
||||
if (w.length) return `${w.length} processes work in ${o.work}`
|
||||
return null
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
o.server.getConnections((e, n) => {
|
||||
if (!e && n > 0) return
|
||||
if (why()) return
|
||||
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
|
||||
clearInterval(timer)
|
||||
o.server.close()
|
||||
exit()
|
||||
})
|
||||
}, o.everyMs ?? 30_000)
|
||||
timer.unref()
|
||||
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
|
||||
}
|
||||
+25
-21
@@ -39,13 +39,9 @@
|
||||
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { homedir } from "node:os"
|
||||
import { keepAlive } from "./alive.ts"
|
||||
import { files } from "./files.ts"
|
||||
import { stopWhenIdle } from "./idle.ts"
|
||||
import { WebSocketServer } from "ws"
|
||||
import { installed, spawnFor } from "./agents.ts"
|
||||
import { guard } from "./memguard.ts"
|
||||
@@ -177,6 +173,24 @@ async function body(req: IncomingMessage): Promise<Buffer> {
|
||||
return Buffer.concat(parts)
|
||||
}
|
||||
|
||||
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
const p = resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT")
|
||||
return body(req).then((b) => {
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
writeFileSync(p, b)
|
||||
json(res, { path: path.relative(WORK, p), bytes: b.length })
|
||||
})
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
|
||||
}
|
||||
|
||||
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
|
||||
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
|
||||
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
|
||||
@@ -239,10 +253,6 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
||||
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
|
||||
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
|
||||
// box stopped as idle the moment it ended (12-03)
|
||||
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
|
||||
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
|
||||
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
|
||||
if (url.pathname === "/host/judge" && req.method === "POST") {
|
||||
@@ -283,7 +293,7 @@ const server = createServer(async (req, res) => {
|
||||
running: running.size,
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
|
||||
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
|
||||
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
|
||||
if (url.pathname === "/v1/jobs" && req.method === "POST") {
|
||||
@@ -396,7 +406,11 @@ server.on("upgrade", (req, socket, head) => {
|
||||
}
|
||||
running.add(child)
|
||||
agentSockets.add(ws)
|
||||
const beat = keepAlive(ws, agent.id)
|
||||
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
|
||||
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
|
||||
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
|
||||
// never sees it
|
||||
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
|
||||
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
|
||||
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
|
||||
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
|
||||
@@ -475,16 +489,6 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
|
||||
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
|
||||
const idle =
|
||||
idleMin > 0
|
||||
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
|
||||
: null
|
||||
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
|
||||
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
|
||||
server.requestTimeout = 0
|
||||
server.headersTimeout = 60_000
|
||||
server.listen(PORT, async () => {
|
||||
await versionKnown
|
||||
const d = device(childEnv())
|
||||
|
||||
+1
-11
@@ -91,15 +91,6 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
|
||||
throw new Error(`${what} ended without an exit code`)
|
||||
}
|
||||
|
||||
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
|
||||
export const onSprite = (url: string): boolean => {
|
||||
try {
|
||||
return new URL(url).hostname.endsWith(".sprites.app")
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export class RaeaCloud {
|
||||
readonly url: string
|
||||
private token: string
|
||||
@@ -112,8 +103,7 @@ export class RaeaCloud {
|
||||
constructor(o: { url: string; token: string; spriteToken?: string }) {
|
||||
this.url = o.url.replace(/\/+$/, "")
|
||||
this.token = o.token
|
||||
// only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
|
||||
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
|
||||
this.spriteToken = o.spriteToken
|
||||
}
|
||||
|
||||
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
|
||||
|
||||
@@ -69,11 +69,6 @@ class FakeGpu:
|
||||
def starmap(self, calls, order_outputs=False, return_exceptions=True):
|
||||
return [self.remote(*c) for c in calls]
|
||||
|
||||
def spawn(self, *a, **kw):
|
||||
# a run spawned on its own (farm_plan.hedged, waited): answered at once
|
||||
r = self.remote(*a, **kw)
|
||||
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
|
||||
|
||||
|
||||
lines = []
|
||||
log = lambda t, err=False: lines.append(t)
|
||||
@@ -349,50 +344,3 @@ assert not any("waiting" in l for l in lines), lines
|
||||
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
|
||||
class Call:
|
||||
def __init__(self, answer_at, r, clock):
|
||||
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
|
||||
|
||||
def get(self, timeout=None):
|
||||
if self.clock() >= self.answer_at:
|
||||
return self.r
|
||||
raise TimeoutError()
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
|
||||
class Straggly:
|
||||
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock, self.spawned = clock, []
|
||||
|
||||
def with_options(self, **kw):
|
||||
return self
|
||||
|
||||
def spawn(self, id, args, frames, first, *rest):
|
||||
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
|
||||
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
|
||||
self.spawned.append((first, c))
|
||||
return c
|
||||
|
||||
|
||||
now = [0.0]
|
||||
clock = lambda: now[0]
|
||||
def tick(_s):
|
||||
now[0] += 1
|
||||
st = Straggly(clock)
|
||||
lines.clear()
|
||||
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
|
||||
got = []
|
||||
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
|
||||
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
|
||||
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
|
||||
assert now[0] < 100, now
|
||||
assert any("sent again" in l for l in lines), lines
|
||||
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
|
||||
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
|
||||
@@ -13,7 +13,6 @@ import { shellEnv } from "../server/shell-os.ts"
|
||||
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
|
||||
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||
import { localSources } from "../server/media.ts"
|
||||
import { keepAlive } from "../server/alive.ts"
|
||||
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
|
||||
|
||||
const L4 = `Devices:
|
||||
@@ -238,28 +237,3 @@ console.log("units: ok")
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
console.log("ok critic")
|
||||
}
|
||||
|
||||
{
|
||||
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
|
||||
const { WebSocketServer, WebSocket } = await import("ws")
|
||||
const wss = new WebSocketServer({ port: 0 })
|
||||
const port = (wss.address() as { port: number }).port
|
||||
const ended: boolean[] = []
|
||||
wss.on("connection", (ws) => {
|
||||
const beat = keepAlive(ws, "test", 120, 20)
|
||||
ws.on("close", () => (clearInterval(beat), ended.push(true)))
|
||||
})
|
||||
const live = new WebSocket(`ws://127.0.0.1:${port}`)
|
||||
await new Promise((ok) => live.on("open", ok))
|
||||
await new Promise((ok) => setTimeout(ok, 400))
|
||||
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
|
||||
live.close()
|
||||
await new Promise((ok) => setTimeout(ok, 50))
|
||||
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
|
||||
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
|
||||
await new Promise((ok) => gone.on("open", ok))
|
||||
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
|
||||
assert.ok(closed, "a caller that answered no ping wasn't ended")
|
||||
wss.close()
|
||||
console.log("ok an agent socket's caller gone is ended")
|
||||
}
|
||||
+3
-66
@@ -9,19 +9,14 @@ import type { Contract } from "./contract.ts"
|
||||
import * as media from "./media.ts"
|
||||
import type { Faces, Levels, Word } from "./media.ts"
|
||||
import type { Scene } from "./packs/place.ts"
|
||||
import { outOf, planScene, said } from "./plan.ts"
|
||||
import type { Project } from "./project.ts"
|
||||
|
||||
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
|
||||
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
|
||||
/** a text on a frame, in render pixels: its layout box and its ink */
|
||||
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number; lines?: number }
|
||||
/** a video on a frame, in render pixels: its source and the source second it shows, its box (and what of it a box it's
|
||||
* in leaves showing, `clip`), its object-fit and object-position ([x px, x share of the free space, y px, y share]) */
|
||||
export type ManifestVideo = { src: string; at: number; box: number[]; clip?: number[]; fit?: string; position?: number[]; opacity?: number }
|
||||
/** `raea render --manifest`: the frames with their texts and videos, and the sound's clips; `plan`: written by `raea
|
||||
* render --plan`, which draws nothing (every frame laid out, no picture) */
|
||||
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; plan?: boolean; frames?: { frame: number; text?: ManifestText[]; videos?: ManifestVideo[]; pictures?: { kind?: string; box?: number[]; opacity?: number }[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||||
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
|
||||
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
|
||||
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||||
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
|
||||
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
|
||||
|
||||
@@ -42,9 +37,6 @@ export interface FileFacts {
|
||||
height: number | null
|
||||
fps: number
|
||||
manifest: Manifest | null
|
||||
/** a cut checked on its plan, before it's drawn (plan.ts): `manifest` is the plan, `path` and `abs` name the export
|
||||
* it's of (which may not be there yet), and its words and scene are what its takes say and its sources show */
|
||||
plan: boolean
|
||||
moment: Moment
|
||||
contract: Contract | null
|
||||
/** what it says, word by word */
|
||||
@@ -133,7 +125,6 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
|
||||
height: shape?.height ?? manifest?.height ?? null,
|
||||
fps: manifest?.fps ?? shape?.fps ?? 30,
|
||||
manifest,
|
||||
plan: false,
|
||||
moment,
|
||||
contract,
|
||||
words: once(() => media.words(abs)),
|
||||
@@ -176,57 +167,3 @@ export function runIn(dir: string) {
|
||||
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
|
||||
}
|
||||
}
|
||||
|
||||
/** a composition checked on a plan of one of its cuts (`raea goal check --at edit --manifest OUT.plan.json EDIT.tsx`):
|
||||
* the facts of the export the plan is of (OUT.mp4 beside the plan), known before it's drawn. Its words are its voice
|
||||
* clips' takes' words where the clips put them, its scene its videos' source frames' (plan.ts); its own level, sheet
|
||||
* and look wait for the export */
|
||||
export function planFacts(plan: Manifest, planAbs: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
|
||||
const abs = `${outOf(planAbs)}.mp4`
|
||||
const roots = [root, path.dirname(planAbs)]
|
||||
const fps = Number(plan.fps) || 30
|
||||
const takeWords = new Map<string, Promise<Word[]>>()
|
||||
const take = (src: string) => onMachine(src, roots)
|
||||
const wordsOfTake = (src: string) => {
|
||||
const f = take(src)
|
||||
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
|
||||
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
|
||||
return takeWords.get(f)!
|
||||
}
|
||||
const st = statSync(planAbs)
|
||||
return {
|
||||
path: path.relative(root, abs),
|
||||
abs,
|
||||
root,
|
||||
kind: "other",
|
||||
made: true,
|
||||
stamp: `${Math.round(st.mtimeMs)} ${st.size}`,
|
||||
seconds: (Number(plan.length) || plan.frames?.length || 0) / fps,
|
||||
width: Number(plan.width) || null,
|
||||
height: Number(plan.height) || null,
|
||||
fps,
|
||||
manifest: plan,
|
||||
plan: true,
|
||||
moment,
|
||||
contract,
|
||||
words: once(async () => {
|
||||
const clips = plan.sounds?.clips ?? []
|
||||
const got = new Map<string, Word[]>()
|
||||
for (const c of clips) {
|
||||
if (got.has(c.src)) continue
|
||||
try {
|
||||
got.set(c.src, await wordsOfTake(c.src))
|
||||
} catch {}
|
||||
}
|
||||
return said(clips, plan.sounds?.fps ?? fps, (src) => got.get(src) ?? null)
|
||||
}),
|
||||
take,
|
||||
takeWords: wordsOfTake,
|
||||
levels: (a, b, src) => (src ? media.levels(take(src) ?? src, a, b) : { start: a ?? 0, db: [] }),
|
||||
scene: once(() => planScene(root, plan, take)),
|
||||
sheet: () => {
|
||||
throw new media.Unmet("a plan has no picture to make a sheet of: render it")
|
||||
},
|
||||
seen: () => null,
|
||||
}
|
||||
}
|
||||
+18
-31
@@ -233,7 +233,24 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
|
||||
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
|
||||
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
|
||||
const { faces, scenes } = await readScenes(jpgs.map((n) => readFileSync(path.join(dir, n))))
|
||||
const faces: Faces[] = []
|
||||
const scenes: Scene[] = []
|
||||
for (let i = 0; i < jpgs.length; i += 300) {
|
||||
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
|
||||
const r = await post("/v1/scene", body, "application/json")
|
||||
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
|
||||
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
|
||||
if (!g) {
|
||||
faces.push(null)
|
||||
scenes.push(null)
|
||||
continue
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
}
|
||||
if (whole && scenes.length) {
|
||||
try {
|
||||
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
|
||||
@@ -245,36 +262,6 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
}
|
||||
}
|
||||
|
||||
/** frames (JPEGs, a null where there's none) read by the farm's scene reader, 300 a request: each one's faces and seams,
|
||||
* and its scene (people, faces, things, words in the shot) */
|
||||
export async function readScenes(jpgs: (Buffer | null)[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
|
||||
if (!farm()) throw new Unmet("no scene reader on this machine (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)")
|
||||
const faces: Faces[] = []
|
||||
const scenes: Scene[] = []
|
||||
const real = jpgs.flatMap((j, i) => (j ? [i] : []))
|
||||
const got = new Map<number, Record<string, any> | null>()
|
||||
for (let i = 0; i < real.length; i += 300) {
|
||||
const part = real.slice(i, i + 300)
|
||||
const body = JSON.stringify({ frames: part.map((k) => jpgs[k]!.toString("base64")) })
|
||||
const r = await post("/v1/scene", body, "application/json")
|
||||
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
|
||||
;(JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames.forEach((g, n) => got.set(part[n], g))
|
||||
}
|
||||
for (let i = 0; i < jpgs.length; i++) {
|
||||
const g = got.get(i)
|
||||
if (!g) {
|
||||
faces.push(null)
|
||||
scenes.push(null)
|
||||
continue
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
return { faces, scenes }
|
||||
}
|
||||
|
||||
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
|
||||
export function sheet(file: string): string {
|
||||
const out = `${stem(file)}.sheet.jpg`
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RATE, type Word } from "../media.ts"
|
||||
import { samples, textFrames } from "../plan.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import type { TextLine } from "./place.ts"
|
||||
|
||||
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
|
||||
@@ -236,15 +235,13 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
|
||||
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
// a cut's plan (plan.ts): what it shows is its own text, as laid out, and what it says its takes' words where its
|
||||
// clips put them; an export's is what the reader reads and hears in it
|
||||
const sc = f.plan && f.manifest ? { rate: RATE, scenes: [] } : await f.scene()
|
||||
const frames: Frame[] = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
|
||||
const shown = captionsOf(frames, sc.rate || 2, heard)
|
||||
const rate = sc.rate || 2
|
||||
|
||||
@@ -10,7 +10,6 @@ import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RAEA, stem } from "../media.ts"
|
||||
import { textRules, ZONE_FIX } from "../plan.ts"
|
||||
import { bookkeeping } from "./naming.ts"
|
||||
|
||||
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
|
||||
@@ -54,13 +53,7 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
|
||||
|
||||
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
|
||||
|
||||
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["edit", "render", "publish", "done"] }, async (f) => {
|
||||
// a cut's plan (plan.ts): the text rules raea check holds a manifest to, on every frame, before it's drawn; what only
|
||||
// the picture and the mix show (contrast, freezes, flashing, loudness, blotching) waits for the export
|
||||
if (f.plan && f.manifest) {
|
||||
for (const x of textRules(f.manifest)) found({ level: x.level, says: x.says, fix: x.rule === "safe-area" ? ZONE_FIX : undefined, seconds: x.at })
|
||||
return
|
||||
}
|
||||
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
|
||||
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
|
||||
for (const x of floorOf(f.abs, m, f.root)) say(x)
|
||||
|
||||
@@ -13,7 +13,6 @@ import { existsSync, readFileSync } from "node:fs"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RATE, stem, type Faces } from "../media.ts"
|
||||
import { PLAN_SOFT } from "../plan.ts"
|
||||
|
||||
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
|
||||
export const FACE_MIN = 0.05
|
||||
@@ -142,17 +141,13 @@ export const despite = (abs: string) => {
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
|
||||
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
// at edit only a cut's plan (plan.ts): its faces are its sources' frames, mapped into the cut's
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
|
||||
// the text's sizes are said even where the faces wait for a scene reader
|
||||
const why = despite(f.abs)
|
||||
// on a plan a face cut by the edge is a warning (plan.ts ON_PLAN_WARNS): its source frames are read without the cut's
|
||||
// text over them, and the render's check holds it
|
||||
for (const x of cutFaces((await f.scene()).faces, RATE))
|
||||
say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : f.plan && x.kind === "face-cut" && x.level === "error" ? { ...x, level: "warn", says: `${x.says}${PLAN_SOFT}` } : x)
|
||||
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
|
||||
},
|
||||
)
|
||||
+16
-45
@@ -5,7 +5,7 @@
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
import { spawn } from "node:child_process"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
@@ -167,22 +167,7 @@ function piecesOf(r: Said, dir: string): string[] {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
|
||||
}
|
||||
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
|
||||
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
|
||||
export const CLEF_AT_ONCE = 6
|
||||
|
||||
/** `f` on each item, at most `n` at once, the answers in the items' order */
|
||||
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
|
||||
export function clefVerdict(g: Contract, dir: string, ask = askClef, only: Said[] = saysOf(g)): Verdict["rules"] {
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of only) {
|
||||
@@ -197,10 +182,8 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
for (const k of groups.values()) {
|
||||
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
}
|
||||
const rules: Verdict["rules"] = {}
|
||||
@@ -214,21 +197,12 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
return new Promise((ok, no) => {
|
||||
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
})
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
|
||||
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
|
||||
return rows
|
||||
}
|
||||
|
||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
||||
@@ -240,15 +214,12 @@ export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef;
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
||||
const read = all.filter((r) => !watched.includes(r))
|
||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
||||
const [heard, said] = await Promise.all([
|
||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
||||
])
|
||||
const rules: Verdict["rules"] = { ...heard }
|
||||
if (said !== null) {
|
||||
const v = lastVerdict(said)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
||||
const rules: Verdict["rules"] = watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : {}
|
||||
if (read.length) {
|
||||
const agent = o.agent ?? askAgent
|
||||
const words = await agent(dir, prompt(g, dir, read))
|
||||
const v = lastVerdict(words)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${words.slice(-300).trim()}`)
|
||||
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
|
||||
}
|
||||
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
|
||||
|
||||
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import type { Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { type Faces, Unmet } from "../media.ts"
|
||||
import { cutOf } from "./cut.ts"
|
||||
|
||||
@@ -294,9 +294,9 @@ export function placeReport(file: string, scenes: Scene[], size: [number, number
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
|
||||
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && !f.plan) || !f.manifest?.frames?.length) return
|
||||
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
|
||||
const { scenes } = await f.scene()
|
||||
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
},
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
// editor holds (and the skill's end card rule: few words, held long enough).
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RATE, type Word } from "../media.ts"
|
||||
import { samples, textFrames } from "../plan.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
|
||||
|
||||
export type Block = { text: string; words: number; from: number; to: number; size?: number }
|
||||
@@ -106,14 +105,11 @@ export function reading(blocks: Block[]): Finding[] {
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
|
||||
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
// a cut's plan (plan.ts): its own text as laid out (a sign in the footage isn't meant to be read); an export's,
|
||||
// what the reader reads in it
|
||||
const planned = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : null
|
||||
const sc = planned ? { rate: RATE, scenes: [] } : await f.scene()
|
||||
const frames: Frame[] = planned ?? sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((x) => x.lines.length)) return
|
||||
const rate = sc.rate || 2
|
||||
const heard = await f.words()
|
||||
|
||||
@@ -229,10 +229,9 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "levels"] },
|
||||
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
// at edit only a cut's plan (plan.ts), whose clips are the export's
|
||||
if (f.kind !== "video" && f.kind !== "audio" && !f.plan) return
|
||||
if (f.kind !== "video" && f.kind !== "audio") return
|
||||
if (!f.made) return
|
||||
if (!f.manifest) {
|
||||
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
|
||||
|
||||
@@ -1,475 +0,0 @@
|
||||
// A cut checked before it's drawn (12-04, round 22: every run missed its budget the same way, a full render of every cut
|
||||
// and only then dozens of errors, fixed, and everything rendered again). `raea render EDIT.tsx --composition ID --plan
|
||||
// -o OUT.plan.json` runs each frame through React and layout and gathers the sound, drawing nothing: its plan is a render
|
||||
// manifest of every frame. `raea goal check --at edit --manifest OUT.plan.json EDIT.tsx` holds the plan to what can be
|
||||
// known from it:
|
||||
//
|
||||
// floor its text clipped by the frame or in the app's UI zones, and up too briefly (apps/check/text's rules)
|
||||
// frames text too small, and faces cut by the frame or a split screen's seam
|
||||
// place text over a face, a person or what the shot is about
|
||||
// sound clips cut inside a word or on sound, lines and effects at uneven levels (from each take's words and level)
|
||||
// captions what's said with no caption over it, and a caption that isn't what's said there
|
||||
// reading text up too briefly to read
|
||||
//
|
||||
// What the cut says is its voice clips' takes' words, laid where the clips put them. What its frames show is the scene of
|
||||
// each SOURCE frame a video shows there (the farm's POST /v1/scene, as for an export), mapped through the video's box,
|
||||
// fit and object-position into the cut's frame: the picture the render would draw, read without drawing it. Each
|
||||
// source frame's reading is kept under review/scenes/, so a plan checked again asks only for frames it hasn't read.
|
||||
// What only the export has (the words heard in the mix, its loudness, contrast, blotching) waits for --at render.
|
||||
//
|
||||
// A plan's errors stop the renders (raea cloud renders a batch only when every cut's plan passes), so on a plan an error
|
||||
// is only what the plan knows as exactly as the export's check: floor's text rules, text too small, sound's edit points
|
||||
// and levels. Place, captions, reading and faces cut by the edge are read from the source frames without the cut's own
|
||||
// text over them, or held against the takes' words rather than the mix, and on round 22's Body Shop each cut had one
|
||||
// such error the export's check didn't give (ON_PLAN_WARNS): on a plan they're warnings, and the render's check holds
|
||||
// them. The plan holds its own cut alone: the project's checks and the goals' job checks (the count, the brief's quotes)
|
||||
// don't run on it, and a check that can't run (the farm busy) waits instead of failing it.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import type { Clip, Manifest, ManifestVideo } from "./facts.ts"
|
||||
import * as media from "./media.ts"
|
||||
import type { Faces, Word } from "./media.ts"
|
||||
import { busOf } from "./packs/sound.ts"
|
||||
import type { Scene, Thing } from "./packs/place.ts"
|
||||
|
||||
/** a file a plan is checked for: a composition (the plan of one of its compositions) */
|
||||
export const COMPOSITION = /\.(tsx|jsx|ts|js|mjs)$/i
|
||||
/** the export a plan is of: OUT.plan.json (or OUT.render.json, OUT.manifest.json) is OUT's */
|
||||
export const outOf = (plan: string) => media.stem(plan).replace(/\.(plan|render|manifest)$/i, "")
|
||||
|
||||
/** checks whose errors are warnings on a plan (frames' faces cut by the edge too, in frames.ts; its text sizes stay
|
||||
* errors): each is read or heard otherwise than the export's check reads and hears it */
|
||||
export const ON_PLAN_WARNS = new Set(["place", "captions", "reading"])
|
||||
/** said after each error a plan tells and doesn't hold */
|
||||
export const PLAN_SOFT = " (on the plan a warning: the render's check holds it)"
|
||||
|
||||
/** the width the scene reader reads a frame at (media.ts SIDE), so sizes are the export's */
|
||||
const SIDE = 540
|
||||
/** a grid cell's side, as the farm's scene reader makes them (540x960: 27x48) */
|
||||
const CELL = 20
|
||||
/** a video under this opacity is fading: what's under it, or over it, is what's seen */
|
||||
const SEEN = 0.5
|
||||
/** a thing or a face with less than this share of it inside its video's visible box is out of the shot */
|
||||
const VISIBLE = 0.25
|
||||
/** a thing this much covered by a video drawn over it is hidden */
|
||||
const HIDDEN = 0.75
|
||||
|
||||
type Rect = [number, number, number, number]
|
||||
|
||||
/** the times a plan's frames are read at: RATE a second, from 0 to its end */
|
||||
export function samples(m: Manifest, rate = media.RATE): number[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const len = Number(m.length) || m.frames?.length || 0
|
||||
const n = Math.max(0, Math.ceil((len / fps) * rate - 1e-9))
|
||||
return Array.from({ length: n }, (_, i) => i / rate)
|
||||
}
|
||||
|
||||
/** where a picture sw x sh is drawn in a video's box: its fit, then its object-position ([x px, x share of the free
|
||||
* space, y px, y share], centred when unset); `native`: the picture's own size, for fit none and scale-down */
|
||||
export function drawn(v: ManifestVideo, sw: number, sh: number, native: [number, number] = [sw, sh]): Rect {
|
||||
const [bx, by, bw, bh] = v.box
|
||||
let dw = bw
|
||||
let dh = bh
|
||||
const contain = Math.min(bw / sw, bh / sh)
|
||||
const fit = v.fit ?? "fill"
|
||||
if (fit === "cover" || fit === "contain" || fit === "scale-down" || fit === "none") {
|
||||
const s = fit === "cover" ? Math.max(bw / sw, bh / sh) : fit === "contain" ? contain : fit === "none" ? native[0] / sw : Math.min(contain, native[0] / sw)
|
||||
dw = sw * s
|
||||
dh = sh * s
|
||||
}
|
||||
const p = v.position ?? [0, 0.5, 0, 0.5]
|
||||
return [bx + p[0] + p[1] * (bw - dw), by + p[2] + p[3] * (bh - dh), dw, dh]
|
||||
}
|
||||
|
||||
const meet = (a: Rect, b: Rect): Rect | null => {
|
||||
const x0 = Math.max(a[0], b[0])
|
||||
const y0 = Math.max(a[1], b[1])
|
||||
const x1 = Math.min(a[0] + a[2], b[0] + b[2])
|
||||
const y1 = Math.min(a[1] + a[3], b[1] + b[3])
|
||||
return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null
|
||||
}
|
||||
const area = (r: Rect | null) => (r ? r[2] * r[3] : 0)
|
||||
|
||||
/** what a video shows in a frame: where its picture (`size`, as decoded: rotation applied) is drawn, what of it is seen
|
||||
* in the frame (cut px), and that part of the picture as shares of it ([x, y, w, h], the `crop` read for its scene) */
|
||||
export type Layer = { v: ManifestVideo; size: [number, number]; draw: Rect; seen: Rect; crop: Rect }
|
||||
|
||||
/** the videos a frame shows, bottom first: each drawn by its box, fit and position, cut to what its box (and the box
|
||||
* clipping it) leaves showing in the frame. A fading video (under SEEN) only when nothing else shows */
|
||||
export function layersOf(videos: ManifestVideo[], W: number, H: number, sizeOf: (v: ManifestVideo) => [number, number] | null): Layer[] {
|
||||
const frame: Rect = [0, 0, W, H]
|
||||
const opaque = videos.filter((v) => (v.opacity ?? 1) >= SEEN)
|
||||
const shown = opaque.length ? opaque : [...videos].sort((a, b) => (b.opacity ?? 1) - (a.opacity ?? 1)).slice(0, 1)
|
||||
const out: Layer[] = []
|
||||
for (const v of shown) {
|
||||
if (!v.box || v.box.length < 4) continue
|
||||
const size = sizeOf(v)
|
||||
if (!size) continue
|
||||
const seen = meet(meet(v.box as Rect, (v.clip as Rect | undefined) ?? frame) ?? [0, 0, 0, 0], frame)
|
||||
if (!seen) continue
|
||||
const draw = drawn(v, size[0], size[1], size)
|
||||
const round = (x: number) => Math.round(x * 1000) / 1000
|
||||
const x0 = Math.max(0, (seen[0] - draw[0]) / draw[2])
|
||||
const y0 = Math.max(0, (seen[1] - draw[1]) / draw[3])
|
||||
const x1 = Math.min(1, (seen[0] + seen[2] - draw[0]) / draw[2])
|
||||
const y1 = Math.min(1, (seen[1] + seen[3] - draw[1]) / draw[3])
|
||||
if (x1 <= x0 || y1 <= y0) continue
|
||||
out.push({ v, size, draw, seen, crop: [round(x0), round(y0), round(x1 - x0), round(y1 - y0)] })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the scene read of the part of a source frame a layer shows (its crop, at the reader's size, as the export's reader
|
||||
* sees it: a face half out of the shot is read as the export reads it) */
|
||||
export type Source = { scene: NonNullable<Scene>; faces: NonNullable<Faces> }
|
||||
|
||||
/** what a frame of the cut shows, from the scenes of the parts of the source frames its videos show: each one's things,
|
||||
* faces and person mask mapped through its crop and its drawn box into the cut's frame (SIDE wide), and hidden where a
|
||||
* video is drawn over it. A video's edge inside the frame is a seam (a split screen, a picture in a picture). Null
|
||||
* when no video shows there */
|
||||
export function compose(all: Layer[], W: number, H: number, sourceOf: (l: Layer) => Source | null): { scene: Scene; faces: Faces } {
|
||||
const k = SIDE / Math.min(W, H)
|
||||
const w = Math.round(W * k)
|
||||
const h = Math.round(H * k)
|
||||
const layers = all.flatMap((l) => {
|
||||
const src = sourceOf(l)
|
||||
return src ? [{ ...l, src }] : []
|
||||
})
|
||||
if (!layers.length) return { scene: null, faces: null }
|
||||
type Read = (typeof layers)[number]
|
||||
// a box in a crop's scene, in the cut's pixels
|
||||
const toCut = (l: Read, t: readonly unknown[]): Rect => {
|
||||
const [x, y, bw, bh] = [0, 1, 2, 3].map((i) => Number(t[i]) || 0)
|
||||
const sx = (v: number) => (l.crop[0] + (v / l.src.scene.w) * l.crop[2]) * l.draw[2]
|
||||
const sy = (v: number) => (l.crop[1] + (v / l.src.scene.h) * l.crop[3]) * l.draw[3]
|
||||
return [l.draw[0] + sx(x), l.draw[1] + sy(y), sx(x + bw) - sx(x), sy(y + bh) - sy(y)]
|
||||
}
|
||||
const scaled = (r: Rect): [number, number, number, number] => [r[0] * k, r[1] * k, r[2] * k, r[3] * k]
|
||||
// what of a box is seen: inside its layer's visible box, and not hidden by a layer over it
|
||||
const seenOf = (i: number, b: readonly unknown[]): Rect | null => {
|
||||
const l = layers[i]
|
||||
const r = toCut(l, b)
|
||||
const vis = meet(r, l.seen)
|
||||
if (!vis || area(vis) < VISIBLE * area(r)) return null
|
||||
for (const o of layers.slice(i + 1)) if (area(meet(vis, o.seen)) >= HIDDEN * area(vis)) return null
|
||||
return vis
|
||||
}
|
||||
const things: Thing[] = []
|
||||
const faces: Thing[] = []
|
||||
layers.forEach((l, i) => {
|
||||
for (const t of l.src.scene.things) {
|
||||
const r = seenOf(i, t)
|
||||
if (r) things.push([...scaled(r), t[4], t[5]] as Thing)
|
||||
}
|
||||
for (const f of l.src.scene.faces) {
|
||||
const r = seenOf(i, f)
|
||||
if (r) faces.push([...scaled(r), "face", Number(f[5] ?? f[4]) || 0] as Thing)
|
||||
}
|
||||
})
|
||||
// the person mask: each cell's centre, in the topmost layer that shows there, read from its crop's grid
|
||||
const cols = Math.round(w / CELL)
|
||||
const rows = Math.round(h / CELL)
|
||||
const people: string[] = []
|
||||
for (let r = 0; r < rows; r++) {
|
||||
let line = ""
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const x = ((c + 0.5) / cols) * W
|
||||
const y = ((r + 0.5) / rows) * H
|
||||
const l = layers.findLast((o) => x >= o.seen[0] && x < o.seen[0] + o.seen[2] && y >= o.seen[1] && y < o.seen[1] + o.seen[3])
|
||||
if (!l) {
|
||||
line += "0"
|
||||
continue
|
||||
}
|
||||
const g = l.src.scene.grid
|
||||
const sc = Math.floor((((x - l.draw[0]) / l.draw[2] - l.crop[0]) / l.crop[2]) * g.cols)
|
||||
const sr = Math.floor((((y - l.draw[1]) / l.draw[3] - l.crop[1]) / l.crop[3]) * g.rows)
|
||||
line += g.people[sr]?.[sc] ?? "0"
|
||||
}
|
||||
people.push(line)
|
||||
}
|
||||
// a video's edge inside the frame: a seam, where it shows over a good part of the frame's other side
|
||||
const seams: media.Seam[] = []
|
||||
for (const l of layers) {
|
||||
const [x, y, sw, sh] = l.seen
|
||||
if (sw >= W * 0.5) for (const e of [y, y + sh]) if (e > H * 0.02 && e < H * 0.98) seams.push(["h", Math.round(e * k), sw / W])
|
||||
if (sh >= H * 0.5) for (const e of [x, x + sw]) if (e > W * 0.02 && e < W * 0.98) seams.push(["v", Math.round(e * k), sh / H])
|
||||
}
|
||||
const texts = layers.flatMap((l, i) => (l.src.scene.texts ?? []).flatMap((t) => {
|
||||
const r = seenOf(i, t)
|
||||
return r ? [[...scaled(r), t[4], t[5]] as [number, number, number, number, string, number]] : []
|
||||
}))
|
||||
return {
|
||||
scene: { w, h, grid: { cols, rows, people }, things, faces, texts },
|
||||
faces: { w, h, faces: faces.map((f) => [f[0], f[1], f[2], f[3], f[5]]), seams },
|
||||
}
|
||||
}
|
||||
|
||||
/** what a plan's cut says: each voice clip's take's words that fall inside it, laid where the clip puts them (a word
|
||||
* the clip cuts into is said if most of it is inside; the sound pack holds the cut itself) */
|
||||
export function said(clips: Clip[], fps: number, wordsOf: (src: string) => Word[] | null): Word[] {
|
||||
const out: Word[] = []
|
||||
for (const c of clips) {
|
||||
if (busOf(c) !== "voice") continue
|
||||
const ws = wordsOf(c.src)
|
||||
if (!ws) continue
|
||||
const a = c.at
|
||||
const b = c.at + (c.to - c.from) / fps
|
||||
for (const w of ws) {
|
||||
const inside = Math.min(b, w.end) - Math.max(a, w.start)
|
||||
// a word the clip cuts into is heard when much of it is in (a transcriber hears half a word)
|
||||
if (inside <= 0 || inside < Math.min(0.12, 0.4 * Math.max(0.01, w.end - w.start))) continue
|
||||
const shift = c.from / fps - a
|
||||
out.push({ text: w.text, start: Math.max(c.from / fps, w.start + shift), end: Math.min(c.to / fps, w.end + shift) })
|
||||
}
|
||||
}
|
||||
return out.sort((x, y) => x.start - y.start)
|
||||
}
|
||||
|
||||
/** a plan's frames by number */
|
||||
export function byFrame(m: Manifest): Map<number, NonNullable<Manifest["frames"]>[number]> {
|
||||
return new Map((m.frames ?? []).map((f) => [Number(f.frame), f]))
|
||||
}
|
||||
|
||||
type Line = [number, number, number, number, string, number]
|
||||
/** a text laid out on `n` lines, as the reader reads it: a line each, its words shared out by their letters (where
|
||||
* layout broke it isn't in the manifest, only how many lines it made) */
|
||||
export function linesOf(text: string, b: number[], n: number): Line[] {
|
||||
const words = text.split(/\s+/).filter(Boolean)
|
||||
if (n <= 1 || words.length < 2) return [[b[0], b[1], b[2], b[3], text, 1]]
|
||||
const k = Math.min(n, words.length)
|
||||
const total = words.reduce((s, w) => s + w.length + 1, 0)
|
||||
const parts: string[][] = Array.from({ length: k }, () => [])
|
||||
let at = 0
|
||||
for (const w of words) {
|
||||
// each word on the line its middle letter falls on
|
||||
parts[Math.min(k - 1, Math.floor(((at + w.length / 2) / total) * k))].push(w)
|
||||
at += w.length + 1
|
||||
}
|
||||
return parts.flatMap((p, l) => (p.length ? [[b[0], b[1] + (b[3] * l) / k, b[2], b[3] / k, p.join(" "), 1] as Line] : []))
|
||||
}
|
||||
|
||||
/** the frame nearest a time, and the text it shows, as the scene reader would read lines: [x, y, w, h, text, score] in
|
||||
* the pixels of a frame `h` high, a text laid out on several lines a line each */
|
||||
export function textFrames(m: Manifest, at: number[]): { h: number; lines: Line[] }[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const H = Number(m.height) || 1920
|
||||
const frames = byFrame(m)
|
||||
return at.map((t) => {
|
||||
const fr = frames.get(Math.round(t * fps))
|
||||
const lines = (fr?.text ?? []).filter((x) => (x.opacity ?? 1) > 0.3 && String(x.text ?? "").trim()).flatMap((x) => linesOf(String(x.text).trim(), (x.ink ?? x.box ?? [0, 0, 0, 0]) as number[], Number(x.lines) || 1))
|
||||
return { h: H, lines }
|
||||
})
|
||||
}
|
||||
|
||||
/** a frame's opaque fills over the whole frame: a cut's backgrounds are on every frame, so a frame with more than the
|
||||
* fewest any frame with a video has holds a card over its videos (an end card), which hides them. (The manifest says
|
||||
* where a fill is, not whether it's over a video or under it.) */
|
||||
const covers = (fr: NonNullable<Manifest["frames"]>[number] | undefined, W: number, H: number) =>
|
||||
(fr?.pictures ?? []).filter((p) => (p.opacity ?? 1) >= 0.9 && p.box && p.box[0] <= 1 && p.box[1] <= 1 && p.box[0] + p.box[2] >= W - 1 && p.box[1] + p.box[3] >= H - 1).length
|
||||
|
||||
// ---- the source frames' scenes, read by the farm and kept ------------------------------------------------------------
|
||||
|
||||
type Kept = { stamp: string; side: number; at: Record<string, Source> }
|
||||
/** a read's key in a source's keeping: its second and its crop */
|
||||
export const readKey = (at: number, crop: Rect) => `${at.toFixed(2)} ${crop.join(",")}`
|
||||
type Want = { file: string; at: number; crop: Rect }
|
||||
|
||||
/** parts of source frames read for a plan, each (file, second, crop) once: from review/scenes/ when read before, else
|
||||
* extracted (several ffmpeg at once where there's a shell) and read by the farm. Unmet when there's no farm here */
|
||||
export async function sourceScenes(root: string, wants: Want[]): Promise<Map<string, Source>> {
|
||||
const out = new Map<string, Source>()
|
||||
const byFile = new Map<string, Map<string, Want>>()
|
||||
for (const w of wants) byFile.set(w.file, (byFile.get(w.file) ?? new Map()).set(readKey(w.at, w.crop), w))
|
||||
const dir = path.join(root, "review", "scenes")
|
||||
for (const [file, mine] of byFile) {
|
||||
const st = statSync(file)
|
||||
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
|
||||
const keep = path.join(dir, `${path.basename(file)}.json`)
|
||||
let kept: Kept = { stamp, side: SIDE, at: {} }
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(keep, "utf8")) as Kept
|
||||
if (k.stamp === stamp && k.side === SIDE) kept = k
|
||||
} catch {}
|
||||
const need = [...mine.entries()].filter(([k]) => !kept.at[k])
|
||||
if (need.length) {
|
||||
const read = await readAt(file, need.map(([, w]) => w))
|
||||
need.forEach(([k], i) => {
|
||||
const s = read.scenes[i]
|
||||
const f = read.faces[i]
|
||||
if (s && f) kept.at[k] = { scene: s, faces: f }
|
||||
})
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true })
|
||||
// read again just before writing: a plan of another cut may have read other frames of the same file meanwhile
|
||||
try {
|
||||
const now = JSON.parse(readFileSync(keep, "utf8")) as Kept
|
||||
if (now.stamp === stamp && now.side === SIDE) kept.at = { ...now.at, ...kept.at }
|
||||
} catch {}
|
||||
const tmp = `${keep}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, JSON.stringify(kept))
|
||||
renameSync(tmp, keep)
|
||||
} catch {}
|
||||
}
|
||||
for (const k of mine.keys()) if (kept.at[k]) out.set(`${file}@${k}`, kept.at[k])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** parts of a file's frames (a second and a crop, in shares of the picture), read by the farm's scene reader at the
|
||||
* reader's size, as the export's reader reads that part of the cut's frame */
|
||||
async function readAt(file: string, wants: Want[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
|
||||
if (!process.env.RAEA_CLOUD_GPU_URL) throw new media.Unmet(`no scene reader on this machine for ${path.basename(file)}'s frames (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-plan-"))
|
||||
try {
|
||||
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
|
||||
const jpgs = wants.map((_, i) => path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`))
|
||||
const one = (w: Want, i: number) => {
|
||||
const [x, y, cw, ch] = w.crop
|
||||
const crop = `crop=iw*${cw}:ih*${ch}:iw*${x}:ih*${y}`
|
||||
return ["-v", "error", "-y", "-ss", w.at.toFixed(3), "-i", file, "-frames:v", "1", "-vf", `${crop},${scale}`, "-q:v", "4", jpgs[i]]
|
||||
}
|
||||
if (process.platform !== "win32" && spawnSync("ffmpeg", ["-version"], { encoding: "utf8" }).status === 0) {
|
||||
// eight at a time through the shell: this runtime has only spawnSync, and a plan reads 60-80 frames
|
||||
const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
|
||||
const lines = wants.map((w, i) => `ffmpeg ${one(w, i).map(q).join(" ")} &${(i + 1) % 8 === 0 ? "\nwait" : ""}`)
|
||||
spawnSync("sh", ["-c", `${lines.join("\n")}\nwait`], { encoding: "utf8", maxBuffer: 1 << 24 })
|
||||
}
|
||||
wants.forEach((w, i) => {
|
||||
if (!existsSync(jpgs[i])) media.ffmpeg(one(w, i))
|
||||
})
|
||||
return await media.readScenes(jpgs.map((j) => (existsSync(j) ? readFileSync(j) : null)))
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** a video file's picture as decoded: its width and height, swapped when it's stored rotated a quarter turn */
|
||||
export function pictureOf(file: string): [number, number] | null {
|
||||
const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_tags=rotate:stream_side_data=rotation", "-of", "json", file], { encoding: "utf8" })
|
||||
try {
|
||||
const s = JSON.parse(r.stdout ?? "").streams?.[0]
|
||||
if (s?.width) {
|
||||
const rot = Math.abs(Number(s.tags?.rotate ?? s.side_data_list?.find((d: { rotation?: number }) => d.rotation !== undefined)?.rotation ?? 0)) % 180
|
||||
return rot === 90 ? [s.height, s.width] : [s.width, s.height]
|
||||
}
|
||||
} catch {}
|
||||
const sh = media.shape(file)
|
||||
return sh ? [sh.width, sh.height] : null
|
||||
}
|
||||
|
||||
/** the scenes of a plan's frames, RATE a second: each composed from the parts of its videos' source frames it shows
|
||||
* (`file`: a source on this machine, or null) */
|
||||
export async function planScene(root: string, m: Manifest, file: (src: string) => string | null): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
|
||||
const W = Number(m.width) || 1080
|
||||
const H = Number(m.height) || 1920
|
||||
const fps = Number(m.fps) || 30
|
||||
const at = samples(m)
|
||||
const frames = byFrame(m)
|
||||
const withVideo = [...frames.values()].filter((f) => f.videos?.length)
|
||||
const backgrounds = withVideo.length ? Math.min(...withVideo.map((f) => covers(f, W, H))) : 0
|
||||
const missing = new Set<string>()
|
||||
const sizes = new Map<string, [number, number] | null>()
|
||||
const sizeOf = (v: ManifestVideo) => {
|
||||
const f = file(v.src)
|
||||
if (!f) {
|
||||
missing.add(v.src)
|
||||
return null
|
||||
}
|
||||
if (!sizes.has(f)) sizes.set(f, pictureOf(f))
|
||||
return sizes.get(f) ?? null
|
||||
}
|
||||
const shows = at.map((t) => {
|
||||
const fr = frames.get(Math.round(t * fps))
|
||||
return covers(fr, W, H) > backgrounds ? [] : layersOf((fr?.videos ?? []) as ManifestVideo[], W, H, sizeOf)
|
||||
})
|
||||
const wants = shows.flatMap((ls) => ls.map((l) => ({ file: file(l.v.src)!, at: l.v.at, crop: l.crop })))
|
||||
if (!wants.length && missing.size) throw new media.Unmet(`the plan's videos aren't on this machine (${[...missing].slice(0, 3).join(", ")}), so what its frames show can't be read`)
|
||||
const read = await sourceScenes(root, wants)
|
||||
const out = shows.map((ls) => compose(ls, W, H, (l) => read.get(`${file(l.v.src)}@${readKey(l.v.at, l.crop)}`) ?? null))
|
||||
return { rate: media.RATE, faces: out.map((o) => o.faces), scenes: out.map((o) => o.scene) }
|
||||
}
|
||||
|
||||
// ---- the floor's text rules, from the plan (apps/check/text's text_runs and text_rules) --------------------------------
|
||||
|
||||
export type Run = { text: string; from: number; to: number; box: Rect; boxes: Rect[]; size: number }
|
||||
|
||||
/** a text as it stays on screen, from the frame it comes on to the frame it leaves; typing (a text growing into the next)
|
||||
* and counting (only its digits changing) are one run, judged by its last text */
|
||||
export function textRuns(m: Manifest): Run[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const key = (s: string) => s.replace(/[0-9]/g, "").trim().toLowerCase()
|
||||
let open: Run[] = []
|
||||
const done: Run[] = []
|
||||
for (const f of [...(m.frames ?? [])].sort((a, b) => a.frame - b.frame)) {
|
||||
const t = Number(f.frame) / fps
|
||||
const next: Run[] = []
|
||||
for (const x of f.text ?? []) {
|
||||
const text = String(x.text ?? "").trim()
|
||||
if ((x.opacity ?? 1) <= 0.05 || !text) continue
|
||||
const quad = (b?: number[]): Rect | null => (b ? [0, 1, 2, 3].map((i) => Number(b[i]) || 0) as Rect : null)
|
||||
const b = quad(x.box) ?? [0, 0, 0, 0]
|
||||
const ink = quad(x.ink)
|
||||
const k = key(text)
|
||||
const i = open.findIndex((r) => {
|
||||
const rk = key(r.text)
|
||||
return rk === k || (rk !== "" && k.startsWith(rk)) || (k !== "" && rk.startsWith(k) && k.length * 2 > rk.length)
|
||||
})
|
||||
const r: Run = i >= 0 ? open.splice(i, 1)[0] : { text, from: t, to: t, box: b, boxes: [], size: 0 }
|
||||
if (text.length > r.text.length) r.boxes = []
|
||||
if (text.length >= r.text.length) {
|
||||
r.text = text
|
||||
r.box = b
|
||||
r.boxes.push(ink ?? b)
|
||||
}
|
||||
r.to = t + 1 / fps
|
||||
r.size = Number(x.size) || 0
|
||||
next.push(r)
|
||||
}
|
||||
done.push(...open)
|
||||
open = next
|
||||
}
|
||||
done.push(...open)
|
||||
return done.sort((a, b) => a.from - b.from)
|
||||
}
|
||||
|
||||
/** the zones where text can't go, [top, right, bottom, left] at the frame's width (apps/check/text zones(): default) */
|
||||
export function zones(w: number, h: number): [number, number, number, number] {
|
||||
const r = w / h
|
||||
const z: [number, number, number, number] | null = r < 0.7 ? [220, 140, 420, 60] : r < 0.9 ? [110, 60, 170, 60] : r < 1.2 ? [70, 60, 120, 60] : null
|
||||
if (!z) return [(120 * h) / 1080, (60 * w) / 1920, (120 * h) / 1080, (60 * w) / 1920]
|
||||
return z.map((v) => (v * w) / 1080) as [number, number, number, number]
|
||||
}
|
||||
|
||||
const quote = (s: string) => `“${[...s].slice(0, 40).join("")}”`
|
||||
|
||||
/** what `raea check` says of a render's text from its manifest: clipped off the frame (an error), in the app's UI zones
|
||||
* (an error), up too briefly to read (a warning, the reading pack holds it to its words) */
|
||||
export function textRules(m: Manifest): { level: "error" | "warn"; rule: string; at: number; says: string }[] {
|
||||
const w = Number(m.width) || 1080
|
||||
const h = Number(m.height) || 1920
|
||||
const [zt, zr, zb, zl] = zones(w, h)
|
||||
const out: { level: "error" | "warn"; rule: string; at: number; says: string }[] = []
|
||||
for (const r of textRuns(m)) {
|
||||
const [x, y, bw, bh] = r.box
|
||||
const q = quote(r.text)
|
||||
const boxes = r.boxes.length ? r.boxes : [r.box]
|
||||
const off = ([x, y, bw, bh]: Rect) => x < -1 || y < -1 || x + bw > w + 1 || y + bh > h + 1
|
||||
const zoned = ([x, y, bw, bh]: Rect) => y < zt || x + bw > w - zr || y + bh > h - zb || x < zl
|
||||
if (boxes.every(off)) out.push({ level: "error", rule: "clipped", at: r.from, says: `${q} runs off the frame (box ${x.toFixed(0)},${y.toFixed(0)} ${bw.toFixed(0)}x${bh.toFixed(0)} in ${w}x${h}); fit it or break the line` })
|
||||
else if (boxes.every(zoned)) {
|
||||
const [ix, iy, iw, ih] = boxes[boxes.length - 1]
|
||||
const edge = iy < zt ? `the top (keep ${zt.toFixed(0)} px clear)` : iy + ih > h - zb ? `the bottom (keep ${zb.toFixed(0)} px clear)` : ix < zl ? `the left (keep ${zl.toFixed(0)} px clear)` : `the right (keep ${zr.toFixed(0)} px clear)`
|
||||
out.push({ level: "error", rule: "safe-area", at: r.from, says: `${q} sits in the app's UI zone at ${edge}: its ${r.boxes.length && boxes[boxes.length - 1] !== r.box ? "letters" : "box"} ${ix.toFixed(0)},${iy.toFixed(0)} ${iw.toFixed(0)}x${ih.toFixed(0)} in ${w}x${h}` })
|
||||
}
|
||||
const words = r.text.split(/\s+/).filter(Boolean).length
|
||||
const need = Math.max(1, 0.3 * words)
|
||||
const held = r.to - r.from
|
||||
if (held + 0.05 < need && r.size >= 24) out.push({ level: "warn", rule: "reading", at: r.from, says: `${q} is on for ${held.toFixed(1)} s; ${words} words need ${need.toFixed(1)} s to read` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the fix a UI-zone finding asks for, said once */
|
||||
export const ZONE_FIX = "keep text inside the safe area: 220 px from the top, 420 px from the bottom, 140 px from the right and 60 px from the left of a 1080x1920 frame"
|
||||
+17
-54
@@ -3,9 +3,6 @@
|
||||
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
|
||||
//
|
||||
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
|
||||
// (EDIT.tsx --at edit --manifest OUT.plan.json: one cut of the composition checked on its plan, `raea render
|
||||
// --plan`, before it's drawn: plan.ts. Only that cut's file checks run, only what the plan knows exactly is an
|
||||
// error, and a check that can't run waits, so exit 1 always names something in the cut to fix)
|
||||
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
|
||||
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
|
||||
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
|
||||
@@ -17,13 +14,12 @@
|
||||
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
|
||||
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
|
||||
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
|
||||
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
|
||||
import { fileFacts, type FileFacts, type Job, kindOf, planFacts, runIn } from "./facts.ts"
|
||||
import { COMPOSITION, ON_PLAN_WARNS, PLAN_SOFT } from "./plan.ts"
|
||||
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
|
||||
import * as media from "./media.ts"
|
||||
import { registeredPack } from "./packs/job.ts"
|
||||
import { tastePack } from "./packs/taste.ts"
|
||||
@@ -141,22 +137,13 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
const broke: Report["broke"] = []
|
||||
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
|
||||
const fps = file?.fps ?? 30
|
||||
for (const x of r.findings) {
|
||||
// on a plan, what's read from the source frames or held against the takes' words is told, not held (ON_PLAN_WARNS)
|
||||
const soft = file?.plan && x.level === "error" && ON_PLAN_WARNS.has(x.check)
|
||||
findings.push({ goal, check: x.check, level: soft ? "warn" : x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: soft ? `${x.says}${PLAN_SOFT}` : x.says, fix: x.fix, by: x.by })
|
||||
}
|
||||
// on a plan, a check that couldn't run (the farm busy or down, a frame that wouldn't extract) waits: nothing in the
|
||||
// cut to fix, and the render's own check runs it again
|
||||
for (const t of r.threw) (t.waits || file?.plan ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.waits || !file?.plan ? t.says : `couldn't check the plan, so the render's check holds it: ${t.says}` })
|
||||
for (const x of r.findings)
|
||||
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
|
||||
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
|
||||
}
|
||||
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
|
||||
// a composition named with a manifest: one of its cuts checked on its plan (`raea render --plan`), before it's drawn
|
||||
// (plan.ts). It holds that cut alone: the project's own checks and the goals' job checks (the count, the brief's
|
||||
// quotes) are the render's and publish's to hold, never a reason not to draw one cut
|
||||
const planned = cutPlan(o.manifest, named, cwd)
|
||||
// the project's own: once, whatever its goals
|
||||
const once = planned ? [] : ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
|
||||
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
|
||||
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
|
||||
const verdicts: GoalVerdict[] = []
|
||||
const allFiles = new Set<string>()
|
||||
@@ -168,16 +155,10 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
: at === "publish" || at === "done"
|
||||
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
|
||||
: []
|
||||
// a cut's plan (above), else a render's manifest kept away from its export (`raea render --manifest M`): the one
|
||||
// file named reads it
|
||||
const files: FileFacts[] = planned
|
||||
? [planFacts(planned.manifest, planned.abs, root, at, contract)]
|
||||
: wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
|
||||
if (o.manifest && !planned && files.length === 1) {
|
||||
files[0].manifest = JSON.parse(readFileSync(path.resolve(cwd, o.manifest), "utf8")) as FileFacts["manifest"]
|
||||
files[0].fps = files[0].manifest?.fps ?? files[0].fps
|
||||
}
|
||||
const checks = checksOf(contract, at, o.only).filter((c) => !planned || c.over !== "job")
|
||||
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
|
||||
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
|
||||
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
|
||||
const checks = checksOf(contract, at, o.only)
|
||||
const before = findings.length
|
||||
const brokeBefore = broke.length
|
||||
const j = job(contract, deliverables, files)
|
||||
@@ -210,32 +191,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
}
|
||||
}
|
||||
|
||||
/** a composition's plan: `--manifest` naming a plan (or any manifest) with one composition named */
|
||||
export function cutPlan(manifest: string | undefined, named: string[], cwd = process.cwd()): { abs: string; manifest: FileFacts["manifest"] & object } | null {
|
||||
if (!manifest || named.length !== 1 || !COMPOSITION.test(named[0])) return null
|
||||
const abs = path.resolve(cwd, manifest)
|
||||
return { abs, manifest: JSON.parse(readFileSync(abs, "utf8")) }
|
||||
}
|
||||
|
||||
/** written whole or not at all: plans of several cuts are checked at once, each writing review/goal.json */
|
||||
const writeWhole = (p: string, text: string) => {
|
||||
const tmp = `${p}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, text)
|
||||
renameSync(tmp, p)
|
||||
}
|
||||
|
||||
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
|
||||
* each file named (a plan's beside the plan: OUT.plan.check.json) */
|
||||
export function writeReport(r: Report, named: string[], plan?: string) {
|
||||
* each file named */
|
||||
export function writeReport(r: Report, named: string[]) {
|
||||
const dir = path.join(r.root, "review")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeWhole(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
|
||||
const one = (f: string, out: string) => {
|
||||
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
|
||||
for (const f of named) {
|
||||
const mine = r.findings.filter((x) => x.file === f)
|
||||
writeWhole(out, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
|
||||
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
|
||||
}
|
||||
for (const f of named) one(f, `${media.stem(path.join(r.root, f))}.check.json`)
|
||||
if (plan) for (const f of r.files) one(f, `${media.stem(plan)}.check.json`)
|
||||
}
|
||||
|
||||
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
|
||||
@@ -261,8 +226,7 @@ function flag(a: string[], name: string): string | undefined {
|
||||
}
|
||||
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
|
||||
|
||||
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
|
||||
raea goal check EDIT.tsx --at edit --manifest OUT.plan.json (a cut checked on its plan, raea render --plan, before it's drawn)
|
||||
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
|
||||
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
|
||||
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
|
||||
@@ -285,8 +249,7 @@ export async function main(argv: string[]): Promise<number> {
|
||||
console.error(`raea goal check: ${(e as Error).message}`)
|
||||
return 2
|
||||
}
|
||||
const plan = cutPlan(flag(a, "--manifest"), files.map((n) => path.relative(r.root, path.resolve(n))))
|
||||
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))), plan?.abs)
|
||||
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
|
||||
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
|
||||
return r.passed ? 0 : 1
|
||||
}
|
||||
|
||||
@@ -121,13 +121,13 @@ test("a check runs only at its moments", async () => {
|
||||
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
|
||||
})
|
||||
|
||||
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", async () => {
|
||||
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
||||
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
|
||||
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
|
||||
const asked: string[] = []
|
||||
const rules = await clefVerdict(g, d, (_dir, file, says, from, to) => {
|
||||
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
|
||||
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
|
||||
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
|
||||
})
|
||||
@@ -136,7 +136,7 @@ test("clef judges a rule on the file it names, else on every video made, and say
|
||||
expect(rules.all?.pass).toBe(false)
|
||||
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
|
||||
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||
expect((await clefVerdict(g, empty, () => [])).all?.why).toContain("names no file on disk")
|
||||
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
|
||||
})
|
||||
|
||||
test("a reading kept beside a file isn't the work changing", () => {
|
||||
@@ -150,20 +150,3 @@ test("a reading kept beside a file isn't the work changing", () => {
|
||||
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
|
||||
expect(newest(d)!).toBeGreaterThan(1_000_000)
|
||||
})
|
||||
|
||||
test("clef hears several cuts at once, and the critic reads while it does", async () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-at-once-"))
|
||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
||||
const names = ["a", "b", "c", "d", "e", "f", "g", "h"]
|
||||
for (const n of names) writeFileSync(path.join(d, `out/cuts/${n}_9x16.mp4`), "x")
|
||||
const g = { name: "rules", rules: [{ id: "seen", says: "No caption covers a face" }] } as never
|
||||
let now = 0, most = 0
|
||||
const rules = await clefVerdict(g, d, async (_dir, _file, says) => {
|
||||
most = Math.max(most, ++now)
|
||||
await new Promise((ok) => setTimeout(ok, 20))
|
||||
now--
|
||||
return says.map(() => ({ choice: "true", says: "fine" }))
|
||||
})
|
||||
expect(most).toBe(6)
|
||||
expect(rules.seen?.pass).toBe(true)
|
||||
})
|
||||
@@ -1,201 +0,0 @@
|
||||
// A cut checked on its plan before it's drawn (src/plan.ts): what its frames show read from its sources' frames, what it
|
||||
// says from its takes' words, and the floor's text rules on every frame
|
||||
import { expect, test } from "bun:test"
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { type Answer, useSender } from "../src/media.ts"
|
||||
import { compose, drawn, layersOf, linesOf, PLAN_SOFT, said, samples, textRules, textRuns } from "../src/plan.ts"
|
||||
import { goalCheck, text, writeReport } from "../src/run.ts"
|
||||
import { CLIP, project, put } from "./project.ts"
|
||||
|
||||
const full = (over: Record<string, unknown> = {}) => ({ src: "a.mp4", at: 1, box: [0, 0, 1080, 1920], fit: "cover", ...over })
|
||||
|
||||
test("a video is drawn by its fit and object-position, and what of it the frame shows is its crop", () => {
|
||||
// a 16:9 picture covering a 9:16 frame, centred: 3413 px wide, 1167 px of it off each side
|
||||
const c = drawn(full(), 1920, 1080)
|
||||
expect(c.map(Math.round)).toEqual([-1167, 0, 3413, 1920])
|
||||
// object-position 76% across (as `position: [0, 0.76, 0, 0.5]` says it)
|
||||
expect(Math.round(drawn(full({ position: [0, 0.76, 0, 0.5] }), 1920, 1080)[0])).toBe(Math.round(0.76 * (1080 - 3413.33)))
|
||||
// contain letterboxes it; fill stretches it
|
||||
expect(drawn(full({ fit: "contain" }), 1920, 1080).map(Math.round)).toEqual([0, 656, 1080, 608])
|
||||
expect(drawn(full({ fit: "fill" }), 1920, 1080)).toEqual([0, 0, 1080, 1920])
|
||||
const [l] = layersOf([full() as never], 1080, 1920, () => [1920, 1080])
|
||||
expect(l.crop).toEqual([0.342, 0, 0.316, 1])
|
||||
// a box clipped by its parent (`clip`) shows only that part of it
|
||||
const [h] = layersOf([full({ box: [-566, 0, 4096, 2304], clip: [0, 0, 1080, 1920] }) as never], 1080, 1920, () => [3840, 2160])
|
||||
expect(h.seen).toEqual([0, 0, 1080, 1920])
|
||||
expect(h.crop[3]).toBeCloseTo(1920 / 2304, 3)
|
||||
// a fading video is left out while another shows; alone it's what's seen
|
||||
expect(layersOf([full() as never, full({ opacity: 0.2 }) as never], 1080, 1920, () => [1920, 1080])).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("a source's scene, read of its crop, lands in the cut's frame: a face at the crop's edge is a face at the frame's", () => {
|
||||
// the reader read the crop (304x540 of a 960x540 picture) at 540 wide: a face touching its right edge, a person
|
||||
const scene = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array.from({ length: 48 }, (_, r) => (r > 20 ? "7".repeat(27) : "0".repeat(27))) }, things: [[100, 300, 300, 660, "person", 0.9]], faces: [[480, 200, 60, 80, "face", 0.9]] }
|
||||
const faces = { w: 540, h: 960, faces: [[480, 200, 60, 80, 0.9]] }
|
||||
const ls = layersOf([full() as never], 1080, 1920, () => [960, 540])
|
||||
const out = compose(ls, 1080, 1920, () => ({ scene, faces }) as never)
|
||||
expect(out.scene?.w).toBe(540)
|
||||
const [x, y, w, h] = out.faces!.faces[0]
|
||||
expect(Math.round(x + w)).toBe(540)
|
||||
expect([Math.round(y), Math.round(h)]).toEqual([200, 80])
|
||||
expect(out.scene!.grid.people[30]).toBe("7".repeat(27))
|
||||
expect(out.scene!.things[0][4]).toBe("person")
|
||||
// a video drawn over the bottom half hides what's under it there, and its top edge is a seam
|
||||
const two = layersOf([full() as never, full({ box: [0, 960, 1080, 960] }) as never], 1080, 1920, () => [960, 540])
|
||||
const low = { ...scene, things: [[100, 600, 300, 300, "dog", 0.9]] }
|
||||
const o2 = compose(two, 1080, 1920, (l) => (l.v.box[1] ? ({ scene: { ...scene, things: [], faces: [] }, faces: { ...faces, faces: [] } } as never) : ({ scene: low, faces } as never)))
|
||||
expect(o2.faces!.seams).toContainEqual(["h", 480, 1])
|
||||
expect(o2.scene!.things).toEqual([])
|
||||
})
|
||||
|
||||
test("what a plan's cut says is its voice clips' takes' words, where the clips put them", () => {
|
||||
const take = [{ text: "one", start: 10, end: 10.4 }, { text: "two", start: 10.5, end: 10.9 }, { text: "three", start: 11, end: 11.5 }, { text: "four", start: 11.6, end: 12 }]
|
||||
// frames 30-75 at 30 fps (1.0-2.5 s) show the take from 10.45 s: "one" is out, "three" whole, "four" cut a little
|
||||
const w = said([{ from: 30, to: 75, src: "media/take.mp4", at: 10.45 }], 30, () => take)
|
||||
expect(w.map((x) => x.text)).toEqual(["two", "three", "four"])
|
||||
expect(w[0].start).toBeCloseTo(1.05, 5)
|
||||
// music isn't speech
|
||||
expect(said([{ from: 0, to: 30, src: "music/bed.mp3", at: 0 }], 30, () => take)).toEqual([])
|
||||
})
|
||||
|
||||
test("the floor's text rules hold every frame of a plan: the UI zones, the frame's edges", () => {
|
||||
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, text: [
|
||||
{ text: "In the zone at the right", box: [100, 830, 900, 93], ink: [139, 830, 860, 93], size: 58 },
|
||||
{ text: "Clear of everything", box: [200, 1000, 680, 93], size: 58 },
|
||||
{ text: "Off the frame entirely here", box: [900, 1200, 600, 93], ink: [900, 1200, 600, 93], size: 58 },
|
||||
] }))
|
||||
const m = { width: 1080, height: 1920, fps: 30, length: 60, frames }
|
||||
const r = textRules(m)
|
||||
expect(r.map((x) => [x.rule, x.level])).toEqual([["safe-area", "error"], ["clipped", "error"]])
|
||||
expect(r[0].says).toMatch(/sits in the app's UI zone at the right \(keep 140 px clear\)/)
|
||||
// a typed text (growing into the next) is one run, judged by its last text
|
||||
const typed = textRuns({ fps: 30, frames: ["Hel", "Hello", "Hello there"].map((t, f) => ({ frame: f, text: [{ text: t, box: [300, 900, 400, 80], size: 60 }] })) })
|
||||
expect(typed.map((x) => x.text)).toEqual(["Hello there"])
|
||||
expect(samples(m)).toEqual([0, 0.5, 1, 1.5])
|
||||
// a text laid out on several lines is read a line each, as the export's reader reads it
|
||||
expect(linesOf("Make your Wishlist and organize your Gift Exchange", [0, 100, 600, 200], 2).map((l) => l[4])).toEqual(["Make your Wishlist and", "organize your Gift Exchange"])
|
||||
})
|
||||
|
||||
test("raea goal check --at edit --manifest PLAN EDIT.tsx: the cut's plan is checked, named for its export, before it's drawn", async () => {
|
||||
const d = project(null)
|
||||
put(d, "edit.tsx", "export default 1\n")
|
||||
put(d, "media/take.mp4", readFileSync(CLIP))
|
||||
const frames = Array.from({ length: 90 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Down in the bottom zone", box: [140, 1600, 800, 90], size: 60 }] }))
|
||||
const plan = put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 90, plan: true, frames, sounds: { fps: 30, clips: [] } }))
|
||||
// the farm's reader, standing in: every crop read has a face cut by its right edge
|
||||
const before = process.env.RAEA_CLOUD_GPU_URL
|
||||
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
|
||||
let read = 0
|
||||
useSender(async (_url, body): Promise<Answer> => {
|
||||
const n = (JSON.parse(String(body)) as { frames: string[] }).frames.length
|
||||
read += n
|
||||
const g = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [[470, 300, 70, 120, "face", 0.9]], seams: [] }
|
||||
return { status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(g) }) }
|
||||
})
|
||||
try {
|
||||
const r = await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
|
||||
const mine = r.findings.filter((x) => x.file === "out/cuts/ad_concept_v1_9x16.mp4")
|
||||
expect(mine.some((x) => x.check === "floor" && x.level === "error" && /UI zone at the bottom/.test(x.says))).toBe(true)
|
||||
// a face cut by the edge is read from the source frames: on a plan it's told, and the render's check holds it
|
||||
expect(mine.some((x) => x.check === "frames" && x.level === "warn" && /right edge/.test(x.says) && x.says.endsWith(PLAN_SOFT))).toBe(true)
|
||||
// only what the plan knows exactly holds it: floor, sound and text sizes
|
||||
expect(mine.filter((x) => x.level === "error").every((x) => x.check === "floor" || x.check === "sound" || (x.check === "frames" && /px/.test(x.says)))).toBe(true)
|
||||
expect(r.passed).toBe(false)
|
||||
expect(read).toBe(6)
|
||||
// each source frame's reading is kept: the plan checked again reads nothing
|
||||
await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
|
||||
expect(read).toBe(6)
|
||||
writeReport(r, [], plan)
|
||||
expect(existsSync(path.join(d, "out/cuts/ad_concept_v1_9x16.plan.check.json"))).toBe(true)
|
||||
} finally {
|
||||
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
|
||||
else process.env.RAEA_CLOUD_GPU_URL = before
|
||||
}
|
||||
})
|
||||
|
||||
/** a plan of one cut with nothing in it to fix: its text inside the safe area, over the test clip */
|
||||
function cleanPlan(d: string, name = "out/cuts/ad_concept_v1_9x16.plan.json") {
|
||||
put(d, "edit.tsx", "export default 1\n")
|
||||
put(d, "media/take.mp4", readFileSync(CLIP))
|
||||
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Safe in the middle", box: [140, 900, 800, 90], size: 60 }] }))
|
||||
return put(d, name, JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 60, plan: true, frames, sounds: { fps: 30, clips: [] } }))
|
||||
}
|
||||
/** the farm's reader, standing in for a test: `answer` gives each POST's reply */
|
||||
async function withFarm<T>(answer: (n: number) => Answer, run: () => Promise<T>): Promise<T> {
|
||||
const before = process.env.RAEA_CLOUD_GPU_URL
|
||||
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
|
||||
useSender(async (_url, body) => answer((JSON.parse(String(body)) as { frames: string[] }).frames.length))
|
||||
try {
|
||||
return await run()
|
||||
} finally {
|
||||
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
|
||||
else process.env.RAEA_CLOUD_GPU_URL = before
|
||||
}
|
||||
}
|
||||
const EMPTY = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [], seams: [] }
|
||||
|
||||
test("a plan holds its own cut alone: the brief's count, its quotes and the project's checks don't stop it being drawn", async () => {
|
||||
// the brief asks for 10 cuts, 1 is planned, and the open item about the count waits for a person (who answers at the
|
||||
// first stop, after the first render); the brief's text isn't in the project either
|
||||
const asked = { question: "Only 2 interviews came: cut fewer?", from: "10 total videos", about: "count" }
|
||||
const d = project({ kind: "cut", packs: { naming: false }, cut: { brief: "media/brief.txt", count: { value: 10, from: "10 total videos" }, formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }], open: [asked] } })
|
||||
const plan = cleanPlan(d)
|
||||
const r = await withFarm(
|
||||
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(EMPTY) }) }),
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
|
||||
expect(r.checks).not.toContain("count")
|
||||
expect(r.checks).not.toContain("quotes")
|
||||
expect(r.checks).not.toContain("registered")
|
||||
expect(r.passed).toBe(true)
|
||||
// the same project checked at edit without a plan still holds the count
|
||||
const whole = await goalCheck({ cwd: d, at: "edit" })
|
||||
expect(whole.findings.some((x) => x.check === "count" && x.level === "error")).toBe(true)
|
||||
})
|
||||
|
||||
test("a plan the farm can't read waits: nothing to fix, so it doesn't fail", async () => {
|
||||
const d = project(null)
|
||||
const plan = cleanPlan(d)
|
||||
let asked = 0
|
||||
const r = await withFarm(
|
||||
() => {
|
||||
asked++
|
||||
return { status: 503, ok: false, text: "busy" }
|
||||
},
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
expect(asked).toBeGreaterThan(0)
|
||||
expect(r.broke).toEqual([])
|
||||
expect(r.waits.map((w) => w.check)).toContain("frames")
|
||||
expect(r.waits.find((w) => w.check === "frames")?.says).toMatch(/render's check holds it.*503/)
|
||||
expect(r.errors).toBe(0)
|
||||
expect(r.passed).toBe(true)
|
||||
expect(text(r)).toMatch(/^PASSED .*waiting/m)
|
||||
})
|
||||
|
||||
test("on a plan, text over a face and talking with no captions are warnings: the render's check holds them", async () => {
|
||||
const d = project({ kind: "cut", packs: { naming: false }, cut: { formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }] } })
|
||||
// a caption with nothing said under it, straight over a face the farm reads in every frame
|
||||
const plan = cleanPlan(d)
|
||||
const m = JSON.parse(readFileSync(plan, "utf8"))
|
||||
m.length = 240
|
||||
m.frames = Array.from({ length: 240 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: (f % 90) / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: f < 60 ? [{ text: "Nobody says this at all", box: [140, 300, 800, 300], size: 60 }] : [] }))
|
||||
// ... and from 5 s, past a text hook's opening, the take talks with no caption up
|
||||
put(d, "media/take.words.json", JSON.stringify("so this is what we said".split(" ").map((t, i) => ({ text: t, start: 0.3 + i * 0.4, end: 0.6 + i * 0.4 }))))
|
||||
m.sounds.clips = [{ key: "v", from: 150, to: 240, src: "media/take.mp4", at: 0 }]
|
||||
put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify(m))
|
||||
const face = { ...EMPTY, faces: [[170, 150, 200, 200, "face", 0.95]] }
|
||||
const r = await withFarm(
|
||||
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(face) }) }),
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
const soft = r.findings.filter((x) => x.says.endsWith(PLAN_SOFT))
|
||||
expect(soft.length).toBeGreaterThan(0)
|
||||
expect(soft.every((x) => x.level === "warn" && ["place", "captions", "reading", "frames"].includes(x.check))).toBe(true)
|
||||
expect(soft.some((x) => x.check === "place" && /covers a face/.test(x.says))).toBe(true)
|
||||
expect(soft.some((x) => x.check === "captions" && /no captions over the talking/.test(x.says))).toBe(true)
|
||||
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
|
||||
expect(r.passed).toBe(true)
|
||||
})
|
||||
@@ -20,8 +20,7 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
|
||||
every project. A line there beats any guide.
|
||||
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
|
||||
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
|
||||
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
|
||||
`raea guide brief` has its types, a cut goal's contract and an example.
|
||||
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction.
|
||||
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
|
||||
4. **The floor**: what breaks a piece, read again right before every edit.
|
||||
5. **One guide per mode**: what that kind of piece has to do.
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
# brief.ts: the brief as code
|
||||
|
||||
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
|
||||
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
|
||||
one is on this page, so you don't need to open the SDK.
|
||||
|
||||
## The shape
|
||||
|
||||
```ts
|
||||
import { brief, cut, rules } from "raea/brief"
|
||||
|
||||
export default brief({
|
||||
title: string, // the project as people name it
|
||||
for?: string, // the client or person it's for
|
||||
audience?: string, // who watches, and where
|
||||
believe?: string, // the one thing they should think afterwards
|
||||
voice?: string, look?: string, sound?: string,
|
||||
notDoing?: string[], // the anti-goals
|
||||
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
|
||||
sections?: { heading: string, text: string }[],
|
||||
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
|
||||
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
|
||||
})
|
||||
```
|
||||
|
||||
A goal made with `cut({...})` or `rules({...})` takes these fields:
|
||||
|
||||
| Field | What it is |
|
||||
| --- | --- |
|
||||
| `aim` | what the goal is, in the person's words |
|
||||
| `rules` | `{ id, run? , timeout?, file?, says? }[]`: what must hold before you stop (below) |
|
||||
| `cut` | a cut job's contract, the brief as rules (below) |
|
||||
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
|
||||
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
|
||||
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
|
||||
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
|
||||
|
||||
## A cut job's contract (`cut: {...}`)
|
||||
|
||||
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
|
||||
rule came from. raea refuses a `from` it can't find.
|
||||
|
||||
| Field | Type | What it holds |
|
||||
| --- | --- | --- |
|
||||
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
|
||||
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
|
||||
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
|
||||
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
|
||||
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
|
||||
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
|
||||
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
|
||||
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
|
||||
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
|
||||
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
|
||||
|
||||
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
|
||||
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
|
||||
one of the brief's hook types, as the brief names it.
|
||||
|
||||
A cut's `beats` are decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
|
||||
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
|
||||
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
|
||||
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
|
||||
(longer) or `"hold"` (even). The montage check holds the cut to them.
|
||||
|
||||
## Rules
|
||||
|
||||
| Kind | Example | How it's checked |
|
||||
| --- | --- | --- |
|
||||
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
|
||||
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
|
||||
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
|
||||
|
||||
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
|
||||
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
|
||||
is read.
|
||||
|
||||
## An example
|
||||
|
||||
```ts
|
||||
// brief.ts
|
||||
import { brief, cut } from "raea/brief"
|
||||
|
||||
export default brief({
|
||||
title: "Juniper Tea · street interviews, round 1",
|
||||
for: "Juniper Tea",
|
||||
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
|
||||
believe: "Juniper tastes like the tea shop, at home",
|
||||
goal: cut({
|
||||
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
|
||||
cut: {
|
||||
brief: "brief_docs/brief.txt",
|
||||
count: { value: 10, from: "10 unique cuts total" },
|
||||
seconds: [20, 40],
|
||||
formats: ["9:16"],
|
||||
cuts: [
|
||||
{
|
||||
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
|
||||
beats: [
|
||||
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
|
||||
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
|
||||
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
|
||||
],
|
||||
},
|
||||
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
|
||||
],
|
||||
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
|
||||
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
|
||||
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
|
||||
open: [
|
||||
{
|
||||
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
|
||||
from: "10 unique cuts total", about: "count",
|
||||
// left out until the person answers; then their words and who gave them
|
||||
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
|
||||
},
|
||||
],
|
||||
},
|
||||
rules: [
|
||||
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
|
||||
],
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
|
||||
@@ -16,11 +16,6 @@
|
||||
- Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels
|
||||
behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text
|
||||
and the face (`motion/placement`).
|
||||
- To put a caption or hook in a box that hugs each line, as TikTok draws its text, use `HugText` from
|
||||
`raea/hug-text`: `<HugText lines={[...]} fill="#E8423F" color="#fff" className="..." />`. Each line gets a fill as
|
||||
wide as its words, with one rounded shape around them all. You give the lines, so you decide where each breaks
|
||||
(a caption's come from its word groups). Its emoji draw in colour on any machine, as `EmojiText` from the same
|
||||
module also does. The box is allowed, never required.
|
||||
- Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export
|
||||
capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're
|
||||
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
|
||||
import type { Beat } from "./brief.gen";
|
||||
|
||||
export type Goal = { kind: GoalKind,
|
||||
/**
|
||||
@@ -232,29 +233,7 @@ text?: string, formats?: Array<string>, seconds?: [number, number],
|
||||
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
|
||||
* before the cut (Murch: emotion and story weigh most), and its pace
|
||||
*/
|
||||
beats?: Array<CutBeat>, };
|
||||
|
||||
export type CutBeat = {
|
||||
/**
|
||||
* where it starts, in seconds from the cut's start (0 for the first)
|
||||
*/
|
||||
at: number,
|
||||
/**
|
||||
* what the viewer feels here, in the person's words ("the itch of a chore left undone")
|
||||
*/
|
||||
feel: string,
|
||||
/**
|
||||
* what the viewer understands by its end ("the app does the reminding")
|
||||
*/
|
||||
story?: string,
|
||||
/**
|
||||
* its average shot length in seconds: the shots inside it average within a third of this
|
||||
*/
|
||||
asl?: number,
|
||||
/**
|
||||
* how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
|
||||
*/
|
||||
tempo?: string, };
|
||||
beats?: Array<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
|
||||
+1
-1
Submodule skills updated: 6c71231e97...fb72c5e256.
@@ -22,8 +22,7 @@ generic=(
|
||||
)
|
||||
# allowed: example home folders, the credits for what raea ports (NOTICE, ported headers), and licence boilerplate. Written
|
||||
# split ('Hyper''Frames') so this line doesn't match the names list itself.
|
||||
# (/home/sprite and /home/raea are raea cloud's box users, a Sprite's and a Fly Machine's: no person's folder)
|
||||
allow='/Users/(a|you|me|name|user|USER|runner)/|/home/(you|user|runner|USER|sprite|raea)/|PERFORMANCE OF'
|
||||
allow='/Users/(a|you|me|name|user|USER|runner)/|/home/(you|user|runner|USER)/|PERFORMANCE OF'
|
||||
allow+='|Portions ported from Hyper''Frames \(Apache-2\.0|ports? from Hyper''Frames|github\.com/heygen-com/hyper''frames'
|
||||
|
||||
names_file() {
|
||||
|
||||
Reference in new issue
Block a user