Communitygithub.com

concept-map-reel

Make Manim (3Blue1Brown-style) study videos that explain concepts from any technical course as a zoomable concept map, plus printable mind maps and a series overview map; plans the videos with the user first, then builds several in parallel with subagents.

What is concept-map-reel?

concept-map-reel is a Claude Code agent skill that make Manim (3Blue1Brown-style) study videos that explain concepts from any technical course as a zoomable concept map, plus printable mind maps and a series overview map; plans the videos with the user first, then builds several in parallel with subagents.

Works with✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/pablochivite/visual-study-skill/tree/HEAD/concept-map-reel

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

Concept-map study videos (Manim)

The goal is to help the user understand concepts they did not understand before, and to see the bigger picture: how each concept connects to the rest of the course. It works for any technical subject (machine learning, data science, statistics, engineering, computer science and so on).

This is not a fixed format to fill in. For each video, design the structure, the components and the visuals that best explain that concept to this user, drawing on their materials (slides, notes, transcripts, syllabus) and on what you know about them. What stays the same in every video is the house style:

  • the 3Blue1Brown / Manim look;
  • the zoom storytelling: zoom into each idea ("stop"), zoom out halfway to show where you are, and finally zoom all the way out to the course map with a You are here marker;
  • one course map and one set of colour roles per course, shared by every video of that course;
  • the deliverables below.

What every run delivers

  1. Video: landscape 1920x1080, 30 fps, black background. The content sets the length, usually 60-90 s. File: <topic>_map_<lang>.mp4.
  2. Printable mind map of the final zoomed-out view: light theme (white background, ink-friendly), vector PDF (A4 landscape) plus PNG at 300 dpi: <topic>_map_print.pdf / .png.
  3. Voiceover script in the reply, one paragraph per segment, timed to the video.
  4. Series overview map, only when the agreed plan has two or more videos: one printable mind map that puts every video's concepts together on the course map. Light theme, vector PDF plus PNG at 300 dpi: <series>_overview_print.pdf / .png. See section 6b.

Language of the video text and script: the one the user asks for; otherwise the language of their materials; otherwise English.

