惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
IT之家
IT之家
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
The GitHub Blog
The GitHub Blog
宝玉的分享
宝玉的分享
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Announcements
Recent Announcements
Engineering at Meta
Engineering at Meta
MyScale Blog
MyScale Blog
博客园 - 【当耐特】
I
Intezer
Recorded Future
Recorded Future
C
Cisco Blogs
Know Your Adversary
Know Your Adversary
T
Threat Research - Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V2EX - 技术
V2EX - 技术
L
Lohrmann on Cybersecurity
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tenable Blog
U
Unit 42
Google Online Security Blog
Google Online Security Blog
Attack and Defense Labs
Attack and Defense Labs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
SecWiki News
SecWiki News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
GRAHAM CLULEY
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美
博客园_首页
N
News | PayPal Newsroom
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
Project Zero
Project Zero
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
Schneier on Security
Schneier on Security
V
Vulnerabilities – Threatpost

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I built a YouTube slide renderer in Python — eight kinds, no browser
MORINAGA · 2026-06-26 · via DEV Community

The two-host YouTube pipeline I described last week turns a JSON spec into an MP4 by rendering still images for each dialogue segment, running TTS, and using ffmpeg to concat the clips. The part that deserved more than a paragraph was the still-image renderer. Every frame is produced by slides.py, a 480-line Python module using Pillow. No browser, no Puppeteer, no headless Chromium, no screenshot API.

Here's how it works, what decisions I made along the way, and what I'd change.

Why render slides in Python at all

Three constraints made a purpose-built renderer the right call:

CI-only execution. Every video renders inside a GitHub Actions job triggered by a commit. Tools requiring a GUI, a running browser, or a persistent daemon don't fit. The single CI pipeline has to produce a deterministic PNG from data without any human in the loop.

Brand consistency at scale. The pipeline is automated — once a script goes in, the video comes out. Every frame needs the same background colour, font, header and footer chrome, and layout margins. Presentation tools drift when you're generating output programmatically rather than authoring by hand.

Zero ongoing cost. I'm running three directory sites for about $25/month. Every SaaS slide or video tool has a seat fee; Pillow doesn't.

The output: 1920×1080 PNG frames, deterministic from a JSON spec, rendering in under a second per frame on a standard GitHub Actions Ubuntu runner. The module uses Pillow (PIL Fork) throughout — specifically ImageDraw for vector primitives and ImageFont.truetype() for text.

The dispatch table design

The renderer supports eight slide kinds. Each maps to a Python function that takes a spec dict and returns a PIL.Image:

_RENDERERS = {
    "title":   slide_title,
    "bullets": slide_bullets,
    "table":   slide_table,
    "tool":    slide_tool,
    "outro":   slide_outro,
    "diagram": slide_diagram,
    "chart":   slide_chart,
    "image":   slide_image,
}

def render_one(spec: dict) -> Image.Image:
    fn = _RENDERERS.get(spec.get("kind", "bullets"))
    if fn is None:
        raise ValueError(f"unknown slide kind: {spec.get('kind')}")
    return fn(spec)

render_one() is the single entry point used by build_longform.py. Adding a new kind means one function and one dict entry — no conditionals to update, no subclasses. I tried a class hierarchy first (subclasses of a Slide base), but the render functions don't share mutable state. They take a dict and return an image. A dispatch table is the right level of abstraction.

Brand chrome: the shared foundation

Every slide starts by calling _chrome(img, draw, page=""), which draws four things before the content renderer touches the canvas:

  • A 10px accent-blue bar across the top edge
  • The brand logo mark (lazy-loaded PNG) and wordmark in the top-left
  • A hairline at H - 78
  • Site URLs in the footer and an optional page indicator at bottom-right
def _chrome(img, draw, page=""):
    draw.rectangle([0, 0, W, 10], fill=ACCENT)
    x = MARGIN
    logo = _brand_logo()
    if logo is not None:
        lg = logo.copy()
        lg.thumbnail((58, 58))
        img.paste(lg, (x, 36), lg)
        x += lg.width + 16
    draw.text((x, 42), BRAND, font=font(40, "bold"), fill=INK)
    # hairline + footer text below

The logo load is guarded by a module-level _LOGO_LOADED flag so the file check runs once per process. If the logo doesn't exist, chrome renders without it. This matters in CI where brand assets might not be present yet — the pipeline degrades to wordmark-only rather than crashing.

Font resolution is the most fragile piece. Pillow's ImageFont.truetype() requires a full path; it doesn't search system font directories. The fix is a candidate list per weight:

_FONT_CANDIDATES = {
    "bold": [
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf",
        "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
        "/Library/Fonts/Arial Bold.ttf",
    ],
    "regular": [...],
}

The Ubuntu runner (GitHub Actions standard image) has DejaVu at the first path. macOS has it at the third. If neither exists, the script exits with a clear error rather than silently using Pillow's built-in bitmap font, which looks terrible at 96px.

The eight slide kinds

title: Full-screen centred headline with optional subtitle in accent green. Text wrap is manual — draw.textlength() measures each candidate line until it fits within W - 2 * MARGIN, then breaks. Pillow has no built-in text wrapping.

bullets: Heading at top, 120px accent underline rule, bullet list below. Each bullet draws a filled 20px circle rather than a Unicode bullet character — glyphs missing from the font would silently disappear.

table: The most complex renderer. The first column gets 30% of the table width; the remaining columns split the rest equally. Header row renders on a dark panel background with accent-coloured column labels. Body rows alternate between two background shades. Values in the second column that start with a digit get highlighted in accent green — useful for GitHub star counts or benchmark numbers. Cell values that overflow their column width get truncated with an ellipsis.

