AlterProgramming commited on
Commit
1e3ce4c
·
verified ·
1 Parent(s): de1cf54

Initial venture-studio deploy: pixel_cursor + studio + app.py

Browse files
app.py CHANGED
@@ -1,154 +1,102 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
 
 
 
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
 
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
 
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
 
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
  )
152
 
 
153
  if __name__ == "__main__":
154
  demo.launch()
 
1
+ """Hugging Face Space entry point — venture-studio deployed as a ZeroGPU Space.
 
 
2
 
3
+ Push this whole repo to a HF Space (sdk: gradio). The Space's Python build will
4
+ install `requirements.txt` (torch + diffusers + transformers + gradio + spaces)
5
+ and call `app.py:infer` for each request. `@spaces.GPU` allocates an A100 only
6
+ for the duration of the call (ZeroGPU model), so the Space is free for the
7
+ maintainer and shared fairly across users.
8
 
9
+ Locally this file is not imported — `studio` CLI uses `studio.backends.hf_space`
10
+ to call this Space remotely via gradio_client.
11
+ """
12
+ from __future__ import annotations
13
+ import io
14
 
15
+ import gradio as gr
16
+ import numpy as np
17
+ import spaces
18
+ from PIL import Image as PILImage
19
 
20
+ from pixel_cursor import open_cursor, FrameStack
21
+ from pixel_cursor.artifact import _new_image
22
+ from studio.backends.animatediff import AnimateDiffAdapter, MOTION_LORA_MAP
23
 
 
 
24
 
25
+ _adapter: AnimateDiffAdapter | None = None
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ def _get_adapter() -> AnimateDiffAdapter:
29
+ global _adapter
30
+ if _adapter is None:
31
+ _adapter = AnimateDiffAdapter()
32
+ _adapter.register()
33
+ return _adapter
 
 
 
 
 
 
34
 
 
35
 
36
+ @spaces.GPU(duration=90)
37
+ def infer(
38
+ image: np.ndarray,
39
+ preset: str,
40
+ num_frames: int,
41
+ num_inference_steps: int,
42
+ guidance_scale: float,
43
+ prompt: str,
44
+ negative_prompt: str,
45
+ seed: int,
46
+ ) -> str:
47
+ """Generate motion on a single image. Returns path to an mp4 file."""
48
+ import tempfile
49
+ import imageio.v3 as iio
50
+
51
+ adapter = _get_adapter()
52
+ img = _new_image(image.astype(np.uint8))
53
+ cur = open_cursor(img).bind_motion_exemplar([preset], backend="animatediff")
54
+
55
+ motion_spec = {
56
+ "num_frames": int(num_frames),
57
+ "num_inference_steps": int(num_inference_steps),
58
+ "guidance_scale": float(guidance_scale),
59
+ "prompt": prompt,
60
+ "negative_prompt": negative_prompt,
61
+ "seed": int(seed),
62
+ }
63
+ stack: FrameStack = cur.write_motion(motion_spec, backend="animatediff")
64
+
65
+ out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
66
+ iio.imwrite(out.name, stack.frames, fps=stack.fps)
67
+ return out.name
68
+
69
+
70
+ with gr.Blocks(title="Venture-Studio") as demo:
71
+ gr.Markdown(
72
+ "# Venture-Studio · Pixel-Cursor Animation\n"
73
+ "Single image → 24fps animation via PixelCursor + AnimateDiff MotionLoRA.\n"
74
+ "Running on Hugging Face ZeroGPU (free A100, ~90s/call)."
75
+ )
76
+ with gr.Row():
77
+ with gr.Column():
78
+ image_in = gr.Image(label="Source image", type="numpy", height=384)
79
+ preset = gr.Dropdown(
80
+ choices=sorted(MOTION_LORA_MAP), value="zoom_in", label="MotionLoRA preset"
81
  )