Send all the files with SendUserFile. If the device bridge is connected, also commit them to the user's folder for the course's videos, in a <topic>/ subfolder (ask for that folder the first time if you don't know it).

Never use AI video models for diagrams, text or formulas: they deform them and cost far more credits than free plans have. Everything visual is drawn in Manim.

0. Agree the plan with the user, then decide who builds each video

The user is often learning the topic from scratch and doesn't know what they don't know. They may ask for separate videos on concepts that only make sense together, ask for a concept that is too big for one video, miss a prerequisite, or phrase the list in a confusing order. Treat their list as a starting point, not as a spec. Nothing gets rendered until the plan is agreed.

Step A. Gather the starting point.

  • The materials: slides, notes, transcripts, syllabus, or a project with them. If there are none, work from your own knowledge and say so.
  • The course map: if the user's course folder already has a _course_map.md from earlier videos, load it and reuse it (section 1).
  • The concepts: if the user named some, start from those. If they did not, ask which concepts they want. Only if they ask you to choose, pick them yourself from the materials.

Step B. Do enough research to see how the concepts relate (section 1): which ones depend on which, which are parts of a bigger idea, how the materials present each one, and what each video would need as stops.

Step C. Propose a plan. Show it as a compact table, one row per video: title, the concepts it covers, its visual structure and why (section 2; say how the materials present it when that is the reason), its stops, and where it sits on the course map. If there is no course map yet, also show its outline so the user can correct it. Under the table, list each change you suggest with a one-line reason. Typical suggestions:

  • Merge concepts that only make sense together into one video (for example, two steps of the same process).
  • Split a concept that is too big for one video into two.
  • Fold a concept that is really a detail of another into that video, as one of its stops or as a foundation.
  • Add a missing prerequisite or bridging concept, so the series makes sense on its own.
  • Reorder the videos into a learning sequence, and say which one to watch first.
  • Flag confusion: two names for the same thing, a concept from another part of the course, or a term the class uses differently from the slides.
  • Mind maps: one per video, and whenever the plan has two or more videos, the series overview map as well (section 6b). The overview is always included, not a suggestion; just show it as the last row of the table.

Give your recommendation, but the user decides. End with at most 2-3 focused questions.

Step D. Iterate until the user agrees. Adjust the table to their answers and show it again only if it changed. If the user says to just do what they asked, follow their list as given. If nobody is there to answer (an unattended run), build the user's list as given and put your suggestions in the reply. Once the plan is agreed, save the course map (section 1).

Who builds what (count the videos in the agreed plan, not the concepts the user first asked for):

One video: do sections 1-6 yourself.

Two or more videos: you are the coordinator, and every video is built by its own subagent (video + printable map + voiceover script). Always, whatever the number of videos and however short they are.

  1. Shared groundwork, before launching anything.
    • Do the research in section 1 for every video yourself (subagents may not have project tools such as project_search), and keep the material each video needs: slide content, notes and transcript excerpts, in the materials' own terminology and notation.
    • Make sure the course map covers every video in the plan, and write it to reels/_shared/course_map.md in the working directory.
    • Check the environment (section 3) once.
    • Create one output folder per video: reels/<topic>/.
  2. A self-contained brief per subagent (a fresh general-purpose agent, not a fork). Each brief contains:
    • the path to this SKILL.md (the skill's base directory) and the instruction to follow sections 2, 4, 5 and 6 from it;
    • its row of the agreed plan (title, concepts, visual structure, stops), plus the material for those concepts;
    • the path to reels/_shared/course_map.md and this video's place on it;
    • the video's language, its output folder and the file names to use;
    • what to report back: the paths of the video, PDF and PNG, the voiceover script, the contact-sheet path, and anything it could not fix;
    • that it must not send files to the user or commit to the device, since the coordinator does that.
  3. Launch in batches of 2-3 at a time, in the background. Wait until every agent in a batch has reported before launching the next batch (Manim renders compete for the CPU).
  4. Review and deliver. For each video, look at its contact sheet and its printable PNG yourself. If something is off, send it back to the same agent with the fix needed, or fix it yourself. Then build the series overview map yourself (section 6b), send all the files with SendUserFile, commit them to each topic's folder if the device bridge is connected, and give every voiceover script in the reply under one heading per video.

If this session has no tool for subagents, build the videos one after another yourself, still with the shared groundwork from step 1.

1. Understand the concept and place it on the course map

  • The user's materials come first. Search and read them for the concept: definitions, the examples the teacher used, the notation, the diagrams, and the related topics. If they are in a project, use project_search. Keep their terminology and notation, so that the video matches what the user will be examined on.
  • The course map is a map of the course's topics and how they relate (what contains what, what comes before what, what builds on what). Build it from the syllabus, the slides' structure and the transcripts; it is not tied to any one subject.
    • One map per course, shared by every video of that course. Only the highlighted region and the "You are here" marker move from video to video.
    • Save it as _course_map.md in the user's course folder (through the device bridge when connected), and load it at the start of later runs instead of building a new one. When a new video needs topics the map doesn't have yet, extend it and save the update. If the bridge isn't connected, send the file to the user with the rest and ask them to keep it in that folder.
    • Keep the file short: the topics as an outline (with their parent and their links to other topics), the course's colour roles (section 2), and the videos made so far with their place on the map.
  • Place the concept on the map: the path from the course's root topic down to it (drawn in gold), its siblings, and, if it adds something, what builds on it or where it is used. That last part is specific to each concept; leave it out when it doesn't help.

2. Design the video (write the voiceover script first)

Structure follows the content. Before drawing anything, work out the shape of the concept: what its parts are and how they relate (a sequence, a loop, a hierarchy, a comparison, a cause and its effects, data being transformed step by step, a trade-off, a layered system, or whatever the concept really is). Lay out the stops to show that shape. When the materials draw or order the concept in a particular way, start from that, since it is the version the user is studying. There is no catalogue of layouts: design the one this concept needs, and say in the plan which one it is and why.

Stops. Each stop explains one idea; use as many as the concept needs (typically 3-6). Each stop has:

  • one visual metaphor or analogy that maps the mechanism, not just the name, ideally from physical, everyday experience (gears passing on a rotation for the chain rule, a sieve letting only some things through for filtering, a queue at a counter for scheduling, a thermostat correcting itself for a feedback loop);
  • the key formula, code, table or diagram, when there is one;
  • a 1-2 line caption.

House beats (their content and layout are free; only the sequence is fixed):

  1. Hook (about 4 s): a question the concept answers, plus the title in gold and "a map in N stops".
  2. Stops, about 7-9 s each.
  3. Mid zoom-out (about 5 s, after roughly half the stops): the local structure, with the visited stops solid and the unvisited ones as dashed ghosts with a "?". The caption states what is known so far and asks the question that motivates the next stop.
  4. Remaining stops. Optionally dip into a foundation: a prerequisite (maths or an earlier idea) placed next to the stop that relies on it and joined to it by an arrow.
  5. Final zoom-out 1 (about 4 s): the whole local structure, with a short animation that shows how it works as a whole (a flash running along the arrows, data moving through, the loop turning and so on).
  6. Final zoom-out 2 (about 7 s): the course map fades in around it, the gold path is drawn from the root to the concept, "You are here" points at the key stop, and, if it helps, what builds on the concept appears. Hold for 3 s at the end.

Timing: about 2.5 spoken words per second, so the script sets the length.

Colour roles. Colours mean roles, not decoration. Decide them once per course, write them in _course_map.md, and keep them in every video of that course: for example one colour for inputs or data, one for measuring or intermediate values, one for errors or costs, one for improvement or results, and one for alternatives. Gold is always the big-picture path and titles, and grey is sibling topics not covered in this video. The backpropagation example uses blue = data and forward, yellow = measuring, red = error and gradient, green = improvement, purple = alternatives.

3. Environment

which latex dvisvgm || (apt-get update -q && apt-get install -y -q dvisvgm texlive-latex-extra)
python3 -c "import manim" 2>/dev/null || { apt-get install -y -q libpango1.0-dev; pip install --break-system-packages -q manim; }
which pdftoppm   # poppler, for the 300 dpi PNG

4. Build

The template at the end of this file has two parts:

  • ENGINE: config, palettes, helpers (T, tile, ghost, box, arrow, view_of), the camera methods (cam, fit, stop, cap) and export_pdf. Copy it unchanged into concept_map.py.
  • EXAMPLE (backpropagation): positions, views, build_net, gear and the whole construct(). It shows the level of polish, the pacing and how the engine is used. It is a style and quality reference only. Do not copy its structure (a loop of four stops on a 2x2 grid), its number of stops, its metaphors, its course map or its right column. Write your own construct() for the plan's structure.

Layout rules (world units; the frame is 16x9 at width 16):

  • A stop is a tile (default 11.6 x 11, header near the top). Arrange the tiles in whatever shape the structure needs (row, column, grid, tree, ring, two sides of a comparison), leaving about 6 units between neighbouring tiles for the arrows. Foundations sit next to the stop they support, joined to it by an arrow.
  • Content must fit inside its tile with a margin: within about +/-5.3 wide and +/-4.8 high of the tile's centre for the default size.
  • Zoomed-in stop: camera width ZW = 26, with the tile on one side and the caption panel on the other: self.stop(c, side) and self.cap(text, c, color, side), where side = +1 puts the caption on the right and -1 on the left. Put the caption on the side with free space. Break captions over two lines with \\.
  • Zoom-outs: frame the views with self.fit(*mobjects) (or view_of) from what should be on screen, not with hard-coded numbers. Leave room for side captions in mid views.
  • Text scale when zoomed out: a camera width W needs a Tex scale of about W/16 to look like scale 1. Manim stroke widths do not scale with zoom.
  • Accents and apostrophes in Tex: \\'e. Call clear_updaters() on always_redraw objects before the camera moves on.

5. Check before the final render

  • Render the video (python3 -W ignore -m manim --disable_caching -o <topic>_map_<lang> concept_map.py ConceptMap; it takes a minute or two).
  • Build a contact sheet with one frame every 4 s (ffmpeg -vf fps=1/4,scale=480:270, then tile them with PIL) and look at it. Check for overlaps, text cut off at the frame edges, captions colliding with tiles, and anything unreadable in the zoomed-out views. Also check that the layout shows the concept's real shape and doesn't look like the backpropagation example with new labels. Fix it and render again.

6. Printable map

THEME=light POSTER=$PWD/out/<topic>_map_print.pdf python3 -W ignore -m manim -s --disable_caching -o poster concept_map.py ConceptMap
pdftoppm -png -r 300 -singlefile out/<topic>_map_print.pdf out/<topic>_map_print

At the end of construct(), call self.export_pdf(POSTER, view=view_of(*map_mobjects, aspect=842 / 595)) when POSTER is set, so the page frames the final map. export_pdf draws the scene onto a Cairo PDF surface, so the output is true vector, and it already undoes Manim's RGB reversal. Look at the PNG before delivering.

6b. Series overview map (two or more videos)

The coordinator builds it after every video is done, so it shows what the videos actually contain.

  • Start from reels/_shared/course_map.md and each video's final concept_map.py. Reuse their tile titles, colours and key formulas instead of rewriting them.
  • Write one static scene, SeriesMap, to reels/_shared/series_map.py, with the template's ENGINE part. It only needs to add the mobjects and call export_pdf; there is no animation.
  • Layout: the course map around the outside, as in the videos' final zoom-out. In the centre, one cluster per video: its title in gold with its number in viewing order, and its stops as small boxes with their key formula, arranged in each video's own structure.
  • Draw the links between videos: an arrow from a video to the one that relies on it, and an idea that appears in two videos drawn once and joined to both clusters. The gold path runs from the course's root through each video's place on the map.
  • Add a short legend: the course's colour roles and "1, 2, 3 = suggested viewing order".
  • Page size: A4 landscape when it fits; A3 landscape (export_pdf(path, w_pt=1191, h_pt=842, view=view_of(..., aspect=1191 / 842))) when there are more than about 4 videos.
  • Render it and make the PNG:
THEME=light POSTER=$PWD/reels/_shared/<series>_overview_print.pdf python3 -W ignore -m manim -s --disable_caching -o overview reels/_shared/series_map.py SeriesMap
pdftoppm -png -r 300 -singlefile reels/_shared/<series>_overview_print.pdf reels/_shared/<series>_overview_print
  • Look at the PNG before delivering: no overlaps, no crossing arrows that could be avoided, and every label readable when printed. Fix it and render again.
  • If the device bridge is connected, commit it to the course folder's _series/<series>/ subfolder.

7. Voice and music (the user does this part)

  • Give the script in the reply. For the voice, recommend ElevenLabs directly on its free plan (about 10,000 characters a month, roughly a dozen scripts) rather than an ElevenLabs model inside another tool that charges credits per second. Suggested settings: stability medium-low, speed about 1.05.
  • Background music can come from any music generator. If its downloads are blocked from this workspace, ask the user to drop the voice and music mp3s into the topic's folder.
  • Once the mp3s are there: stage them with device_stage_files, retime the stops to the voice (adjust run_time and wait per segment), mix with ffmpeg (voice at about 0 dB, music at about -20 dB, ducked under the voice), optionally burn in subtitles, and commit the result back.

Template (ENGINE + EXAMPLE: backpropagation)

"""Concept-map study reel (Manim, 3Blue1Brown look) — landscape 16:9.

PART 1 = ENGINE: reuse unchanged in every video (config, palettes, helpers, camera, print export).
PART 2 = EXAMPLE (backpropagation): a style and quality reference only. Write your own scene;
         do NOT copy its structure, number of stops, loop, metaphors, course map or right column.

Render video :  manim --disable_caching -o <name> concept_map.py ConceptMap
Render poster:  THEME=light POSTER=/path/map.pdf manim -s --disable_caching concept_map.py ConceptMap
"""
from manim import *
import numpy as np
import os

# ================================================================== ENGINE
# ------------------------------------------------------------------ ENGINE: config
POSTER = os.environ.get("POSTER")          # if set: write a vector PDF of the final map here
THEME = os.environ.get("THEME", "dark")    # dark (video) | light (print)
config.pixel_width = 1920
config.pixel_height = 1080
config.frame_width = 16
config.frame_height = 9
config.frame_rate = 30

PAL = {
    "dark": dict(BG="#000000", FG="#FFFFFF", GOLD="#F5D98B", BL="#58C4DD", RD="#FC6255", YL="#FFFF00",
                 GR="#83C167", PU="#B189F5", MUTED="#9A9A9A", EDGE="#444444", SIB="#BBBBBB", ON="#000000"),
    "light": dict(BG="#FFFFFF", FG="#111111", GOLD="#9C6B00", BL="#1F78B4", RD="#D62728", YL="#B8860B",
                  GR="#2E8B3A", PU="#6A3FB5", MUTED="#666666", EDGE="#BBBBBB", SIB="#777777", ON="#FFFFFF"),
}[THEME]
BG, FG, GOLD_T, BL, RD, YL, GR, PU, GREY_T, EDGE, SIB, ON = (PAL[k] for k in
    ["BG", "FG", "GOLD", "BL", "RD", "YL", "GR", "PU", "MUTED", "EDGE", "SIB", "ON"])
config.background_color = BG
Tex.set_default(color=FG)
MathTex.set_default(color=FG)


# ------------------------------------------------------------------ ENGINE: layout constants
ZW = 26.0                        # zoomed-in camera width (one tile + caption panel)
CAP = 1.5                        # caption scale when zoomed in
OFF = 5.0                        # camera shifts this far to the outer side; captions sit there
POSTERV = None                   # print framing; set it with view_of(..., aspect=1.414) before export_pdf


# ------------------------------------------------------------------ ENGINE: helpers
def T(s, size=1.0, color=None):
    return Tex(s, color=color or FG).scale(size)


def tile(c, color, title, w=11.6, h=11.0, hs=1.7, hy=4.5):
    r = RoundedRectangle(corner_radius=0.6, width=w, height=h, color=color, stroke_width=3)
    r.move_to(c).set_fill(color, 0.05)
    return r, T(title, hs, color).move_to(c + UP * hy)


def ghost(c, w=11.6, h=11.0):
    r = DashedVMobject(RoundedRectangle(corner_radius=0.6, width=w, height=h, color=EDGE, stroke_width=3),
                       num_dashes=70).move_to(c)
    return VGroup(r, T("?", 6, EDGE).move_to(c))


def box(c, title, sub, color, s=2.0, ss=1.4, pad=1.0):
    t = T(title, s, color)
    g = VGroup(t, T(sub, ss, GREY_T)).arrange(DOWN, buff=0.3) if sub else VGroup(t)
    r = RoundedRectangle(corner_radius=0.6, width=g.width + 2 * pad, height=g.height + 1.6 * pad,
                         color=color, stroke_width=3).set_fill(color, 0.06)
    g.move_to(c); r.move_to(c)
    return VGroup(r, g)


def arrow(p, q, color, w=6, tip=0.4):
    return Arrow(p, q, buff=0, color=color, stroke_width=w, max_tip_length_to_length_ratio=tip)


def view_of(*mobs, aspect=16 / 9, margin=1.12):
    """camera view (center, width) that frames mobs at the given aspect; use for zoom-outs and POSTERV"""
    g = VGroup(*mobs)
    return dict(center=g.get_center(), width=max(g.width, g.height * aspect) * margin)



# ================================================================== EXAMPLE (backpropagation)
# Style reference only. Positions, views and helpers below are specific to this video.
F = np.array([-9.0, 8.0, 0])     # stop 1
LO = np.array([9.0, 8.0, 0])     # stop 2
B = np.array([9.0, -8.0, 0])     # stop 3
A = np.array([-9.0, -8.0, 0])    # stop 4
K = np.array([9.0, -21.5, 0])    # foundation under stop 3
GD = np.array([-9.0, -21.5, 0])  # foundation under stop 4
MID = dict(center=np.array([5.5, 1.5, 0]), width=60.0)       # mid zoom-out: the loop
LOOPV = dict(center=np.array([5.0, -4.5, 0]), width=82.0)    # final zoom-out step 1
MAPV = dict(center=np.array([-4.0, -4.3, 0]), width=85.0)    # final zoom-out step 2: whole map
POSTERV = dict(center=np.array([-4.0, -3.9, 0]), width=84.0)  # A4-landscape framing for print
LX = [-3.0, 0.0, 3.0]
LY = [[1.2, -1.2], [2.1, 0.0, -2.1], [0.0]]
NR = 0.42
GRAD = {((1, 0), (2, 0)): 0.95, ((1, 1), (2, 0)): 0.35, ((1, 2), (2, 0)): 0.7,
        ((0, 0), (1, 0)): 0.8, ((0, 0), (1, 1)): 0.2, ((0, 0), (1, 2)): 0.55,
        ((0, 1), (1, 0)): 0.3, ((0, 1), (1, 1)): 0.12, ((0, 1), (1, 2)): 0.45}


def build_net(shift):
    nodes = {}
    for l, ys in enumerate(LY):
        for i, y in enumerate(ys):
            c = Circle(radius=NR, color=FG, stroke_width=3).set_fill(BG, 1)
            c.move_to(np.array([LX[l], y, 0]) + shift)
            nodes[(l, i)] = c
    edges = {}
    for a in nodes:
        for b in nodes:
            if b[0] == a[0] + 1:
                p, q = nodes[a].get_center(), nodes[b].get_center()
                u = (q - p) / np.linalg.norm(q - p)
                edges[(a, b)] = Line(p + u * NR, q - u * NR, color=EDGE, stroke_width=2.5)
    return nodes, edges


def gear(center, r, teeth, ang, color):
    th = 0.13
    pts = []
    pitch = TAU / teeth
    for k in range(teeth):
        base = ang + k * pitch
        for off, rr in [(-0.27, r - th), (-0.15, r + th), (0.15, r + th), (0.27, r - th)]:
            a = base + off * pitch
            pts.append(center + rr * np.array([np.cos(a), np.sin(a), 0]))
    pts.append(pts[0])
    g = VMobject(color=color, stroke_width=3).set_points_as_corners(pts).set_fill(color, 0.18)
    hole = Circle(radius=max(0.09, r * 0.22), color=color, stroke_width=3).move_to(center).set_fill(BG, 1)
    d = np.array([np.cos(ang), np.sin(ang), 0])
    spoke = Line(center + 0.3 * r * d, center + (r - th - 0.05) * d, color=color, stroke_width=5)
    return VGroup(g, hole, spoke)



# ------------------------------------------------------------------ scene
class ConceptMap(MovingCameraScene):
    def cam(self, center, width, rt=1.5):
        self.play(self.camera.frame.animate.move_to(center).set(width=width), run_time=rt, rate_func=smooth)

    @staticmethod
    def side(c):
        return -1 if c[0] < 0 else 1

    def stop(self, c, side=None):
        """camera centre for a stop: tile on one side, caption panel on the other.
        side=+1 puts the caption on the right, -1 on the left; default: the outer side (sign of x)."""
        return c + RIGHT * OFF * (side or self.side(c))

    def cap(self, s, c, color=None, side=None):
        return T(s, CAP, color).move_to(c + RIGHT * 12.4 * (side or self.side(c)))

    def fit(self, *mobs, margin=1.12, rt=1.5):
        """move the camera so that everything in mobs is on screen (16:9), instead of hard-coded views"""
        v = view_of(*mobs, margin=margin)
        self.cam(v["center"], v["width"], rt)

    # -------------------------------------------------------------- print export
    def export_pdf(self, path, w_pt=842.0, h_pt=595.0, view=None):
        """Vector PDF (A4 landscape by default; A3 = 1191 x 842) of everything on screen (Cairo PDF surface).
        view: dict(center, width) framing the map, e.g. view_of(*map_mobjects, aspect=w_pt / h_pt); default POSTERV."""
        import cairo
        v = view or POSTERV
        fr = self.camera.frame
        fr.move_to(v["center"]).set(width=v["width"])
        fw = v["width"]
        fh = fw * h_pt / w_pt
        fc = v["center"]
        cam = self.renderer.camera
        surf = cairo.PDFSurface(path, w_pt, h_pt)
        ctx = cairo.Context(surf)
        bg = ManimColor(BG).to_rgb()
        ctx.set_source_rgb(*bg); ctx.paint()
        ctx.set_matrix(cairo.Matrix(w_pt / fw, 0, 0, -(h_pt / fh), w_pt / 2 - fc[0] * w_pt / fw, h_pt / 2 + fc[1] * h_pt / fh))
        def rgb_color(c, rgbas, vmobject):
            # the PNG pipeline reverses RGB for Cairo's BGRA image buffer; a PDF surface must not
            c.set_source_rgba(*rgbas[0][:3], rgbas[0][3])
            return cam
        cam.get_cairo_context = lambda pixel_array: ctx
        cam.set_cairo_context_color = rgb_color
        try:
            cam.capture_mobjects(self.mobjects)
        finally:
            del cam.get_cairo_context, cam.set_cairo_context_color   # back to the class methods
            surf.finish()

    # ============================================================== EXAMPLE scene (backpropagation)
    # Replace construct() entirely with your own video. Keep only the house beats:
    # hook -> stops -> mid zoom-out -> remaining stops -> full local structure -> course map + "You are here".
    def construct(self):
        fr = self.camera.frame
        fr.set(width=ZW).move_to(self.stop(F))

        # ---------------- HOOK
        hc = self.stop(F)
        q1 = T(r"How does a neural network", 2.2).move_to(hc + UP * 3.4)
        q2 = T(r"actually \textit{learn}?", 2.2).next_to(q1, DOWN, buff=0.3)
        ttl = T(r"Backpropagation", 3.3, GOLD_T).move_to(hc + DOWN * 0.8)
        sub = T(r"a map in 4 stops", 1.5, GREY_T).next_to(ttl, DOWN, buff=0.5)
        self.play(FadeIn(q1, shift=UP * 0.3), FadeIn(q2, shift=UP * 0.3), run_time=0.7)
        self.play(Write(ttl), run_time=1.1)
        self.play(FadeIn(sub), run_time=0.5)
        self.wait(0.7)
        self.play(FadeOut(VGroup(q1, q2, ttl, sub)), run_time=0.5)

        # ---------------- STOP 1: FORWARD
        rF, hF = tile(F, BL, r"1.\ Forward")
        self.play(Create(rF), Write(hF), run_time=0.8)
        nodes, edges = build_net(F + DOWN * 0.4)
        net = VGroup(*edges.values(), *nodes.values())
        labs = VGroup(MathTex("x_1", color=GREY_T).scale(0.9).next_to(nodes[(0, 0)], UP, buff=0.15),
                      MathTex("x_2", color=GREY_T).scale(0.9).next_to(nodes[(0, 1)], UP, buff=0.15),
                      MathTex(r"\hat y", color=GREY_T).next_to(nodes[(2, 0)], UP, buff=0.15))
        self.play(Create(net, lag_ratio=0.03), FadeIn(labs), run_time=0.9)
        v1 = DecimalNumber(0.8, num_decimal_places=1, color=ON).scale(0.8).move_to(nodes[(0, 0)])
        v2 = DecimalNumber(0.2, num_decimal_places=1, color=ON).scale(0.8).move_to(nodes[(0, 1)])
        self.play(nodes[(0, 0)].animate.set_fill(BL, 1), nodes[(0, 1)].animate.set_fill(BL, 1),
                  FadeIn(v1), FadeIn(v2), run_time=0.5)
        capF = self.cap(r"Data flows forward", F)
        self.play(FadeIn(capF, shift=UP * 0.2), run_time=0.5)
        e1 = [edges[x] for x in edges if x[0][0] == 0]
        e2 = [edges[x] for x in edges if x[0][0] == 1]
        self.play(*[ShowPassingFlash(e.copy().set_stroke(BL, 8), time_width=0.6) for e in e1],
                  *[e.animate.set_stroke(BL, 3, opacity=0.6) for e in e1], run_time=0.9)
        self.play(*[nodes[(1, j)].animate.set_fill(BL, 0.55) for j in range(3)], run_time=0.3)
        self.play(*[ShowPassingFlash(e.copy().set_stroke(BL, 8), time_width=0.6) for e in e2],
                  *[e.animate.set_stroke(BL, 3, opacity=0.6) for e in e2], run_time=0.8)
        out = DecimalNumber(0.30, num_decimal_places=2, color=ON).scale(0.65).move_to(nodes[(2, 0)])
        predF = MathTex(r"\hat y = 0.30", color=BL).scale(1.4).move_to(F + DOWN * 4.0)
        self.play(nodes[(2, 0)].animate.set_fill(BL, 1), FadeIn(out), Write(predF), run_time=0.8)
        capF2 = self.cap(r"and the network\\makes a prediction", F)
        self.play(FadeTransform(capF, capF2), run_time=0.5)
        self.wait(0.8)

        # ---------------- STOP 2: LOSS
        aFL = arrow(F + RIGHT * 6.0, LO + LEFT * 6.0, FG)
        self.play(FadeOut(capF2), GrowArrow(aFL), run_time=0.4)
        self.cam(self.stop(LO), ZW, 1.2)
        rL, hL = tile(LO, YL, r"2.\ Loss")
        self.play(Create(rL), Write(hL), run_time=0.7)
        line = NumberLine(x_range=[0, 1, 0.1], length=8, tick_size=0.08, color=GREY_T).move_to(LO + UP * 1.4)
        n0 = MathTex("0", color=GREY_T).scale(0.8).next_to(line.n2p(0), DOWN, buff=0.25)
        n1 = MathTex("1", color=GREY_T).scale(0.8).next_to(line.n2p(1), DOWN, buff=0.25)
        dp = Dot(line.n2p(0.3), color=BL, radius=0.15)
        dy_ = Dot(line.n2p(1.0), color=YL, radius=0.15)
        tp = MathTex(r"\hat y = 0.30", color=BL).next_to(dp, UP, buff=0.35)
        ty = MathTex(r"y = 1.00", color=YL).next_to(dy_, UP, buff=0.35).shift(LEFT * 0.5)
        self.play(Create(line), FadeIn(n0, n1), run_time=0.6)
        self.play(FadeIn(dp, scale=2), Write(tp), run_time=0.5)
        self.play(FadeIn(dy_, scale=2), Write(ty), run_time=0.5)
        br = BraceBetweenPoints(line.n2p(0.3), line.n2p(1.0), DOWN, color=RD).shift(DOWN * 0.5)
        bt = MathTex(r"\text{error} = 0.70", color=RD).scale(0.95).next_to(br, DOWN, buff=0.2)
        self.play(GrowFromCenter(br), Write(bt), run_time=0.7)
        lossF = MathTex(r"L", r"=", r"(y - \hat y)^2", r"=", r"0.49").scale(1.45).move_to(LO + DOWN * 3.3)
        lossF[0].set_color(RD); lossF[4].set_color(RD)
        capL = self.cap(r"The loss measures\\how wrong it is", LO)
        self.play(Write(lossF), FadeIn(capL, shift=UP * 0.2), run_time=1.1)
        self.wait(0.8)
        capL2 = self.cap(r"So\dots\ who's to blame?", LO, RD)
        self.play(FadeTransform(capL, capL2), run_time=0.5)
        self.wait(0.9)

        # ---------------- MID ZOOM-OUT: the loop so far
        gB, gA = ghost(B), ghost(A)
        aLB = arrow(LO + DOWN * 5.7, B + UP * 5.7, EDGE)
        aBA = arrow(B + LEFT * 6.0, A + RIGHT * 6.0, EDGE)
        aAF = arrow(A + UP * 5.7, F + DOWN * 5.7, EDGE)
        loopT = T(r"Training a neural network", 2.4, GOLD_T).move_to(UP * 16.4)
        self.play(FadeOut(capL2), run_time=0.3)
        newbits = [gB, gA, aLB, aBA, aAF, loopT]
        self.add(*newbits)
        for m in newbits:
            m.set_opacity(0)
        self.play(fr.animate.move_to(MID["center"]).set(width=MID["width"]),
                  *[m.animate.set_opacity(1) for m in newbits], run_time=1.8, rate_func=smooth)
        mc = VGroup(T(r"It can predict", 2.8), T(r"and measure its error\dots", 2.8),
                    T(r"but how does it \textit{learn}?", 2.8, RD)).arrange(DOWN, buff=0.7).move_to(RIGHT * 26.0)
        self.play(FadeIn(mc[0], shift=UP * 0.3), FadeIn(mc[1], shift=UP * 0.3), run_time=0.7)
        self.play(FadeIn(mc[2], shift=UP * 0.3), Indicate(gB[1], color=RD, scale_factor=1.3), run_time=0.9)
        self.play(ShowPassingFlash(aLB.copy().set_color(RD).set_stroke(width=12), time_width=0.7), run_time=0.8)
        self.wait(0.6)
        self.play(FadeOut(mc), run_time=0.4)

        # ---------------- STOP 3: BACKWARD
        self.cam(self.stop(B), ZW, 1.5)
        rB, hB = tile(B, RD, r"3.\ Backward")
        self.play(FadeOut(gB), aLB.animate.set_color(FG), Create(rB), Write(hB), run_time=0.8)
        nodes, edges = build_net(B + DOWN * 0.4)
        for kk in nodes:
            nodes[kk].set_fill(BL, 0.25 if kk[0] == 1 else 0.6)
        netB = VGroup(*edges.values(), *nodes.values())
        self.play(FadeIn(netB), run_time=0.5)
        lt = MathTex("L = 0.49", color=RD).scale(0.9).next_to(nodes[(2, 0)], UP, buff=0.2)
        self.play(nodes[(2, 0)].animate.set_fill(RD, 1).set_stroke(RD), FadeIn(lt), run_time=0.5)
        capB = self.cap(r"Blame flows backwards", B)
        self.play(FadeIn(capB, shift=UP * 0.2), run_time=0.4)

        def back(es):
            an = []
            for kk, e in es:
                rev = Line(e.get_end(), e.get_start())
                an.append(ShowPassingFlash(rev.set_stroke(RD, 9), time_width=0.6))
                an.append(e.animate.set_stroke(RD, 1.5 + 12 * GRAD[kk], opacity=0.35 + 0.6 * GRAD[kk]))
            return an
        self.play(*back([(x, edges[x]) for x in edges if x[0][0] == 1]), run_time=1.1)
        self.play(*[nodes[(1, j)].animate.set_stroke(RD) for j in range(3)], run_time=0.25)
        self.play(*back([(x, edges[x]) for x in edges if x[0][0] == 0]), run_time=1.1)
        self.play(*[nodes[(0, i)].animate.set_stroke(RD) for i in range(2)], run_time=0.25)
        tag = MathTex(r"\frac{\partial L}{\partial w} = 0.42", color=RD).scale(0.8).move_to(B + np.array([1.75, 1.6, 0]))
        capB2 = self.cap(r"thicker line\\$=$ more to blame", B)
        self.play(FadeIn(tag, shift=DOWN * 0.1), FadeTransform(capB, capB2), run_time=0.6)
        self.wait(0.9)
        capB3 = self.cap(r"How is the\\blame split? $\downarrow$", B, YL)
        self.play(FadeTransform(capB2, capB3), run_time=0.4)
        self.wait(0.4)

        # ---------------- STOP 3b: CHAIN RULE (foundation)
        rK, hK = tile(K, YL, r"Calculus: the chain rule", h=10.0, hs=1.4, hy=4.0)
        aKB = arrow(K + UP * 5.0, B + DOWN * 5.5, YL, tip=0.45)
        self.play(FadeOut(capB3), run_time=0.2)
        self.cam(self.stop(K), ZW, 1.3)
        self.play(Create(rK), Write(hK), GrowArrow(aKB), run_time=0.8)
        theta = ValueTracker(0)
        s = 0.85
        gc = K + UP * 0.9
        cA, cB_, cC = gc + LEFT * 1.2 * s, gc + RIGHT * 1.2 * s, gc + RIGHT * 2.4 * s
        gA_ = always_redraw(lambda: gear(cA, 1.6 * s, 24, theta.get_value(), BL))
        gB_ = always_redraw(lambda: gear(cB_, 0.8 * s, 12, np.radians(15) - 2 * theta.get_value(), YL))
        gC_ = always_redraw(lambda: gear(cC, 0.4 * s, 6, 4 * theta.get_value(), RD))
        glabs = VGroup(MathTex("w", color=BL).scale(1.1).move_to(cA + DOWN * 1.85),
                       MathTex("h", color=YL).scale(1.1).move_to(cB_ + DOWN * 1.2),
                       MathTex("L", color=RD).scale(1.1).move_to(cC + DOWN * 0.9))
        capK = self.cap(r"Think of gears", K)
        self.play(FadeIn(gA_, gB_, gC_), FadeIn(glabs), FadeIn(capK, shift=UP * 0.2), run_time=0.7)
        self.play(theta.animate.set_value(0.8), run_time=1.0, rate_func=smooth)
        x2a = MathTex(r"\times 2", color=YL).scale(0.95).move_to(cB_ + UP * 1.2)
        self.play(FadeIn(x2a, scale=1.5), theta.animate.set_value(1.5), run_time=1.1, rate_func=linear)
        x2b = MathTex(r"\times 2", color=RD).scale(0.95).move_to(cC + UP * 0.85)
        self.play(FadeIn(x2b, scale=1.5), theta.animate.set_value(2.2), run_time=1.1, rate_func=linear)
        tot = MathTex(r"2 \times 2 = 4", color=GR).scale(1.15).move_to(K + DOWN * 1.95)
        chain = MathTex(r"\frac{\partial L}{\partial w}", r"=", r"\frac{\partial L}{\partial h}", r"\cdot",
                        r"\frac{\partial h}{\partial w}").scale(1.05).move_to(K + DOWN * 3.55)
        chain[0].set_color(BL); chain[2].set_color(RD); chain[4].set_color(YL)
        capK2 = self.cap(r"Multiply every\\link of the chain", K)
        self.play(Write(tot), FadeTransform(capK, capK2), theta.animate.set_value(2.9), run_time=1.1, rate_func=linear)
        self.play(Write(chain), theta.animate.set_value(3.8), run_time=1.3, rate_func=linear)
        self.play(theta.animate.set_value(4.4), run_time=0.8, rate_func=linear)
        for g in (gA_, gB_, gC_):
            g.clear_updaters()

        # ---------------- STOP 4: UPDATE
        self.play(FadeOut(capK2), run_time=0.2)
        self.cam(self.stop(A), ZW, 1.5)
        rA, hA = tile(A, GR, r"4.\ Update")
        self.play(FadeOut(gA), aBA.animate.set_color(FG), Create(rA), Write(hA), run_time=0.8)
        upd = MathTex(r"w", r"\leftarrow", r"w", r"-", r"\eta", r"\,", r"\frac{\partial L}{\partial w}").scale(1.35).move_to(A + UP * 2.7)
        upd[4].set_color(YL); upd[6].set_color(RD)
        self.play(Write(upd), run_time=0.9)
        ax = Axes(x_range=[-2, 2, 1], y_range=[0, 4, 1], x_length=7, y_length=3.8, tips=False,
                  axis_config={"color": EDGE, "stroke_width": 2}).move_to(A + DOWN * 1.9)
        f = lambda x: x ** 2
        curve = ax.plot(f, color=FG, stroke_width=4)
        self.play(Create(ax), Create(curve), run_time=0.7)
        xs = [-1.85, -1.1, -0.6, -0.28, -0.06]
        xt = ValueTracker(xs[0])
        dot = always_redraw(lambda: Dot(ax.c2p(xt.get_value(), f(xt.get_value())), color=BL, radius=0.14))
        tan = always_redraw(lambda: ax.plot(lambda x: f(xt.get_value()) + 2 * xt.get_value() * (x - xt.get_value()),
                                            x_range=[max(-2, xt.get_value() - 0.6), min(2, xt.get_value() + 0.6)],
                                            color=RD, stroke_width=3))
        lv = DecimalNumber(0.49, num_decimal_places=2, color=RD).scale(0.95)
        lgrp = VGroup(MathTex("L =").scale(0.95), lv).arrange(RIGHT, buff=0.15).move_to(ax.c2p(1.15, 3.3))
        capA = self.cap(r"Every weight gets\\nudged a little", A)
        self.play(FadeIn(dot, scale=2), Create(tan), FadeIn(lgrp), FadeIn(capA, shift=UP * 0.2), run_time=0.6)
        for i, v in enumerate([0.21, 0.08, 0.02, 0.00], start=1):
            self.play(xt.animate.set_value(xs[i]), ChangeDecimalToValue(lv, v), run_time=0.5)
        dot.clear_updaters(); tan.clear_updaters()
        capA2 = self.cap(r"and the loss\\goes down", A)
        self.play(FadeTransform(capA, capA2), FadeOut(tan), run_time=0.5)
        self.wait(0.6)

        rG, hG = tile(GD, GR, r"Optimization: gradient descent", h=10.0, hs=1.2, hy=4.0)
        axg = Axes(x_range=[-2, 2, 1], y_range=[0, 4, 1], x_length=6, y_length=4, tips=False,
                   axis_config={"color": EDGE, "stroke_width": 2}).move_to(GD + DOWN * 0.7)
        gdNode = VGroup(rG, hG, axg, axg.plot(f, color=FG, stroke_width=4),
                        VGroup(*[Dot(axg.c2p(x, f(x)), color=GR, radius=0.12) for x in xs]),
                        arrow(GD + UP * 5.0, A + DOWN * 5.5, GR, tip=0.45))

        # ---------------- FINAL ZOOM-OUT 1: the full loop
        self.play(FadeOut(capA2), run_time=0.2)
        self.play(fr.animate.move_to(LOOPV["center"]).set(width=LOOPV["width"]), aAF.animate.set_color(FG),
                  FadeIn(gdNode), run_time=1.8, rate_func=smooth)
        fc = VGroup(T(r"\dots and repeat.", 3.0), T(r"Thousands of times.", 3.0, GOLD_T)).arrange(DOWN, buff=0.7).move_to(RIGHT * 28)
        self.play(FadeIn(fc, shift=UP * 0.3), run_time=0.5)
        for _ in range(2):
            for a in (aFL, aLB, aBA, aAF):
                self.play(ShowPassingFlash(a.copy().set_color(GOLD_T).set_stroke(width=14), time_width=0.8),
                          run_time=0.28, rate_func=linear)
        self.play(FadeOut(fc), run_time=0.4)

        # ---------------- FINAL ZOOM-OUT 2: the course map + "you are here"
        ia = T(r"Artificial Intelligence", 4.0, GOLD_T).move_to(np.array([-31.0, 17.5, 0]))
        ml = box(np.array([-31.0, 11.0, 0]), r"Machine Learning", None, FG, s=3.0, pad=1.1)
        reg = box(np.array([-40.0, 4.0, 0]), r"Regression", r"linear \textperiodcentered\ logistic", SIB, s=1.8, ss=1.3)
        tre = box(np.array([-32.0, 4.0, 0]), r"Decision trees", r"\& forests", SIB, s=1.8, ss=1.3)
        nn = box(np.array([-23.5, 4.0, 0]), r"Neural networks", r"deep learning", GOLD_T, s=2.1, ss=1.4)
        neu = box(np.array([-27.5, -4.5, 0]), r"The neuron", r"$w \cdot x + b$", BL, s=1.9, ss=1.5)
        act = box(np.array([-19.5, -4.5, 0]), r"Activation", r"sigmoid \textperiodcentered\ ReLU", PU, s=1.9, ss=1.3)
        archT = T(r"All trained with backprop", 2.4, GOLD_T).move_to(np.array([29.0, 12.5, 0]))
        cnn = box(np.array([30.0, 6.5, 0]), r"CNN", r"images", BL, s=2.2, ss=1.4)
        rnn = box(np.array([30.0, 0.5, 0]), r"RNN", r"sequences", PU, s=2.2, ss=1.4)
        trf = box(np.array([30.0, -5.5, 0]), r"Transformers", r"LLMs: GPT, Claude", RD, s=2.2, ss=1.4)

        def ln(p, q, col=EDGE, w=4):
            return Line(p, q, color=col, stroke_width=w)
        spine_x = 23.0
        tree = VGroup(
            ln(ml[0].get_bottom(), reg[0].get_top()), ln(ml[0].get_bottom(), tre[0].get_top()),
            ln(nn[0].get_bottom(), neu[0].get_top()), ln(nn[0].get_bottom(), act[0].get_top()),
            ln(np.array([spine_x, archT.get_bottom()[1] - 0.4, 0]), np.array([spine_x, trf.get_center()[1], 0])),
            *[ln(np.array([spine_x, m.get_center()[1], 0]), m[0].get_left()) for m in (cnn, rnn, trf)],
        )
        gold = VGroup(
            ln(ia.get_bottom() + DOWN * 0.3, ml[0].get_top(), GOLD_T, 9),
            ln(ml[0].get_bottom(), nn[0].get_top(), GOLD_T, 9),
            arrow(nn[0].get_right(), np.array([F[0] - 5.9, nn.get_center()[1], 0]), GOLD_T, w=9, tip=0.25),
            arrow(np.array([LO[0] + 5.9, archT.get_center()[1], 0]), archT.get_left() + LEFT * 0.4, GOLD_T, w=9, tip=0.25),
        )
        pinA = arrow(np.array([21.5, -10.3, 0]), np.array([15.3, -8.6, 0]), GOLD_T, w=12, tip=0.3)
        pinT = T(r"You are here", 2.4, GOLD_T).next_to(pinA.get_start(), RIGHT, buff=0.4)
        self.play(fr.animate.move_to(MAPV["center"]).set(width=MAPV["width"]),
                  LaggedStart(*[FadeIn(m) for m in (ia, ml, reg, tre, nn, neu, act)], lag_ratio=0.15),
                  Create(tree[:4]), run_time=2.6, rate_func=smooth)
        self.play(LaggedStart(*[Create(g) for g in gold[:3]], lag_ratio=0.6), run_time=1.3)
        self.play(GrowArrow(pinA), FadeIn(pinT, shift=LEFT * 0.5), rB.animate.set_stroke(GOLD_T, 8), run_time=0.8)
        self.play(Create(gold[3]), FadeIn(archT, shift=LEFT * 0.4), Create(tree[4:]),
                  LaggedStart(FadeIn(cnn), FadeIn(rnn), FadeIn(trf), lag_ratio=0.25), run_time=1.4)
        self.wait(3.0)

        if POSTER:
            self.export_pdf(POSTER)

Related Skills