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
34 changes: 32 additions & 2 deletions backend/scripts/x_post_candidates.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
pwc-cron x_post_candidates list
One JSON object on stdout: {"generated_at", "candidates": [...]}.
Each candidate has kind, subject_key, draft, link, facts, score,
screenshot_url, and image_png_base64 (a chart card, or null).
screenshot_url, image_png_base64 (a chart card, or null) and
extra_images_png_base64 (more images for the same post; the
roundups carry one page-one card per paper).

pwc-cron x_post_candidates card --paper-id 1 2
{"cards": {paper_id: base64 PNG or null}}: the 2:3 page-one card
for single-paper posts; null without an arXiv PDF.

pwc-cron x_post_candidates record --kind new_sota --subject-key K \
--post-id 123 [--reply-id 456]
Expand All @@ -32,8 +38,16 @@
import json
from datetime import UTC, datetime

from sqlalchemy import select

from backend.database.connection import get_database_session
from backend.services.x_post_candidates import KINDS, gather, record
from backend.models.database import Paper
from backend.services.x_post_candidates import (
KINDS,
gather,
paper_page_card,
record,
)
from backend.services.x_post_requests import (
RESOLUTIONS,
requested_candidates,
Expand All @@ -58,6 +72,10 @@ def main() -> int:
record_parser.add_argument("--post-id", required=True)
record_parser.add_argument("--reply-id")
commands.add_parser("requests", help="Print open Tweet it requests as JSON")
card_parser = commands.add_parser(
"card", help="Print page-one PNG cards for single-paper posts as JSON"
)
card_parser.add_argument("--paper-id", type=int, nargs="+", required=True)
resolve_parser = commands.add_parser("resolve-request", help="Close a request")
resolve_parser.add_argument("--paper-id", type=int, required=True)
resolve_parser.add_argument("--resolution", choices=RESOLUTIONS, required=True)
Expand All @@ -76,8 +94,20 @@ def main() -> int:
if candidate.image
else None
)
item["extra_images_png_base64"] = [
base64.b64encode(image).decode() for image in candidate.extra_images
]
candidates.append(item)
output = {"generated_at": now.isoformat(), "candidates": candidates}
elif args.command == "card":
papers = db.scalars(select(Paper).where(Paper.id.in_(args.paper_id)))
cards = {str(paper.id): paper_page_card(db, paper) for paper in papers}
output = {
"cards": {
paper_id: base64.b64encode(card).decode() if card else None
for paper_id, card in cards.items()
}
}
elif args.command == "requests":
output = {"requests": requested_candidates(db)}
elif args.command == "resolve-request":
Expand Down
164 changes: 159 additions & 5 deletions backend/services/x_insight_cards.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
"""Image cards attached to Papers with Code insight posts on X.

Two layouts, both 1200x675 (X's 16:9 preview), built on the brand frame
(`backend/services/brand.py`, `pwc-brand` skill): a horizontal bar chart for
leaderboards and trend scores, and a ranked list for top papers.
Built on the brand frame (`backend/services/brand.py`, `pwc-brand` skill):
two 1200x675 layouts (X's 16:9 preview), a horizontal bar chart for
leaderboards and trend scores and a ranked list for top papers, and a 1600x2400
card that shows page one of a paper's PDF, for multi-image roundups.
"""

from __future__ import annotations

import io
import re
from dataclasses import dataclass

from PIL import Image
import fitz
from PIL import Image, ImageDraw, ImageFont

from backend.services.brand import LIGHT, fit_text, font, frame, wrap_text
from backend.services.brand import (
LIGHT,
draw_tracked,
fit_text,
font,
frame,
tracked_length,
wrap_text,
)

SIZE = (1200, 675)
P = LIGHT
Expand Down Expand Up @@ -96,3 +107,146 @@ def render_list_card(
):
draw.text((margin + 56, y + offset * 32), line, font=item_font, fill=P.ink)
return _png(card.image)


PAGE_CARD_SIZE = (1600, 2400)
_INTRODUCTION = re.compile(r"^\s*(1\.?\s*)?Introduction\b", re.IGNORECASE)
_MARGINALIA = re.compile(r"^\s*(\d+|[∗*†].*)\s*$")


