Repository navigation
Fix the flaky red badge: compare figures by content, not bytes #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| """Fail when a regenerated figure differs from the committed one in content. | ||
|
|
||
| The figure step used to require byte equality. On Nov 29 commit 4071c1e failed | ||
| it (tariff-explorer 01_regime_bill_curves.png, 141094 -> 141097 bytes) and on | ||
| Nov 30 the same commit passed it, with identical runner image, Python and | ||
| library versions. Byte equality is therefore not stable even in CI, and a red | ||
| badge from it says nothing about whether a figure is stale. | ||
|
|
||
| This check keeps the purpose (catch a figure that was not regenerated after a | ||
| code or results change, such as a corrected title) and drops the flake: a | ||
| figure fails if its size changes or if more of its pixels | ||
| move by more than PIXEL_TOLERANCE on any channel than MAX_PIXELS. One changed digit | ||
| in an annotation moves well over a hundred pixels; antialiasing noise moves a few. | ||
|
|
||
| Usage, after the make_figures scripts have run: | ||
| python tools/check_figures.py # compare working tree to HEAD | ||
| python tools/check_figures.py --self-test | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| import subprocess | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from PIL import Image, ImageDraw, ImageFont | ||
|
|
||
| ROOT = Path(__file__).resolve().parents[1] | ||
| PIXEL_TOLERANCE = 16 # out of 255, per channel | ||
| MAX_PIXELS = 25 # a single changed digit in a 10 pt label moves far more | ||
|
|
||
|
|
||
| def _git(*args: str) -> bytes: | ||
| return subprocess.run(["git", *args], cwd=ROOT, check=True, capture_output=True).stdout | ||
|
|
||
|
|
||
| def changed_figures() -> list[str]: | ||
| out = _git("diff", "--name-only", "--", "*/figures/*.png").decode().split() | ||
| untracked = _git("ls-files", "--others", "--exclude-standard", "--", "*/figures/*.png") | ||
| return sorted(set(out) | set(untracked.decode().split())) | ||
|
|
||
|
|
||
| def compare(old: Image.Image, new: Image.Image) -> tuple[bool, str]: | ||
| if old.size != new.size: | ||
| return False, f"size {old.size} -> {new.size}" | ||
| a = np.asarray(old.convert("RGBA"), dtype=np.int16) | ||
| b = np.asarray(new.convert("RGBA"), dtype=np.int16) | ||
| moved = (np.abs(a - b).max(axis=2) > PIXEL_TOLERANCE) | ||
| frac = float(moved.mean()) | ||
| return int(moved.sum()) <= MAX_PIXELS, f"{int(moved.sum())} pixels moved ({frac:.4%})" | ||
|
|
||
|
|
||
| def check() -> int: | ||
| failures = [] | ||
| for rel in changed_figures(): | ||
| new = Image.open(ROOT / rel) | ||
| try: | ||
| old = Image.open(io.BytesIO(_git("show", f"HEAD:{rel}"))) | ||
| except subprocess.CalledProcessError: | ||
| failures.append(f"{rel}: not committed") | ||
| continue | ||
| ok, detail = compare(old, new) | ||
| print(f"{'ok ' if ok else 'FAIL'} {rel}: bytes differ, {detail}") | ||
| if not ok: | ||
| failures.append(rel) | ||
| if failures: | ||
| print("\nFigures in the repo do not match the code. Regenerate and commit:") | ||
| for f in failures: | ||
| print(f" {f}") | ||
| return 1 | ||
| print("figures match the code (byte-identical or within rendering noise)") | ||
| return 0 | ||
|
|
||
|
|
||
| def self_test() -> int: | ||
| title = ImageFont.load_default(size=28) # about a 13.5 pt title at 150 dpi | ||
| label = ImageFont.load_default(size=20) # about a 10 pt annotation | ||
|
|
||
| def draw(title_text: str, label_text: str) -> Image.Image: | ||
| img = Image.new("RGB", (1400, 800), "white") | ||
| d = ImageDraw.Draw(img) | ||
| d.text((100, 50), title_text, fill="black", font=title) | ||
| d.text((600, 400), label_text, fill="black", font=label) | ||
| return img | ||
|
|
||
| base = draw("Original title", "$1,234/yr spread") | ||
| noisy = base.copy() | ||
| noisy.putpixel((10, 10), (240, 240, 240)) | ||
| cases = [ | ||
| ("identical", base, True), | ||
| ("one faint pixel", noisy, True), | ||
| ("changed title", draw("Corrected title text", "$1,234/yr spread"), False), | ||
| ("one digit swapped in a label", draw("Original title", "$1,243/yr spread"), False), | ||
| ("changed size", base.resize((1401, 800)), False), | ||
| ] | ||
| for name, img, want in cases: | ||
| print(f" {name}: {compare(base, img)[1]}") | ||
| bad = [name for name, img, want in cases if compare(base, img)[0] != want] | ||
| print("figure check self-test:", "passed" if not bad else f"FAILED on {bad}") | ||
| return 1 if bad else 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(self_test() if "--self-test" in sys.argv else check()) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a contributor stages regenerated PNGs before running this documented checker,
git diffcompares the worktree to the index, whilegit ls-files --othersomits staged files.changed_figures()can therefore be empty and the check falsely succeeds without inspecting the staged image. CI currently runs from a clean checkout, but the local check should include staged changes when comparing againstHEAD.Useful? React with 👍 / 👎.