Photoreal Blender scenes from a one-paragraph brief, built by AI agents: image→3D props on fal, scripted layout, lighting, camera and grade.
Python
Move AnyShot to its own repo; the builder's shot routes call it over the API
Apekshik Panigrahicac014eb8f8a
diff --git a/README.md b/README.mdindex 19d4756..94d0db9 100644--- a/README.md+++ b/README.md@@ -76,13 +76,14 @@ SKILL.md the process; agents start herebuilder/CRAFT.md the review loop that separates good scenes from first draftsgenerate/ fal client: images and image→3D (Tripo H3.1, Meshy 7.1), with a local spend logpipeline/ Blender/ffmpeg discovery, a FIFO GPU queue, comparison renders, gallery pages, floating-prop check-camera/ camera rig and shot renderer: moves, rack focus, handheld walk, lens effects (camera/README.md)+camera/ camera rig and shot renderer: moves, rack focus, handheld walk, lens effects (synced from AnyShot)breakdown/ behind-the-scenes videos, promo cuts and the launch supercutscenes/<name>/ one folder per scene: assets.json, picks.json, shots.json, NOTES.md, brief.md, scripts/-farm/ a fal Serverless render farm for Cycles, and a client that renders a scene's shots on it+farm/ a fal Serverless render farm for Cycles (app.py, synced from AnyShot), and a client that renders a scene's shots on itblender_addon/ the fal Render Farm add-on for Blenderbuilder/ the same process packaged as a fal Serverless app (the hosted endpoint)docs/ endpoint and API notes, README images+scripts/ sync_from_anyshot.py: refresh the files shared with AnyShot from a sibling ../anyshot checkout```## Hosted endpoint (optional)@@ -97,12 +98,25 @@ The endpoint's code is in [`builder/`](builder) if you want to deploy your own c(`fal deploy builder/app.py::SceneBuilderApp --app-name anyscene-builder`). It needs `FAL_KEY` and `OPENROUTER_API_KEY` setas secrets on the app, and the `endpoint/` folder alongside it (the builder imports its planner and schema).+## Shooting builds: AnyShot++Stills and camera moves of a finished build are made by [AnyShot](https://github.com/apekshik/anyshot), an AI+cinematographer that lives in its own repo and runs as its own fal app. Deploy it on the same fal account and set+`fal secrets set ANYSHOT_APP=<your-fal-username>/anyshot`: the builder's `/scene2image`, `/scene2video` and `/shots`+routes (and the optional `shots` order on `/ref2scene`) forward to it over the fal API and relay its live log, and+AnyShot reads the build straight from the account's `/data` storage by `build_id`. AnyShot also takes any uploaded+`.blend`, so you can call it directly.++The code both repos use (`camera/`, `builder/blender_gpu.py`, `farm/app.py`, `pipeline/env.sh`, `pipeline/gpu_run.sh`)+lives in AnyShot; the copies here carry a "synced from" header. Edit them there, then run+`python scripts/sync_from_anyshot.py` with AnyShot checked out next to this repo.+## Render farm add-on[`blender_addon/`](blender_addon) is a Blender add-on that renders the open scene on fal GPUs instead of your own:direct a scene in Blender, press **Render animation on fal**, and the frames come back into the scene's output pathwith the same names a local render would give them. See [`blender_addon/README.md`](blender_addon/README.md) for-install and settings. The farm itself is [`farm/app.py`](farm/app.py); you can deploy your own and point the add-on's+install and settings. The farm itself is [`farm/app.py`](farm/app.py) (its home is AnyShot's `farm/app.py`); you can deploy your own and point the add-on's**Farm app** preference at it.## Licencediff --git a/anyshot/README.md b/anyshot/README.mddeleted file mode 100644index 57e974f..0000000--- a/anyshot/README.md+++ /dev/null@@ -1,228 +0,0 @@-# AnyShot: an AI cinematographer for 3D scenes--AnyShot turns a 3D scene and plain-language shot directions into finished stills and camera moves. It is not a-render farm with a prompt box: a Claude agent works the set the way a DP would. It reads the scene, works out what-is where, turns "slow push along the counter, rack focus to the register" into a real camera move with a lens, an-ease and a focus pull, checks every frame of the move for clearance against walls and furniture, blocks each shot-with quick previews and fixes what reads wrong from the new angle, then renders and grades the finals.--- **`/scene2image`**: finished, graded stills, rendered with Cycles on the agent's own GPU.-- **`/scene2video`**: camera moves as mp4s. The agent plans and checks the moves; the frames are rendered on a render- farm app (`farm/app.py`) across up to 100 GPUs at once, then graded and encoded.--Direct it shot by shot (`shots`), or just brief it in words (`prompt`: "a 40-second piece: open wide, walk in like a-visitor, then three close dolly reveals with rack focus") and the agent plans the shot list itself.--The scene comes in one of two ways:-- `scene_url`: a `.blend`, or a `.zip` holding a `.blend` and its textures, uploaded anywhere (fal storage, S3,- a signed link). The agent unpacks it, finds the main `.blend`, repairs texture paths, packs a self-contained copy- and works only on that copy. It keeps the scene's own look.-- `build_id`: an [AnyScene](../README.md) build (`/ref2scene`) on the same fal account's storage. The agent also gets- the builder's notes and scouting cameras, so shots can be asked for by name.--Optionally, `floor_plan_url` is an image of the set's plan, with or without a camera path drawn on it. The agent-registers the plan to the scene and places cameras from it, following a drawn path as a walkthrough.--Each order is retry-safe: an identical request (same scene, shots, settings) returns the finished result, attaches to-the attempt still running, or resumes a dead one where it stopped, without re-rendering frames already on disk.--## How it works--```-request ─▶ AnyShotApp (fal, 1 GPU) farm/app.py (fal, up to 100 GPUs)- ├ fetch the scene (or open the AnyScene build)- ├ Claude agent (builder/shots.py, builder/SHOTS.md)- │ read the set · plan cameras (camera/camrig.py)- │ clearance check every frame · block with Eevee previews- │ stills: Cycles finals on this GPU, ffmpeg grade- │ video: farm_render ────────────────────────────────▶ frame chunks, one Blender per request- │ grade + encode mp4 ◀───────────────────────── frames zip on fal storage- └ stills / videos / result.json ─▶ response-```--The code is shared with the AnyScene scene builder rather than copied. `anyshot/app.py` imports `builder/shots.py`-(the `ShotsDirector` agent and its `farm_render` tool), `builder/scene_builder.py` (the agent harness: hooks, stage-events, session resume) and `endpoint/planner.py`, and ships them with `local_python_modules`. The agent's workspace-gets `camera/` (the camrig shot rig), `pipeline/` and `SHOTS.md` (its instructions) at deploy time. The scene-builder's own `/scene2image` and `/scene2video` routes run the same code.--## Deploy your own--You need a fal account with Serverless access and an [OpenRouter](https://openrouter.ai) or Anthropic API key.--1. **Secrets.** fal secrets are shared by every app on the account, so set each once:-- ```bash- fal secrets set OPENROUTER_API_KEY=... # Claude through OpenRouter (or ANTHROPIC_API_KEY=... for the Anthropic API)- fal secrets set FAL_KEY=... # a fal key of this account: uploads, and the farm calls- fal secrets set FAL_SERVERLESS_KEY=... # optional: the key the farm is called with (defaults to FAL_KEY)- fal secrets set ANYSHOT_FARM_APP=<your-fal-username>/blender-farm- ```-- With both OPENROUTER_API_KEY and ANTHROPIC_API_KEY set, OpenRouter is used. Optional: `FARM_WORKERS` (default- 100) caps how many farm requests run at once; keep it at or under the farm's `max_concurrency` and your- account's concurrency limit.--2. **The render farm** (for `/scene2video`):-- ```bash- fal deploy farm/app.py::BlenderFarm --app-name blender-farm --auth private- ```-- Without `ANYSHOT_FARM_APP` (or if the farm is down), `/scene2video` still works: the agent renders the frames on- its own GPU in chunks, which is slower.-- How the farm is set up, and why:- - **RTX 5090 workers** (`machine_type` in `farm/app.py`): $2.50/h against $4.00/h for an RTX PRO 6000, with about- 10% fewer cores. Switch to `GPU-RTXPRO6000` for sets that need more than 32 GB of VRAM.- - **Chunks of at least 24 frames** (`FARM_MIN_CHUNK`, a secret/env on the AnyShot app). Every chunk pays a worker- boot, the scene download and Blender setting up the set; at 5 frames a chunk that overhead was about 75% of the- bill.- - **Each worker downloads the scene to its own disk** from the bundle's CDN URL. Don't point workers at one shared- copy on `/data`: when 42 workers read the same 1.6 GB set at once, each waited about 30 minutes before its first- frame, against 18 seconds to download its own copy.- - **Shared OptiX kernel cache** on `/data/anyscene-farm/optix/<gpu>/` (a small file, read once at boot). OptiX- compiles its kernels on a worker's first Cycles render, about 2 minutes; each worker starts from the shared cache,- warms it in `setup()` and saves it back when it grows.- - **`keep_alive = 300`** so a burst of orders reuses booted workers.-- Measured on a 1.6 GB set (458 objects, 8.6M triangles, 118 textures) at 1920x804 and 160 samples: 42 chunks of 8- frames on 42 RTX 5090s, all done in 3 minutes, about 102 s of Blender per chunk (17 s to the first frame, then- about 11 s a frame). A 20-second walkthrough at 1920x804 and 256 samples cost about $9 of farm time.--3. **AnyShot:**-- ```bash- fal deploy anyshot/app.py::AnyShotApp --app-name anyshot --auth private- ```-- Deploy from the repository root: the app pulls in `builder/`, `endpoint/` and `camera/`. Requirements are listed- on the app class (`fal==1.84.0`, `claude-agent-sdk==0.2.176`, `anthropic`, `pydantic`, `pillow`, `fal-client`);- the deploying Python needs the same packages, e.g.- `uv run --python 3.13 --with fal==1.84.0 --with pydantic --with anthropic --with pillow --with fal-client --with claude-agent-sdk==0.2.176 fal deploy ...`.- The worker image installs Blender 5.0.1, ffmpeg and node. `request_timeout` is 7200 s (fal's cap): the agent- stops itself at 110 minutes to deliver what it has, and a retried request resumes the order.--4. **Optional, AnyScene:** `/ref2scene` on the scene builder (`builder/app.py`) takes a `shots` order and hands the- finished build to AnyShot. Set `ANYSHOT_APP=<your-fal-username>/anyshot` so it calls your deployment.--Storage: AnyShot keeps uploaded scenes and its retry index under `/data/anyshot/`, and reads AnyScene builds from-`/data/anyscene/builder/`, on the account's persistent `/data` volume. Each order's working files (blocking-previews, frames, the packed copy) live in `out/shots/<job_id>/` inside the scene's workspace.--## API--Both routes take the same body and return the same response.--| field | type | |-|---|---|---|-| `scene_url` | string | A `.blend`, or a `.zip` with a `.blend` and its textures. Give this **or** `build_id`. |-| `build_id` | string | An AnyScene build (`b_...`) on the same account. |-| `prompt` | string | Direction for the whole order in your own words ("a 45 s trailer: open wide, walk in like a visitor, then slow dolly reveals with rack focus; moody"). On its own, the agent plans the shot list; with `shots`, it applies to all of them. Give `prompt`, `shots`, or both. |-| `shots` | list | Optional. Each `{"name": ..., "description": ...}`; either or both. A name picks an existing camera (an AnyScene scouting camera, or a camera in the `.blend`) and names the output file. |-| `floor_plan_url` | string | Optional plan image, optionally with a camera path or camera marks drawn on it. |-| `settings` | object | Optional: `res` `[w, h]`, `samples`, `fps`, `seconds` (per video shot), `lens_mm`, `handheld` (`none` / `walk` / `subtle`), `look` (`clean` / `cinematic` / `gritty` / `vintage`). Missing ones are chosen per shot. |-| `dials` | object | Optional changes to the set for this order only (`time_of_day`, `atmosphere`, `power`, `warmth`, `wetness`, ...). The source scene is never changed. |-| `effort` | string | Claude effort: `low`, `medium` (default), `high`, `xhigh`, `max`. |-| `fresh` | bool | Shoot again even if an identical order already finished. |--Response: `job_id`, `scene_id`, `stills` (URLs), `videos` (URLs), `result` (per shot: camera, lens, move, settings-and a note), `missing` (anything not delivered), `agent_cost_usd`, `minutes`.--The agent streams its progress as `ANYSCENE_STAGE {json}` lines in the request's logs (`stage`, `message`, and a-`preview_url` for blocking frames and finals). An order takes minutes for a couple of stills and longer for video-(blocking, the farm, grading); use the queue, not a synchronous call.--### curl--```bash-# 1. upload the scene (any URL works; this uses fal storage via the client below, or your own bucket)-# 2. submit-curl -s https://queue.fal.run/<your-fal-username>/anyshot/scene2video \- -H "Authorization: Key $FAL_KEY" -H "Content-Type: application/json" \- -d '{- "scene_url": "https://example.com/my_set.zip",- "shots": [- {"name": "counter_push", "description": "slow push along the counter at eye level, ending close on the register; rack focus from the jar in the foreground to the register"},- {"description": "walk in through the door and turn to reveal the back room, handheld walk, 24mm"}- ],- "settings": {"seconds": 6, "fps": 24, "res": [1920, 1080]}- }'-# -> {"request_id": "...", "status_url": ".../requests/<id>/status", "response_url": ".../requests/<id>"}--curl -s "https://queue.fal.run/<your-fal-username>/anyshot/requests/<id>/status?logs=1" -H "Authorization: Key $FAL_KEY"-curl -s "https://queue.fal.run/<your-fal-username>/anyshot/requests/<id>" -H "Authorization: Key $FAL_KEY"-```--### Python--```python-import fal_client # FAL_KEY in the environment--scene = fal_client.upload_file("my_set.zip")-res = fal_client.subscribe(- "<your-fal-username>/anyshot/scene2image",- arguments={- "scene_url": scene,- "shots": [{"description": "wide establishing shot from the doorway, eye level, 24mm"},- {"description": "tight 85mm detail of the teapot on the counter, shallow focus"}],- "settings": {"res": [1920, 1080]},- },- with_logs=True,- on_queue_update=lambda u: [print(l["message"]) for l in getattr(u, "logs", None) or []],-)-print(res["stills"])-```--### Command line--`anyshot/client.py` uploads local files, prints the agent's live log and downloads the results:--```bash-export FAL_KEY=... ANYSHOT_APP=<your-fal-username>/anyshot-python anyshot/client.py image --scene my_set.blend --shot "wide from the doorway, 24mm" --shot "hero: tight on the teapot, f/1.8"-python anyshot/client.py video --scene my_set.zip --floor-plan plan_with_path.png \- --shot "follow the drawn path at walking pace" --settings '{"seconds": 8}'-python anyshot/client.py video --build-id b_1234567890 --shot hero_wide --shot "orbit the bar, 35mm"-```--`--shot` takes a camera name, words, or `name: words` for both. Results land in `--out` (default `anyshot_out/`):-`response.json`, `events.jsonl`, and the stills and videos.--## Shot grammar--Describe shots the way you would to a camera crew. The agent maps the words onto the camrig moves-(`camera/README.md`) and checks each against the set:--| say | the agent does |-|---|---|-| push in, dolly in, pull out, track along X | a dolly move on 2+ keys; "slow" is about 0.2-0.4 m/s |-| truck, crab, slide past X | sideways move |-| crane up, jib, rise, pedestal down | vertical move, aim held or reframed |-| pan, tilt, whip pan to X | same position, the aim moves |-| orbit, arc, circle around X | an orbit on X's centre, with a radius and an angle range |-| reveal X | starts on a foreground element or behind an occluder and moves until X comes into view and frames it |-| rack focus / pull focus from A to B | a hold on A, then a focus pull to B, with a shallow f-stop so it reads |-| walkthrough, follow the path, Steadicam | a smooth path at walking pace and eye height; `handheld: walk` adds an operator's step and sway |-| dolly zoom, vertigo | the lens is solved per frame to hold the subject's size |-| locked off, tripod | a static camera; `subtle` handheld for life |-| wide / normal / tight, 24mm, 85mm | 18-24 mm / 35-50 mm / 85-135 mm, or the exact focal length |-| low angle, eye level, top down, over the shoulder of X | camera height and aim |-| "a 6 second push" | the shot's length (wins over `settings.seconds`) |--Objects are found by name in the scene, so naming them helps ("the teapot", "the red stool"); the agent also looks-at the set to find what you mean. A drawn path on a `floor_plan_url` becomes a walkthrough along it, and camera marks-(an X, a camera icon, a cone of view) become camera positions.--Every move is checked so the camera never passes within 0.45 m of a wall, furniture or a prop (dust, haze and glass-the move is meant to pass don't count). A path through an obstacle goes around it, and the result says so.--## Files--- `anyshot/app.py`: the fal app (`AnyShotApp`): request handling, scene fetching, retry index.-- `anyshot/client.py`: the CLI.-- `builder/shots.py`: `ShotsDirector` (the agent), `farm_render`, scene fetching and the shared `shoot()` runner.-- `builder/SHOTS.md`: the agent's instructions.-- `builder/scene_builder.py`: the agent harness shared with the scene builder.-- `camera/`: camrig (moves, focus, handheld) and `shoot.py` (previews, framing, finals).-- `farm/app.py`: the render farm.diff --git a/anyshot/app.py b/anyshot/app.pydeleted file mode 100644index 48de861..0000000--- a/anyshot/app.py+++ /dev/null@@ -1,274 +0,0 @@-"""AnyShot as a fal Serverless app: an AI cinematographer for 3D scenes (see anyshot/README.md).-- fal deploy anyshot/app.py::AnyShotApp --app-name anyshot --auth private- python anyshot/client.py video --scene ./set.zip --shot "slow push along the counter, ending on the register"--POST /scene2image a scene + shots in words or by name -> finished, graded stills (rendered on this worker's GPU)-POST /scene2video a scene + shots in words or by name -> camera moves as mp4s (frames rendered on the farm app)--The scene is either `scene_url` (a .blend, or a .zip holding a .blend and its textures) or `build_id` (an AnyScene-build on the same fal account's storage). A Claude agent (builder/shots.py, instructions in builder/SHOTS.md) reads-the set, plans every camera (moves, lenses, focus pulls, a path drawn on an optional floor plan), checks clearance on-every frame, blocks with quick previews, then renders finals. It streams ANYSCENE_STAGE lines that the fal queue relays-to the caller as logs.--Configuration is all environment (fal secrets): OPENROUTER_API_KEY or ANTHROPIC_API_KEY, FAL_KEY,-FAL_SERVERLESS_KEY (the key the farm is called with; defaults to FAL_KEY) and ANYSHOT_FARM_APP (the farm app id).-The agent, its tools and the camera rig are shared with the scene builder, not copied: this module imports them from-builder/, endpoint/ and camera/, the way kit/app.py does.-"""--import json-import os-import sys-from pathlib import PurePosixPath--import fal-from fal.container import ContainerImage-from pydantic import BaseModel, Field--_HERE = os.path.dirname(os.path.abspath(__file__))-_REPO = os.path.dirname(_HERE)-sys.path.insert(0, os.path.join(_REPO, "builder"))-sys.path.insert(0, os.path.join(_REPO, "endpoint"))-import planner # noqa: E402,F401 (Claude client used by scene_builder; module level so fal bundles it)-import schema # noqa: E402,F401-import scene_builder # noqa: E402-import shots # noqa: E402 (ShotsDirector, the farm_render tool, scene fetching)--if os.name == "nt":- # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath Linux can't unpickle.- _posix = PurePosixPath("/tmp")- ContainerImage.__dataclass_fields__["context_dir"].default = _posix- ContainerImage.context_dir = _posix- ContainerImage.__init__.__defaults__ = tuple(- _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()- )--TOOLKIT = scene_builder.toolkit_files() # SHOTS.md, SKILL.md, camera/, pipeline/...: carried in the app-BLENDER_GPU = open(os.path.join(_REPO, "builder", "blender_gpu.py"), encoding="utf-8").read()-OPTIX_CACHE_LOCAL = "/var/tmp/OptixCache_root/optix7cache.db"-OPTIX_CACHE_SHARED = "/data/anyscene/cache/optix7cache.db" # shared with the scene builder on the same account-BUILDS_DIR = "/data/anyscene/builder" # AnyScene builds (build_id) on this account's storage-SHOT_DIR = "/data/anyshot" # uploaded scenes (scenes/<scene_id>) and the retry index (_index)-BLENDER_VERSION = "5.0.1"-BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'-WARMUP = """import bpy-s = bpy.context.scene-s.render.engine = "CYCLES"; s.cycles.samples = 4; s.render.resolution_x = s.render.resolution_y = 64-m = bpy.data.materials.new("glass"); m.use_nodes = True; m.node_tree.nodes.new("ShaderNodeBsdfGlass")-bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))-bpy.context.object.data.materials.append(m)-bpy.ops.render.render()-print("WARMUP done")-"""--# identical to the scene builder's, so the image layers are shared-DOCKERFILE = f"""-FROM python:3.13-slim-ENV NVIDIA_DRIVER_CAPABILITIES=all-RUN apt-get update && apt-get install -y --no-install-recommends \\- curl ca-certificates xz-utils git procps fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 \\- libegl1 libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 ffmpeg nodejs ripgrep zip \\- && rm -rf /var/lib/apt/lists/*-RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\- | tar -xJ -C /opt \\- && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender.real-"""---def save_optix_cache():- """Copy this worker's OptiX cache to /data if it has grown, so new workers skip the ~2 min kernel compile."""- import shutil- if os.path.exists(OPTIX_CACHE_LOCAL) and (not os.path.exists(OPTIX_CACHE_SHARED)- or os.path.getsize(OPTIX_CACHE_LOCAL) > os.path.getsize(OPTIX_CACHE_SHARED)):- os.makedirs(os.path.dirname(OPTIX_CACHE_SHARED), exist_ok=True)- tmp = f"{OPTIX_CACHE_SHARED}.{os.getpid()}.tmp"- shutil.copy(OPTIX_CACHE_LOCAL, tmp)- os.replace(tmp, OPTIX_CACHE_SHARED)---class Shot(BaseModel):- name: str = Field("", description="A camera or move by name: one of an AnyScene build's scouting cameras "- "(its shots.json), a camera in the uploaded .blend, or a new name for the output.")- description: str = Field("", description="The shot in words, e.g. 'slow push along the pastry case, ending close "- "on the croissants, rack focus to the price card'. With a name, it adjusts "- "that camera.")---class ShotRequest(BaseModel):- scene_url: str | None = Field(None, description="The scene: a .blend, or a .zip holding a .blend and its textures "- "(any public or signed URL). Give this or build_id.")- build_id: str | None = Field(None, description="Or an AnyScene build (b_...) on the same fal account's storage.")- prompt: str = Field("", description=(- "Direction for the whole order in your own words, like you'd brief a camera crew: 'a 45 second trailer: "- "open wide, walk in like a visitor, then three slow dolly reveals with rack focus; moody, let the caustics "- "move'. With no shots, the agent plans the shot list from this; with shots, it applies to all of them."))- shots: list[Shot] = Field(default_factory=list, description="The shots to make, by name or in words. Optional "- "when prompt describes them.")- floor_plan_url: str | None = Field(None, description="Optional plan of the set (image), optionally with a camera "- "path or camera marks drawn on it; the agent follows it.")- settings: dict = Field(default_factory=dict, description=(- "Optional: res [w, h], samples, fps, seconds (per video shot), lens_mm, handheld (none|walk|subtle), "- "look (clean|cinematic|gritty|vintage). Missing ones are chosen per shot."))- dials: dict[str, float | str] = Field(default_factory=dict, description=(- "Optional changes to the set for this order only (time_of_day, atmosphere, power, warmth, wetness, ...); "- "the source scene is never changed."))- effort: str = Field("medium", description="Claude effort for the agent: low, medium, high, xhigh, max.")- fresh: bool = Field(False, description="Shoot again even if an identical request already has a result.")---class ShotResponse(BaseModel):- job_id: str- scene_id: str = Field(description="The build_id, or the id of the uploaded scene's workspace (s_...).")- stills: list[str]- videos: list[str]- result: dict = Field(description="Per shot: the camera, lens, move and settings used, and a note.")- missing: list[str]- agent_cost_usd: float | None- minutes: float---def _stage(stage, status, message):- print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": stage, "status": status, "message": message}), flush=True)---class AnyShotApp(fal.App):- machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]- image = ContainerImage.from_dockerfile_str(DOCKERFILE)- requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]- local_python_modules = ["shots", "scene_builder", "planner", "schema"]- min_concurrency = 0- max_concurrency = 10- request_timeout = 7200 # fal's cap; the agent stops at 110 min to deliver, and a retried request resumes- startup_timeout = 1200-- def setup(self):- import shutil- import subprocess- import time- os.makedirs("/opt/anyscene", exist_ok=True)- with open(shots.BLENDER_GPU_PATH, "w") as f:- f.write(BLENDER_GPU)- with open("/usr/local/bin/blender", "w") as f:- f.write(BLENDER_WRAPPER)- os.chmod("/usr/local/bin/blender", 0o755)- if os.path.exists(OPTIX_CACHE_SHARED):- os.makedirs(os.path.dirname(OPTIX_CACHE_LOCAL), exist_ok=True)- shutil.copy(OPTIX_CACHE_SHARED, OPTIX_CACHE_LOCAL)- t = time.time()- r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True, text=True,- timeout=900)- print(f"setup: OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s", flush=True)- save_optix_cache()-- @fal.endpoint("/scene2image")- async def scene2image(self, req: ShotRequest) -> ShotResponse:- """Finished, graded stills of a 3D scene: cameras named or described in words."""- return await self._order(req, "images")-- @fal.endpoint("/scene2video")- async def scene2video(self, req: ShotRequest) -> ShotResponse:- """Camera moves through a 3D scene, planned and clearance-checked by the agent, rendered on the farm."""- return await self._order(req, "video")-- async def _order(self, req: ShotRequest, mode: str) -> ShotResponse:- import asyncio- import hashlib- import time- import uuid-- t0 = time.time()- if bool(req.scene_url) == bool(req.build_id):- raise ValueError("give exactly one of scene_url or build_id")- if not req.shots and not req.prompt.strip():- raise ValueError("give shots, a prompt, or both")- if req.build_id and not req.build_id.replace("_", "").isalnum():- raise ValueError("bad build_id")-- # Retry-safe, as builder/app.py's _build: fal's queue re-runs a request that times out or loses its worker.- # Each identical order maps to one job; a repeat returns the finished result, attaches to a live attempt, or- # resumes a dead one in the same job folder (frames already on disk are not rendered again).- order = {"mode": mode, "scene_url": req.scene_url, "build_id": req.build_id, "floor_plan": req.floor_plan_url,- "prompt": req.prompt, "shots": [s.model_dump() for s in req.shots], "settings": req.settings, "dials": req.dials,- "effort": req.effort}- fp = hashlib.sha256(json.dumps(order, sort_keys=True).encode()).hexdigest()[:20]- index = os.path.join(SHOT_DIR, "_index", fp + ".json")- os.makedirs(os.path.dirname(index), exist_ok=True)- resume, rec = False, None- if not req.fresh and os.path.exists(index):- told = False- while True:- rec = json.load(open(index))- if rec.get("response"):- _stage("done", "done", f"identical request: returning finished job {rec['job_id']}")- return ShotResponse(**rec["response"])- alive = os.path.join(rec["work"], "out", "shots", rec["job_id"], ".alive")- if not os.path.exists(alive) or time.time() - os.path.getmtime(alive) > 90:- break # its attempt died: resume it below- if not told:- _stage("received", "running", f"identical request: attached to job {rec['job_id']}, still running")- told = True- await asyncio.sleep(20)- resume = True- else:- if req.build_id:- work, scene_id = os.path.join(BUILDS_DIR, req.build_id), req.build_id- else:- scene_id = "s_" + hashlib.sha256(req.scene_url.encode()).hexdigest()[:12]- work = os.path.join(SHOT_DIR, "scenes", scene_id)- rec = {"job_id": "j_" + uuid.uuid4().hex[:8], "work": work, "scene_id": scene_id, "fingerprint": fp,- "started": time.time()}- json.dump(rec, open(index, "w"))- job_dir = os.path.join(rec["work"], "out", "shots", rec["job_id"])- os.makedirs(job_dir, exist_ok=True)-- async def keep_alive(): # proves this attempt is alive to any retry of the same request- while True:- open(os.path.join(job_dir, ".alive"), "w").close()- await asyncio.sleep(20)- alive_task = asyncio.create_task(keep_alive())- try:- return await self._order_in(req, mode, rec, index, job_dir, resume, t0)- finally:- alive_task.cancel()-- async def _order_in(self, req, mode, rec, index, job_dir, resume, t0) -> ShotResponse:- import asyncio- import time-- from fal.toolkit import File-- upload = lambda p: File.from_path(p).url- work, job_id = rec["work"], rec["job_id"]- if req.build_id:- if not os.path.isdir(work):- raise ValueError(f"build {req.build_id} is not on this account's storage")- scene = shots.build_scene_name(work)- source = {"kind": "build", "build_id": req.build_id}- else:- scene = "scene"- _stage("received", "running", "fetching the scene")- await asyncio.to_thread(shots.fetch_scene, work, req.scene_url)- for d in (f"scenes/{scene}", "out"):- os.makedirs(os.path.join(work, d), exist_ok=True)- source = {"kind": "upload", "scene_url": req.scene_url, "files": "input/scene/"}- shots.write_toolkit(work, TOOLKIT) # the current tools and SHOTS.md; never the scene's own files- request = {"mode": mode, "source": source, "prompt": req.prompt, "shots": [s.model_dump() for s in req.shots],- "settings": req.settings, "dials": req.dials, "floor_plan_url": req.floor_plan_url, "floor_plan": None}- if req.floor_plan_url:- if not os.path.exists(os.path.join(job_dir, "floor_plan.png")):- await asyncio.to_thread(shots.fetch_floor_plan, req.floor_plan_url, job_dir)- request["floor_plan"] = os.path.relpath(os.path.join(job_dir, "floor_plan.png"), work).replace(os.sep, "/")-- d, out = await shots.shoot(work, scene, job_id, request, upload, effort=req.effort, resume=resume)- res = ShotResponse(**out, scene_id=rec["scene_id"], minutes=round((time.time() - t0) / 60, 1))- save_optix_cache()- d.emit("packaged", "done", f"{len(res.stills)} stills, {len(res.videos)} videos after {res.minutes:.0f} min",- stills=res.stills, videos=res.videos)- if not res.missing: # a repeat of this order now gets this result; an incomplete one is resumed instead- rec = json.load(open(index))- rec.update(response=res.model_dump(), finished=time.time())- json.dump(rec, open(index, "w"))- await asyncio.sleep(2) # let the last stage lines reach the queue logs before COMPLETED- return resdiff --git a/anyshot/client.py b/anyshot/client.pydeleted file mode 100644index c239bef..0000000--- a/anyshot/client.py+++ /dev/null@@ -1,100 +0,0 @@-"""AnyShot command-line client: send a scene and shot directions, follow the agent's live log, save the results.-- pip install fal-client # or: uv run --with fal-client python anyshot/client.py ...- export FAL_KEY=... # a key of the account the app is deployed under- export ANYSHOT_APP=<your-fal-username>/anyshot-- python anyshot/client.py image --scene ./set.blend --shot "wide establishing shot from the doorway, 24mm"- python anyshot/client.py video --scene ./set.zip --shot "slow push along the counter, ending on the register" \- --settings '{"seconds": 6, "res": [1920, 1080]}' --floor-plan ./plan_with_path.png- python anyshot/client.py video --build-id b_1234567890 --shot hero_wide --shot "orbit the bar, 35mm"----scene and --floor-plan take a local file (uploaded to fal storage first) or a URL. Every stage event is written to-<out>/events.jsonl; the response goes to <out>/response.json and the stills/videos next to it.-"""--import argparse-import json-import os-import sys-import time-import urllib.request--STAGE = "ANYSCENE_STAGE " # the agent's stage events in the queue logs (shared with the scene builder)---def main():- p = argparse.ArgumentParser(description="AnyShot: shots of a 3D scene, planned by an AI cinematographer.")- p.add_argument("mode", choices=["image", "video"], help="image: /scene2image (stills). video: /scene2video.")- src = p.add_mutually_exclusive_group(required=True)- src.add_argument("--scene", help="a .blend, or a .zip holding a .blend and its textures (path or URL)")- src.add_argument("--build-id", help="an AnyScene build (b_...) on the app's account")- p.add_argument("--prompt", default="", help="direction for the whole order in words; enough on its own")- p.add_argument("--shot", action="append", default=[],- help="a camera name, or a shot in words (repeatable); 'name: words' gives both")- p.add_argument("--floor-plan", help="optional plan image, optionally with a camera path drawn on it (path or URL)")- p.add_argument("--settings", default="{}", help='JSON, e.g. {"seconds": 6, "fps": 24, "res": [1920, 1080]}')- p.add_argument("--dials", default="{}", help='JSON, e.g. {"time_of_day": "night", "atmosphere": 0.6}')- p.add_argument("--effort", default="medium")- p.add_argument("--fresh", action="store_true", help="shoot again even if an identical order already finished")- p.add_argument("--app", default=os.environ.get("ANYSHOT_APP"), help="fal app id (default: $ANYSHOT_APP)")- p.add_argument("--out", default="anyshot_out")- a = p.parse_args()- if not a.shot and not a.prompt:- p.error("give --prompt, --shot, or both")- if not a.app:- p.error("set ANYSHOT_APP=<owner>/<app> or pass --app")- if not os.environ.get("FAL_KEY"):- p.error("set FAL_KEY to a key of the account the app is deployed under")- sys.stdout.reconfigure(encoding="utf-8")- import fal_client-- up = lambda s: s if s is None or s.startswith(("http://", "https://")) else fal_client.upload_file(s)- shots = []- for s in a.shot:- name, sep, words = s.partition(":")- if sep and name.strip().replace("_", "").isalnum():- shots.append({"name": name.strip(), "description": words.strip()})- elif " " in s.strip():- shots.append({"description": s.strip()})- else:- shots.append({"name": s.strip()})- payload = {"prompt": a.prompt, "shots": shots, "settings": json.loads(a.settings), "dials": json.loads(a.dials), "effort": a.effort,- "fresh": a.fresh, "floor_plan_url": up(a.floor_plan)}- if a.scene:- payload["scene_url"] = up(a.scene)- else:- payload["build_id"] = a.build_id-- os.makedirs(a.out, exist_ok=True)- events = open(os.path.join(a.out, "events.jsonl"), "a", encoding="utf-8")- t0, seen = time.time(), set()-- def on_update(update):- for log in getattr(update, "logs", None) or []:- msg = log.get("message", "")- if msg in seen or STAGE not in msg:- continue- seen.add(msg)- ev = json.loads(msg.split(STAGE, 1)[1])- if ev.get("stage") == "heartbeat":- continue- events.write(json.dumps(ev) + "\n")- events.flush()- line = f"[{(time.time() - t0) / 60:5.1f}m] {ev['stage']:<10} {ev.get('message', '')[:160]}"- if ev.get("preview_url"):- line += f"\n{'':19}image: {ev['preview_url']}"- print(line, flush=True)-- route = "scene2image" if a.mode == "image" else "scene2video"- res = fal_client.subscribe(f"{a.app}/{route}", arguments=payload, with_logs=True, on_queue_update=on_update,- on_enqueue=lambda rid: print(f"request {rid}", flush=True), client_timeout=3 * 3600)- with open(os.path.join(a.out, "response.json"), "w", encoding="utf-8") as f:- json.dump(res, f, indent=1)- for url in res.get("stills", []) + res.get("videos", []):- urllib.request.urlretrieve(url, os.path.join(a.out, url.rsplit("/", 1)[-1]))- print(json.dumps({k: v for k, v in res.items() if k != "result"}, indent=1))---if __name__ == "__main__":- main()diff --git a/blender_addon/README.md b/blender_addon/README.mdindex 3b251ac..55d82c7 100644--- a/blender_addon/README.md+++ b/blender_addon/README.md@@ -141,7 +141,7 @@ render (PSNR), and renders one EXR frame. It ends with a `TEST-SUMMARY` JSON lin## Farm change (blender-farm-2)`farm/app.py` gained one optional request field, `outputs` (glob patterns relative to `{out}`). It defaults to-`["**/*.png"]`, which is exactly the old behaviour, so existing clients (`farm/farm.py`, `builder/shots.py`) are+`["**/*.png"]`, which is exactly the old behaviour, so existing clients (`farm/farm.py`, AnyShot's `farm_render`) areunaffected. The add-on always sends `["frames/**/*"]`, and an older `blender-farm` deployment ignores the unknown field.The changed app is deployed as `blender-farm-2` on your own account:diff --git a/builder/SHOTS.md b/builder/SHOTS.mddeleted file mode 100644index 8be4d45..0000000--- a/builder/SHOTS.md+++ /dev/null@@ -1,119 +0,0 @@-# AnyShot (scene to images / scene to video)--You are the DP and colourist on a set that is already built. Your job is shots of it: stills, or camera moves-(dollies, push-ins, reveals, orbits, rack focus, walkthroughs) that stay clear of the set and read as filmed.-Read `{job}/request.json` and `camera/README.md` first.--## Where the set comes from--`{job}/request.json` has `source.kind`:--- **`build`**: an AnyScene build; this workspace is the build's own. `out/scene.blend` is the finished set (if the- build is still running or was cut off, there is no `out/scene.blend` yet: use the newest working file,- `scenes/{scene}/scene.blend`, and don't modify it). `scenes/{scene}/scripts/` are the scripts that built it,- `scenes/{scene}/NOTES.md` is what the builder learned (read it), and `out/shots.json` holds its cameras (the scouting- previews are in `out/previews/`).-- **`upload`**: a scene the customer uploaded, unpacked as it came in `input/scene/` (a single `.blend`, or the- contents of their zip: a `.blend` plus its textures, maybe more). There is no builder, no NOTES.md from one and no- shots.json. Before anything else:- 1. Find the `.blend` to shoot. If there are several, take the main one: the one with the most mesh objects or the- one the others link to, not a `.blend1` backup, an asset library or a single prop.- 2. Open it once and survey it: scenes, the active camera and any other cameras, lights, world, render engine, units,- the set's bounds and its floor height, and the big objects (`camera/shoot.py --list ""` prints names with- bounds). Note linked libraries and missing files.- 3. Repair texture and library paths: `bpy.ops.file.find_missing_files(directory=<input/scene>)` and- `bpy.ops.file.make_paths_relative()`, then check that nothing is still missing (`bpy.data.images` with no data,- pink materials in a quick render). Make linked libraries local if they are in the upload.- 4. Save a packed, self-contained copy as `{job}/scene.blend` (`bpy.ops.file.pack_all()`, then save as) and work only- on that copy from now on, for stills and video alike. Never modify anything in `input/scene/`.- 5. Write what you learned (what the set is, where its main areas are, scale, floor height, sightlines, problem- spots, the render settings it looks right with) to `scenes/{scene}/NOTES.md`, so the next order on this upload- starts from it. If it already exists, read it and add to it.- Keep the scene's own look: its lights, world, materials and engine settings. If it renders with Eevee and looks- right that way, keep Eevee unless the order asks otherwise; if it has no lights at all, add a simple, motivated- key and fill and say so in the result.--## The job--`{job}/request.json` is the customer's order:-- `mode`: `images` (finished stills) or `video` (animated shots).-- `prompt`: the customer's direction in their own words, for the whole order (pace, mood, length, what to show,- what to avoid). If `shots` is empty, plan the shot list from it yourself: pick the shots a good DP would make for- that brief (a typical arc is establishing wide, a walk, then close dolly reveals), name each, and list them with- why in `result.json`. If `shots` is given, the prompt applies to every shot; where they conflict, the shot wins.-- `shots`: each one is a name from `out/shots.json` (use that camera or move as the start; builds only), a- description in words ("slow push along the pastry case, ending close on the croissants"), or both. Turn each into- a camera (images) or a camera move (video) in camrig format, written to `{job}/shots.json`. Name each shot by its- `name`, or a short `[a-z0-9_]` name of your own for a description; the customer gets files by those names.-- `settings`: resolution, samples, fps, seconds per shot, lens, handheld (`none` | `walk` | `subtle`), `look`.- Anything missing: choose well for the shot.-- `dials`: optional changes to the set for this order only (time_of_day, atmosphere, power, warmth, wetness, ...).- Apply them to a copy (`{job}/scene.blend`), never to `out/scene.blend` or `input/scene/`. With no dials, a build is- rendered from `out/scene.blend` as it is.-- `floor_plan`: if set, `{job}/floor_plan.png` is a plan of the set (see below).--### Shot language--Read the descriptions the way a crew would. Map them onto camrig moves:-- push in / dolly in / pull out / track along: `push_in` or `dolly`, 2+ keys; "slow" means about 0.2-0.4 m/s.-- truck / crab / slide: `truck` (sideways). Crane / jib / pedestal / rise: `crane`, `pedestal`.-- pan / tilt / whip: `pan`, `tilt` (same position, aim moves).-- orbit / arc / circle around X: `orbit` with `center_obj`.-- reveal: start on a foreground element or behind an occluder (a wall edge, a shelf, a doorway) and move so the- subject comes into view; end on the subject, framed.-- rack focus / pull focus from A to B: `focus.mode: rack` with a hold, then the pull; use a shallow `fstop` (1.4-2.8)- so it reads.-- walkthrough / follow the path / Steadicam: `path` with 4-6 keys at walking pace (0.4-0.6 m/s) and eye height- (1.5-1.7 m) unless told otherwise, with `handheld: {"profile": "walk"}` when it should feel carried.-- vertigo / dolly zoom: `dolly_zoom`. Locked off / tripod: `static`.-- lens words: wide = 18-24 mm, normal = 35-50 mm, tight / telephoto = 85-135 mm. "Low angle", "eye level", "top- down", "over the shoulder of X" set the camera height and aim.-- A length in the description ("a 6 second push") wins over `settings.seconds`.--## Floor plan--When `{job}/floor_plan.png` exists, it is the customer's plan of the set, drawn, photographed or exported, maybe with-a camera path drawn on it (a line or arrows, often in a bright colour), camera marks (an X, a dot, a camera icon, a-cone of view) or labels. Use it to place the cameras:-1. Register it to the scene: render an orthographic top view of the set (floor up to about 2 m, walls visible) and- match the plan's walls, doors and big furniture to it to get the plan's scale, rotation and offset. Check the- registration by drawing the set's walls over the plan; write the transform into `{job}/floor_plan.json`.-2. A drawn path becomes a `path` move: sample the line into 4-8 key positions in world space, in drawing order- (arrowheads give the direction; otherwise start at the end nearer a door or the plan's label). Aim along the path- unless the order says what to look at. Eye height and pace as for a walkthrough unless told otherwise.-3. Camera marks become camera positions; a cone or arrow gives the aim. Labels name what is where.-4. Follow the plan's intent, not its exact pixels: a path drawn through a table goes around it, a mark inside a wall- moves out to clearance. Say in the result where you deviated and why.-Report the registered plan overlay with stage `blocking`.--## How--1. Block every shot first: quick Eevee or low-sample Cycles frames (start, middle and end frame for a move). Look at- them. Check framing, focus, that the camera never passes within 0.45 m of a solid surface, and that nothing reads wrong- from the new angle (floating props, missing backs, holes, untextured faces). Fix the camera, or fix the set in- the copy, and look again. Report each blocked shot with stage `blocking` and its image.- Clearance is about walls, furniture and props only: leave out dust motes, particles, haze and volume boxes,- light shafts, decals, glass panes the move is meant to pass, and anything smaller than ~5 cm. A real camera- moves through dust. Check every shot in ONE Blender session (load the set once, build the BVH once, test every- frame of every move), not one Blender launch per attempt: the set file can be close to 1 GB.-2. Finals:- - `images`: render each at full quality on this machine's GPU, grade it (ffmpeg, as `SKILL.md` step 14) and save- `{job}/stills/<shot>.png`. Report each with stage `finals`.- - `video`: first save a packed copy of the set to `{job}/scene.blend` (`bpy.ops.file.pack_all()`, every- texture inside; for an upload it already exists): the farm receives only that file. Then call `farm_render`- with the shot names. It renders every frame on a render farm (up to 100 GPUs) and puts them in- `{job}/frames/<shot>/frames/####.png`. Check a few frames, then grade and encode `{job}/video/<shot>.mp4` (h264,- the requested fps). Check the duration and frame count of every file. Report each with stage `finals` and a- frame from it. If `farm_render` fails (no farm configured, no farm access, farm down), render the frames on this- machine instead: `camera/shoot.py` with `--only <shot> --frames a-b --no-encode` in chunks short enough to stay- under ~9 minutes per call, into the same `{job}/frames/` layout.-3. Write `{job}/result.json`: per shot, the camera and settings used, plus a one-line note (and, with a floor plan,- how the shot follows it).--Work fast: the customer is waiting. Keep previews small. One Blender GPU job at a time on this machine-(`pipeline/gpu_run.sh`). Never let one Bash call run longer than ~9 minutes; background long jobs and check on them.--## Rules--- Don't rebuild or restyle the set. These are shots of the scene the customer approved.-- No real brands. Never print keys.diff --git a/builder/app.py b/builder/app.pyindex 8fd2578..e23cc1d 100644--- a/builder/app.py+++ b/builder/app.py@@ -6,6 +6,10 @@POST /build reference images (+ prompt) -> stills, scene.blend, scene.glb, panoramas, package, critic rounds.The agent (scene_builder.py) streams ANYSCENE_STAGE lines that the fal queue relays to the caller as logs: every toolcall, every report with its image, every critique. There is no time budget: it ends when the critic passes (or stalls).++Shots of a build (/scene2image, /scene2video, /shots, and /ref2scene's `shots`) are made by AnyShot+(github.com/apekshik/anyshot), a separate fal app named by the ANYSHOT_APP secret. This app only forwards the order+over the fal API and relays AnyShot's stage lines into its own log."""import json@@ -22,7 +26,6 @@ sys.path.insert(0, _HERE)sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "endpoint"))import planner # noqa: E402 (the critic's Claude client; bundled by value)import scene_builder # noqa: E402-import shots # noqa: E402import gallery # noqa: E402 (the shared builds gallery: /builds, /build_events)import schema # noqa: E402,F401@@ -74,10 +77,42 @@ def save_optix_cache():BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'BUILDS_DIR = "/data/anyscene/builder"-# /ref2scene's optional `shots` go to the AnyShot app (anyshot/app.py) named by ANYSHOT_APP, a fal secret on your own-# account (e.g. <your-fal-username>/anyshot). No default: an unset name says so instead of calling someone else's app.+# Shots go to the AnyShot app (github.com/apekshik/anyshot) named by ANYSHOT_APP, a fal secret on your own account+# (e.g. <your-fal-username>/anyshot). No default: an unset name says so instead of calling someone else's app.ANYSHOT_APP_ENV = "ANYSHOT_APP"SHOTS_WAIT_S = 7200 - 300 # wait for AnyShot until 5 min before this request's cap, then return its request_id+++def anyshot_app():+ return os.environ.get(ANYSHOT_APP_ENV, "").strip().strip("/")+++async def call_anyshot(route, arguments, deadline, on_submit=None):+ """Submit an order to AnyShot (<ANYSHOT_APP>/<route>) and relay its stage lines into this request's log until it+ completes or `deadline` (epoch seconds) passes. Returns (request_id, response, or None if still running). AnyShot+ is retry-safe on its side: a retry of the same order attaches to the same job instead of starting a second one."""+ import asyncio+ import time++ import fal_client++ app = anyshot_app()+ client = fal_client.AsyncClient(key=os.environ.get("FAL_SERVERLESS_KEY") or os.environ.get("FAL_KEY"))+ handle = await client.submit(f"{app}/{route}", arguments=arguments)+ if on_submit:+ on_submit(handle.request_id)+ seen = set()+ while time.time() < deadline:+ st = await handle.status(with_logs=True)+ for log in getattr(st, "logs", None) or []:+ msg = log.get("message", "")+ if scene_builder.PREFIX in msg and msg not in seen:+ seen.add(msg)+ print(msg, flush=True)+ if isinstance(st, fal_client.Completed):+ return handle.request_id, await handle.get()+ await asyncio.sleep(10)+ return handle.request_id, NoneBLENDER_VERSION = "5.0.1"DOCKERFILE = f"""@@ -192,7 +227,7 @@ class SceneBuilderApp(fal.App):machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]image = ContainerImage.from_dockerfile_str(DOCKERFILE)requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]- local_python_modules = ["scene_builder", "shots", "planner", "schema", "gallery"]+ local_python_modules = ["scene_builder", "planner", "schema", "gallery"]min_concurrency = 0max_concurrency = 10request_timeout = 7200 # fal's cap; longer builds resume in a second request@@ -239,12 +274,9 @@ class SceneBuilderApp(fal.App):async def _anyshot(self, req: BuildRequest, res: BuildResponse, t0: float):"""Hand a passed build to the AnyShot app and wait for it while this request has time left. AnyShot isretry-safe on its side, so a retry of this request attaches to the same shots job instead of a second one."""- import asyncioimport time- import fal_client-- app = os.environ.get(ANYSHOT_APP_ENV, "").strip().strip("/")+ app = anyshot_app()route = "scene2video" if req.shots.mode == "video" else "scene2image"res.shots_job = {"app": app, "route": route, "status": "skipped"}if not app:@@ -257,31 +289,21 @@ class SceneBuilderApp(fal.App):returnsay = lambda status, msg, **kw: print(scene_builder.PREFIX + json.dumps({"t": round(time.time() - t0, 1), "stage": "shots", "status": status, "message": msg, **kw}), flush=True)+ def submitted(request_id):+ res.shots_job.update(request_id=request_id, status="running")+ say("running", f"AnyShot {route}: {len(req.shots.shots)} shot(s) on {res.build_id}", request_id=request_id)+try:- client = fal_client.AsyncClient(key=os.environ.get("FAL_SERVERLESS_KEY") or os.environ.get("FAL_KEY"))- handle = await client.submit(f"{app}/{route}", arguments={+ request_id, out = await call_anyshot(route, {"build_id": res.build_id, "shots": [s.model_dump() for s in req.shots.shots],- "settings": req.shots.settings, "dials": req.shots.dials, "effort": req.effort})- res.shots_job.update(request_id=handle.request_id, status="running")- say("running", f"AnyShot {route}: {len(req.shots.shots)} shot(s) on {res.build_id}",- request_id=handle.request_id)- deadline = t0 + SHOTS_WAIT_S- seen = set()- while time.time() < deadline:- st = await handle.status(with_logs=True)- for log in getattr(st, "logs", None) or []: # relay AnyShot's stage lines into this build's log- msg = log.get("message", "")- if scene_builder.PREFIX in msg and msg not in seen:- seen.add(msg)- print(msg, flush=True)- if isinstance(st, fal_client.Completed):- out = await handle.get()- res.shot_stills, res.shot_videos = out.get("stills", []), out.get("videos", [])- res.shots_job.update(status="done", job_id=out.get("job_id"), missing=out.get("missing", []))- say("done", f"AnyShot: {len(res.shot_stills)} stills, {len(res.shot_videos)} videos")- return- await asyncio.sleep(15)- say("running", f"AnyShot is still running; fetch request {handle.request_id} from {app} when it finishes")+ "settings": req.shots.settings, "dials": req.shots.dials, "effort": req.effort},+ t0 + SHOTS_WAIT_S, submitted)+ if out is not None:+ res.shot_stills, res.shot_videos = out.get("stills", []), out.get("videos", [])+ res.shots_job.update(status="done", job_id=out.get("job_id"), missing=out.get("missing", []))+ say("done", f"AnyShot: {len(res.shot_stills)} stills, {len(res.shot_videos)} videos")+ return+ say("running", f"AnyShot is still running; fetch request {request_id} from {app} when it finishes")except Exception as e: # the build itself is delivered either wayres.shots_job.update(status="failed", error=f"{type(e).__name__}: {str(e)[:300]}")say("running", f"AnyShot call failed: {res.shots_job['error']}")@@ -445,33 +467,29 @@ class SceneBuilderApp(fal.App):return await self._shots(req)async def _shots(self, req: ShotsRequest) -> ShotsResponse:- """Scene to images / scene to video: an agent shoots a finished build (see builder/SHOTS.md)."""+ """Scene to images / scene to video on a finished build: forwarded to the AnyShot app (ANYSHOT_APP), which+ shoots the build in place on this account's storage. Its stage lines are relayed into this request's log."""import time- import uuid-- from fal.toolkit import Filet0 = time.time()if not req.build_id.replace("_", "").isalnum():raise ValueError("bad build_id")- work = os.path.join(BUILDS_DIR, req.build_id)- try:- scene = shots.build_scene_name(work)- except ValueError as e:- raise ValueError(f"build {req.build_id}: {e}")- # older builds carry older tools: refresh the toolkit (never the scene's own scripts or outputs)- shots.write_toolkit(work, TOOLKIT)- job_id = "j_" + uuid.uuid4().hex[:8]- upload = lambda p: File.from_path(p).url- # the same agent and tools as the AnyShot app (anyshot/app.py), on the build's own workspace- request = {**req.model_dump(), "source": {"kind": "build", "build_id": req.build_id}}- d, out = await shots.shoot(work, scene, job_id, request, upload, effort=req.effort)- res = ShotsResponse(**out, minutes=round((time.time() - t0) / 60, 1))- save_optix_cache()- d.emit("packaged", "done", f"{len(res.stills)} stills, {len(res.videos)} videos after {res.minutes:.0f} min",- stills=res.stills, videos=res.videos)- await __import__("asyncio").sleep(2)- return res+ if not os.path.isdir(os.path.join(BUILDS_DIR, req.build_id)):+ raise ValueError(f"build {req.build_id}: no such build")+ app = anyshot_app()+ if not app:+ raise ValueError(f"no AnyShot app configured: set the fal secret {ANYSHOT_APP_ENV}="+ "<your-fal-username>/anyshot and redeploy")+ route = "scene2video" if req.mode == "video" else "scene2image"+ print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "received", "status": "running",+ "message": f"forwarding to AnyShot {route} on {req.build_id}"}), flush=True)+ request_id, out = await call_anyshot(route, {+ "build_id": req.build_id, "shots": [s.model_dump() for s in req.shots], "settings": req.settings,+ "dials": req.dials, "effort": req.effort}, t0 + 7200 - 120)+ if out is None:+ raise RuntimeError(f"AnyShot is still running: fetch request {request_id} from {app}/{route} when it finishes")+ await __import__("asyncio").sleep(2) # let the last relayed lines reach the queue logs before COMPLETED+ return ShotsResponse(**{k: out.get(k) for k in ShotsResponse.model_fields})# The shared builds gallery: every build anyone ran, read from storage (the fal queue only shows a request to the# key that submitted it). Light and read-only; see builder/gallery.py.diff --git a/builder/blender_gpu.py b/builder/blender_gpu.pyindex 13d33dd..6279f1b 100644--- a/builder/blender_gpu.py+++ b/builder/blender_gpu.py@@ -1,6 +1,7 @@-"""Every Blender the builder starts renders Cycles on the GPU, even with --factory-startup and no gpu_prefs script.+# synced from github.com/apekshik/anyshot agent/blender_gpu.py+"""Every Blender the agent starts renders Cycles on the GPU, even with --factory-startup and no GPU prefs script.On the fal worker `blender` is a wrapper that runs this first (`blender.real --python blender_gpu.py "$@"`): headless-Blender otherwise renders on the CPU, which an agent forgot once and lost most of a build to."""+Blender otherwise renders on the CPU, which an agent forgot once and lost most of a two-hour job to."""import bpyfrom bpy.app.handlers import persistentdiff --git a/builder/scene_builder.py b/builder/scene_builder.pyindex 25d3a1e..40ff760 100644--- a/builder/scene_builder.py+++ b/builder/scene_builder.py@@ -61,7 +61,6 @@ def toolkit_files():files = {"SKILL.md": open(os.path.join(REPO, "SKILL.md"), encoding="utf-8").read(),"CRAFT.md": open(os.path.join(HERE, "CRAFT.md"), encoding="utf-8").read(),".builder/PROMPT.md": open(os.path.join(HERE, "PROMPT.md"), encoding="utf-8").read(),- ".builder/SHOTS.md": open(os.path.join(HERE, "SHOTS.md"), encoding="utf-8").read(),"endpoint/refine_blender.py": open(os.path.join(REPO, "endpoint", "refine_blender.py"), encoding="utf-8").read()}for d in TOOLKIT_DIRS:for root, dirs, names in os.walk(os.path.join(REPO, d)):@@ -173,7 +172,7 @@ def run_critic(refs, stills):# ---------------------------------------------------------------- runclass SceneBuilder:- # what a subclass changes for another job on the same workspace (see shots.py)+ # what a subclass changes for another job on the same workspacePROMPT_FILE = "PROMPT.md" # under .builder/ASK = "Build the scene from the reference in input/. Start by reading SKILL.md."diff --git a/builder/shots.py b/builder/shots.pydeleted file mode 100644index b5dafb0..0000000--- a/builder/shots.py+++ /dev/null@@ -1,315 +0,0 @@-"""Scene to images / scene to video: an agent shoots a 3D set (AnyShot, see anyshot/README.md).--Shared by the AnyShot app (anyshot/app.py) and the scene builder's /scene2image and /scene2video (builder/app.py).-The set is either an AnyScene build's own workspace (/data/anyscene/builder/<build_id>: the finished out/scene.blend,-the builder's scripts, NOTES.md and its scouting cameras) or an uploaded scene unpacked into a workspace of its own-(input/scene/). Each order gets a job folder out/shots/<job_id>/ with request.json; the agent blocks every shot with-quick previews, then renders finals: stills on this worker's GPU, or video frames on a render farm app-(farm/app.py, named by ANYSHOT_FARM_APP) through the farm_render tool.-"""--import asyncio-import hashlib-import io-import json-import os-import urllib.request-import zipfile--from claude_agent_sdk import tool--import scene_builder-from scene_builder import SceneBuilder--# The render farm app (farm/app.py deployed on your own account), e.g. "<your-fal-username>/blender-farm". Read when a-# farm call is made, so a fal secret set after deploy applies. Unset: farm_render fails and the agent renders the-# frames on its own GPU instead (slower, same result).-FARM_APP_ENV = "ANYSHOT_FARM_APP"-# Frames are spread over farm workers in chunks of at least FARM_MIN_CHUNK frames, up to FARM_WORKERS at once (default-# 100, the farm app's max_concurrency). Every chunk pays a worker boot, the scene download and Blender loading the set-# (~2 min together), so small chunks spend most of their GPU time on setup: at 5 frames a chunk that was ~75% of the-# bill. 24 frames a chunk keeps the wall time to a few minutes while most of each worker's time goes to rendering.-FARM_PARALLEL = int(os.environ.get("FARM_WORKERS", "100"))-FARM_MIN_CHUNK = int(os.environ.get("FARM_MIN_CHUNK", "24"))-# The GPU-forcing startup script every app in this repo writes on its worker (builder/blender_gpu.py)-BLENDER_GPU_PATH = "/opt/anyscene/blender_gpu.py"---def farm_app():- return os.environ.get(FARM_APP_ENV, "").strip().strip("/")---class ShotsDirector(SceneBuilder):- PROMPT_FILE = "SHOTS.md"-- def __init__(self, work, scene, job_id, request, resume=False, **kw):- super().__init__(work, [], scene, out_rel=os.path.join("out", "shots", job_id), **kw)- self.job_id, self.request = job_id, request- self.job = os.path.relpath(self.out, work).replace(os.sep, "/")- with open(os.path.join(self.out, "request.json"), "w", encoding="utf-8") as f:- json.dump(request, f, indent=1)- kind = (request.get("source") or {}).get("kind", "build")- if kind == "upload":- self.ASK = (f"Shoot the order in {self.job}/request.json. The set is an uploaded scene in input/scene/ (not "- f"an AnyScene build). Start by reading the request, camera/README.md and, if an earlier order "- f"left one, scenes/{scene}/NOTES.md.")- else:- self.ASK = (f"Shoot the order in {self.job}/request.json on the built scene. Start by reading "- f"scenes/{scene}/NOTES.md, camera/README.md and the request.")- if resume:- self.ASK += (f" This order was cut off (its request was retried) and is resuming in the same job folder: "- f"read {self.job}/builder.log and {self.job}/events.jsonl and look at what is already in "- f"{self.job}/ first. Don't redo finished work; farm_render skips frames that already exist.")- self.uploads = {}-- def tools(self):- d = self- report = [t for t in super().tools() if t.name == "report"]-- @tool("farm_render", "Render every frame of the named video shots on the render farm (up to 100 GPUs). "- "Reads the cameras from <job>/shots.json and the set from <job>/scene.blend if it exists, "- "else out/scene.blend. Frames land in <job>/frames/<shot>/frames/####.png. Returns per-shot "- "frame counts and timing. Already-rendered frames are skipped, so it can be called again "- "to fill gaps or after changing one shot.",- {"type": "object", "properties": {"shots": {"type": "array", "items": {"type": "string"}}},- "required": ["shots"]})- async def farm_render(args):- try:- text = await d.farm(args["shots"])- return {"content": [{"type": "text", "text": text}]}- except Exception as e:- return {"content": [{"type": "text", "text": f"farm_render failed: {type(e).__name__}: {e}"}],- "is_error": True}-- return report + [farm_render]-- async def farm(self, names):- import fal_client-- app = farm_app()- if not app:- raise RuntimeError(f"no render farm configured ({FARM_APP_ENV} is not set): render the frames on this GPU")- shots_path = os.path.join(self.out, "shots.json")- cfg = json.load(open(shots_path, encoding="utf-8"))- defs = {s["name"]: s for s in cfg["shots"]}- unknown = [n for n in names if n not in defs]- if unknown:- raise ValueError(f"not in {self.job}/shots.json: {unknown}")- blend = os.path.join(self.out, "scene.blend")- if not os.path.exists(blend):- blend = os.path.join(self.work, "out", "scene.blend")- if not os.path.exists(blend):- raise FileNotFoundError(f"no set to send: save the packed copy as {self.job}/scene.blend first")-- # bundle: the set, the camera rig, these shots and the GPU script; the farm caches it by content hash- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as z:- z.write(blend, "scene.blend")- z.write(shots_path, "shots.json")- for n in ("camrig.py", "shoot.py"):- z.write(os.path.join(self.work, "camera", n), f"camera/{n}")- z.write(BLENDER_GPU_PATH, "blender_gpu.py")- data = buf.getvalue()- bundle_id = hashlib.sha256(data).hexdigest()[:16]- if bundle_id not in self.uploads:- path = os.path.join(self.out, f"bundle_{bundle_id}.zip")- with open(path, "wb") as f:- f.write(data)- self.uploads[bundle_id] = await asyncio.to_thread(self.upload, path)- os.remove(path)- url = self.uploads[bundle_id]-- frames_dir = os.path.join(self.out, "frames")- total = sum(int(defs[n].get("frames", cfg.get("defaults", {}).get("frames", 120))) for n in names)- chunk = max(FARM_MIN_CHUNK, -(-total // FARM_PARALLEL))- jobs = []- for name in names:- n = int(defs[name].get("frames", cfg.get("defaults", {}).get("frames", 120)))- have = {f for f in range(1, n + 1) if os.path.exists(os.path.join(frames_dir, name, "frames", f"{f:04d}.png"))}- for a in range(1, n + 1, chunk):- b = min(a + chunk - 1, n)- if all(f in have for f in range(a, b + 1)):- continue- args = ["{bundle}/scene.blend", "--python", "{bundle}/blender_gpu.py", "--python",- "{bundle}/camera/shoot.py", "--", "--shots", "{bundle}/shots.json", "--out", "{out}",- "--only", name, "--frames", f"{a}-{b}", "--no-encode"]- jobs.append((name, a, b, {"bundle_url": url, "bundle_id": bundle_id, "blender_args": args}))- if not jobs:- return "every frame is already rendered"- self.emit("farm", "running", f"render farm: {len(jobs)} chunks of up to {chunk} frames on up to {FARM_PARALLEL} GPUs for "- f"{', '.join(names)}", bundle_url=url, bundle_id=bundle_id)-- client = fal_client.AsyncClient(key=os.environ.get("FAL_SERVERLESS_KEY") or os.environ.get("FAL_KEY"))- sem = asyncio.Semaphore(FARM_PARALLEL)- done, failed, gpu_s = 0, [], 0.0-- async def one(job):- nonlocal done, gpu_s- name, a, b, payload = job- async with sem:- for attempt in range(3):- try:- res = await client.subscribe(app, arguments=payload)- raw = await asyncio.to_thread(- lambda: urllib.request.urlopen(res["frames_url"], timeout=600).read())- with zipfile.ZipFile(io.BytesIO(raw)) as z:- for member in z.namelist(): # <shot>/frames/####.png- dest = os.path.normpath(os.path.join(frames_dir, member))- if not dest.startswith(os.path.normpath(frames_dir) + os.sep):- continue- os.makedirs(os.path.dirname(dest), exist_ok=True)- with open(dest, "wb") as f:- f.write(z.read(member))- done += 1- gpu_s += res.get("render_seconds", 0)- self.emit("farm", "running", f"{name} frames {a}-{b} in ({done} of {len(jobs)} chunks)",- progress=round(done / len(jobs), 3), bundle_s=res.get("bundle_seconds"),- blender_s=res.get("render_seconds"))- return- except Exception as e:- err = f"{name} {a}-{b}: {type(e).__name__}: {str(e)[:200]}"- failed.append(err)-- await asyncio.gather(*(one(j) for j in jobs))- counts = {n: len([f for f in os.listdir(os.path.join(frames_dir, n, "frames"))])- if os.path.isdir(os.path.join(frames_dir, n, "frames")) else 0 for n in names}- summary = (f"{done} of {len(jobs)} chunks rendered ({gpu_s / 3600:.2f} GPU-h). Frames per shot: {counts}."- + (f" Failed (call again to retry): {failed}" if failed else ""))- self.emit("farm", "done" if not failed else "running", summary)- return summary-- def format_prompt(self, text):- return super().format_prompt(text).replace("{job}", self.job)-- def missing(self):- mode = self.request.get("mode", "images")- # an order given only as a prompt has as many shots as the agent planned (at least one)- names = [s.get("name") or f"shot_{i + 1}" for i, s in enumerate(self.request.get("shots", []))] or ["planned"]- sub, ext = ("stills", ".png") if mode == "images" else ("video", ".mp4")- have = [f for f in os.listdir(os.path.join(self.out, sub))] if os.path.isdir(os.path.join(self.out, sub)) else []- miss = []- if len([f for f in have if f.endswith(ext)]) < len(names):- miss.append(f"{self.job}/{sub} has {len(have)} of {len(names)} {ext} files")- if not os.path.exists(os.path.join(self.out, "result.json")):- miss.append(f"{self.job}/result.json")- return miss-- def stalled(self):- return False---# ---------------------------------------------------------------- shared by the apps-def write_toolkit(work, toolkit):- """Refresh the shared tools in a workspace (never a scene's own scripts or outputs)."""- for rel, text in toolkit.items():- path = os.path.join(work, rel)- os.makedirs(os.path.dirname(path), exist_ok=True)- with open(path, "w", encoding="utf-8", newline="\n") as f:- f.write(text)- if rel.endswith(".sh"):- os.chmod(path, 0o755)---def build_scene_name(work):- """The scene folder of an AnyScene build, checking it has something to shoot."""- scenes = os.path.join(work, "scenes")- if not os.path.isdir(scenes):- raise ValueError("no such build")- scene = next((d for d in sorted(os.listdir(scenes))), "scene")- if not os.path.exists(os.path.join(work, "out", "scene.blend")) \- and not os.path.exists(os.path.join(scenes, scene, "scene.blend")):- # a build still running (or cut off) has no packed final yet: the agent shoots its working scene- raise ValueError("the build has no scene file yet")- return scene---def _safe_extract(zpath, dest):- with zipfile.ZipFile(zpath) as z:- for m in z.infolist():- name = m.filename.replace("\\", "/")- if name.startswith("/") or ".." in name.split("/") or ":" in name.split("/")[0] or "__MACOSX" in name:- continue- target = os.path.join(dest, *name.split("/"))- if m.is_dir():- os.makedirs(target, exist_ok=True)- continue- os.makedirs(os.path.dirname(target), exist_ok=True)- with z.open(m) as src, open(target, "wb") as out:- while chunk := src.read(8 << 20):- out.write(chunk)---def fetch_scene(work, scene_url):- """Download an uploaded scene once into <work>/input/scene/: a .blend as scene.blend, a .zip unpacked as it is.- Concurrent orders on the same upload race harmlessly (each unpacks into its own folder; the first rename wins)."""- dest = os.path.join(work, "input", "scene")- if os.path.isdir(dest):- return dest- tmp = os.path.join(work, "input", f"_dl_{os.getpid()}_{os.urandom(3).hex()}")- os.makedirs(tmp)- raw = os.path.join(tmp, "download")- with urllib.request.urlopen(scene_url, timeout=600) as r, open(raw, "wb") as f:- while chunk := r.read(8 << 20):- f.write(chunk)- with open(raw, "rb") as f:- head = f.read(8)- unpacked = os.path.join(tmp, "scene")- os.makedirs(unpacked)- if head.startswith(b"PK\x03\x04"):- _safe_extract(raw, unpacked)- elif head.startswith((b"BLENDER", b"\x28\xb5\x2f\xfd", b"\x1f\x8b")): # plain, zstd- or gzip-compressed .blend- name = os.path.basename(scene_url.split("?", 1)[0])- name = name if name.lower().endswith(".blend") and name.replace(".", "").replace("_", "").replace("-", "").isalnum() \- else "scene.blend"- os.replace(raw, os.path.join(unpacked, name))- else:- raise ValueError("scene_url must point to a .blend or a .zip holding one")- blends = [os.path.join(r, n) for r, _, ns in os.walk(unpacked) for n in ns if n.lower().endswith(".blend")]- if not blends:- raise ValueError("the uploaded zip holds no .blend file")- try:- os.rename(unpacked, dest)- except OSError:- if not os.path.isdir(dest):- raise- import shutil- shutil.rmtree(tmp, ignore_errors=True)- return dest---def fetch_floor_plan(url, job_dir):- """The order's floor plan as <job>/floor_plan.png (any image format in)."""- from PIL import Image- src = os.path.join(job_dir, "floor_plan_src")- urllib.request.urlretrieve(url, src)- Image.open(src).convert("RGB").save(os.path.join(job_dir, "floor_plan.png"))- os.remove(src)---async def shoot(work, scene, job_id, request, uploader, effort="medium", resume=False):- """Run the shots agent on one order. Returns (director, response dict: stills, videos, result, missing, cost)."""- d = ShotsDirector(work, scene, job_id, request, resume=resume, uploader=uploader, effort=effort)- src = request.get("source") or {}- d.emit("received", "running", f"{'resuming ' if resume else ''}{request.get('mode')} job {job_id} on "- f"{src.get('build_id') or 'an uploaded scene'}: {len(request.get('shots', []))} shot(s)",- source=src, mode=request.get("mode"), shots=request.get("shots"), settings=request.get("settings"),- dials=request.get("dials"), floor_plan_url=request.get("floor_plan_url"))- result = None- try:- result = await d.run(scene_builder.agent_env())- except Exception as e: # deliver whatever exists rather than a bare 500- import traceback- print(traceback.format_exc(), flush=True)- d.emit("error", "failed", f"shots stopped: {type(e).__name__}: {str(e)[:300]}")-- def files(sub, ext):- p = os.path.join(d.out, sub)- return [uploader(os.path.join(p, f)) for f in sorted(os.listdir(p)) if f.lower().endswith(ext)] \- if os.path.isdir(p) else []- rpath = os.path.join(d.out, "result.json")- try:- res_json = json.load(open(rpath, encoding="utf-8")) if os.path.exists(rpath) else {}- except ValueError:- res_json = {}- return d, {"job_id": job_id, "stills": files("stills", ".png"), "videos": files("video", ".mp4"),- "result": res_json, "missing": d.missing(), "agent_cost_usd": getattr(result, "total_cost_usd", None)}diff --git a/camera/README.md b/camera/README.mdindex 7f9904c..29f39c6 100644--- a/camera/README.md+++ b/camera/README.md@@ -1,3 +1,4 @@+<!-- synced from github.com/apekshik/anyshot camera/README.md --># camrig: cinematic camera rig and shot renderer`camera/shoot.py` adds one camera rig per shot to a scene .blend, then renders:@@ -6,7 +7,8 @@- lens charts,- final Cycles frames and mp4s.-Shots are described in a JSON file. Each scene keeps its own at `scenes/<scene>/shots.json`. Copies of the examples live in `examples/`.+Shots are described in a JSON file: an AnyShot order writes its own as `out/shots/<job>/shots.json`, and an AnyScene+build keeps its scouting cameras in `out/shots.json`. Examples live in `camera/examples/`.The contract is stable. New fields may be added, but existing ones will not change meaning.@@ -15,10 +17,11 @@ The contract is stable. New fields may be added, but existing ones will not chan```bash. pipeline/env.sh # sets $B (Blender) and $ROOT_ABS (absolute repo root)# always through the shared GPU queue-pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen.blend --python camera/shoot.py -- \- --shots $ROOT_ABS/scenes/tokyo-ramen-shop/shots.json \- --out $ROOT_ABS/scenes/tokyo-ramen-shop/out/shots \- [--only a,b] [--preview | --framing | --lenschart NAME] [--frames 1-24] [--still 12] [--save rigged.blend] [--no-encode] \n [--engine eevee|cycles|workbench] [--step N]+pipeline/gpu_run.sh "$B" -b scenes/my-set/set.blend --python camera/shoot.py -- \+ --shots $ROOT_ABS/scenes/my-set/shots.json \+ --out $ROOT_ABS/scenes/my-set/out/shots \+ [--only a,b] [--preview | --framing | --lenschart NAME] [--frames 1-24] [--still 12] [--save rigged.blend] [--no-encode] \+ [--engine eevee|cycles|workbench] [--step N]```| Mode | What it does | Output (`<out>/<shot>/…`) |@@ -118,7 +121,7 @@ All moves interpolate between `keys`; `move` sets defaults and validation:- **Baking:** everything is baked per frame onto `CR_<shot>_shake` (location in metres, rotation in radians, in the camera's local axes).It is deterministic per shot index.- **Setting it up:** use `move: "path"` with 4–6 keys at a walking pace (about 0.3–0.6 m/s) and `ease: "inout"`, so the operator starts and stops gently.- Check the camera path against the scene before rendering. In the repair scene, `scenes/tokyo-electronics-repair/scripts/check_path.py` reports the closest mesh and its frame.+ Check the camera path against the scene before rendering: load the scene once, build a BVH of its meshes, and report the closest mesh and its frame for every frame of the move.## Rig hierarchy (in the saved .blend)@@ -167,7 +170,7 @@ camrig.find("ramen_bowl") # exact name or prefix match"$B" -b scene.blend --python camera/shoot.py -- --list bowl```-## Measured on this box (RTX 5070 Ti, Blender 5.0.1)+## Measured (RTX 5070 Ti, Blender 5.0.1, on two of AnyScene's reference sets)| Pass | Scene | Time ||---|---|---|@@ -204,11 +207,7 @@ Scale final times by pixels × samples before you pick a `--frames` chunk size.- Light falloff is flatter.- Previews are for framing, move and focus, not for look.-## Examples and tests-- `examples/ramen_shots.json` and `examples/repair_shots.json`: 35 mm push-in with a foreground→subject rack, 85 mm static handheld at f/1.8, 24 mm orbit, and a dolly zoom. All are wired to real object names in each scene.-- Test outputs are in `test/{ramen,repair}/`:- - `_framing.png`- - `<shot>/preview.mp4`- - `scope_85_lenschart.png`- - `bench_push/frames` (Cycles, with lens_fx)- - `tiny/` (full chunked final → mp4 + contact)+## Examples+- `camera/examples/ramen_shots.json` and `camera/examples/repair_shots.json`: 35 mm push-in with a foreground->subject+ rack, 85 mm static handheld at f/1.8, 24 mm orbit, and a dolly zoom, written for two of AnyScene's reference sets+ (the object names are from those scenes).diff --git a/camera/camrig.py b/camera/camrig.pyindex b26c790..4564e72 100644--- a/camera/camrig.py+++ b/camera/camrig.py@@ -1,3 +1,4 @@+# synced from github.com/apekshik/anyshot camera/camrig.py"""camrig: cinematic camera rigs for the night-shop scenes (Blender 5.0). See README.md for the shots.json contract.Rig per shot: CR_<shot>_base (baked position) -> CR_<shot>_aim (Track To CR_<shot>_target) -> CR_<shot>_shake (noise)diff --git a/camera/shoot.py b/camera/shoot.pyindex d4ec433..796033f 100644--- a/camera/shoot.py+++ b/camera/shoot.py@@ -1,3 +1,4 @@+# synced from github.com/apekshik/anyshot camera/shoot.py"""camrig CLI. Run through pipeline/gpu_run.sh:blender -b <scene.blend> --python camera/shoot.py -- --shots <shots.json> --out <abs dir>[--only a,b] [--preview | --framing | --lenschart NAME | --still N] [--frames a-b] [--save x.blend] [--no-encode]diff --git a/docs/ENDPOINT.md b/docs/ENDPOINT.mdindex 1c213a7..4289f8d 100644--- a/docs/ENDPOINT.md+++ b/docs/ENDPOINT.md@@ -10,8 +10,11 @@ POST /build plan_id (or reference images + auto_approve) -> package zip```Both run on the fal queue and stream their progress as stage events (see Progress). The app lives in `endpoint/`;-final renders go to the `blender-farm` app (`farm/`). A third call, `/scene-to-scene`, changes a built scene's dials-(see Dials) and re-renders it.+final renders go to the `blender-farm` app (`farm/app.py`, synced from AnyShot). A third call, `/scene-to-scene`,+changes a built scene's dials (see Dials) and re-renders it.++To shoot a finished build (stills or camera moves described in words), use+[AnyShot](https://github.com/apekshik/anyshot): the builder's `/scene2image` and `/scene2video` forward to it.## Dialsdiff --git a/farm/app.py b/farm/app.pyindex 8fb8b4f..51daea0 100644--- a/farm/app.py+++ b/farm/app.py@@ -1,14 +1,16 @@-"""AnyScene render farm: headless Blender on fal serverless GPUs.+# synced from github.com/apekshik/anyshot farm/app.py+"""Render farm: headless Blender on fal Serverless GPUs (AnyShot's /scene2video renders its frames here).-One request = one chunk of frames. The scene arrives as a self-contained bundle (see farm/pack.py) behind a short-lived-download URL; each runner downloads a bundle once to its own local disk, so later chunks of the same scene on that-runner start rendering straight away. Frames go back as a zip on fal's file store, so the worker never holds storage credentials.+One request = one chunk of frames. The scene arrives as a self-contained bundle zip (scene.blend plus whatever the+Blender arguments reference) behind a download URL; each runner downloads a bundle once to its own local disk, so later+chunks of the same scene on that runner start rendering straight away. Frames go back as a zip on fal's file store,+so the worker never holds storage credentials.- fal deploy farm/app.py::BlenderFarm # or: fal run farm/app.py::BlenderFarm for a throwaway URL- fal deploy farm/app.py::BlenderFarm --app-name blender-farm-2 --auth private- (adds `outputs`, which the Blender add-on in blender_addon/- uses to get non-PNG frames back; requests without it behave as before)- uv run --with fal-client --with boto3 python farm/submit.py ... (see farm/README.md)+ fal deploy farm/app.py::BlenderFarm --app-name blender-farm --auth private++Request: bundle_url, bundle_id (the bundle's sha256 prefix), blender_args (after `blender -b`; {bundle} and {out}+expand to the unpacked bundle and the output folder), optional timeout_s and outputs (globs of the files to return,+default PNGs only). Any client can use it, not just AnyShot: AnyScene's Blender add-on renders the open scene on it."""import hashlibdiff --git a/pipeline/env.sh b/pipeline/env.shindex 4e45dd1..79b7fd4 100644--- a/pipeline/env.sh+++ b/pipeline/env.sh@@ -1,3 +1,4 @@+# synced from github.com/apekshik/anyshot pipeline/env.sh# Sourced by every shell script: finds the repo root, Blender and ffmpeg.# . pipeline/env.sh (from the repo root)# Override any of them in your shell: BLENDER=/path/to/blender FFMPEG=/path/to/ffmpegdiff --git a/pipeline/gpu_run.sh b/pipeline/gpu_run.shindex 473af0c..a86c987 100644--- a/pipeline/gpu_run.sh+++ b/pipeline/gpu_run.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# synced from github.com/apekshik/anyshot pipeline/gpu_run.sh# Run a command holding the shared GPU, first come first served, so parallel scene builds never render in Cycles at once# (16 GB card) and nobody can re-grab the GPU ahead of a caller that is already waiting.# pipeline/gpu_run.sh "$B" -b ...diff --git a/scripts/sync_from_anyshot.py b/scripts/sync_from_anyshot.pynew file mode 100644index 0000000..fadfc47--- /dev/null+++ b/scripts/sync_from_anyshot.py@@ -0,0 +1,48 @@+"""Copy the code AnyScene shares with AnyShot from a sibling AnyShot checkout (github.com/apekshik/anyshot).++ python scripts/sync_from_anyshot.py [path/to/anyshot] (default: ../anyshot next to this repo)++AnyShot is the home of these files; edit them there, then run this. Each copy gets a one-line header naming its source.+"""++import os+import sys++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+# anyscene path: anyshot path+FILES = {+ "builder/blender_gpu.py": "agent/blender_gpu.py",+ "camera/camrig.py": "camera/camrig.py",+ "camera/shoot.py": "camera/shoot.py",+ "camera/README.md": "camera/README.md",+ "farm/app.py": "farm/app.py",+ "pipeline/env.sh": "pipeline/env.sh",+ "pipeline/gpu_run.sh": "pipeline/gpu_run.sh",+}+++def header(src_rel):+ text = f"synced from github.com/apekshik/anyshot {src_rel}"+ return f"<!-- {text} -->" if src_rel.endswith(".md") else f"# {text}"+++def main():+ src_root = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(REPO, "..", "anyshot"))+ if not os.path.exists(os.path.join(src_root, "agent", "director.py")):+ sys.exit(f"not an AnyShot checkout: {src_root}")+ for dst_rel, src_rel in FILES.items():+ lines = open(os.path.join(src_root, src_rel), encoding="utf-8").read().splitlines(keepends=True)+ at = 1 if lines and lines[0].startswith("#!") else 0 # keep a shebang first+ lines.insert(at, header(src_rel) + "\n")+ dst = os.path.join(REPO, dst_rel)+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ old = open(dst, encoding="utf-8").read() if os.path.exists(dst) else None+ new = "".join(lines)+ if new != old:+ with open(dst, "w", encoding="utf-8", newline="\n") as f:+ f.write(new)+ print(f"{'updated' if new != old else 'same '} {dst_rel} <- {src_rel}")+++if __name__ == "__main__":+ main()