Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added lessons/01-first-pr-in-browser/captures/repo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 25 additions & 12 deletions lessons/01-first-pr-in-browser/script.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -84,20 +94,23 @@ 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
> arrow at the top: your fork on the right, pointing into the original repo
> 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
Expand Down
50 changes: 50 additions & 0 deletions tests/test_captures.py
Original file line number Diff line number Diff line change
@@ -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)
90 changes: 90 additions & 0 deletions tools/capture_pages.py
Original file line number Diff line number Diff line change
@@ -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:]))
22 changes: 22 additions & 0 deletions tools/check_lessons.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("_"))

Expand Down
Loading
Loading