tool: Single-tool highlight card. Name in 84px bold, optional logo pasted top-right via img.paste() with alpha mask, then "chip" badges for stars and license using draw.rounded_rectangle() with coloured outlines. Followed by a free-form editorial take paragraph.

outro: CTA slide. The URL sits inside an accent-coloured pill. This slide stays up during the subscribe callout at the end of every video.

diagram: Delegates to visuals.render_mermaid(), then pastes the output PNG into the branded scaffold via _paste_visual(). The Mermaid definition lives inline in the JSON spec.

chart: Delegates to visuals.render_chart(), which uses matplotlib.use("Agg") — the headless backend that doesn't need a display server.

image: Fetches a CC0 photo from the Openverse API, pastes it in the content area, and renders an attribution caption at the bottom in 24px muted text. The caption always appears even when the license is CC0 and attribution is legally unnecessary — it's a safeguard against Openverse's license data being slightly wrong.

The thumbnail renderer

YouTube thumbnails are separate from video frames: 1280×720, high-contrast, built for click-through on a small tile. render_thumbnail() is a distinct function in the same module:

def render_thumbnail(out_png, lines, sub="", host_png=None, accent_idx=None):
    TW, TH = 1280, 720
    img = Image.new("RGB", (TW, TH), BG)
    d = ImageDraw.Draw(img)
    d.rectangle([0, 0, TW, 12], fill=ACCENT)
    if host_png and os.path.isfile(host_png):
        h = Image.open(host_png).convert("RGBA")
        ratio = (TH + 110) / h.height
        h = h.resize((int(h.width * ratio), int(h.height * ratio)), Image.LANCZOS)
        img.paste(h, (TW - h.width + 30, TH - h.height + 50), h)
    n = max(1, len(lines))
    hsize = 150 if n <= 2 else 104
    ...

The host face is scaled to slightly taller than the frame height and anchored bottom-right, bleeding off the bottom edge — the same composition seen on most high-CTR tech thumbnails. Headline text lives on the left in 1-3 short lines. The accent_idx parameter highlights one line in accent green; when Claude Haiku generates the script, it outputs an integer index rather than repeating the text.

I previously used ffmpeg's overlay filter for thumbnail composition; switching to Pillow for longform thumbnails made exact positioning predictable without writing ffmpeg filter graph syntax.

Unlike OG images for articles — which use Playwright because they need real HTML rendering — thumbnails are simple enough that direct PIL drawing is faster and less brittle.

Headless Mermaid and matplotlib

The diagram and chart kinds delegate to visuals.py, which handles the two harder rendering cases.

Mermaid via mmdc: writes a temp .mmd file, builds a brand-matched theme config JSON, and calls the mmdc binary. Resolution order: node_modules/.bin/mmdc → PATH → npx @mermaid-js/mermaid-cli. In GitHub Actions, mmdc often runs as root, so the Puppeteer --no-sandbox flag is required. That gets passed via a puppeteer config JSON written to temp rather than a command-line arg (mmdc doesn't forward arbitrary CLI flags to Puppeteer directly).

matplotlib bars: matplotlib.use("Agg") lets you render charts without a display server. The chart uses the brand palette: navy background, accent-blue bars, accent-green for the top-highlighted entry. Value labels print inline to the right of each bar rather than using axis ticks, which gives better control over number formatting.

Both renderers write to a tempfile.mkstemp() file. _paste_visual() scales that file to fit the content area — between the heading and the chrome footer — and composites it onto the slide background.

What worked, and what I'd change

What worked: the dispatch table made it easy to add diagram, chart, and image after the first five kinds were stable. Each addition was isolated. No layout regressions across 40+ videos.

Font handling is fragile. The candidate-path list works on every runner I've tested. It would silently break if Ubuntu changed its DejaVu install path. The correct fix is committing the fonts as repo assets and referencing them by path relative to the script. This would eliminate the OS-path dependency entirely.

_paste_visual() mishandles portrait diagrams. Mermaid flowcharts that render tall and narrow get letterboxed with wide empty margins on the sides. The function scales to fit the content area height without considering whether the width constraint is tighter. A smarter version would compute min(box_w / vis.width, box_h / vis.height) rather than using PIL's thumbnail().

No CJK support. The word-wrap logic assumes space-delimited text. Japanese or Chinese titles would require Cairo/Pango or pre-rendering text as SVG. Not a current problem; a real architectural limit.

Whether more elaborate slide transitions (Ken Burns zoom, cross-fades) would improve watch time is something the analytics feedback loop will tell me eventually. Until then, still images keep ffmpeg concat trivially simple.

FAQ

Why not use python-pptx?

python-pptx authors PPTX files; it doesn't render pixels. Converting PPTX to PNG requires LibreOffice or an equivalent dependency, which adds non-trivial install overhead. Rendering directly to PIL means output is exactly what the code specifies — no intermediate format.

Can this run locally without GitHub Actions?

Yes. python3 slides.py --demo --outdir /tmp/slides renders a full 5-slide sample deck using demo data embedded in the module. The only CI-specific behaviour is the Puppeteer --no-sandbox flag in Mermaid rendering, which mmdc handles via the puppeteer config file.

What happens when Openverse returns no CC0 results for a query?

fetch_image() raises RuntimeError. slide_image() catches it and returns the branded heading-only card — the slide renders cleanly without a photo rather than crashing the entire video render job.

How does the spec generator decide which slide kind to use?

It doesn't decide fully upfront. Claude Haiku is prompted to include "slide" objects only for segments that introduce a new concept or transition. build_longform.py carries forward the last rendered slide for segments without one, so a long dialogue exchange can stay on a single comparison table without repeating the render call each time.


Related: Two-host video pipeline with edge-tts and ffmpegGenerating OG images with Playwright

Part of an ongoing 6-month experiment running three AI-curated directory sites. The technical claims here are real; this article was AI-assisted.