82
+ with gr.Accordion("Advanced", open=False):
83
+ num_frames = gr.Slider(8, 24, value=16, step=2, label="num_frames")
84
+ steps = gr.Slider(10, 50, value=25, step=1, label="num_inference_steps")
85
+ guidance = gr.Slider(1.0, 15.0, value=7.5, step=0.5, label="guidance_scale")
86
+ prompt = gr.Textbox(value="high quality, detailed", label="prompt")
87
+ neg = gr.Textbox(value="bad quality, blurry", label="negative_prompt")
88
+ seed = gr.Number(value=42, precision=0, label="seed")
89
+ run = gr.Button("Generate", variant="primary")
90
+ with gr.Column():
91
+ video_out = gr.Video(label="Output", autoplay=True, loop=True)
92
+
93
+ run.click(
94
+ infer,
95
+ inputs=[image_in, preset, num_frames, steps, guidance, prompt, neg, seed],
96
+ outputs=video_out,
97
+ api_name="infer",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
99
 
100
+
101
  if __name__ == "__main__":
102
  demo.launch()
pixel_cursor/__init__.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """pixel_cursor — the cursor primitive that owns animation studio pixel mutation.
2
+
3
+ Public surface:
4
+ PixelCursor, open_cursor — the cursor type and entry point
5
+ Point, Region, Mask, Token, — selector types
6
+ Layer, Anchor3D, Selector
7
+ TemporalScope, FrameIndex, — temporal scope
8
+ FrameRange, ALL_FRAMES
9
+ DepthScope, OpacityProfile, — auxiliary scope
10
+ IdentityLock
11
+ Image, FrameStack, Artifact — artifacts (immutable; construct via cursor or loader)
12
+ load_image — disk loader
13
+ ease_between, step_on_stride, — timing primitives (A1 classical-animation layer)
14
+ hold_with_micro, AnimationSegment, interp_t, CURVES
15
+ ops — backend registration registry
16
+
17
+ Backends register concrete write_* via pixel_cursor.ops.register_backend(op, name, fn).
18
+ """
19
+ from .cursor import PixelCursor, open_cursor
20
+ from .selectors import Point, Region, Mask, Token, Layer, Anchor3D, Selector
21
+ from .scope import (
22
+ TemporalScope,
23
+ FrameIndex,
24
+ FrameRange,
25
+ ALL_FRAMES,
26
+ DepthScope,
27
+ IdentityLock,
28
+ OpacityProfile,
29
+ )
30
+ from .artifact import Artifact, Image, FrameStack, load_image
31
+ from .timing import (
32
+ AnimationSegment,
33
+ ease_between,
34
+ step_on_stride,
35
+ hold_with_micro,
36
+ interp_t,
37
+ CURVES,
38
+ )
39
+ from . import ops
40
+
41
+ __all__ = [
42
+ "PixelCursor",
43
+ "open_cursor",
44
+ "Point",
45
+ "Region",
46
+ "Mask",
47
+ "Token",
48
+ "Layer",
49
+ "Anchor3D",
50
+ "Selector",
51
+ "TemporalScope",
52
+ "FrameIndex",
53
+ "FrameRange",
54
+ "ALL_FRAMES",
55
+ "DepthScope",
56
+ "OpacityProfile",
57
+ "IdentityLock",
58
+ "Artifact",
59
+ "Image",
60
+ "FrameStack",
61
+ "load_image",
62
+ "AnimationSegment",
63
+ "ease_between",
64
+ "step_on_stride",
65
+ "hold_with_micro",
66
+ "interp_t",
67
+ "CURVES",
68
+ "ops",
69
+ ]
pixel_cursor/_internal.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal mutation token. Only pixel_cursor.* should import this module."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class _Token:
6
+ __slots__ = ()
7
+
8
+ def __repr__(self) -> str:
9
+ return "<pixel_cursor mutation token>"
10
+
11
+
12
+ _MUTATION_TOKEN = _Token()
13
+
14
+
15
+ def _verify(token: object) -> None:
16
+ if token is not _MUTATION_TOKEN:
17
+ raise PermissionError(
18
+ "Artifact construction requires the pixel_cursor mutation token. "
19
+ "All Artifact creation and mutation must go through a PixelCursor "
20
+ "(see pixel_cursor.open_cursor and cursor.write_* methods)."
21
+ )
pixel_cursor/artifact.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Artifacts: the pixel-space data structures that only PixelCursor may produce.
2
+
3
+ External code may hold and inspect Artifacts but cannot construct them directly;
4
+ the only path to a fresh Artifact is a cursor write_* op or a loader in this
5
+ module. This is the structural enforcement of the "cursor owns the studio" claim.
6
+ """
7
+ from __future__ import annotations
8
+ from dataclasses import dataclass, field
9
+ from typing import Union
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ from ._internal import _MUTATION_TOKEN, _verify
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, eq=False, repr=False)
18
+ class Image:
19
+ pixels: np.ndarray
20
+ name: str = ""
21
+ _token: object = field(default=None, repr=False)
22
+
23
+ def __post_init__(self) -> None:
24
+ _verify(self._token)
25
+
26
+ def __repr__(self) -> str:
27
+ return f"Image(shape={tuple(self.pixels.shape)}, name={self.name!r})"
28
+
29
+
30
+ @dataclass(frozen=True, slots=True, eq=False, repr=False)
31
+ class FrameStack:
32
+ frames: np.ndarray
33
+ fps: int = 24
34
+ name: str = ""
35
+ _token: object = field(default=None, repr=False)
36
+
37
+ def __post_init__(self) -> None:
38
+ _verify(self._token)
39
+
40
+ @property
41
+ def num_frames(self) -> int:
42
+ return int(self.frames.shape[0])
43
+
44
+ def __repr__(self) -> str:
45
+ return f"FrameStack(shape={tuple(self.frames.shape)}, fps={self.fps}, name={self.name!r})"
46
+
47
+
48
+ Artifact = Union[Image, FrameStack]
49
+
50
+
51
+ def _new_image(pixels: np.ndarray, name: str = "") -> Image:
52
+ return Image(pixels=pixels, name=name, _token=_MUTATION_TOKEN)
53
+
54
+
55
+ def _new_framestack(frames: np.ndarray, fps: int = 24, name: str = "") -> FrameStack:
56
+ return FrameStack(frames=frames, fps=fps, name=name, _token=_MUTATION_TOKEN)
57
+
58
+
59
+ def load_image(path: str | Path) -> Image:
60
+ from PIL import Image as PILImage
61
+
62
+ arr = np.array(PILImage.open(path).convert("RGB"))
63
+ return _new_image(arr, name=str(path))
pixel_cursor/cursor.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PixelCursor: the spatio-temporal-semantic-identity selector that owns pixel mutation.
2
+
3
+ Every studio operation that touches pixels routes through a PixelCursor. Artifacts
4
+ are immutable from outside this package; the only way to produce a new Artifact is
5
+ via cursor.write_* methods.
6
+
7
+ Op-set (closed):
8
+ seek_* — reposition (returns new cursor)
9
+ range / at_frame / all_frames / propagate_temporal — temporal traversal
10
+ lock_identity — pin subject or motion identity
11
+ bind_motion_exemplar — few-shot motion attach (returns new cursor)
12
+ read_* — non-mutating queries (returns data)
13
+ write_* — mutation (returns new Artifact)
14
+ tell — introspect cursor state
15
+ """
16
+ from __future__ import annotations
17
+ from dataclasses import dataclass, replace, field
18
+ from typing import Optional, Sequence, Tuple
19
+
20
+ import numpy as np
21
+
22
+ from .artifact import Artifact
23
+ from .selectors import Selector, Point, Region, Mask, Token, Layer, Anchor3D
24
+ from .scope import (
25
+ TemporalScope,
26
+ FrameIndex,
27
+ FrameRange,
28
+ ALL_FRAMES,
29
+ DepthScope,
30
+ IdentityLock,
31
+ OpacityProfile,
32
+ )
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class PixelCursor:
37
+ artifact: Artifact
38
+ selector: Selector
39
+ temporal: TemporalScope
40
+ depth: Optional[DepthScope] = None
41
+ identity_lock: Optional[IdentityLock] = None
42
+ opacity: OpacityProfile = field(default_factory=lambda: OpacityProfile(kind="hard"))
43
+
44
+ # ── seek_* : reposition without mutating the artifact ──
45
+
46
+ def seek_point(self, x: float, y: float, z: Optional[float] = None) -> "PixelCursor":
47
+ return replace(self, selector=Point(x=x, y=y, z=z))
48
+
49
+ def seek_region(self, x: int, y: int, w: int, h: int) -> "PixelCursor":
50
+ return replace(self, selector=Region(x=x, y=y, w=w, h=h))
51
+
52
+ def seek_mask(self, bitmap: np.ndarray, is_soft: bool = False) -> "PixelCursor":
53
+ return replace(self, selector=Mask(bitmap=bitmap, is_soft=is_soft))
54
+
55
+ def seek_token(self, text: str, embedding_id: Optional[str] = None) -> "PixelCursor":
56
+ return replace(self, selector=Token(text=text, embedding_id=embedding_id))
57
+
58
+ def seek_layer(self, layer_id: str) -> "PixelCursor":
59
+ return replace(self, selector=Layer(layer_id=layer_id))
60
+
61
+ def seek_3d_anchor(
62
+ self, anchor_id: str, bbox: Tuple[float, float, float, float, float, float]
63
+ ) -> "PixelCursor":
64
+ return replace(self, selector=Anchor3D(anchor_id=anchor_id, bbox=bbox))
65
+
66
+ # ── temporal ──
67
+
68
+ def at_frame(self, index: int) -> "PixelCursor":
69
+ return replace(self, temporal=FrameIndex(index=index))
70
+
71
+ def range(self, start: int, end: int) -> "PixelCursor":
72
+ return replace(self, temporal=FrameRange(start=start, end=end))
73
+
74
+ def all_frames(self) -> "PixelCursor":
75
+ return replace(self, temporal=ALL_FRAMES)
76
+
77
+ def propagate_temporal(self, end_frame: int, mode: str = "forward") -> "PixelCursor":
78
+ """Extend cursor temporal extent. Backend (e.g. CoTracker3, SAM2) does the actual traversal."""
79
+ cur = self.temporal
80
+ if isinstance(cur, FrameIndex):
81
+ if mode == "backward":
82
+ new: TemporalScope = FrameRange(start=end_frame, end=cur.index + 1)
83
+ else:
84
+ new = FrameRange(start=cur.index, end=end_frame)
85
+ elif isinstance(cur, FrameRange):
86
+ new = FrameRange(start=cur.start, end=max(cur.end, end_frame))
87
+ else:
88
+ new = cur
89
+ return replace(self, temporal=new)
90
+
91
+ # ── identity ──
92
+
93
+ def lock_identity(self, lock: IdentityLock) -> "PixelCursor":
94
+ return replace(self, identity_lock=lock)
95
+
96
+ def bind_motion_exemplar(
97
+ self, exemplar_paths: Sequence[str], backend: str = "auto"
98
+ ) -> "PixelCursor":
99
+ from .ops import _dispatch
100
+
101
+ return _dispatch("bind_motion_exemplar", backend, self, exemplar_paths)
102
+
103
+ # ── read ops (non-mutating) ──
104
+
105
+ def read_state(self) -> dict:
106
+ return self.tell()
107
+
108
+ def read_pixels(self) -> np.ndarray:
109
+ from .artifact import Image, FrameStack
110
+
111
+ a = self.artifact
112
+ if isinstance(a, Image):
113
+ return a.pixels
114
+ if isinstance(a, FrameStack):
115
+ t = self.temporal
116
+ if isinstance(t, FrameIndex):
117
+ return a.frames[t.index]
118
+ if isinstance(t, FrameRange):
119
+ return a.frames[t.start : t.end]
120
+ return a.frames
121
+ raise TypeError(f"read_pixels: unsupported artifact type {type(a).__name__}")
122
+
123
+ # ── write ops (return new Artifact) ──
124
+
125
+ def write_motion(self, motion_spec, backend: str = "auto") -> Artifact:
126
+ from .ops import _dispatch
127
+
128
+ return _dispatch("write_motion", backend, self, motion_spec)
129
+
130
+ def write_displacement(self, target_xy: Tuple[float, float], backend: str = "auto") -> Artifact:
131
+ from .ops import _dispatch
132
+
133
+ return _dispatch("write_displacement", backend, self, target_xy)
134
+
135
+ def write_inpaint(self, prompt: str, backend: str = "auto") -> Artifact:
136
+ from .ops import _dispatch
137
+
138
+ return _dispatch("write_inpaint", backend, self, prompt)
139
+
140
+ def write_keyframe(self, frame_index: int, pose_state, backend: str = "auto") -> Artifact:
141
+ from .ops import _dispatch
142
+
143
+ return _dispatch("write_keyframe", backend, self, frame_index, pose_state)
144
+
145
+ def write_condition(self, control_signal, backend: str = "auto") -> Artifact:
146
+ from .ops import _dispatch
147
+
148
+ return _dispatch("write_condition", backend, self, control_signal)
149
+
150
+ # ── introspection ──
151
+
152
+ def tell(self) -> dict:
153
+ return {
154
+ "selector": type(self.selector).__name__,
155
+ "selector_value": self.selector,
156
+ "temporal": self.temporal,
157
+ "depth": self.depth,
158
+ "identity_locked": self.identity_lock is not None,
159
+ "identity_source": (self.identity_lock.source if self.identity_lock else None),
160
+ "opacity_kind": self.opacity.kind,
161
+ "artifact": type(self.artifact).__name__,
162
+ }
163
+
164
+
165
+ def open_cursor(
166
+ artifact: Artifact,
167
+ selector: Optional[Selector] = None,
168
+ temporal: Optional[TemporalScope] = None,
169
+ ) -> PixelCursor:
170
+ if selector is None:
171
+ selector = Token(text="*all*")
172
+ if temporal is None:
173
+ temporal = ALL_FRAMES
174
+ return PixelCursor(artifact=artifact, selector=selector, temporal=temporal)
pixel_cursor/ops.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Op dispatch registry.
2
+
3
+ The cursor core defines the op contract; backends (in studio/backends/) register
4
+ concrete implementations via register_backend. Keeps pixel_cursor/ free of model
5
+ imports — torch/diffusers/MotionClone never enter the core package.
6
+ """
7
+ from __future__ import annotations
8
+ from typing import Callable, Any
9
+
10
+
11
+ _REGISTRY: dict[tuple[str, str], Callable] = {}
12
+
13
+
14
+ def register_backend(op_name: str, backend_name: str, fn: Callable) -> None:
15
+ _REGISTRY[(op_name, backend_name)] = fn
16
+
17
+
18
+ def list_backends(op_name: str | None = None) -> list[tuple[str, str]]:
19
+ if op_name is None:
20
+ return sorted(_REGISTRY.keys())
21
+ return sorted(k for k in _REGISTRY if k[0] == op_name)
22
+
23
+
24
+ def _dispatch(op_name: str, backend: str, cursor, *args, **kwargs) -> Any:
25
+ if backend == "auto":
26
+ for (op, _name), fn in _REGISTRY.items():
27
+ if op == op_name:
28
+ return fn(cursor, *args, **kwargs)
29
+ raise NotImplementedError(
30
+ f"No backend registered for op {op_name!r}. "
31
+ f"Register one via pixel_cursor.ops.register_backend()."
32
+ )
33
+ fn = _REGISTRY.get((op_name, backend))
34
+ if fn is None:
35
+ available = sorted({n for (o, n) in _REGISTRY if o == op_name})
36
+ raise NotImplementedError(
37
+ f"No backend {backend!r} for op {op_name!r}; available: {available}"
38
+ )
39
+ return fn(cursor, *args, **kwargs)
pixel_cursor/scope.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scope: WHERE in time, depth, identity, and opacity the cursor extends."""
2
+ from __future__ import annotations
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Union
5
+
6
+ import numpy as np
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class FrameIndex:
11
+ index: int
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class FrameRange:
16
+ start: int
17
+ end: int
18
+
19
+
20
+ class _AllFrames:
21
+ __slots__ = ()
22
+
23
+ def __repr__(self) -> str:
24
+ return "ALL_FRAMES"
25
+
26
+
27
+ ALL_FRAMES = _AllFrames()
28
+ TemporalScope = Union[FrameIndex, FrameRange, _AllFrames]
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class DepthScope:
33
+ layer_id: Optional[str] = None
34
+
35
+
36
+ @dataclass(frozen=True, slots=True, eq=False)
37
+ class OpacityProfile:
38
+ kind: str = "hard"
39
+ falloff: Optional[np.ndarray] = None
40
+
41
+
42
+ @dataclass(frozen=True, slots=True, eq=False)
43
+ class IdentityLock:
44
+ embedding: np.ndarray
45
+ source: str = ""
pixel_cursor/selectors.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Selectors: WHAT a cursor targets in pixel space.
2
+
3
+ Hierarchy (each subsumes the previous as a special case):
4
+ Point < Mask < Region < Layer < Anchor3D
5
+
6
+ Token is orthogonal — semantic rather than spatial; the cross-attention map
7
+ of the bound model materializes the spatial extent at op time.
8
+ """
9
+ from __future__ import annotations
10
+ from dataclasses import dataclass
11
+ from typing import Optional, Tuple, Union
12
+
13
+ import numpy as np
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class Point:
18
+ x: float
19
+ y: float
20
+ z: Optional[float] = None
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class Region:
25
+ x: int
26
+ y: int
27
+ w: int
28
+ h: int
29
+
30
+
31
+ @dataclass(frozen=True, slots=True, eq=False)
32
+ class Mask:
33
+ bitmap: np.ndarray
34
+ is_soft: bool = False
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Token:
39
+ text: str
40
+ embedding_id: Optional[str] = None
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class Layer:
45
+ layer_id: str
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Anchor3D:
50
+ anchor_id: str
51
+ bbox: Tuple[float, float, float, float, float, float]
52
+
53
+
54
+ Selector = Union[Point, Region, Mask, Token, Layer, Anchor3D]
pixel_cursor/timing.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Timing primitives from classical animation (the A1 layer).
2
+
3
+ These compile a sparse sequence of keyframe-cursor states into a dense 24fps
4
+ frame stream by interpolating between pinned states with classical-animation rules:
5
+ eases, stride (on-twos), and moving-hold micro-vibration.
6
+
7
+ This is what makes the cursor's temporal layer load-bearing for animation
8
+ specifically rather than decoration around a video-generation model.
9
+ """
10
+ from __future__ import annotations
11
+ from dataclasses import dataclass
12
+ from typing import Callable, Optional
13
+ import math
14
+
15
+
16
+ Curve = Callable[[float], float]
17
+
18
+
19
+ def linear(t: float) -> float:
20
+ return t
21
+
22
+
23
+ def ease_in_out_cubic(t: float) -> float:
24
+ return 4 * t * t * t if t < 0.5 else 1 - (-2 * t + 2) ** 3 / 2
25
+
26
+
27
+ def ease_in_quad(t: float) -> float:
28
+ return t * t
29
+
30
+
31
+ def ease_out_quad(t: float) -> float:
32
+ return 1 - (1 - t) ** 2
33
+
34
+
35
+ def spring(t: float, tension: float = 0.3) -> float:
36
+ return 1 - math.cos(t * math.pi * (1 + tension)) * math.exp(-3 * t)
37
+
38
+
39
+ CURVES: dict[str, Curve] = {
40
+ "linear": linear,
41
+ "ease": ease_in_out_cubic,
42
+ "ease-in": ease_in_quad,
43
+ "ease-out": ease_out_quad,
44
+ "spring": lambda t: spring(t),
45
+ }
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class AnimationSegment:
50
+ """A compiled keyframe→keyframe segment. Intent, not rendered pixels."""
51
+
52
+ start_frame: int
53
+ end_frame: int
54
+ curve_name: str
55
+ stride: int = 2
56
+ micro_profile: Optional[str] = None
57
+
58
+
59
+ def ease_between(
60
+ start_frame: int,
61
+ end_frame: int,
62
+ curve: str = "ease",
63
+ stride: int = 2,
64
+ ) -> AnimationSegment:
65
+ if curve not in CURVES:
66
+ raise ValueError(f"Unknown curve {curve!r}; choices: {sorted(CURVES)}")
67
+ if stride < 1:
68
+ raise ValueError(f"stride must be >= 1; got {stride}")
69
+ return AnimationSegment(start_frame, end_frame, curve, stride)
70
+
71
+
72
+ def step_on_stride(start_frame: int, end_frame: int, stride: int = 2) -> list[int]:
73
+ """Return the per-frame *sample frame index* under stride-N discipline.
74
+
75
+ On-twos: every 2 frames advance; intermediate frame holds the prior sample.
76
+ """
77
+ out = []
78
+ for f in range(start_frame, end_frame):
79
+ rel = f - start_frame
80
+ sample_rel = (rel // stride) * stride
81
+ out.append(start_frame + sample_rel)
82
+ return out
83
+
84
+
85
+ def hold_with_micro(
86
+ start_frame: int, duration: int, micro: str = "breath"
87
+ ) -> AnimationSegment:
88
+ """A moving-hold: spatial pin + micro-vibration to signal life over long holds."""
89
+ return AnimationSegment(start_frame, start_frame + duration, "linear", 1, micro)
90
+
91
+
92
+ def interp_t(curve_name: str, t: float) -> float:
93
+ return CURVES[curve_name](max(0.0, min(1.0, t)))
requirements.txt CHANGED
@@ -1,6 +1,13 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
4
- torch
5
- transformers
6
- xformers
 
 
 
 
 
 
 
 
1
+ # HF Space deployment requirements (used by Spaces build, not local dev).
2
+ # Local dev uses pyproject.toml — see [project.optional-dependencies].
3
+ # gradio itself is provided by HF via README frontmatter `sdk_version: 6.5.1`;
4
+ # do NOT pin it here or builds can conflict.
5
+ numpy>=1.26
6
+ Pillow>=10.0
7
+ imageio>=2.34
8
+ imageio-ffmpeg>=0.5
9
+ torch>=2.2
10
+ diffusers>=0.27
11
+ transformers>=4.40
12
+ accelerate>=0.30
13
+ spaces>=0.30
studio/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Studio: orchestration shell for animation development.
2
+
3
+ The Studio class is a thin convenience facade. It holds no direct reference to
4
+ model code; every pixel mutation routes through pixel_cursor.PixelCursor.write_*.
5
+ Enable a backend by importing its adapter (e.g. studio.backends.motionclone) —
6
+ the adapter self-registers with pixel_cursor.ops.register_backend.
7
+ """
8
+ from __future__ import annotations
9
+ from dataclasses import dataclass
10
+ from typing import Iterable, Optional
11
+
12
+ from pixel_cursor import (
13
+ PixelCursor,
14
+ open_cursor,
15
+ Image,
16
+ FrameStack,
17
+ AnimationSegment,
18
+ load_image,
19
+ )
20
+
21
+
22
+ @dataclass
23
+ class Studio:
24
+ cursor: Optional[PixelCursor] = None
25
+
26
+ def load(self, image_path: str) -> "Studio":
27
+ img = load_image(image_path)
28
+ self.cursor = open_cursor(img)
29
+ return self
30
+
31
+ def with_cursor(self, cursor: PixelCursor) -> "Studio":
32
+ self.cursor = cursor
33
+ return self
34
+
35
+ def compile_24fps_from_keyframes(
36
+ self,
37
+ keyframe_cursors: Iterable[PixelCursor],
38
+ segments: Iterable[AnimationSegment],
39
+ ) -> FrameStack:
40
+ from .compile_24fps import compile_keyframes
41
+
42
+ return compile_keyframes(keyframe_cursors, segments)
43
+
44
+
45
+ __all__ = ["Studio"]
studio/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
studio/backends/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Studio backends. Each backend module self-registers with pixel_cursor.ops on import."""
studio/backends/animatediff.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AnimateDiff backend adapter (Apache 2.0).
2
+
3
+ Wraps `diffusers.AnimateDiffSparseControlNetPipeline` so a `PixelCursor` over a
4
+ single Image can be animated through one of the 8 verified MotionLoRA presets
5
+ (zoom, pan, tilt, roll). SparseCtrl is the I2V path: frame 0 is pinned to the
6
+ cursor's source image, frames 1..N-1 are diffused with motion-LoRA conditioning.
7
+
8
+ Light surface (works without torch):
9
+ - `register()` wires bind_motion_exemplar + write_motion into the op registry
10
+ - `bind_motion_exemplar(cursor, ["zoom_in"])` packs the resolved MotionLoRA
11
+ id into an IdentityLock — no model load
12
+ - `dry_run(cursor)` returns a diagnostic dict (what would happen, what it costs)
13
+
14
+ Heavy surface (requires `pip install -e '.[backends]'`):
15
+ - `write_motion(cursor, motion_spec)` lazy-imports torch + diffusers, loads
16
+ the pipeline, runs SparseCtrl-conditioned generation, returns FrameStack
17
+
18
+ References:
19
+ diffusers AnimateDiffSparseControlNetPipeline docs (Apache 2.0)
20
+ guoyww/animatediff-motion-adapter-v1-5-2 (Apache 2.0)
21
+ guoyww/animatediff-sparsectrl-rgb (Apache 2.0)
22
+ """
23
+ from __future__ import annotations
24
+ from dataclasses import dataclass
25
+ from typing import Sequence
26
+
27
+ import numpy as np
28
+
29
+ from pixel_cursor import PixelCursor, Image, IdentityLock, FrameStack, ops
30
+ from pixel_cursor.artifact import _new_framestack
31
+
32
+
33
+ # Verified by A5 research (background subagent, confidence: high)
34
+ MOTION_LORA_MAP: dict[str, str] = {
35
+ "zoom_in": "guoyww/animatediff-motion-lora-zoom-in",
36
+ "zoom_out": "guoyww/animatediff-motion-lora-zoom-out",
37
+ "pan_left": "guoyww/animatediff-motion-lora-pan-left",
38
+ "pan_right": "guoyww/animatediff-motion-lora-pan-right",
39
+ "tilt_up": "guoyww/animatediff-motion-lora-tilt-up",
40
+ "tilt_down": "guoyww/animatediff-motion-lora-tilt-down",
41
+ "roll_anticlockwise": "guoyww/animatediff-motion-lora-rolling-anticlockwise",
42
+ "roll_clockwise": "guoyww/animatediff-motion-lora-rolling-clockwise",
43
+ }
44
+
45
+ DEFAULT_MOTION_ADAPTER = "guoyww/animatediff-motion-adapter-v1-5-2"
46
+ DEFAULT_SPARSECTRL = "guoyww/animatediff-sparsectrl-rgb"
47
+ DEFAULT_BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
48
+
49
+ INSTALL_HINT = (
50
+ "AnimateDiff inference requires torch + diffusers. Install with:\n"
51
+ " pip install -e '.[backends]'\n"
52
+ "(or: pip install torch diffusers transformers)"
53
+ )
54
+
55
+
56
+ class AnimateDiffAdapter:
57
+ """Adapter exposing AnimateDiff primitives to the PixelCursor op registry."""
58
+
59
+ SOURCE_TAG = "animatediff"
60
+
61
+ def __init__(
62
+ self,
63
+ motion_adapter_id: str = DEFAULT_MOTION_ADAPTER,
64
+ base_model_id: str = DEFAULT_BASE_MODEL,
65
+ sparsectrl_id: str = DEFAULT_SPARSECTRL,
66
+ ) -> None:
67
+ self.motion_adapter_id = motion_adapter_id
68
+ self.base_model_id = base_model_id
69
+ self.sparsectrl_id = sparsectrl_id
70
+
71
+ def register(self) -> None:
72
+ ops.register_backend("bind_motion_exemplar", "animatediff", self.bind_motion_exemplar)
73
+ ops.register_backend("write_motion", "animatediff", self.write_motion)
74
+
75
+ def bind_motion_exemplar(
76
+ self, cursor: PixelCursor, exemplar: Sequence[str]
77
+ ) -> PixelCursor:
78
+ """Resolve a preset name (e.g. ["zoom_in"]) to a MotionLoRA id and pack into
79
+ an IdentityLock on the cursor. No model load happens here.
80
+
81
+ Accepts a sequence to keep the signature uniform with MotionDirector
82
+ (which takes K reference clips). For AnimateDiff a single preset is expected;
83
+ a list of clip paths is rejected with a helpful error pointing to session 3.
84
+ """
85
+ if len(exemplar) != 1:
86
+ raise ValueError(
87
+ f"animatediff.bind_motion_exemplar expects exactly one preset name; "
88
+ f"got {len(exemplar)} items. For few-shot training from K reference "
89
+ f"clips, use backend='motiondirector' (session 3)."
90
+ )
91
+ preset = exemplar[0]
92
+ if preset.endswith((".mp4", ".webm", ".mkv", ".gif", ".avi", ".mov")):
93
+ raise ValueError(
94
+ f"animatediff backend takes preset names from MOTION_LORA_MAP "
95
+ f"(e.g. 'zoom_in'); got what looks like a video path: {preset!r}. "
96
+ f"For exemplar-based few-shot, use backend='motiondirector'."
97
+ )
98
+ if preset not in MOTION_LORA_MAP:
99
+ valid = sorted(MOTION_LORA_MAP)
100
+ raise ValueError(
101
+ f"Unknown AnimateDiff preset {preset!r}. Valid presets: {valid}"
102
+ )
103
+ lora_id = MOTION_LORA_MAP[preset]
104
+ lock = IdentityLock(
105
+ embedding=np.zeros(0, dtype=np.float32),
106
+ source=f"{self.SOURCE_TAG}:{preset}:{lora_id}",
107
+ )
108
+ return cursor.lock_identity(lock)
109
+
110
+ def dry_run(self, cursor: PixelCursor, motion_spec: dict | None = None) -> dict:
111
+ """Return what `write_motion` WOULD do without running it.
112
+
113
+ Useful for verifying the preset mapping and resource estimate before
114
+ paying the install + model-download cost. Safe to call without torch.
115
+ """
116
+ if cursor.identity_lock is None or not cursor.identity_lock.source.startswith(
117
+ f"{self.SOURCE_TAG}:"
118
+ ):
119
+ raise ValueError(
120
+ "dry_run requires bind_motion_exemplar(..., backend='animatediff') first"
121
+ )
122
+ if not isinstance(cursor.artifact, Image):
123
+ raise TypeError(
124
+ f"AnimateDiff dry_run expects an Image artifact; got {type(cursor.artifact).__name__}"
125
+ )
126
+
127
+ _, preset, lora_id = cursor.identity_lock.source.split(":", 2)
128
+ ms = motion_spec or {}
129
+ return {
130
+ "backend": "animatediff",
131
+ "pipeline_class": "diffusers.AnimateDiffSparseControlNetPipeline",
132
+ "base_model": self.base_model_id,
133
+ "motion_adapter": self.motion_adapter_id,
134
+ "sparsectrl": self.sparsectrl_id,
135
+ "preset": preset,
136
+ "motion_lora_id": lora_id,
137
+ "input_image_shape": tuple(cursor.artifact.pixels.shape),
138
+ "num_frames": ms.get("num_frames", 16),
139
+ "native_fps": 8,
140
+ "target_fps": 24,
141
+ "post_interpolation": "RIFE 3x (8fps -> 24fps), MIT licensed",
142
+ "expected_output_shape": (ms.get("num_frames", 16), *cursor.artifact.pixels.shape),
143
+ "hardware_floor_vram_gb": 13,
144
+ "expected_wall_time_s_4090": 45,
145
+ "prompt": ms.get("prompt", "(none — cursor has no text prompt yet)"),
146
+ "guidance_scale": ms.get("guidance_scale", 7.5),
147
+ "num_inference_steps": ms.get("num_inference_steps", 25),
148
+ "torch_installed": _torch_available(),
149
+ "note": (
150
+ "If torch_installed is False, `write_motion` will raise ImportError. "
151
+ "Install with: pip install -e '.[backends]'"
152
+ ),
153
+ }
154
+
155
+ def write_motion(self, cursor: PixelCursor, motion_spec: dict | None = None) -> FrameStack:
156
+ if cursor.identity_lock is None or not cursor.identity_lock.source.startswith(
157
+ f"{self.SOURCE_TAG}:"
158
+ ):
159
+ raise ValueError(
160
+ "write_motion(animatediff) requires bind_motion_exemplar(..., backend='animatediff') first"
161
+ )
162
+ if not isinstance(cursor.artifact, Image):
163
+ raise TypeError(
164
+ f"AnimateDiff write_motion expects an Image artifact; got {type(cursor.artifact).__name__}"
165
+ )
166
+
167
+ try:
168
+ import torch # noqa: F401
169
+ from diffusers import ( # noqa: F401
170
+ AnimateDiffSparseControlNetPipeline,
171
+ MotionAdapter,
172
+ SparseControlNetModel,
173
+ DDIMScheduler,
174
+ )
175
+ except ImportError as e:
176
+ raise ImportError(INSTALL_HINT) from e
177
+
178
+ return self._run_inference(cursor, motion_spec or {})
179
+
180
+ def _run_inference(self, cursor: PixelCursor, motion_spec: dict) -> FrameStack:
181
+ import torch
182
+ from PIL import Image as PILImage
183
+ from diffusers import (
184
+ AnimateDiffSparseControlNetPipeline,
185
+ MotionAdapter,
186
+ SparseControlNetModel,
187
+ DDIMScheduler,
188
+ )
189
+
190
+ _, preset, lora_id = cursor.identity_lock.source.split(":", 2)
191
+ dtype = torch.float16
192
+
193
+ motion_adapter = MotionAdapter.from_pretrained(self.motion_adapter_id, torch_dtype=dtype)
194
+ controlnet = SparseControlNetModel.from_pretrained(self.sparsectrl_id, torch_dtype=dtype)
195
+ pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
196
+ self.base_model_id,
197
+ motion_adapter=motion_adapter,
198
+ controlnet=controlnet,
199
+ torch_dtype=dtype,
200
+ )
201
+ pipe.scheduler = DDIMScheduler.from_config(
202
+ pipe.scheduler.config,
203
+ clip_sample=False,
204
+ timestep_spacing="linspace",
205
+ beta_schedule="linear",
206
+ steps_offset=1,
207
+ )
208
+ pipe.enable_vae_slicing()
209
+ pipe.enable_model_cpu_offload()
210
+ pipe.load_lora_weights(lora_id, adapter_name=preset)
211
+ pipe.set_adapters([preset], adapter_weights=[motion_spec.get("lora_weight", 1.0)])
212
+
213
+ conditioning_pil = PILImage.fromarray(cursor.artifact.pixels)
214
+ output = pipe(
215
+ prompt=motion_spec.get("prompt", "high quality, detailed"),
216
+ negative_prompt=motion_spec.get("negative_prompt", "bad quality, blurry"),
217
+ num_frames=motion_spec.get("num_frames", 16),
218
+ guidance_scale=motion_spec.get("guidance_scale", 7.5),
219
+ num_inference_steps=motion_spec.get("num_inference_steps", 25),
220
+ conditioning_frames=[conditioning_pil],
221
+ controlnet_conditioning_scale=motion_spec.get("controlnet_scale", 1.0),
222
+ controlnet_frame_indices=[0],
223
+ generator=torch.Generator("cpu").manual_seed(motion_spec.get("seed", 42)),
224
+ )
225
+ frames_pil = output.frames[0]
226
+ frames_np = np.stack([np.array(f) for f in frames_pil], axis=0).astype(np.uint8)
227
+ return _new_framestack(frames_np, fps=8, name=f"animatediff:{preset}")
228
+
229
+
230
+ @dataclass(frozen=True)
231
+ class _ProbeResult:
232
+ torch_installed: bool
233
+ diffusers_installed: bool
234
+
235
+
236
+ def _torch_available() -> bool:
237
+ try:
238
+ import torch # noqa: F401
239
+ return True
240
+ except ImportError:
241
+ return False
242
+
243
+
244
+ def probe() -> _ProbeResult:
245
+ """Diagnostic: are the heavy deps installed?"""
246
+ try:
247
+ import torch # noqa: F401
248
+ t = True
249
+ except ImportError:
250
+ t = False
251
+ try:
252
+ import diffusers # noqa: F401
253
+ d = True
254
+ except ImportError:
255
+ d = False
256
+ return _ProbeResult(torch_installed=t, diffusers_installed=d)
studio/backends/hf_space.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF Spaces backend adapter (free ZeroGPU A100 via `gradio_client`).
2
+
3
+ Local CLI client that calls a deployed Hugging Face Space hosting the studio's
4
+ inference pipeline. The Space provides the GPU; the local machine needs only
5
+ `gradio_client` + a HF token. No torch, no diffusers, no model downloads locally.
6
+
7
+ Token resolution order (most-specific wins):
8
+ 1. explicit `hf_token=` param
9
+ 2. `HF_TOKEN` env var
10
+ 3. `huggingface_hub.HfFolder.get_token()` (reads ~/.cache/huggingface/token)
11
+
12
+ The deployed Space is expected to expose a Gradio function (default api_name
13
+ `/infer`) with the signature:
14
+ (image_pil, preset_name, num_frames, num_inference_steps, guidance_scale,
15
+ prompt, negative_prompt, seed) -> video_filepath
16
+
17
+ Pair this with the host-mode `app.py` at the repo root for end-to-end ownership.
18
+ """
19
+ from __future__ import annotations
20
+ from dataclasses import dataclass
21
+ import os
22
+ import tempfile
23
+ from pathlib import Path
24
+ from typing import Optional, Sequence
25
+
26
+ import numpy as np
27
+ from PIL import Image as PILImage
28
+
29
+ from pixel_cursor import PixelCursor, Image, IdentityLock, FrameStack, ops
30
+ from pixel_cursor.artifact import _new_framestack
31
+ from .animatediff import MOTION_LORA_MAP
32
+
33
+
34
+ INSTALL_HINT = (
35
+ "HF Space backend requires gradio_client. Install with:\n"
36
+ " pip install -e '.[hf]' (or: pip install gradio_client imageio imageio-ffmpeg)"
37
+ )
38
+
39
+
40
+ def _resolve_hf_token(explicit: Optional[str] = None) -> Optional[str]:
41
+ if explicit:
42
+ return explicit
43
+ if os.environ.get("HF_TOKEN"):
44
+ return os.environ["HF_TOKEN"]
45
+ try:
46
+ from huggingface_hub import HfFolder
47
+ return HfFolder.get_token()
48
+ except ImportError:
49
+ return None
50
+
51
+
52
+ @dataclass
53
+ class HFSpaceAdapter:
54
+ """Adapter that routes write_motion through a deployed HF Space."""
55
+
56
+ space_id: str
57
+ api_name: str = "/infer"
58
+ hf_token: Optional[str] = None
59
+ SOURCE_TAG: str = "hf_space"
60
+
61
+ def register(self) -> None:
62
+ ops.register_backend("bind_motion_exemplar", "hf_space", self.bind_motion_exemplar)
63
+ ops.register_backend("write_motion", "hf_space", self.write_motion)
64
+
65
+ def bind_motion_exemplar(
66
+ self, cursor: PixelCursor, exemplar: Sequence[str]
67
+ ) -> PixelCursor:
68
+ """Same preset semantics as AnimateDiff; the Space carries the same MotionLoRA map."""
69
+ if len(exemplar) != 1:
70
+ raise ValueError(
71
+ "hf_space.bind_motion_exemplar expects exactly one preset name."
72
+ )
73
+ preset = exemplar[0]
74
+ if preset not in MOTION_LORA_MAP:
75
+ valid = sorted(MOTION_LORA_MAP)
76
+ raise ValueError(f"Unknown preset {preset!r}. Valid: {valid}")
77
+ lock = IdentityLock(
78
+ embedding=np.zeros(0, dtype=np.float32),
79
+ source=f"{self.SOURCE_TAG}:{preset}:{MOTION_LORA_MAP[preset]}",
80
+ )
81
+ return cursor.lock_identity(lock)
82
+
83
+ def dry_run(self, cursor: PixelCursor, motion_spec: dict | None = None) -> dict:
84
+ if cursor.identity_lock is None or not cursor.identity_lock.source.startswith(
85
+ f"{self.SOURCE_TAG}:"
86
+ ):
87
+ raise ValueError("dry_run requires bind_motion_exemplar(..., backend='hf_space') first")
88
+ if not isinstance(cursor.artifact, Image):
89
+ raise TypeError("HF Space dry_run expects an Image artifact")
90
+
91
+ _, preset, lora_id = cursor.identity_lock.source.split(":", 2)
92
+ ms = motion_spec or {}
93
+ token_present = _resolve_hf_token() is not None
94
+ return {
95
+ "backend": "hf_space",
96
+ "space_id": self.space_id,
97
+ "api_name": self.api_name,
98
+ "preset": preset,
99
+ "motion_lora_id": lora_id,
100
+ "input_image_shape": tuple(cursor.artifact.pixels.shape),
101
+ "num_frames": ms.get("num_frames", 16),
102
+ "expected_output_shape": (ms.get("num_frames", 16), *cursor.artifact.pixels.shape),
103
+ "hf_token_resolved": token_present,
104
+ "token_source": (
105
+ "explicit" if self.hf_token
106
+ else "env:HF_TOKEN" if os.environ.get("HF_TOKEN")
107
+ else "~/.cache/huggingface/token" if token_present
108
+ else "NONE"
109
+ ),
110
+ "gradio_client_installed": _gradio_client_available(),
111
+ "note": (
112
+ "Anonymous calls work but quota is tight; an HF token raises the limit. "
113
+ "ZeroGPU cold-start ~10-30s; subsequent calls ~5-15s warm."
114
+ ),
115
+ }
116
+
117
+ def write_motion(self, cursor: PixelCursor, motion_spec: dict | None = None) -> FrameStack:
118
+ if cursor.identity_lock is None or not cursor.identity_lock.source.startswith(
119
+ f"{self.SOURCE_TAG}:"
120
+ ):
121
+ raise ValueError(
122
+ "write_motion(hf_space) requires bind_motion_exemplar(..., backend='hf_space') first"
123
+ )
124
+ if not isinstance(cursor.artifact, Image):
125
+ raise TypeError("HF Space write_motion expects an Image artifact")
126
+
127
+ try:
128
+ from gradio_client import Client, handle_file
129
+ except ImportError as e:
130
+ raise ImportError(INSTALL_HINT) from e
131
+
132
+ token = _resolve_hf_token(self.hf_token)
133
+ client = Client(self.space_id, hf_token=token)
134
+
135
+ _, preset, _ = cursor.identity_lock.source.split(":", 2)
136
+ ms = motion_spec or {}
137
+
138
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
139
+ PILImage.fromarray(cursor.artifact.pixels).save(tmp.name)
140
+ video_path = client.predict(
141
+ handle_file(tmp.name),
142
+ preset,
143
+ ms.get("num_frames", 16),
144
+ ms.get("num_inference_steps", 25),
145
+ ms.get("guidance_scale", 7.5),
146
+ ms.get("prompt", "high quality, detailed"),
147
+ ms.get("negative_prompt", "bad quality, blurry"),
148
+ ms.get("seed", 42),
149
+ api_name=self.api_name,
150
+ )
151
+
152
+ return _video_path_to_framestack(video_path, preset)
153
+
154
+
155
+ def _video_path_to_framestack(video_path: str | Path, preset: str) -> FrameStack:
156
+ try:
157
+ import imageio.v3 as iio
158
+ except ImportError as e:
159
+ raise ImportError(
160
+ "Loading the Space's video response requires imageio. Install with:\n"
161
+ " pip install -e '.[hf]'"
162
+ ) from e
163
+ frames = iio.imread(str(video_path))
164
+ if frames.ndim != 4:
165
+ raise ValueError(f"unexpected video shape from Space: {frames.shape}")
166
+ return _new_framestack(frames.astype(np.uint8), fps=8, name=f"hf_space:{preset}")
167
+
168
+
169
+ def _gradio_client_available() -> bool:
170
+ try:
171
+ import gradio_client # noqa: F401
172
+ return True
173
+ except ImportError:
174
+ return False
studio/backends/motionclone.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MotionClone backend adapter.
2
+
3
+ MotionClone (Bujiazi et al., ICLR 2025) extracts a motion descriptor from one or
4
+ more reference videos via sparse temporal attention — training-free, no inversion.
5
+ Repo: https://github.com/Bujiazi/MotionClone (514 stars, last push 2025-06-17).
6
+
7
+ This file is a contract adapter. The cursor and op-set are wired correctly; the
8
+ last-mile model call is stubbed pending vendoring. To activate:
9
+ 1. Confirm upstream license is compatible (no LICENSE declared at last check).
10
+ 2. git submodule add https://github.com/Bujiazi/MotionClone vendor/motionclone
11
+ 3. Implement _extract_motion_descriptor and _apply_motion below against the
12
+ vendored module.
13
+ 4. Call MotionCloneAdapter().register() at studio startup.
14
+ """
15
+ from __future__ import annotations
16
+ from dataclasses import dataclass
17
+ from typing import Sequence
18
+
19
+ import numpy as np
20
+
21
+ from pixel_cursor import PixelCursor, Image, IdentityLock, FrameStack, ops
22
+ from pixel_cursor.artifact import _new_framestack
23
+
24
+
25
+ @dataclass
26
+ class MotionDescriptor:
27
+ sparse_attention: np.ndarray
28
+ source_paths: tuple[str, ...]
29
+
30
+
31
+ class MotionCloneAdapter:
32
+ """Adapter exposing MotionClone primitives to the PixelCursor op registry."""
33
+
34
+ SOURCE_TAG = "motionclone"
35
+
36
+ def register(self) -> None:
37
+ ops.register_backend("bind_motion_exemplar", "motionclone", self.bind_motion_exemplar)
38
+ ops.register_backend("write_motion", "motionclone", self.write_motion)
39
+
40
+ def bind_motion_exemplar(
41
+ self, cursor: PixelCursor, exemplar_paths: Sequence[str]
42
+ ) -> PixelCursor:
43
+ descriptor = self._extract_motion_descriptor(exemplar_paths)
44
+ lock = IdentityLock(
45
+ embedding=descriptor.sparse_attention.flatten(),
46
+ source=f"{self.SOURCE_TAG}:{','.join(exemplar_paths)}",
47
+ )
48
+ return cursor.lock_identity(lock)
49
+
50
+ def write_motion(self, cursor: PixelCursor, motion_spec) -> FrameStack:
51
+ if cursor.identity_lock is None or not cursor.identity_lock.source.startswith(
52
+ f"{self.SOURCE_TAG}:"
53
+ ):
54
+ raise ValueError(
55
+ "write_motion(motionclone) requires bind_motion_exemplar(..., backend='motionclone') first"
56
+ )
57
+ if not isinstance(cursor.artifact, Image):
58
+ raise TypeError(
59
+ f"MotionClone write_motion expects an Image artifact; got {type(cursor.artifact).__name__}"
60
+ )
61
+ frames = self._apply_motion(cursor.artifact.pixels, cursor.identity_lock, motion_spec)
62
+ return _new_framestack(frames, fps=24, name=f"{self.SOURCE_TAG}-generated")
63
+
64
+ # ── pending vendoring ──
65
+
66
+ def _extract_motion_descriptor(self, paths: Sequence[str]) -> MotionDescriptor:
67
+ return MotionDescriptor(
68
+ sparse_attention=np.zeros((1, 1, 1), dtype=np.float32),
69
+ source_paths=tuple(paths),
70
+ )
71
+
72
+ def _apply_motion(
73
+ self, image_pixels: np.ndarray, lock: IdentityLock, motion_spec
74
+ ) -> np.ndarray:
75
+ return np.repeat(image_pixels[None, ...], 24, axis=0)
studio/cli.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """studio CLI — verbs mirror cursor ops.
2
+
3
+ Subcommands:
4
+ open <image> validate; print cursor state
5
+ compile <kf0> <kf1> -o <out.npz> two-keyframe timing-layer compile
6
+ export <frames.npz> -o <out.gif|.mp4|.webm> render FrameStack to disk
7
+ """
8
+ from __future__ import annotations
9
+ import argparse
10
+ import sys
11
+
12
+ import json
13
+
14
+ from pixel_cursor import open_cursor, ease_between, load_image
15
+ from . import Studio
16
+ from .io import save_framestack_npz, load_framestack_npz, export_video
17
+
18
+
19
+ def cmd_open(args: argparse.Namespace) -> int:
20
+ img = load_image(args.image)
21
+ cur = open_cursor(img)
22
+ print(f"opened: {img}")
23
+ for k, v in cur.tell().items():
24
+ print(f" {k}: {v}")
25
+ return 0
26
+
27
+
28
+ def cmd_compile(args: argparse.Namespace) -> int:
29
+ kf0 = load_image(args.kf0)
30
+ kf1 = load_image(args.kf1)
31
+ cur_a = open_cursor(kf0).at_frame(0)
32
+ cur_b = open_cursor(kf1).at_frame(args.frames - 1)
33
+ seg = ease_between(0, args.frames, curve=args.curve, stride=args.stride)
34
+ stack = Studio().compile_24fps_from_keyframes([cur_a, cur_b], [seg])
35
+ save_framestack_npz(stack, args.out)
36
+ print(f"compiled {stack.num_frames} frames @ {stack.fps}fps -> {args.out}")
37
+ print(f" curve={args.curve} stride={args.stride} (on-{['ones','twos','threes'][min(args.stride-1, 2)]})")
38
+ return 0
39
+
40
+
41
+ def cmd_export(args: argparse.Namespace) -> int:
42
+ stack = load_framestack_npz(args.frames)
43
+ out = export_video(stack, args.out)
44
+ print(f"exported {stack.num_frames} frames @ {stack.fps}fps -> {out}")
45
+ return 0
46
+
47
+
48
+ def cmd_motion(args: argparse.Namespace) -> int:
49
+ from .backends.animatediff import AnimateDiffAdapter, MOTION_LORA_MAP
50
+ from .backends.hf_space import HFSpaceAdapter
51
+
52
+ if args.list_presets:
53
+ print("MotionLoRA presets (shared by `animatediff` and `hf_space` backends):")
54
+ for name, lora_id in MOTION_LORA_MAP.items():
55
+ print(f" {name:24s} -> {lora_id}")
56
+ return 0
57
+
58
+ if args.preset is None or args.image is None:
59
+ print(
60
+ "error: --preset and --image are required (or use --list-presets)",
61
+ file=sys.stderr,
62
+ )
63
+ return 2
64
+
65
+ if args.backend == "hf_space":
66
+ if not args.space:
67
+ print("error: --space <owner>/<name> is required for --backend hf_space", file=sys.stderr)
68
+ return 2
69
+ adapter = HFSpaceAdapter(space_id=args.space, hf_token=args.hf_token)
70
+ else:
71
+ adapter = AnimateDiffAdapter()
72
+ adapter.register()
73
+
74
+ img = load_image(args.image)
75
+ cur = open_cursor(img).bind_motion_exemplar([args.preset], backend=args.backend)
76
+
77
+ motion_spec = {
78
+ "num_frames": args.num_frames,
79
+ "num_inference_steps": args.steps,
80
+ "guidance_scale": args.guidance,
81
+ "prompt": args.prompt,
82
+ "negative_prompt": args.negative_prompt,
83
+ "seed": args.seed,
84
+ }
85
+
86
+ if args.dry_run:
87
+ diag = adapter.dry_run(cur, motion_spec)
88
+ print(json.dumps(diag, indent=2, default=str))
89
+ return 0
90
+
91
+ if args.out is None:
92
+ print("error: -o/--out is required unless --dry-run is set", file=sys.stderr)
93
+ return 2
94
+
95
+ stack = cur.write_motion(motion_spec, backend=args.backend)
96
+ save_framestack_npz(stack, args.out)
97
+ print(f"generated {stack.num_frames} frames @ {stack.fps}fps -> {args.out}")
98
+ print(f" backend={args.backend} preset={args.preset}")
99
+ return 0
100
+
101
+
102
+ def build_parser() -> argparse.ArgumentParser:
103
+ p = argparse.ArgumentParser(
104
+ prog="studio",
105
+ description="Pixel-cursor animation studio (v0: model-free timing compile)",
106
+ )
107
+ sub = p.add_subparsers(dest="cmd", required=True)
108
+
109
+ p_open = sub.add_parser("open", help="Load an image; print cursor state")
110
+ p_open.add_argument("image")
111
+ p_open.set_defaults(func=cmd_open)
112
+
113
+ p_compile = sub.add_parser(
114
+ "compile",
115
+ help="Compile a two-keyframe segment into a FrameStack via the cursor timing layer",
116
+ )
117
+ p_compile.add_argument("kf0", help="first keyframe image")
118
+ p_compile.add_argument("kf1", help="second keyframe image")
119
+ p_compile.add_argument("-o", "--out", required=True, help="output .npz path")
120
+ p_compile.add_argument("--frames", type=int, default=24, help="total frames (default 24)")
121
+ p_compile.add_argument(
122
+ "--curve",
123
+ default="ease",
124
+ choices=("linear", "ease", "ease-in", "ease-out", "spring"),
125
+ )
126
+ p_compile.add_argument(
127
+ "--stride",
128
+ type=int,
129
+ default=2,
130
+ help="on-twos=2 (default), on-ones=1, on-threes=3",
131
+ )
132
+ p_compile.add_argument("--fps", type=int, default=24, help="target fps (default 24)")
133
+ p_compile.set_defaults(func=cmd_compile)
134
+
135
+ p_export = sub.add_parser(
136
+ "export", help="Render a FrameStack .npz to a video file"
137
+ )
138
+ p_export.add_argument("frames", help="input .npz from `studio compile`")
139
+ p_export.add_argument(
140
+ "-o", "--out", required=True, help="output .gif | .mp4 | .webm | .mkv | .avi"
141
+ )
142
+ p_export.set_defaults(func=cmd_export)
143
+
144
+ p_motion = sub.add_parser(
145
+ "motion",
146
+ help="Generate motion on a single image via AnimateDiff MotionLoRA preset",
147
+ )
148
+ p_motion.add_argument(
149
+ "--list-presets", action="store_true", help="List all 8 verified MotionLoRA presets and exit"
150
+ )
151
+ p_motion.add_argument("--preset", help="preset name (see --list-presets)")
152
+ p_motion.add_argument("--image", help="source image path")
153
+ p_motion.add_argument("-o", "--out", help="output .npz path (required unless --dry-run)")
154
+ p_motion.add_argument(
155
+ "--dry-run",
156
+ action="store_true",
157
+ help="Print what would happen + resource estimate; no model load, no output written",
158
+ )
159
+ p_motion.add_argument("--num-frames", type=int, default=16)
160
+ p_motion.add_argument("--steps", type=int, default=25, help="num_inference_steps")
161
+ p_motion.add_argument("--guidance", type=float, default=7.5, help="guidance_scale")
162
+ p_motion.add_argument("--prompt", default="high quality, detailed")
163
+ p_motion.add_argument("--negative-prompt", default="bad quality, blurry")
164
+ p_motion.add_argument("--seed", type=int, default=42)
165
+ p_motion.add_argument(
166
+ "--backend",
167
+ default="animatediff",
168
+ choices=("animatediff", "hf_space"),
169
+ help="local diffusers run (animatediff) or remote ZeroGPU Space (hf_space)",
170
+ )
171
+ p_motion.add_argument(
172
+ "--space", default=None,
173
+ help="HF Space id (e.g. owner/venture-studio); required when --backend hf_space",
174
+ )
175
+ p_motion.add_argument(
176
+ "--hf-token", default=None,
177
+ help="HF token (overrides HF_TOKEN env var and ~/.cache/huggingface/token)",
178
+ )
179
+ p_motion.set_defaults(func=cmd_motion)
180
+
181
+ return p
182
+
183
+
184
+ def main(argv: list[str] | None = None) -> int:
185
+ parser = build_parser()
186
+ args = parser.parse_args(argv)
187
+ return args.func(args)
188
+
189
+
190
+ if __name__ == "__main__":
191
+ sys.exit(main())
studio/compile_24fps.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """24fps compiler: keyframe cursors + AnimationSegments -> dense 24fps FrameStack.
2
+
3
+ The on-twos discipline (A1) is realized here. For each segment with stride=N, the
4
+ compiler advances to a new sample every N frames; intermediate frames hold the
5
+ prior sample. This is what makes the cursor's temporal layer load-bearing for
6
+ animation specifically — not decoration around a black-box video model.
7
+
8
+ This is real, runnable today on numpy alone. It alpha-blends keyframe artifacts
9
+ along eased curves; with a backend providing write_motion, the same compile path
10
+ fills the same FrameStack from model-generated samples instead.
11
+ """
12
+ from __future__ import annotations
13
+ from typing import Iterable
14
+
15
+ import numpy as np
16
+
17
+ from pixel_cursor import PixelCursor, AnimationSegment, FrameStack, Image, interp_t
18
+ from pixel_cursor.artifact import _new_framestack
19
+
20
+
21
+ def compile_keyframes(
22
+ keyframe_cursors: Iterable[PixelCursor],
23
+ segments: Iterable[AnimationSegment],
24
+ target_fps: int = 24,
25
+ ) -> FrameStack:
26
+ kf = list(keyframe_cursors)
27
+ segs = list(segments)
28
+ if len(kf) < 2:
29
+ raise ValueError("Need at least 2 keyframe cursors")
30
+ if len(segs) != len(kf) - 1:
31
+ raise ValueError(
32
+ f"Expected {len(kf) - 1} segments for {len(kf)} keyframes; got {len(segs)}"
33
+ )
34
+ for cur in kf:
35
+ if not isinstance(cur.artifact, Image):
36
+ raise TypeError(
37
+ f"Keyframe cursors must point at Image artifacts; got {type(cur.artifact).__name__}"
38
+ )
39
+
40
+ total_frames = segs[-1].end_frame
41
+ ref_pixels = kf[0].artifact.pixels
42
+ h, w, c = ref_pixels.shape
43
+
44
+ out = np.zeros((total_frames, h, w, c), dtype=np.uint8)
45
+
46
+ for seg_idx, seg in enumerate(segs):
47
+ a = kf[seg_idx].artifact.pixels
48
+ b = kf[seg_idx + 1].artifact.pixels
49
+ if a.shape != b.shape:
50
+ raise ValueError(
51
+ f"Segment {seg_idx}: keyframe shapes differ {a.shape} vs {b.shape}"
52
+ )
53
+
54
+ seg_len = seg.end_frame - seg.start_frame
55
+ for f in range(seg.start_frame, seg.end_frame):
56
+ rel = f - seg.start_frame
57
+ sample_rel = (rel // seg.stride) * seg.stride
58
+ denom = max(1, seg_len - 1)
59
+ t = sample_rel / denom
60
+ eased = interp_t(seg.curve_name, t)
61
+ blended = (1.0 - eased) * a.astype(np.float32) + eased * b.astype(np.float32)
62
+ out[f] = np.clip(blended, 0, 255).astype(np.uint8)
63
+
64
+ return _new_framestack(out, fps=target_fps, name="compiled-24fps")
studio/io.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """I/O helpers: FrameStack <-> .npz round-trip, ndarray -> video file.
2
+
3
+ GIF export uses Pillow (always available). MP4/WebM/MKV export uses imageio
4
+ when installed (optional extra: `pip install 'venture-studio[video]'`); without
5
+ it, those extensions raise a clean ImportError with the install instruction.
6
+ """
7
+ from __future__ import annotations
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ from PIL import Image as PILImage
12
+
13
+ from pixel_cursor import FrameStack
14
+ from pixel_cursor.artifact import _new_framestack
15
+
16
+
17
+ def save_framestack_npz(stack: FrameStack, path: Path | str) -> Path:
18
+ out = Path(path)
19
+ np.savez_compressed(
20
+ str(out),
21
+ frames=stack.frames,
22
+ fps=np.array(stack.fps, dtype=np.int32),
23
+ name=np.array(stack.name, dtype="U256"),
24
+ )
25
+ return out
26
+
27
+
28
+ def load_framestack_npz(path: Path | str) -> FrameStack:
29
+ data = np.load(str(path), allow_pickle=False)
30
+ name = str(data["name"]) if "name" in data.files else ""
31
+ return _new_framestack(data["frames"], fps=int(data["fps"]), name=name)
32
+
33
+
34
+ def export_video(stack: FrameStack, out_path: Path | str) -> Path:
35
+ out = Path(out_path)
36
+ ext = out.suffix.lower()
37
+ if ext == ".gif":
38
+ return _export_gif(stack, out)
39
+ if ext in (".mp4", ".webm", ".mkv", ".avi"):
40
+ return _export_imageio(stack, out)
41
+ raise ValueError(
42
+ f"Unsupported export extension {ext!r}; supported: .gif .mp4 .webm .mkv .avi"
43
+ )
44
+
45
+
46
+ def _export_gif(stack: FrameStack, out: Path) -> Path:
47
+ frames = [PILImage.fromarray(stack.frames[i]) for i in range(stack.num_frames)]
48
+ duration_ms = max(1, 1000 // max(1, stack.fps))
49
+ frames[0].save(
50
+ out, save_all=True, append_images=frames[1:], duration=duration_ms, loop=0
51
+ )
52
+ return out
53
+
54
+
55
+ def _export_imageio(stack: FrameStack, out: Path) -> Path:
56
+ try:
57
+ import imageio.v3 as iio
58
+ except ImportError as e:
59
+ raise ImportError(
60
+ f"Exporting to {out.suffix} requires imageio. Install with: "
61
+ f"pip install 'venture-studio[video]' (or: pip install imageio imageio-ffmpeg)"
62
+ ) from e
63
+ iio.imwrite(str(out), stack.frames, fps=stack.fps)
64
+ return out