Animation export

Scenes, frame rendering and ffmpeg encoding. svg.Scene is exported at the top level as well.

svgwriter.motion.video.Scene([document, name])

An animation: a drawing built once, then changed over time.

svgwriter.motion.video.Scene.attach(element, ...)

Run behavior on element before every frame: behavior(element, seconds, *args, **kwargs).

svgwriter.motion.video.Scene.bake([fps, ...])

A copy of the document whose SMIL plays what the behaviors and update() do.

svgwriter.motion.video.load_scenes(source[, ...])

Collect scenes from a script, a module or an .svg file.

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: SceneMotion

An 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 animate renders each one.

Parameters:
  • document (Document, optional) – A finished drawing to animate as it is, instead of calling build(). Defaults to None.

  • name (str, optional) – The scene’s name, used for output files. Defaults to the class name.

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, … see size); 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_scenes

Collect the scenes of a file or module.

svgwriter.motion.video.render_animation

The encoder underneath save().

Notes

build() receives an empty document of the class’s size rather than returning one, so width and height mean 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 first update(). Keep the elements that update() changes on self. 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)
width: ClassVar[float] = 640.0
height: ClassVar[float] = 360.0
size: ClassVar[str | PageSize | None] = None
fps: ClassVar[float] = 30.0
duration: ClassVar[float | None] = None
renderer: ClassVar[Renderer | str] = 'skia'
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 width by height.

See also

update

Change 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

build

Draw 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:
  • fps (float, optional) – Overrides the class’s fps.

  • duration (float, optional) – Overrides the class’s duration.

  • renderer (callable or str, optional) – Overrides the class’s renderer.

Yields:

Frame – One frame per 1 / fps seconds.

Raises:

ValueError – If no duration is set and the drawing has no SMIL animation.

See also

save

Encode 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.at

The 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:
  • seconds (float, optional) – The moment to draw. Defaults to 0.0.

  • scale (float, optional) – Pixels per user unit. Defaults to 1.0.

  • background (str, optional) – Background color. Defaults to None (transparent).

Returns:

bytes – A PNG file.

See also

at

The 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; .png writes numbered frames). .svg, .svgz, .html and .pptx save bake()’s document instead, without ffmpeg. Defaults to <name>.mp4 in 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 ffmpeg on PATH.

Returns:

pathlib.Path – The written file, or the pattern of the numbered frames.

Raises:

See also

frames

The 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: object

A 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 update callback, for instance backdrop.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 PATH or SVGWRITER_FFMPEG).

Variables:
  • height (width,) – Frame size in pixels.

  • fps (float) – Frames per second.

  • duration (float) – Length in seconds.

Raises:

See also

svgwriter.Document.render_animation

The 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.

array_at(seconds: float) → ndarray[source]

The frame shown at seconds as a uint8 RGBA array (the last frame past the end).

at(seconds: float) → Image[source]

The frame shown at seconds as an <image> at pixel size, placed at the origin.

class Frame(index: int, seconds: float, width: int, height: int, data: bytes, png: bool)[source]

Bases: object

One rendered frame, ready for the encoder.

Parameters:
  • index (int) – Position in the sequence, starting at 0.

  • seconds (float) – Sample time in seconds.

  • width (int) – Width in pixels.

  • height (int) – Height in pixels.

  • data (bytes) – Encoded PNG bytes, or raw RGBA bytes when png is False.

  • png (bool) – Whether data is a PNG file rather than raw pixels.

See also

to_frame

Build 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
index: int
seconds: float
width: int
height: int
data: bytes
png: bool
class RGBAArray(*args, **kwargs)[source]

Bases: Protocol

An array of shape (height, width, 4) and dtype uint8.

NumPy arrays qualify, as does anything with shape and tobytes.

See also

Frame

What 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
property shape: tuple[int, ...]
tobytes() → bytes[source]
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_frames

Uses 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
What the code above draws
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, else ffmpeg on PATH.

Returns:

str – The resolved path.

Raises:

FFmpegNotFoundError – When it cannot be found; nothing has been rendered at that point.

See also

encode

Needs 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:
  • fps (float) – Frames per second. Must be positive.

  • duration (float) – Length in seconds. Must be positive.

Returns:

list of float – One time per frame; at least one.

Raises:

ValueError – If fps or duration is not positive.

See also

iter_frames

Renders 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/fps seconds 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_animation

Encode 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)]
What the code above draws
load_scenes(source: str | Path, names: Sequence[str] = ()) → list[Scene][source]

Collect scenes from a script, a module or an .svg file.

source is a path to a Python file, an importable module name, either one followed by :Name, or an .svg file. Without names, every Scene subclass 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 a Document.

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

Scene

What 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 .png path writes numbered frames beside it instead: intro.png becomes intro_0000.png, intro_0001.png and 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 ffmpeg found on PATH.

Returns:

pathlib.Path – The written file, or the %04d pattern of the numbered PNG frames.

Raises:

See also

iter_frames

The 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
What the code above draws
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

renderers

Register 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'
What the code above draws
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