侧边栏壁纸
  • 累计撰写 121 篇文章
  • 累计创建 54 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

30-Second Product Promo — Automated Motion-Graphics Workflow (Generic, Replicable)

FlyingEagle
2026-10-10 / 0 评论 / 0 点赞 / 59 阅读 / 14,756 字

30-Second Product Promo — Automated Motion-Graphics Workflow (Generic, Replicable)

Audience: humans + AI agents. After reading, you should be able to reproduce a finished
film of the same spec on a fresh machine, starting from raw assets only.
Fully generic — contains no client names, contacts, financials, or personal information.


0. Delivery Spec

Item Value
Resolution 1920×1080
Frame rate 30 fps
Duration 30.001 s (900 frames)
Encoding H.264 + AAC 44.1 kHz stereo
Loudness -14 LUFS / True Peak ≤ -1.5 dB / LRA target 11
Intermediate outputs out/silent.mp4 (video only), out/music.wav (audio only)

Core principle: audio and video are decoupled. Change audio → re-mix only, never re-render.
Change video → re-render only, never re-mix. This single decision dictates the whole directory layout.


1. Technology Choices

Pure Python + PIL + numpy + scipy + ffmpeg.

Option Verdict
After Effects / Motion Needs GUI + license; agents cannot drive it end-to-end. Rejected.
Remotion / web stack Pulls in node + a browser renderer; far too heavy. Rejected.
Blender / 3D The piece is 2D motion graphics. Overkill. Rejected.
PIL + numpy + ffmpeg Selected: diffable, git-friendly, parallelizable, CPU-only, fully readable and editable by agents.

Dependencies (exact versions as verified in practice):

Pillow        12.3.0      # canvas drawing
numpy         2.4.6       # pixel math
scipy         1.17.1      # ndimage for matting, signal for filters
ffmpeg        5.1+        # encode / AAC / loudnorm

Optional: pedalboard (professional mastering chain), faster-whisper + ctranslate2
(transcribing reference videos), yt-dlp (fetching reference videos).
None of the three is required to produce the finished film.


2. Directory Layout

motion-reel/
  engine.py      base layer: palette, easing, fonts, typography, shape drawing, post
  photo.py       asset layer: matting, grading, compositing, hero-image generation + cache
  scenes.py      scene layer: per-frame drawing for 9 beats
  audio.py       audio layer: music bus + SFX bus + mastering
  render.py      orchestration: parallel segment render → concat → mux → loudness
  sample.py      review tool: cut a sub-clip of a time range for inspection
  fonts/         typefaces (incl. CJK)
  assets/photo/  raw source imagery
  assets/hero/   pre-generated cache (deletable; rebuilt deterministically from seeds)
  image/         original white-background plates
  out/           products (never in version control; large and regenerable)

Dependencies are strictly one-directional:
engine ← photo ← scenes ← render; audio is fully independent.


3. Core Conventions

3.1 Timeline and beats

One global cut table drives the whole structure:

CUTS = [2.0, 6.0, 10.0, 14.0, 18.0, 22.0, 26.0, 28.0]
# → 9 beats: OPEN / IDENTITY / SCALE / PRODUCT / MAKING / RANGE / GLOBAL / STATEMENT / CONTACT

Each beat is a pure function with a uniform signature:

def s_xxx(t, f):   # t = seconds (float), f = frame number (int)
    L = Image.new("RGB", (W, H), BG)   # brand-new canvas, no state
    ...                                 # draw elements
    return L                            # clean frame, WITHOUT post applied

Critical: frame(t, f) only composites the picture and applies transitions. It never calls
post().
Grain, vignette, and chromatic aberration are applied separately by the renderer.
Debugging therefore shows the raw image, undistorted by post — which would otherwise
poison your judgement.

3.2 Palette

ORANGE  = (255, 106, 26)   # primary accent
EMBER   = (255, 148, 60)   # secondary accent
RED     = (255, 60, 60)    # warning / peak
STEEL   = (150, 170, 200)  # metal / structure
SLATE   = (100, 112, 140)  # secondary text
BLUEPRT = (60, 90, 140)    # blueprint blue
CARBON  = (20, 22, 28)     # dark panel
CARBON2 = (30, 33, 42)     # lighter panel
BG      = (9, 10, 14)      # background
INK     = (246, 247, 251)  # primary text
DIM     = (132, 139, 158)  # muted text
FAINT   = (55, 60, 75)     # hairline / outline

3.3 Easing library

Every animation must go through an easing function. Linear motion is banned:

e_out_quad, e_out_cubic, e_out_quart, e_out_expo
e_in_quad, e_in_cubic
ez(t, t0, t1, fn=e_out_cubic)   # normalize [t0,t1] then ease; auto-clamps to 0/1 outside
seg(t, t0, t1)                  # linear ramp (only for alpha fades that need no easing)