def _first_page_hero(pdf: bytes, width: int, height: int) -> Image.Image:
"""Page one from the title down to the introduction, `width` pixels wide.

A short hero runs on into the page, up to `height`, and fades out."""
with fitz.open(stream=pdf, filetype="pdf") as document:
if document.page_count == 0:
raise ValueError("PDF has no pages")
page = document[0]
blocks = [b for b in page.get_text("blocks") if b[2] > page.rect.width * 0.1]
body = [
b
for b in blocks
if not _MARGINALIA.match(b[4].split("\n")[0])
and b[1] < page.rect.height * 0.9
]
if not body:
raise ValueError("PDF page one has no text")
intro = [b for b in blocks if _INTRODUCTION.match(b[4])]
left = max(min(b[0] for b in body) - 10, 0)
top = max(min(b[1] for b in body) - 10, 0)
bottom = max(b[3] for b in body) + 8
end = intro[0][1] - 8 if intro else bottom
fill = top + (page.rect.width - 2 * left) * height / width
faded = fill > end and bottom > end
if faded:
end = min(fill, bottom)
clip = fitz.Rect(left, top, page.rect.width - left, end)
zoom = width * 2 / clip.width
pixmap = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), clip=clip)
image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)
image = image.resize((width, round(image.height / 2)), Image.LANCZOS)
if faded and bottom > end:
fade = round(width * 0.12)
mask = Image.linear_gradient("L").resize((width, fade))
image.paste(
(255, 255, 255), (0, image.height - fade, width, image.height), mask
)
return image


def _fit_sentences(
draw: ImageDraw.ImageDraw,
text: str,
font_: ImageFont.FreeTypeFont,
width: int,
lines: int,
) -> list[str]:
sentences = re.split(r"(?<=[.!?])\s+", " ".join(text.split()))
for count in range(len(sentences), 0, -1):
wrapped = wrap_text(draw, " ".join(sentences[:count]), font_, width, lines + 1)
if len(wrapped) <= lines:
return wrapped
return wrap_text(draw, sentences[0], font_, width, lines)


def render_paper_page_card(
pdf: bytes,
*,
title: str,
subtitle: str,
eyebrow: str,
counter: str,
source: str,
summary: str,
) -> bytes:
"""A 2:3 card that shows page one of a paper's PDF with a why-read-it line."""
width = PAGE_CARD_SIZE[0]
card = frame(
PAGE_CARD_SIZE,
title=title,
subtitle=subtitle,
eyebrow=eyebrow,
palette=P,
title_size=40,
title_lines=2,
)
draw, px, margin = card.draw, card.px, card.margin
counter_font = font("mono", px(17), 500)
counter_width = tracked_length(draw, counter, font=counter_font, tracking=0.12)
draw_tracked(
draw,
(width - margin - counter_width, px(56)),
counter,
font=counter_font,
fill=P.ink_faint,
tracking=0.12,
)

summary_font = font("sans", px(19))
lines = _fit_sentences(draw, summary, summary_font, width - 2 * margin, 4)
line_height = round(summary_font.size * 1.45)
summary_top = card.bottom - len(lines) * line_height - px(34)
draw_tracked(
draw,
(margin, summary_top),
"WHY READ IT",
font=font("mono", px(14), 500),
fill=P.accent,
tracking=0.12,
)
for index, line in enumerate(lines):
draw.text(
(margin, summary_top + px(34) + index * line_height),
line,
font=summary_font,
fill=P.ink,
)

pad = px(14)
sheet_top = card.top
inner_width = width - 2 * margin - 2 * pad
inner_height = summary_top - px(64) - sheet_top - 2 * pad
page = _first_page_hero(pdf, inner_width, inner_height)
if page.height > inner_height:
page = page.resize(
(round(page.width * inner_height / page.height), inner_height),
Image.LANCZOS,
)
sheet_bottom = sheet_top + page.height + 2 * pad
draw.rounded_rectangle(
(margin, sheet_top, width - margin, sheet_bottom),
radius=px(8),
fill=(255, 255, 255),
outline=P.hairline_strong,
width=2,
)
card.image.paste(
page, (margin + pad + (inner_width - page.width) // 2, sheet_top + pad)
)
draw.text(
(margin, sheet_bottom + px(10)),
source,
font=font("mono", px(13)),
fill=P.ink_faint,
)
return _png(card.image)
8 changes: 7 additions & 1 deletion backend/services/x_insight_post_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ def top_papers(db: Session, *, period: str, now: datetime) -> Insight | None:
return None
labels = [paper_label(paper.title) for paper in papers]
text = compose_list(f"{heading} on Papers with Code:", labels)
listed = len(re.findall(r"^\d+\. ", text, re.MULTILINE))
return Insight(
kind=kind,
subject_key=subject,
Expand All @@ -177,7 +178,12 @@ def top_papers(db: Session, *, period: str, now: datetime) -> Insight | None:
[" ".join(paper.title.split()) for paper in papers],
eyebrow=f"Top papers · {'weekly' if period == 'week' else 'monthly'}",
),
facts={"papers": [paper.title for paper in papers], "period": span},
facts={
"papers": [paper.title for paper in papers],
"paper_ids": [paper.id for paper in papers[:listed]],
"heading": heading,
"period": span,
},
)


Expand Down
Loading
Loading