Spaces:
Running on Zero
Running on Zero
Download app/services/watermark.py from cipher-attacks/Dbu-central-bot: direct link, hf CLI and curl.
- Browser
- Download file 5.89 kB
-
https://huggingface.co/spaces/cipher-attacks/Dbu-central-bot/resolve/main/app/services/watermark.py
- Command line
-
hf download hf://spaces/cipher-attacks/Dbu-central-bot/app/services/watermark.py
-
curl -L -o watermark.py https://huggingface.co/spaces/cipher-attacks/Dbu-central-bot/resolve/main/app/services/watermark.py
5.89 kB
| """Stamp every page of a PDF with the official channel link: | |
| * a neat rounded footer pill (clickable link) at the bottom centre | |
| * an optional very faint diagonal brand text in the middle | |
| Handles every page size, crop box and rotation. Latin text only (standard fonts), so no font files needed.""" | |
| import asyncio | |
| import io | |
| import logging | |
| import re | |
| from dataclasses import dataclass | |
| from typing import Optional | |
| log = logging.getLogger(__name__) | |
| MARK_KEY = "/DBUWatermark" # written into the PDF metadata so a file is never stamped twice | |
| BLUE = (0.10, 0.30, 0.60) | |
| class Style: | |
| text: str | |
| url: str | |
| diagonal: bool = True | |
| def footer(self) -> str: | |
| return f"{self.text} | {display_url(self.url)}" | |
| def display_url(url: str) -> str: | |
| return re.sub(r"^https?://", "", url).rstrip("/") | |
| # ------------------------------------------------ geometry (pure, tested) | |
| def display_size(w: float, h: float, rotation: int) -> tuple[float, float]: | |
| return (h, w) if rotation % 360 in (90, 270) else (w, h) | |
| def to_page_space(dx: float, dy: float, w: float, h: float, rotation: int) -> tuple[float, float]: | |
| """A point in what the reader SEES (origin bottom-left of the displayed page) -> the page's own | |
| unrotated coordinates. w,h = unrotated size.""" | |
| r = rotation % 360 | |
| if r == 90: | |
| return w - dy, dx | |
| if r == 180: | |
| return w - dx, h - dy | |
| if r == 270: | |
| return dy, h - dx | |
| return dx, dy | |
| def rect_to_page_space(x0: float, y0: float, x1: float, y1: float, w: float, h: float, rotation: int): | |
| a = to_page_space(x0, y0, w, h, rotation) | |
| b = to_page_space(x1, y1, w, h, rotation) | |
| return (min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1])) | |
| def footer_geometry(text_width: float, dw: float, size: float) -> tuple[float, float, float, float]: | |
| """Display-space rectangle of the footer pill: (x0, y0, x1, y1).""" | |
| half = text_width / 2 + 9 | |
| y0 = 12.0 | |
| return dw / 2 - half, y0, dw / 2 + half, y0 + size + 9 | |
| # ------------------------------------------------ drawing | |
| def _overlay(w: float, h: float, left: float, bottom: float, rotation: int, style: Style) -> tuple[bytes, tuple]: | |
| from reportlab.pdfbase.pdfmetrics import stringWidth | |
| from reportlab.pdfgen import canvas | |
| buf = io.BytesIO() | |
| c = canvas.Canvas(buf, pagesize=(left + w, bottom + h)) | |
| dw, dh = display_size(w, h, rotation) | |
| size = max(6.5, min(9.5, dw / 62)) | |
| font = "Helvetica-Bold" | |
| text_w = stringWidth(style.footer, font, size) | |
| x0, y0, x1, y1 = footer_geometry(text_w, dw, size) | |
| def at(dx: float, dy: float, theta: float, draw) -> None: | |
| x, y = to_page_space(dx, dy, w, h, rotation) | |
| c.saveState() | |
| c.translate(left + x, bottom + y) | |
| c.rotate(theta + rotation) # keep the text upright for the reader, whatever /Rotate says | |
| draw() | |
| c.restoreState() | |
| if style.diagonal: | |
| big = max(24, min(dw, dh) / 8) | |
| def diagonal() -> None: | |
| c.setFont(font, big) | |
| c.setFillColorRGB(*BLUE, 0.06) | |
| c.drawCentredString(0, 0, style.text) | |
| at(dw / 2, dh / 2, 38, diagonal) | |
| def pill() -> None: | |
| c.setFillColorRGB(1, 1, 1, 0.88) | |
| c.setStrokeColorRGB(*BLUE, 0.35) | |
| c.setLineWidth(0.6) | |
| c.roundRect(-(x1 - x0) / 2, -4.5, x1 - x0, size + 9, 5, stroke=1, fill=1) | |
| c.setFillColorRGB(*BLUE, 0.95) | |
| c.setFont(font, size) | |
| c.drawCentredString(0, 0, style.footer) | |
| at(dw / 2, y0 + 4.5, 0, pill) | |
| c.showPage() | |
| c.save() | |
| rx0, ry0, rx1, ry1 = rect_to_page_space(x0, y0, x1, y1, w, h, rotation) | |
| return buf.getvalue(), (left + rx0, bottom + ry0, left + rx1, bottom + ry1) | |
| def stamp_pdf(data: bytes, style: Style) -> bytes: | |
| """Return the stamped PDF. Raises on anything unexpected (the caller then keeps the original).""" | |
| from pypdf import PdfReader, PdfWriter | |
| from pypdf.annotations import Link | |
| reader = PdfReader(io.BytesIO(data)) | |
| if reader.is_encrypted and not reader.decrypt(""): | |
| raise ValueError("the PDF is password protected") | |
| if reader.metadata and MARK_KEY in reader.metadata: | |
| raise ValueError("already stamped") | |
| pages = len(reader.pages) | |
| if pages == 0: | |
| raise ValueError("the PDF has no pages") | |
| writer = PdfWriter(clone_from=reader) | |
| cache: dict = {} | |
| for i, page in enumerate(writer.pages): | |
| box = page.cropbox # what viewers actually show | |
| w, h = float(box.width), float(box.height) | |
| key = (round(w, 1), round(h, 1), round(float(box.left), 1), round(float(box.bottom), 1), page.rotation % 360) | |
| if key not in cache: | |
| cache[key] = _overlay(w, h, float(box.left), float(box.bottom), page.rotation % 360, style) | |
| overlay_bytes, link_rect = cache[key] | |
| page.merge_page(PdfReader(io.BytesIO(overlay_bytes)).pages[0]) | |
| writer.add_annotation(page_number=i, annotation=Link(rect=link_rect, url=style.url)) | |
| writer.add_metadata({MARK_KEY: style.url}) | |
| out = io.BytesIO() | |
| writer.write(out) | |
| result = out.getvalue() | |
| if len(PdfReader(io.BytesIO(result)).pages) != pages: # paranoia: never ship a broken file | |
| raise ValueError("page count changed while stamping") | |
| return result | |
| async def stamp(data: bytes, style: Style) -> tuple[Optional[bytes], str]: | |
| """(stamped bytes or None, reason when None). Heavy work runs in a thread.""" | |
| try: | |
| return await asyncio.to_thread(stamp_pdf, data, style), "" | |
| except Exception as exc: | |
| log.info("Watermark skipped: %r", exc) | |
| return None, str(exc)[:120] or type(exc).__name__ | |
| def current_style() -> Style: | |
| from app.config import get_settings | |
| cfg = get_settings() | |
| return Style(text=cfg.watermark_text, url=cfg.watermark_link, diagonal=cfg.watermark_diagonal) | |