Skip to content

Instantly share code, notes, and snippets.

@jams2
Last active June 20, 2023 16:05
Show Gist options
  • Save jams2/ca0ecc38a48fdf5b90dc377521fc19d2 to your computer and use it in GitHub Desktop.
Save jams2/ca0ecc38a48fdf5b90dc377521fc19d2 to your computer and use it in GitHub Desktop.
Script for generating cropped SVGs and HTML report for Willow
import glob
import io
import os
import sys
from pathlib import Path
from willow import Image
from willow.svg import SvgImage
def get_original_crop_rect(svg_image):
# left, top, right, bottom (not left, top, width, height,
# like viewBox but the same in this case)
return (0, 0, svg_image.image.width, svg_image.image.height)
def main(update=False):
base_dir = Path("tests/images/svg")
original_file_paths = (
Path(x)
for x in glob.iglob(str(base_dir / "originals/**/*-crop-*.svg"), recursive=True)
)
document = """
<html>
<style>
svg { border: 1px solid black; }
</style>
<body style="width: 100vw;">"""
for original_file_path in original_file_paths:
document += "<hr />"
document += str(original_file_path)
document += '<div style="width: 100%;">'
document += '<table><tr><th>Original</th><th>Processed</th></tr><tr>'
with open(original_file_path, "rb") as f:
original_file = Image.open(f)
original = SvgImage.open(original_file)
original_buf = io.BytesIO()
original.image.write(original_buf)
original_buf.seek(0)
document += "<td>"
document += original_buf.read().decode()
document += "</td>"
directive = original_file_path.stem.split("-")[-1]
if directive == "original":
rect = get_original_crop_rect(original)
else:
rect = tuple(int(x) for x in directive.split("_"))
cropped = original.crop(rect)
cropped_buf = io.BytesIO()
cropped.image.write(cropped_buf)
cropped_buf.seek(0)
document += "<td>"
document += cropped_buf.read().decode()
document += "</td></tr></table>"
document += "</div>"
results_file_path = Path(
str(original_file_path).replace("originals", "results")
)
if not results_file_path.exists() or update:
os.makedirs(results_file_path.parent, exist_ok=True)
with open(results_file_path, "wb") as f:
cropped.image.write(f)
document += "</body></html>"
out_path = Path("./svg-report.html")
with open(out_path, "w") as f:
f.write(document)
if __name__ == "__main__":
main(update=len(sys.argv) > 1 and sys.argv[1] == "--update")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment