Spaces:
Sleeping
Sleeping
Download backend/certificates.py from Success-dev/receipter-pro: direct link, hf CLI and curl.
- Browser
- Download file 6.44 kB
-
https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/certificates.py
- Command line
-
hf download hf://spaces/Success-dev/receipter-pro/backend/certificates.py
-
curl -L -o certificates.py https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/certificates.py
6.44 kB
| """ | |
| Per-person certificates: one uploaded image with each recipient's name (or any {Column} text) | |
| drawn onto it, attached to that recipient's copy of a campaign. | |
| The sender places the text by dragging it on the image in the browser; the position arrives | |
| here as fractions of the image's width and height, so it means the same thing at any display | |
| size. The font size is in the image's own pixels. Fonts are the bundled ones in backend/fonts | |
| (the browser loads the same files) or one the sender uploads for this send. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import binascii | |
| import re | |
| from dataclasses import dataclass | |
| from io import BytesIO | |
| from pathlib import Path | |
| from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError | |
| from backend import templating | |
| from backend.email_parts import Attachment, safe_filename | |
| FONTS_DIR = Path(__file__).parent / "fonts" | |
| BUILTIN_FONTS = { | |
| "sans": "DejaVuSans.ttf", | |
| "sans-bold": "DejaVuSans-Bold.ttf", | |
| "serif": "DejaVuSerif.ttf", | |
| "classic": "IMFellEnglishSC-Regular.ttf", | |
| } | |
| MAX_IMAGE_BYTES = 10 * 1024 * 1024 | |
| MAX_FONT_BYTES = 5 * 1024 * 1024 | |
| MAX_SIDE_PX = 8000 | |
| _COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$") | |
| class CertificateSpec: | |
| image: Image.Image | |
| text: str | |
| filename: str | |
| x: float | |
| y: float | |
| font_size: int | |
| color: tuple[int, int, int] | |
| font_bytes: bytes | |
| letter_spacing: int | |
| output: str # "png" or "pdf" | |
| def _b64(value: str | None, what: str) -> bytes: | |
| try: | |
| return base64.b64decode(value or "", validate=True) | |
| except (binascii.Error, ValueError) as exc: | |
| raise ValueError(f"The {what} could not be read") from exc | |
| def parse_spec(raw: dict) -> CertificateSpec: | |
| """Validates the request's certificate settings. Raises ValueError with a message the | |
| sender can act on.""" | |
| image_bytes = _b64(raw.get("image_b64"), "certificate image") | |
| if not image_bytes: | |
| raise ValueError("Choose a certificate image") | |
| if len(image_bytes) > MAX_IMAGE_BYTES: | |
| raise ValueError("The certificate image is larger than 10 MB") | |
| try: | |
| image = Image.open(BytesIO(image_bytes)) | |
| image.load() | |
| except (UnidentifiedImageError, OSError) as exc: | |
| raise ValueError("The certificate image must be a PNG or JPEG") from exc | |
| if max(image.size) > MAX_SIDE_PX: | |
| raise ValueError(f"The certificate image is wider or taller than {MAX_SIDE_PX} pixels") | |
| text = str(raw.get("text") or "").strip() | |
| if not text: | |
| raise ValueError("Say what to write on the certificate, for example {Name}") | |
| if len(text) > 300: | |
| raise ValueError("The certificate text is too long") | |
| try: | |
| x, y = float(raw.get("x", 0.5)), float(raw.get("y", 0.5)) | |
| font_size = int(raw.get("font_size", 64)) | |
| letter_spacing = int(raw.get("letter_spacing", 0)) | |
| except (TypeError, ValueError) as exc: | |
| raise ValueError("The certificate text position is not valid") from exc | |
| if not (0 <= x <= 1 and 0 <= y <= 1): | |
| raise ValueError("Place the text inside the image") | |
| if not 6 <= font_size <= 1000: | |
| raise ValueError("Pick a text size between 6 and 1000") | |
| letter_spacing = max(-50, min(200, letter_spacing)) | |
| color = str(raw.get("color") or "#000000") | |
| if not _COLOR_RE.match(color): | |
| raise ValueError("The text colour must look like #1a2b3c") | |
| font_key = str(raw.get("font") or "sans") | |
| if font_key == "custom": | |
| font_bytes = _b64(raw.get("font_b64"), "font file") | |
| if not font_bytes or len(font_bytes) > MAX_FONT_BYTES: | |
| raise ValueError("Upload a .ttf or .otf font under 5 MB") | |
| elif font_key in BUILTIN_FONTS: | |
| font_bytes = (FONTS_DIR / BUILTIN_FONTS[font_key]).read_bytes() | |
| else: | |
| raise ValueError("Pick one of the listed fonts") | |
| try: | |
| ImageFont.truetype(BytesIO(font_bytes), 12) | |
| except OSError as exc: | |
| raise ValueError("That font file could not be used") from exc | |
| output = "pdf" if raw.get("output") == "pdf" else "png" | |
| filename = str(raw.get("filename") or "Certificate for {Name}").strip() or "Certificate" | |
| return CertificateSpec( | |
| image=image, text=text, filename=filename, x=x, y=y, font_size=font_size, | |
| color=tuple(int(color[i:i + 2], 16) for i in (1, 3, 5)), font_bytes=font_bytes, | |
| letter_spacing=letter_spacing, output=output, | |
| ) | |
| def render(spec: CertificateSpec, text: str) -> bytes: | |
| """Draws `text` centred on (x, y) and returns the finished file's bytes.""" | |
| img = spec.image.convert("RGBA") | |
| draw = ImageDraw.Draw(img) | |
| font = ImageFont.truetype(BytesIO(spec.font_bytes), spec.font_size) | |
| cx, cy = spec.x * img.width, spec.y * img.height | |
| if spec.letter_spacing == 0: | |
| draw.text((cx, cy), text, font=font, fill=spec.color, anchor="mm") | |
| else: | |
| widths = [font.getlength(ch) for ch in text] | |
| total = sum(widths) + spec.letter_spacing * max(0, len(text) - 1) | |
| x = cx - total / 2 | |
| for ch, w in zip(text, widths): | |
| draw.text((x, cy), ch, font=font, fill=spec.color, anchor="lm") | |
| x += w + spec.letter_spacing | |
| buf = BytesIO() | |
| if spec.output == "pdf": | |
| img.convert("RGB").save(buf, "PDF", resolution=150) | |
| else: | |
| img.save(buf, "PNG", optimize=True) | |
| return buf.getvalue() | |
| def text_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> str: | |
| return templating.render(spec.text, row, columns, html=False).strip() | |
| def attachment_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> Attachment: | |
| text = text_for(spec, row, columns) | |
| name = safe_filename(templating.render(spec.filename, row, columns, html=False), "Certificate") | |
| ext = spec.output | |
| return Attachment( | |
| filename=f"{name}.{ext}", | |
| content_type="application/pdf" if ext == "pdf" else "image/png", | |
| data=render(spec, text), | |
| ) | |
| def preview_png(spec: CertificateSpec, text: str, max_width: int = 1400) -> bytes: | |
| """A PNG of the certificate for the composer, scaled down so it loads quickly.""" | |
| png_spec = CertificateSpec(**{**spec.__dict__, "output": "png"}) | |
| img = Image.open(BytesIO(render(png_spec, text))) | |
| if img.width > max_width: | |
| img = img.resize((max_width, round(img.height * max_width / img.width)), Image.LANCZOS) | |
| buf = BytesIO() | |
| img.save(buf, "PNG", optimize=True) | |
| return buf.getvalue() | |