Rule: every visual property (position, scale, opacity, colour, corner radius) must be a pure
function of t.
That is what guarantees arbitrary frames can be rendered independently and
that parallel segments have no side effects.

3.4 Fonts

FONT_MAP = {
    "anton":   "fonts/Anton-Regular.ttf",          # hero titles, ultra-heavy condensed
    "bebas":   "fonts/BebasNeue-Regular.ttf",      # mid-level titles
    "popsp":   "fonts/Poppins-SemiBold.ttf",       # body emphasis
    "mono":    "fonts/SpaceMono-Regular.ttf",      # ALL-CAPS wide-tracked labels
    "cjkb":    ("/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc", 2),  # CJK bold
    "cjk":     ("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
}

The CJK face is a hardcoded system path plus a TTC index — this is the single most commonly
missed item during migration.
Either ship the two .ttc files alongside the project, or
repoint them to a local fonts/ directory.

3.5 Typography primitives

Expose exactly three primitives; every scene is assembled from them:

font(name, size)              # font loading with cache
text_w(text, name, size, track)  # precise width measurement including tracking
tgroup(layer, text, name, size, color, cx, cy, tracking, alpha, char_fn)
                              # character-level typesetting: tracking, cx/cy anchor,
                              # global alpha, per-character char_fn

char_fn = c_fade(t, offset, step, dur) produces the staggered per-character entrance
that is the single largest contributor to the piece’s perceived polish.


4. Per-Layer Implementation Notes

4.1 Asset layer: white-background keying (zero AI weights)

Source imagery is product photography on a white background. Matting is pure algorithm —
no rembg, no ONNX, no model weights of any kind:

_key(rgb)      # white-tolerance threshold → alpha channel (with feathering)
_is_white(px)  # does this pixel belong to the white background
grade_rgba(img, brightness, contrast, sat, tint)  # unify grading across mixed sources
build_hero()   # build and cache the hero image under assets/hero/ (keyed by input hash)

The cache directory is safe to delete. It is rebuilt deterministically from seeds + an
input hash, so it never needs to be version-controlled or migrated.

4.2 Scene layer: the scene template

Every scene is a variation of one template:

[ALL-CAPS mono label + orange rule]   ← top anchor
[oversized anton title]               ← visual anchor
[mono subtitle / caption]             ← explanation
[grid / cards / charts]               ← content area, staggered entrance
[bottom hairline + small type]        ← close

Repeated content elements (cards, cells, rows, arcs) share one stagger pattern,
t0 = base + i * step:

for i in range(8):
    t0 = 18.55 + (i % 4) * 0.10 + (i // 4) * 0.16   # 2D-grid stagger
    kk = ez(t, t0, t0 + 0.5, E.e_out_expo)

All content must come from the source documents. Never invent data. Render specifications
as spec cards / chips; convert every monetary figure to the currency’s primary unit before
displaying it — magnitude abbreviations are an extremely common source of errors.

4.3 Audio layer: three-tier structure

audio.py has three buses:

music bus : BPM=90 / 4/4, drums + bass + pad + lead
SFX bus   : transition-level + graphic-level (two tiers, see §5.5)
mastering : HPF → air shelf → presence → glue comp → limiter

Everything is seed-driven; running audio.py regenerates the output. Fully deterministic.

The mastering chain has two branches: with pedalboard installed it uses the professional
chain, without it a numpy fallback. The two branches sound different. Once you have settled
on one, every machine in the pipeline must match — otherwise re-mixing elsewhere yields a
different timbre.

Final mixdown:

place(MUSIC, 1.0, 0.0)
place(SFX,   0.85, 0.0)   # SFX must sit under the music, or it turns to mud

4.4 Render layer: parallel segments + decoupling

render.py runs four steps:

# 1. split the frame range into N segments, render in parallel (multiprocessing)
# 2. concat into out/silent.mp4  (video only)
# 3. ffmpeg mux out/music.wav + silent.mp4 → finished film
# 4. apply two-pass loudnorm separately (see §5.6)

An audio change only needs steps 3–4: reuse the existing silent.mp4 with the new
music.wav, -c:v copy, and you are done in seconds.


5. Six Reusable Techniques

5.1 First-frame visibility

The most common accident: the opening frame is black. Cause — the fade-in function starts
at 0.

Fix: give every fade-in a floor, so frame 0 already carries 65–70% of the information:

alpha = 0.15 * (0.68 + 0.32 * ez(t, 0.0, 1.5))        # backdrop
k     = 0.42 + 0.58 * ez(t, 0.05, 0.55, e_out_expo)    # rule
alpha = (0.95 + 0.05 * seg(t, 0.0, 0.34))              # main title

Acceptance: scan f=0…60 and allow no dark frames (use a numeric luminance probe, §6.1).

5.2 Per-character entrance

Do not fade a title in as a whole — stagger it character by character:

char_fn = c_fade(t, offset=-0.80, step=0.014, dur=0.26)

offset sets when character 0 starts; step sets the per-character gap. When a title gets
longer, offset must become correspondingly more negative
(38 characters want -0.80;
otherwise the tail characters have not finished entering before the cut).

5.3 Anchor alignment compensation

Changing copy length moves alignment anchors with it. When a left-aligned element uses an
anchor written as x + constant, shortening the string shifts everything left.

Fix: after changing copy, re-measure and put the constant back:

# before: x + 440   (long copy)
# after : x + 357   (short copy; left edge pulled back from 256 to 173, aligned with the element above)

This is the single easiest thing to miss in a pure copy change. A geometric probe is mandatory
afterwards.

5.4 Transition layer

All cuts are handled by one transition layer; scene functions are unaware of cut points:

def _transition_fx(t, f, img):
    # for each CUTS[i]: a whoosh 0.42s before the cut, an impact on the cut
    # some cuts additionally get a crash (long tail); some get riser + rev_cymbal (break the pattern)
    # the last few frames before a cut get speed streaks / a flash to hide the hard cut

Breaking the pattern matters. If every cut hits equally hard, the piece becomes a
metronome. At the narrative turn — a quiet beat late in the piece — deliberately drop to 0.4×
energy, then snap back to 2–4× on the next hit. That is what gives the rhythm breath.

5.5 Two-tier SFX layering

This is the key to “every graphic has its own sound”. Two tiers, gains strictly graded:

Tier Trigger Count Gain
Transition the CUTS points few 0.5–1.0
Graphic every element entrance many (61 in this piece) 0.18–0.42

Two primitives are enough for the graphic tier:

def blip(t0, f=2400, g=0.28, dur=0.09, seed=...): add(SFX, t0, tick(dur, f, g, seed))
def sweep(t0, dur=0.35, g=0.30, seed=..., rise=True): add(SFX, t0, whoosh(dur, g, rise, seed))
Element type Sound
Title / large card entrance sweep + blip stacked
Single row / cell stagger blip, pitch rising with index (1400 + i*380 Hz)
Image / hero swap sweep (0.3–0.85 s)
Number count-up a run of blip, pitch ascending
Arcs / light sweeps long sweep, gain pinned to 0.18

Uniqueness: every cue gets its own seed. Otherwise all ticks sound identical and the layer
degrades into noise.

Order: add every cue first, then run one reverb pass over the whole bus
(reverb(SFX, 1.5, wet=0.30)). Never reverb individual cues.

5.6 Two-pass loudnorm

# pass 1: measure
ffmpeg -i in.mp4 -vn -af loudnorm=I=-14:TP=-1.5:LRA=11:print_format=json -f null -
# record input_i / input_tp / input_lra / input_thresh / target_offset

# pass 2: apply (-c:v copy — video untouched)
ffmpeg -i in.mp4 -af "loudnorm=I=-14:TP=-1.5:LRA=11:measured_I=...:measured_TP=...:measured_LRA=...:measured_thresh=...:offset=...:linear=true" \
  -c:v copy -c:a aac -b:a 192k -ar 44100 -movflags +faststart out.mp4

Acceptance: re-measure the result; input_i ≈ -14.0. A single-pass loudnorm drifts by more
than 0.5 dB on short-form material.


6. Pitfall Log (ordered by cost)

6.1 ⚠️ The image-reading tool returns stale images

In some environments, asking a read-image tool for a rendered frame frequently returns
the previous image you looked at, regardless of the path requested.

Consequence: acting on it corrupts the project.

Protocol:

  1. rm -f old temp PNGs before each read; use a timestamped unique filename
  2. Read each new filename exactly once; never re-read
  3. All critical judgements go through numeric probes, never eyeballing:
# luminance probe : whole-frame mean brightness + bright-pixel count
# ink probe       : pixel count and bbox for a specific colour
# geometry probe  : draw the element onto its own transparent canvas and read the mask bbox

Rule of thumb: for geometry and alignment, an independent-canvas probe beats looking at a
render every time.

6.2 shape() paste-mask alpha is squared

When shape() pastes an alpha layer onto a transparent layer, the effective alpha becomes
a²/255 (whites and blacks go wrong).

Fix: compensate locally at the call site. Do not change the global helper — a global
change re-tunes every already-approved frame at once.

6.3 frame() does not call post()

Calling scenes.frame(t, f) during debugging yields the frame without post-processing.
To see the delivered look you must call it explicitly:

im = scenes.frame(t, f)
im = engine.post(np.asarray(im, np.uint8).copy(), fx, f)

6.4 import audio rewrites its own outputs

audio.py is script-structured; importing it runs the full generation and overwrites
out/music.wav and out/buses.npz.

Consequence: one careless import costs a 2-minute audio rebuild.

Fix: either guard it with if __name__ == "__main__":, or accept it (seeds make the result
identical) — but never import it inside a batch loop.

6.5 Optional-dependency timbre fork

With pedalboard installed or not, the mastering chain is completely different, so re-mixing
on another machine changes the timbre. Migration must explicitly record whether it is
installed
, and the final film’s loudness figures (I / TP / LRA) should serve as the
regression baseline.

6.6 CJK font hardcoded absolute path

/usr/share/fonts/opentype/*.ttc is a system path. It breaks on every machine swap.

Fix: ship the two .ttc files with the project, or repoint to a local path. Note that a
TTC is a multi-font container — you must also carry the index (which font inside it).

6.7 Per-character entrance offset for longer copy

After a title grew from 30 to 38 characters, the original -0.62 start meant the tail
characters had not finished entering before the cut. Recompute offset every time copy
length changes.


7. Verification Protocol (run after every change)

In order:

□ Numeric probe : first-frame / dark-frame scan (f=0..60, no dark frames allowed)
□ Geometry probe: left edge x-coordinate of edited copy matches its alignment reference
□ Output spec   : ffprobe confirms nb_frames / duration / codec / resolution
□ Video hash    : when only audio changed, the video-stream MD5 must equal silent.mp4's
□ Loudness      : re-measure the result; input_i ≈ -14.0, TP ≤ -1.5
□ Envelope corr : finished audio vs SFX bus, correlation ≈ 0.50, lag ≈ 0.5 ms
□ Cut jumps     : pre/post energy ratio at every CUTS point in a sane range;
                  off-pattern points confirmed separately

Video-stream hash (must be bit-identical after -c copy):

ffmpeg -i file.mp4 -map 0:v -c copy -f md5 -

8. From-Zero Reproduction Steps

# 1. environment
pip install Pillow==12.3.0 numpy==2.4.6 scipy==1.17.1
apt install ffmpeg fonts-noto-cjk        # or drop the .ttc files in manually

# 2. place assets
#    assets/photo/  white-background product photography
#    image/         original full-size plates
#    fonts/         9 latin typefaces

# 3. write the scenes (engine → photo → scenes)
#    review with sample.py:
python3 sample.py 0 2 out/qa_open.mp4

# 4. render
python3 render.py          # produces out/silent.mp4 + out/music.wav

# 5. audio (only if you need to adjust it)
python3 audio.py           # regenerates music.wav

# 6. re-mix (no re-render)
ffmpeg -y -i out/silent.mp4 -i out/music.wav \
  -c:a aac -b:a 192k -shortest -c:v copy -movflags +faststart out/mux_tmp.mp4

# 7. two-pass loudness (§5.6) → finished film

9. Packaging and Migration

Measured: the irreducible payload of a 30-second workflow is ≈ 25 MB.

Category Contents Required
Code 6 .py files ✅
Fonts fonts/*.ttf (9 files, 1.2 MB) ✅
CJK NotoSansCJK-{Regular,Bold}.ttc (20 MB each) ✅ most often missed
Assets assets/photo/ + image/ ✅
Hero cache assets/hero/ ❌ rebuildable from seeds
Outputs out/ ❌ large and regenerable
Virtualenv .venv/ ❌
Models — see below

About “models”: rendering uses zero models.

  • Matting is pure white-background keying; no ONNX / rembg weights
  • If you enable reference-video transcription, an ASR model (~145 MB) is pulled on first run
    into ~/.cache/huggingface. That cache normally lives in the user’s home directory, not
    inside the working-directory volume
    — it is safe to omit, and it re-downloads on demand
  • The LLM that writes the code is a development tool, not a rendering dependency

Minimal package:

tar czf motion-reel.tgz --exclude=out --exclude=__pycache__ --exclude=.venv \
  motion-reel/*.py motion-reel/fonts motion-reel/assets motion-reel/image

After migrating, run the full §7 regression first — confirm loudness figures and frame count
match — before delivering anything.


10. In One Sentence

Make the picture pure-functional, per-frame code so it can be parallelised and diffed;
make the sound an independent, re-mixable bus; make verification entirely numeric.
Once all three are decoupled, the cost of any single change drops to seconds — and that is
what makes the whole workflow drivable end-to-end by an agent.

0

评论区