diff --git a/lessons/01-first-pr-in-browser/captures/bot-merges.png b/lessons/01-first-pr-in-browser/captures/bot-merges.png new file mode 100644 index 0000000..551151c Binary files /dev/null and b/lessons/01-first-pr-in-browser/captures/bot-merges.png differ diff --git a/lessons/01-first-pr-in-browser/captures/compare.png b/lessons/01-first-pr-in-browser/captures/compare.png new file mode 100644 index 0000000..52f1c87 Binary files /dev/null and b/lessons/01-first-pr-in-browser/captures/compare.png differ diff --git a/lessons/01-first-pr-in-browser/captures/first-commits.png b/lessons/01-first-pr-in-browser/captures/first-commits.png new file mode 100644 index 0000000..5e6ebf4 Binary files /dev/null and b/lessons/01-first-pr-in-browser/captures/first-commits.png differ diff --git a/lessons/01-first-pr-in-browser/captures/repo.png b/lessons/01-first-pr-in-browser/captures/repo.png new file mode 100644 index 0000000..f00ff54 Binary files /dev/null and b/lessons/01-first-pr-in-browser/captures/repo.png differ diff --git a/lessons/01-first-pr-in-browser/script.md b/lessons/01-first-pr-in-browser/script.md index dac4e6f..43e2463 100644 --- a/lessons/01-first-pr-in-browser/script.md +++ b/lessons/01-first-pr-in-browser/script.md @@ -32,6 +32,8 @@ bullets: visual: browser url: https://github.com/thejesh23/first-python-contribution caption: Click Star, top right +image: captures/repo.png +highlight: 1236,184,96,36 > Open the course repository. The link is in the description. Top right, > there's a Star button. Starring saves the repo to your list of stars, so you @@ -40,8 +42,10 @@ caption: Click Star, top right ## Scene 4: Fork visual: browser -url: https://github.com/thejesh23/first-python-contribution/fork +url: https://github.com/thejesh23/first-python-contribution caption: Fork → Create fork +image: captures/repo.png +highlight: 1138,184,98,36 > Next to Star is Fork. Click it, then click Create fork. After a few > seconds you're on a page with your username in the address. Look under the @@ -51,7 +55,9 @@ caption: Fork → Create fork ## Scene 5: Create your file visual: browser url: https://github.com/thejesh23/first-python-contribution/tree/main/first-commits -caption: first-commits → Add file → Create new file +caption: In your fork: first-commits → Add file → Create new file +image: captures/first-commits.png +highlight: 337,417,1087,41 > In your fork, open the folder called first commits. Click Add file, then > Create new file. Name the file after your GitHub username, followed by dot @@ -72,9 +78,13 @@ message = "Why you're learning Python" > every value needs one at the start and one at the end. ## Scene 7: Commit -visual: browser -url: https://github.com/thejesh23/first-python-contribution -caption: Commit changes... → write a message → Commit changes +visual: slide +title: Commit your file +bullets: +- Click Commit changes... +- Message: Add first commit for octocat +- Keep "Commit directly to the main branch" (it's your fork) +- Click Commit changes > Click Commit changes. Write a short message, like: add first commit for, > and your username. Keep commit directly to the main branch selected. That's @@ -84,7 +94,10 @@ caption: Commit changes... → write a message → Commit changes ## Scene 8: Open the pull request visual: browser url: https://github.com/thejesh23/first-python-contribution/compare -caption: Contribute → Open pull request +caption: Contribute → Open pull request, then check base ← head +image: captures/compare.png +crop: 100,180,1240,250 +highlight: 56,99,260,36 > Go back to the main page of your fork. There's a banner saying your branch > is one commit ahead. Click Contribute, then Open pull request. Check the @@ -92,12 +105,12 @@ caption: Contribute → Open pull request > on the left. Click Create pull request. ## Scene 9: The bot -visual: slide -title: What happens next -bullets: -- A check reads your file with Python's own parser -- All good: the bot comments and merges your PR -- Something wrong: it tells you exactly what to fix +visual: browser +url: https://github.com/thejesh23/first-python-contribution/pull/1 +caption: The bot explains what to fix, then merges when it's right +image: captures/bot-merges.png +height: 2400 +crop: 100,580,900,600 > Now watch. A check called validate first commit starts running. It reads > your file with Python's own parser, the same one Python uses before it runs diff --git a/tests/test_captures.py b/tests/test_captures.py new file mode 100644 index 0000000..7bf77f1 --- /dev/null +++ b/tests/test_captures.py @@ -0,0 +1,50 @@ +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools")) +import capture_pages # noqa: E402 +import check_lessons # noqa: E402 +import render_video # noqa: E402 +import script_format # noqa: E402 + +LESSON = Path(__file__).resolve().parent.parent / "lessons" / "01-first-pr-in-browser" + + +def test_png_size_of_real_capture(): + assert render_video.png_size(LESSON / "captures" / "repo.png") == (1440, 900) + + +def test_capture_layout_scales_highlight(): + scale, box = render_video.capture_layout((1440, 900), "100,200,40,20") + assert scale == min(render_video.CAPTURE_MAX_W / 1440, render_video.CAPTURE_MAX_H / 900) + assert box == tuple(round(v * scale) for v in (100, 200, 40, 20)) + assert render_video.capture_layout((300, 100), None) == (1.4, None) + + +def test_browser_scene_uses_capture(): + script = script_format.load(LESSON / "script.md") + scene = next(s for s in script.scenes if s.fields.get("image") == "captures/repo.png") + html = render_video.scene_html(scene, script.title, LESSON) + assert "captures/repo.png" in html and 'class="spot"' in html + + +def test_browser_scene_without_capture_is_placeholder(): + scene = script_format.Scene(1, "x", {"visual": "browser", "url": "https://example.com", "caption": "c"}) + assert "screen capture goes here" in render_video.scene_html(scene, "t", LESSON) + + +def test_parse_box(): + assert capture_pages.parse_box("1,2,3,4") == (1, 2, 3, 4) + + +def test_highlight_outside_capture_is_reported(tmp_path): + (tmp_path / "captures").mkdir() + (tmp_path / "captures" / "repo.png").write_bytes((LESSON / "captures" / "repo.png").read_bytes()) + script = script_format.parse( + "# Video script: X\n\n## Scene 1: S\nvisual: browser\nurl: u\ncaption: c\n" + "image: captures/repo.png\nhighlight: 1400,880,100,100\n\n> Hi.\n" + "\n## Scene 2: T\nvisual: browser\nurl: u\ncaption: c\nimage: captures/missing.png\n\n> Hi.\n" + ) + problems = check_lessons.check_captures(tmp_path, script) + assert any("outside" in p for p in problems) + assert any("missing" in p for p in problems) diff --git a/tools/capture_pages.py b/tools/capture_pages.py new file mode 100644 index 0000000..391ae40 --- /dev/null +++ b/tools/capture_pages.py @@ -0,0 +1,90 @@ +"""Capture the real web pages shown in a lesson's browser scenes. + +Usage:: + + python tools/capture_pages.py lessons/01-first-pr-in-browser + +For every ``visual: browser`` scene with an ``image:`` field, it opens the +scene's ``url`` in headless Chrome and saves a screenshot to that path inside +the lesson folder. Optional fields: + + height: 2400 capture a taller page (default 900) + crop: x,y,w,h keep only this region of the capture + +Chrome runs with a fresh, empty profile, so pages are captured logged out: +no account, cookies or notifications of whoever runs this end up in a video. +Re-run it whenever GitHub's pages change. +""" + +from __future__ import annotations + +import subprocess +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import script_format # noqa: E402 + +CHROME = Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome") +WIDTH = 1440 +LOAD_BUDGET_MS = 10_000 # let the page's JavaScript finish before the screenshot + + +def parse_box(text: str) -> tuple[int, int, int, int]: + x, y, w, h = (int(part) for part in text.split(",")) + return x, y, w, h + + +def capture(url: str, out: Path, height: int = 900) -> None: + out.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as profile: + subprocess.run( + [ + str(CHROME), + "--headless=new", + "--disable-gpu", + "--hide-scrollbars", + f"--user-data-dir={profile}", + f"--virtual-time-budget={LOAD_BUDGET_MS}", + f"--window-size={WIDTH},{height}", + f"--screenshot={out}", + url, + ], + check=True, + capture_output=True, + ) + + +def crop(path: Path, box: tuple[int, int, int, int]) -> None: + x, y, w, h = box + tmp = path.with_suffix(".crop.png") + subprocess.run( + ["ffmpeg", "-y", "-loglevel", "error", "-i", str(path), "-vf", f"crop={w}:{h}:{x}:{y}", str(tmp)], + check=True, + ) + tmp.replace(path) + + +def main(argv: list[str]) -> int: + if len(argv) != 1: + print("usage: python tools/capture_pages.py LESSON-FOLDER", file=sys.stderr) + return 2 + lesson = Path(argv[0]).resolve() + script = script_format.load(lesson / "script.md") + done: set[str] = set() + for scene in script.scenes: + image = scene.fields.get("image") + if scene.visual != "browser" or not image or image in done: + continue + out = lesson / image + capture(scene.fields["url"], out, int(scene.fields.get("height", 900))) + if scene.fields.get("crop"): + crop(out, parse_box(scene.fields["crop"])) + done.add(image) + print(f"captured {scene.fields['url']} -> {out.relative_to(lesson.parent.parent)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/check_lessons.py b/tools/check_lessons.py index 4c19bfd..e107e42 100644 --- a/tools/check_lessons.py +++ b/tools/check_lessons.py @@ -32,11 +32,33 @@ def check_lesson(folder: Path) -> list[str]: if script_path.is_file(): script = script_format.load(script_path) out.extend(script_format.problems(script)) + out.extend(check_captures(folder, script)) if script.minutes > MAX_MINUTES: out.append(f"script is about {script.minutes:.0f} minutes; keep it under {MAX_MINUTES}") return out +def check_captures(folder: Path, script: script_format.Script) -> list[str]: + """Browser scenes with image: must point at a capture, with the highlight inside it.""" + from render_video import png_size + + out = [] + for scene in script.scenes: + image = scene.fields.get("image") + if scene.visual != "browser" or not image: + continue + path = folder / image + if not path.is_file(): + out.append(f"scene {scene.number}: {image} is missing (run tools/capture_pages.py)") + continue + if scene.fields.get("highlight"): + w, h = png_size(path) + x, y, bw, bh = (int(v) for v in scene.fields["highlight"].split(",")) + if x < 0 or y < 0 or x + bw > w or y + bh > h: + out.append(f"scene {scene.number}: highlight {x},{y},{bw},{bh} is outside the {w}x{h} capture") + return out + + def lesson_folders() -> list[Path]: return sorted(p for p in LESSONS.iterdir() if p.is_dir() and not p.name.startswith("_")) diff --git a/tools/render_video.py b/tools/render_video.py index e35b812..1c8680b 100644 --- a/tools/render_video.py +++ b/tools/render_video.py @@ -20,8 +20,10 @@ import html import re import shutil +import struct import subprocess import sys +import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -58,6 +60,15 @@ color: #444; } .page { height: 520px; display: flex; align-items: center; justify-content: center; color: #57606a; font-size: 38px; } .caption { margin-top: 50px; font-size: 56px; font-weight: 700; color: #ffd43b; } +.capture { position: relative; overflow: hidden; line-height: 0; } +.capture img { display: block; } +.spot { position: absolute; border: 5px solid #ffd43b; border-radius: 12px; + box-shadow: 0 0 0 4000px rgba(0, 0, 0, 0.45), 0 0 24px 6px rgba(255, 212, 59, 0.6); } +.shot-caption { margin-top: 20px; font-size: 38px; font-weight: 700; color: #ffd43b; text-align: center; } +.shot { align-self: center; } +.shot .bar { padding: 12px 20px; gap: 10px; } +.shot .dot { width: 16px; height: 16px; } +.shot .url { font-size: 20px; padding: 8px 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } """ @@ -91,7 +102,51 @@ def _pre(lines: list[str], rendered: list[str]) -> str: return f'
' + "\n".join(rendered) + "
" -def scene_html(scene: Scene, lesson_title: str) -> str: +CAPTURE_MAX_W, CAPTURE_MAX_H = 1560, 640 + + +def png_size(path: Path) -> tuple[int, int]: + """Width and height of a PNG, read from its header.""" + data = path.read_bytes()[16:24] + return struct.unpack(">II", data) + + +def capture_layout(size: tuple[int, int], highlight: str | None) -> tuple[float, tuple[int, ...] | None]: + """Scale a capture to fit the frame, and scale its highlight box with it.""" + w, h = size + scale = min(CAPTURE_MAX_W / w, CAPTURE_MAX_H / h, 1.4) + box = tuple(round(int(v) * scale) for v in highlight.split(",")) if highlight else None + return scale, box + + +def _browser_bar(url: str) -> str: + return ( + '
' + '' + '' + '' + f'{html.escape(url)}
' + ) + + +def _browser_capture(scene: Scene, lesson_dir: Path) -> str: + image = lesson_dir / scene.fields["image"] + size = png_size(image) + scale, box = capture_layout(size, scene.fields.get("highlight")) + w, h = round(size[0] * scale), round(size[1] * scale) + spot = ( + f'
' + if box + else "" + ) + return ( + f'
{_browser_bar(scene.fields["url"])}' + f'
{spot}
' + f'
{html.escape(scene.fields["caption"])}
' + ) + + +def scene_html(scene: Scene, lesson_title: str, lesson_dir: Path | None = None) -> str: kicker = html.escape(scene.heading) if scene.visual == "slide": items = "".join(f"
  • {html.escape(b)}
  • " for b in scene.bullets) @@ -100,14 +155,12 @@ def scene_html(scene: Scene, lesson_title: str) -> str: body = _pre(scene.code, [_highlight_python(line) for line in scene.code]) elif scene.visual == "terminal": body = _pre(scene.code, [_terminal_line(line) for line in scene.code]) + elif scene.visual == "browser" and scene.fields.get("image") and lesson_dir is not None: + body = _browser_capture(scene, lesson_dir) elif scene.visual == "browser": - # Placeholder frame until real page captures (Playwright) are wired in. + # No capture yet: a placeholder frame. Add image: and run tools/capture_pages.py. body = ( - '
    ' - '' - '' - '' - f'{html.escape(scene.fields["url"])}
    ' + f'
    {_browser_bar(scene.fields["url"])}' '
    [ screen capture goes here ]
    ' f'
    {html.escape(scene.fields["caption"])}
    ' ) @@ -122,20 +175,23 @@ def scene_html(scene: Scene, lesson_title: str) -> str: def screenshot(html_path: Path, png_path: Path) -> None: - subprocess.run( - [ - str(CHROME), - "--headless=new", - "--disable-gpu", - "--hide-scrollbars", - "--force-device-scale-factor=1", - f"--window-size={WIDTH},{HEIGHT}", - f"--screenshot={png_path}", - html_path.as_uri(), - ], - check=True, - capture_output=True, - ) + with tempfile.TemporaryDirectory() as profile: # never touch the user's Chrome profile + subprocess.run( + [ + str(CHROME), + "--headless=new", + "--disable-gpu", + "--hide-scrollbars", + "--force-device-scale-factor=1", + "--allow-file-access-from-files", + f"--user-data-dir={profile}", + f"--window-size={WIDTH},{HEIGHT}", + f"--screenshot={png_path}", + html_path.as_uri(), + ], + check=True, + capture_output=True, + ) def synthesize(text: str, out: Path, voice: str, rate: int) -> None: @@ -243,7 +299,7 @@ def render(lesson: Path, voice: str, rate: int, scene_range: str | None) -> Path clips, durations = [], [] for scene in scenes: stem = build / f"scene{scene.number:02}" - stem.with_suffix(".html").write_text(scene_html(scene, script.title), encoding="utf-8") + stem.with_suffix(".html").write_text(scene_html(scene, script.title, lesson), encoding="utf-8") screenshot(stem.with_suffix(".html"), stem.with_suffix(".png")) synthesize(scene.narration, stem.with_suffix(".aiff"), voice, rate) make_clip(stem.with_suffix(".png"), stem.with_suffix(".aiff"), stem.with_suffix(".mp4"))