Animation export¶
Scenes, frame rendering and ffmpeg encoding. svg.Scene is exported at the top level as well.
|
An animation: a drawing built once, then changed over time. |
|
Run behavior on element before every frame: |
|
A copy of the document whose SMIL plays what the behaviors and |
|
Collect scenes from a script, a module or an |
Turning documents into video and GIF files through ffmpeg.
svgwriter does not rasterize by itself. A renderer is any callable
renderer(document, seconds) returning PNG bytes or an
(height, width, 4) uint8 RGBA array; frames are piped to ffmpeg.
The "skia" renderer is built in. A Scene subclass bundles a
drawing, its update and its settings, so one file can hold several
animations.
Example
>>> import svgwriter as svg
>>> doc = svg.Document(64, 64)
>>> dot = doc.circle(32, 32, 4, fill="tomato")
>>> def grow(document, t):
... dot.r = 4 + 20 * t
>>> doc.render_animation("grow.gif", fps=12, duration=1, renderer="skia", update=grow)
- class Scene(document: Document | None = None, *, name: str | None = None)[source]¶
Bases:
SceneMotionAn animation: a drawing built once, then changed over time.
Subclass it, set the class attributes and override
build()and, for procedural motion,update();attach()adds reusable behaviors. SMIL animations in the drawing play as well. Saving as SVG or PowerPoint bakes the Python motion into SMIL (bake()). One file can hold several scenes;svgwriter animaterenders each one.- Parameters:
- Variables:
height (width,) – Size of the document handed to
build(). Default 640 by 360.size (str, PageSize or None) – A named size instead (
"video-1080p",svg.size.instagram_story, … seesize); it sets width and height. Default None.fps (float) – Frames per second. Default 30.0.
duration (float or None) – Seconds to render. Default None, the end of the SMIL animations.
renderer (callable or str) –
renderer(document, seconds), a registered name or"module:function". Default"skia".
See also
svgwriter.motion.video.load_scenesCollect the scenes of a file or module.
svgwriter.motion.video.render_animationThe encoder underneath
save().
Notes
build()receives an empty document of the class’s size rather than returning one, sowidthandheightmean one thing and the method holds only drawing code. It runs when the scene is created, so the elements it stores are there before the firstupdate(). Keep the elements thatupdate()changes onself.update()receives absolute time, so frames can be rendered in any order and a scene can be saved more than once.Examples
>>> import svgwriter as svg >>> class Grow(svg.Scene): ... width, height, fps, duration = 40, 40, 4, 1.0 ... def build(self, doc): ... self.dot = doc.circle(20, 20, 4, fill="tomato") ... def update(self, seconds): ... self.dot.r = 4 + 12 * seconds >>> scene = Grow() >>> [frame.index for frame in scene.frames()] [0, 1, 2, 3] >>> scene.render(0.5)[:4] b'\x89PNG' >>> scene.save("grow.gif") >>> class Story(svg.Scene): ... size = "instagram-story" >>> Story.width, Story.height (1080.0, 1920.0)
- build(doc: Document) None[source]¶
Draw the scene into doc; called once, when the scene is created.
- Parameters:
doc (Document) – An empty document of size
widthbyheight.
See also
updateChange the drawing for each frame.
Examples
>>> import svgwriter as svg >>> class Card(svg.Scene): ... width, height = 80, 40 ... def build(self, doc): ... doc.rect(0, 0, 80, 40, fill="navy") >>> len(Card().document) 1
- update(seconds: float) None[source]¶
Set the drawing to its state at seconds; called before every frame, after the behaviors.
- Parameters:
seconds (float) – Time since the start of the scene.
See also
buildDraw the scene once.
Examples
>>> import svgwriter as svg >>> class Slide(svg.Scene): ... def build(self, doc): ... self.box = doc.rect(0, 0, 10, 10) ... def update(self, seconds): ... self.box.x = 100 * seconds >>> scene = Slide() >>> scene.update(0.5) >>> scene.box.x 50.0
- property document: Document¶
The drawing the scene animates.
- Returns:
Document – The document passed in, or a new one filled by
build().
Examples
>>> import svgwriter as svg >>> svg.Scene().document.root.get("viewBox").width 640.0
- frames(*, fps: float | None = None, duration: float | None = None, renderer: Renderer | str | None = None) Iterator[Frame][source]¶
Render the frames without encoding them.
- Parameters:
- Yields:
Frame – One frame per
1 / fpsseconds.- Raises:
ValueError – If no duration is set and the drawing has no SMIL animation.
See also
saveEncode the frames into a file.
Examples
>>> import svgwriter as svg >>> class Blank(svg.Scene): ... width, height, duration = 8, 6, 1.0 >>> [(f.width, f.height) for f in Blank().frames(fps=2)] [(8, 6), (8, 6)]
- at(seconds: float) Document[source]¶
The scene as it is at seconds: behaviors and
update()run, SMIL sampled.- Parameters:
seconds (float) – The moment, from the start of the scene.
- Returns:
Document – A still copy, like
Document.at; the scene’s own document keeps the Python state of that moment.
See also
svgwriter.Document.atThe SMIL-only moment of a document.
Examples
>>> import svgwriter as svg >>> class Grow(svg.Scene): ... width, height = 10, 10 ... def build(self, doc): ... self.box = doc.rect(0, 0, 1, 1) ... def update(self, seconds): ... self.box.width = 1 + seconds >>> Grow().at(2).root[-1].get("width") 3
- render(seconds: float = 0.0, *, scale: float = 1.0, background: ColorLike | None = None) bytes[source]¶
One frame at seconds as PNG bytes, with SMIL applied.
- Parameters:
- Returns:
bytes – A PNG file.
See also
atThe still copy that is drawn.
Examples
>>> import svgwriter as svg >>> svg.Scene(svg.Document(4, 4)).render(scale=2)[:4] b'\x89PNG'
- save(path: AnyPath | None = None, *, fps: float | None = None, duration: float | None = None, renderer: Renderer | str | None = None, ffmpeg: str | None = None) Path[source]¶
Render the scene and encode it with ffmpeg, or bake it into an animated SVG or PowerPoint deck.
- Parameters:
path (str or path-like, optional) – Output file; the extension picks the format (
.mp4,.gif,.webm,.mov,.apng;.pngwrites numbered frames)..svg,.svgz,.htmland.pptxsavebake()’s document instead, without ffmpeg. Defaults to<name>.mp4in the current folder.fps (float, optional) – Overrides the class’s
fps(the sampling rate when baking).duration (float, optional) – Overrides the class’s
duration.renderer (callable or str, optional) – Overrides the class’s
renderer.ffmpeg (str, optional) – The ffmpeg executable. Defaults to
ffmpegonPATH.
- Returns:
pathlib.Path – The written file, or the pattern of the numbered frames.
- Raises:
FFmpegNotFoundError – Before rendering anything, when ffmpeg is missing.
FFmpegError – When ffmpeg fails.
See also
framesThe frames without encoding.
Examples
>>> import svgwriter as svg >>> class Still(svg.Scene): ... width, height, duration = 8, 6, 1.0 >>> Still().save("still.png", ffmpeg="no-such-ffmpeg") Traceback (most recent call last): ... svgwriter.errors.FFmpegNotFoundError: ...
- class Video(path: AnyPath, *, ffmpeg: str | None = None)[source]¶
Bases:
objectA video file read lazily:
video[i]is frame i as an<image>.Frames are decoded on demand by ffmpeg (seeking for single frames, one stream for iteration), so long videos cost nothing until used. Combine footage with vector graphics in an animation
updatecallback, for instancebackdrop.pixels = video.at(seconds).pixels.- Parameters:
path (str or os.PathLike) – Any file ffmpeg can read (mp4, webm, mov, gif, …).
ffmpeg (str, optional) – The ffmpeg executable. Defaults to None (found on
PATHorSVGWRITER_FFMPEG).
- Variables:
- Raises:
FFmpegNotFoundError – If ffmpeg is not installed.
FFmpegError – If the file has no video stream ffmpeg can read.
See also
svgwriter.Document.render_animationThe other direction, drawings into video.
Examples
>>> from svgwriter.motion.video import Video >>> # clip = Video("clip.mp4"); first = clip[0]; len(clip), clip.fps
- frame(index: int) ndarray[source]¶
Frame index as a
uint8(height, width, 4)RGBA array.- Parameters:
index (int) – Zero-based frame number; negative counts from the end.
- Returns:
numpy.ndarray – The decoded pixels.
- Raises:
IndexError – If there is no such frame.
- class Frame(index: int, seconds: float, width: int, height: int, data: bytes, png: bool)[source]¶
Bases:
objectOne rendered frame, ready for the encoder.
- Parameters:
See also
to_frameBuild a frame from renderer output.
Examples
>>> from svgwriter.motion.video import Frame >>> frame = Frame(0, 0.0, 2, 1, bytes(8), png=False) >>> frame.width * frame.height * 4 == len(frame.data) True
- class RGBAArray(*args, **kwargs)[source]¶
Bases:
ProtocolAn array of shape
(height, width, 4)and dtypeuint8.NumPy arrays qualify, as does anything with
shapeandtobytes.See also
FrameWhat a renderer’s output is wrapped into.
Examples
>>> import numpy as np >>> from svgwriter.motion.video import RGBAArray >>> isinstance(np.zeros((6, 8, 4), dtype="uint8"), RGBAArray) True
- animation_duration(document: Document) float | None[source]¶
End of the last SMIL animation (
begin + dur) in seconds.Only plain clock values count; event or syncbase timings are ignored.
- Parameters:
document (Document) – The drawing to inspect.
- Returns:
float or None – The end time in seconds, or None when no animation qualifies.
See also
iter_framesUses this as the default duration.
Examples
>>> import svgwriter as svg >>> from svgwriter.motion.video import animation_duration >>> doc = svg.Document(10, 10) >>> animation_duration(doc) is None True
- find_ffmpeg(executable: str | None = None) str[source]¶
Full path of the ffmpeg executable.
- Parameters:
executable (str, optional) – A name or path to look up. Defaults to
SVGWRITER_FFMPEG, elseffmpegonPATH.- Returns:
str – The resolved path.
- Raises:
FFmpegNotFoundError – When it cannot be found; nothing has been rendered at that point.
See also
encodeNeeds the resolved executable.
Examples
>>> from svgwriter.errors import FFmpegNotFoundError >>> from svgwriter.motion.video import find_ffmpeg >>> try: ... find_ffmpeg("no-such-ffmpeg") ... except FFmpegNotFoundError: ... print("not found") not found
- frame_times(fps: float, duration: float) list[float][source]¶
Sample times
0, 1/fps, ...covering duration seconds.- Parameters:
- Returns:
list of float – One time per frame; at least one.
- Raises:
ValueError – If fps or duration is not positive.
See also
iter_framesRenders a frame at each of these times.
Examples
>>> from svgwriter.motion.video import frame_times >>> frame_times(4, 1) [0.0, 0.25, 0.5, 0.75]
- iter_frames(document: Document, fps: float = 30.0, duration: float | None = None, renderer: Renderer | str | None = None, *, update: Update | None = None) Iterator[Frame][source]¶
Render one frame per
1/fpsseconds without encoding them.Frames are produced lazily, so the document can be changed by update between them.
- Parameters:
document (Document) – The drawing.
fps (float, optional) – Frames per second. Defaults to 30.0.
duration (float, optional) – Seconds to render. Defaults to the end of the document’s SMIL animations.
renderer (callable, str or None, optional) –
renderer(document, seconds), a registered name such as"skia"or"module:function". Defaults to None, which raises; there is no default renderer.update (callable, optional) –
update(document, seconds)called before each frame. Defaults to None.
- Yields:
Frame – The checked frame for each sample time.
- Raises:
ValueError – If no renderer is given, or no duration is given and the document has no plain-clock SMIL animation.
See also
render_animationEncode the frames into a file.
Examples
>>> import svgwriter as svg >>> from svgwriter.motion.video import iter_frames >>> doc = svg.Document(8, 6) >>> [(f.index, f.width, f.height) for f in iter_frames(doc, fps=2, duration=1, renderer="skia")] [(0, 8, 6), (1, 8, 6)]
- load_scenes(source: str | Path, names: Sequence[str] = ()) list[Scene][source]¶
Collect scenes from a script, a module or an
.svgfile.source is a path to a Python file, an importable module name, either one followed by
:Name, or an.svgfile. Without names, everyScenesubclass the file or module defines is returned, in definition order; classes whose names start with_are skipped, so a shared base class can be private. A name may also refer to a scene instance or aDocument.- Parameters:
source (str or pathlib.Path) –
"scenes.py","scenes.py:Intro","pkg.scenes:Intro"or"drawing.svg".names (sequence of str, optional) – Scenes to pick, in this order. Defaults to all of them.
- Returns:
list of Scene – New instances, ready to save.
- Raises:
SceneError – If nothing matches, or a name is not a scene.
See also
SceneWhat the file defines.
Examples
>>> from svgwriter.motion.video import load_scenes >>> [scene.name for scene in load_scenes("svgwriter.motion.video.scene:Scene")] Traceback (most recent call last): ... svgwriter.errors.SceneError: 'Scene' in svgwriter.motion.video.scene is not a scene
- render_animation(document: Document, path: AnyPath, fps: float = 30.0, duration: float | None = None, renderer: Renderer | str | None = None, *, update: Update | None = None, ffmpeg: str | None = None) Path[source]¶
Render frames and encode them with ffmpeg.
ffmpeg is located first, so a missing executable fails before any frame is rendered. Frames are piped to a single ffmpeg process.
- Parameters:
document (Document) – The drawing.
path (str or path-like) – Output file; the extension picks the encoder (
.mp4,.gif,.webm,.mov,.apng, anything else ffmpeg knows). A.pngpath writes numbered frames beside it instead:intro.pngbecomesintro_0000.png,intro_0001.pngand so on.fps (float, optional) – Frames per second. Defaults to 30.0.
duration (float, optional) – Seconds to render. Defaults to the end of the document’s SMIL animations.
renderer (callable, str, optional) –
renderer(document, seconds)returning PNG bytes or an(height, width, 4)uint8 array; a registered name such as"skia"; or"module:function". Defaults to None, which raises; there is no default renderer.update (callable, optional) –
update(document, seconds)called before each frame, for procedural animation. Defaults to None.ffmpeg (str, optional) – The ffmpeg executable. Defaults to
ffmpegfound onPATH.
- Returns:
pathlib.Path – The written file, or the
%04dpattern of the numbered PNG frames.- Raises:
FFmpegNotFoundError – Before rendering anything, when ffmpeg is missing.
FFmpegError – When ffmpeg fails.
ValueError – If no renderer or duration can be determined.
See also
iter_framesThe frames without encoding.
Examples
>>> import svgwriter as svg >>> from svgwriter.errors import FFmpegNotFoundError >>> from svgwriter.motion.video import render_animation >>> doc = svg.Document(8, 6) >>> try: ... render_animation(doc, "out.gif", duration=1, renderer="skia", ffmpeg="no-such-ffmpeg") ... except FFmpegNotFoundError: ... print("ffmpeg is required") ffmpeg is required
- resolve_renderer(renderer: Renderer | str | None) Renderer[source]¶
Return a renderer from a callable, a registered name or
"module:function".- Parameters:
renderer (callable, str or None) – A renderer, the name of a registered one, or a
"module:function"import path.- Returns:
callable –
renderer(document, seconds)returning PNG bytes or an RGBA array.- Raises:
ValueError – If renderer is None.
UnknownNameError – If renderer is an unregistered name without a colon; the message suggests the closest names.
TypeError – If a
"module:function"path names something that is not callable.
See also
renderersRegister a named renderer.
Examples
>>> from svgwriter.motion.video import resolve_renderer >>> callable(resolve_renderer("skia")) True >>> resolve_renderer("nope") Traceback (most recent call last): ... svgwriter.errors.UnknownNameError: unknown renderer 'nope'; registered: skia
Behaviours¶
Built-in behaviors: Python motion a Scene runs before every frame.
Each one starts from the element’s home and moves it relative to that, about its
anchor, so it never drifts. Attach one by name (element.animate.wiggle()) or typed
(scene.attach(element, wiggle, angle=10)).
Example
>>> import svgwriter as svg
>>> from svgwriter.motion.video.behaviors import wiggle
>>> class Alarm(svg.Scene):
... width, height, duration = 40, 40, 1.0
... def build(self, doc):
... self.bell = self.attach(doc.rect(10, 10, 20, 20), wiggle, angle=15)
>>> scene = Alarm()
>>> scene.update(0.0)
>>> scene.render(0.125)[:4]
b'\x89PNG'
- breathe(element: Transformable, seconds: float, *, amount: float = 0.05, period: float = 2.0) None[source]¶
Grow and shrink by the fraction amount about the anchor, once every period seconds.
- Parameters:
element (Transformable) – The element to scale.
seconds (float) – The scene time.
amount (float, optional) – Largest change of size, as a fraction. Defaults to 0.05.
period (float, optional) – Seconds per full breath. Defaults to 2.
Examples
>>> import svgwriter as svg >>> class Heart(svg.Scene): ... width, height, duration = 40, 40, 2.0 ... def build(self, doc): ... self.heart = doc.circle(20, 20, 10).animate.breathe(amount=0.5).element >>> scene = Heart() >>> breathe(scene.heart, 0.5, amount=0.5) >>> scene.heart.matrix.a 1.5
- hover(element: Transformable, seconds: float, *, height: float = 4.0, period: float = 2.0) None[source]¶
Float up and down by height user units, once every period seconds.
- Parameters:
element (Transformable) – The element to move.
seconds (float) – The scene time.
height (float, optional) – Largest rise above home, in user units. Defaults to 4.
period (float, optional) – Seconds per full rise and fall. Defaults to 2.
Examples
>>> import svgwriter as svg >>> class Balloon(svg.Scene): ... width, height, duration = 40, 40, 2.0 ... def build(self, doc): ... self.balloon = doc.circle(20, 20, 6).animate.hover().element >>> scene = Balloon() >>> hover(scene.balloon, 0.5) >>> scene.balloon.matrix.f -4.0
- wiggle(element: Transformable, seconds: float, *, angle: float = 6.0, period: float = 0.5) None[source]¶
Rock back and forth by up to angle degrees about the anchor, once every period seconds.
- Parameters:
element (Transformable) – The element to move.
seconds (float) – The scene time.
angle (float, optional) – Largest turn either way, in degrees. Defaults to 6.
period (float, optional) – Seconds per full swing. Defaults to 0.5.
Examples
>>> import svgwriter as svg >>> class Bell(svg.Scene): ... width, height, duration = 40, 40, 1.0 ... def build(self, doc): ... self.bell = doc.rect(10, 10, 20, 20).animate.wiggle(angle=10, period=1).element >>> scene = Bell() >>> wiggle(scene.bell, 0.25, angle=10, period=1) >>> round(scene.bell.matrix.decompose()[2], 6) 10.0