From 5c08f6816d5b4ebe3ec113abacf10f688c9864b1 Mon Sep 17 00:00:00 2001 From: Niels Rogge Date: Mon, 23 Nov 2026 14:23:42 +0000 Subject: [PATCH 1/4] Show page one of each paper's PDF on X roundup and paper cards The weekly and monthly roundups now carry one 1600x2400 card per arXiv paper (up to four, X's limit): page one of the PDF from the title to the introduction on a branded sheet, numbered as in the post, with the TL;DR as a why-read-it line. Candidates gain extra_images, which `list` prints as extra_images_png_base64. A new `card` command renders the same card for single-paper posts so the X agent can use it instead of a page screenshot. Co-Authored-By: Claude Opus 5.5 --- backend/scripts/x_post_candidates.py | 39 ++++- backend/services/x_insight_cards.py | 162 ++++++++++++++++++++- backend/services/x_insight_post_service.py | 7 +- backend/services/x_post_candidates.py | 117 ++++++++++++++- backend/tests/test_x_post_candidates.py | 88 +++++++++++ deploy/cron_launcher.py | 2 +- 6 files changed, 400 insertions(+), 15 deletions(-) diff --git a/backend/scripts/x_post_candidates.py b/backend/scripts/x_post_candidates.py index 0432fb364..b7f990a3e 100644 --- a/backend/scripts/x_post_candidates.py +++ b/backend/scripts/x_post_candidates.py @@ -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 [--rank 3 7] + {"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] @@ -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, @@ -58,6 +72,11 @@ 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) + card_parser.add_argument("--rank", type=int, nargs="*", default=[]) 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) @@ -76,8 +95,24 @@ 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": + ranks = dict(zip(args.paper_id, args.rank)) + papers = db.scalars(select(Paper).where(Paper.id.in_(args.paper_id))) + cards = { + str(paper.id): paper_page_card(db, paper, rank=ranks.get(paper.id)) + 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": diff --git a/backend/services/x_insight_cards.py b/backend/services/x_insight_cards.py index c69d9dbb5..3d5c7090b 100644 --- a/backend/services/x_insight_cards.py +++ b/backend/services/x_insight_cards.py @@ -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 @@ -96,3 +107,144 @@ 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: + 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) diff --git a/backend/services/x_insight_post_service.py b/backend/services/x_insight_post_service.py index 407714f6e..bd7dc37c2 100644 --- a/backend/services/x_insight_post_service.py +++ b/backend/services/x_insight_post_service.py @@ -177,7 +177,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], + "heading": heading, + "period": span, + }, ) diff --git a/backend/services/x_post_candidates.py b/backend/services/x_post_candidates.py index 886489ac5..4cfed15af 100644 --- a/backend/services/x_post_candidates.py +++ b/backend/services/x_post_candidates.py @@ -12,10 +12,12 @@ explainer illustrated by a screenshot of its method page; * ``lab_league`` (weekly): which organizations hold the most first places on active leaderboards; -* ``top_papers_week`` / ``top_papers_month``: the trending roundups. +* ``top_papers_week`` / ``top_papers_month``: the trending roundups, with + one 2:3 card per arXiv paper showing page one of its PDF (X takes four). Each candidate carries a draft, the facts the agent may use, the page link, -and a chart card (PNG bytes) or a page to screenshot. Posted subjects are +and a chart card (PNG bytes, plus extra images for multi-image posts) or a +page to screenshot. Posted subjects are recorded in `x_insight_posts`, as for the scheduled insight posts, so no subject is offered twice. @@ -32,6 +34,8 @@ from datetime import UTC, datetime, timedelta from typing import Any, Callable +import fitz +import httpx from sqlalchemy import func, select from sqlalchemy.orm import Session @@ -56,7 +60,12 @@ from backend.models.database import Method as DBMethod from backend.services.method_service import MethodService from backend.services.paper_service import PaperService -from backend.services.x_insight_cards import Bar, render_bar_card +from backend.services.paper_pdf_text_service import _download_arxiv_pdf +from backend.services.x_insight_cards import ( + Bar, + render_bar_card, + render_paper_page_card, +) from backend.services.x_insight_post_service import ( ROUNDUP_CATCH_UP_DAYS, SITE, @@ -89,6 +98,7 @@ "top_papers_week", "top_papers_month", ) +ROUNDUP_PAGE_CARDS = 4 PAPER_POST_KINDS = ("new_sota", "open_sota", "open_release", "trending_paper") SOTA_LIMIT = 20 SOTA_WINDOW = timedelta(days=7) @@ -141,6 +151,10 @@ def unpostable_board(dataset: Dataset, board: Board) -> str | None: LEAGUE_SIZE = 8 +def _arxiv_pdf(paper: Paper) -> bytes: + return _download_arxiv_pdf(paper.arxiv_id, paper.version) + + @dataclass class Candidate: kind: str @@ -151,6 +165,7 @@ class Candidate: image: bytes | None = None screenshot_url: str | None = None score: float = 0.0 + extra_images: list[bytes] = field(default_factory=list) def to_dict(self) -> dict[str, Any]: return { @@ -780,7 +795,7 @@ def paper_candidate( "leaderboard_results": paper_results(db, paper.id), "paper_url": paper_url(paper), } - lead = organizations[0] if organizations else (authors[0] if authors else None) + lead = paper_lead(organizations, authors) draft = f"{lead} just released a new paper!" if lead else "New paper!" draft += f'\n\n"{paper.title}"' if paper.tldr: @@ -796,6 +811,45 @@ def paper_candidate( ) +def paper_lead(organizations: list[str], authors: list[str]) -> str | None: + return organizations[0] if organizations else (authors[0] if authors else None) + + +def paper_page_card( + db: Session, + paper: Paper, + *, + rank: int | None, + fetch_pdf: Callable[[Paper], bytes] = _arxiv_pdf, +) -> bytes | None: + """The 2:3 page-one card for a single-paper post, or None without an arXiv PDF.""" + if paper.source != "arxiv" or not paper.arxiv_id: + return None + authors = list( + db.scalars( + select(Author.name) + .join(PaperAuthor, PaperAuthor.author_id == Author.id) + .where(PaperAuthor.paper_id == paper.id) + .order_by(PaperAuthor.author_order) + ) + ) + lead = paper_lead([o.name for o in paper.organizations], authors) + try: + return render_paper_page_card( + fetch_pdf(paper), + title=f"New from {lead}" if lead else "New paper", + subtitle=f"Published {paper.date_published:%b %-d, %Y}" + if paper.date_published + else "", + eyebrow="Trending paper" if rank else "Paper", + counter=f"#{rank} this week" if rank else "", + source=f"arxiv.org/abs/{paper.arxiv_id} · page 1 of the PDF", + summary=paper.tldr or paper.abstract or "", + ) + except (httpx.HTTPError, ValueError, fitz.FileDataError): + return None + + def x_threads(db: Session, paper_id: int) -> list[dict[str, Any]]: """The paper's reviewed X threads: quote-post candidates for the agent.""" rows = db.execute( @@ -967,18 +1021,69 @@ def gather( return [candidate for candidate in candidates if candidate is not None] -def _roundup(db: Session, period: str, now: datetime) -> Candidate | None: +def roundup_page_cards( + papers: list[Paper], + *, + heading: str, + span: str, + eyebrow: str, + fetch_pdf: Callable[[Paper], bytes] = _arxiv_pdf, +) -> list[bytes]: + """Page-one cards for the roundup's arXiv papers, numbered as in the post. + + A paper whose PDF cannot be fetched or read is left out.""" + cards = [] + for rank, paper in enumerate(papers, 1): + if paper.source != "arxiv" or not paper.arxiv_id: + continue + try: + pdf = fetch_pdf(paper) + card = render_paper_page_card( + pdf, + title=heading, + subtitle=span, + eyebrow=eyebrow, + counter=f"{rank:02d} / {len(papers):02d}", + source=f"arxiv.org/abs/{paper.arxiv_id} · page 1 of the PDF", + summary=paper.tldr or paper.abstract or "", + ) + except (httpx.HTTPError, ValueError, fitz.FileDataError): + continue + cards.append(card) + if len(cards) == ROUNDUP_PAGE_CARDS: + break + return cards + + +def _roundup( + db: Session, + period: str, + now: datetime, + fetch_pdf: Callable[[Paper], bytes] = _arxiv_pdf, +) -> Candidate | None: insight = top_papers(db, period=period, now=now) if insight is None: return None + ids = insight.facts["paper_ids"] + found = { + paper.id: paper for paper in db.scalars(select(Paper).where(Paper.id.in_(ids))) + } + cards = roundup_page_cards( + [found[paper_id] for paper_id in ids], + heading=insight.facts["heading"], + span=insight.facts["period"], + eyebrow=f"Top papers · {'weekly' if period == 'week' else 'monthly'}", + fetch_pdf=fetch_pdf, + ) return Candidate( insight.kind, insight.subject_key, insight.text, insight.link, insight.facts, - insight.image, + cards[0] if cards else insight.image, score=40, + extra_images=cards[1:], ) diff --git a/backend/tests/test_x_post_candidates.py b/backend/tests/test_x_post_candidates.py index a8d8243ef..337ad3ca0 100644 --- a/backend/tests/test_x_post_candidates.py +++ b/backend/tests/test_x_post_candidates.py @@ -1,11 +1,15 @@ from __future__ import annotations +import io from datetime import UTC, datetime +import fitz import pytest +from PIL import Image from backend.models.database import Dataset, Paper from backend.services import x_post_candidates as service +from backend.services.x_insight_cards import _first_page_hero from backend.services.x_post_candidates import ( Board, Candidate, @@ -433,3 +437,87 @@ def item(paper_id, score): found = [item(1, 9), item(2, 30), item(1, 12), item(3, 5), item(2, 8)] kept = service.best_per_paper(found) assert [(paper.id, c.score) for c, paper in kept] == [(2, 30), (1, 12), (3, 5)] + + +def _pdf(title: str) -> bytes: + with fitz.open() as document: + page = document.new_page() + page.insert_text((72, 90), title, fontsize=20) + page.insert_text((72, 130), "Ada Lovelace, Alan Turing", fontsize=10) + page.insert_text((72, 170), "Abstract. We study a thing.", fontsize=10) + page.insert_text((72, 260), "1", fontsize=12) + page.insert_text((72, 275), "Introduction", fontsize=12) + page.insert_text((72, 290), "Body text that should be faded.", fontsize=10) + return document.tobytes() + + +def test_roundup_page_cards_number_arxiv_papers_as_in_the_post(): + papers = [ + Paper(id=1, source="external", source_url="https://x.test", title="Ext"), + Paper( + id=2, + source="arxiv", + arxiv_id="2611.00002", + title="Two", + tldr="Two is good.", + ), + Paper( + id=3, source="arxiv", arxiv_id="2611.00003", title="Three", tldr="Three." + ), + Paper( + id=4, source="arxiv", arxiv_id="2611.00004", title="Four", abstract="Four." + ), + ] + fetched = [] + + def fetch(paper): + fetched.append(paper.id) + if paper.id == 3: + raise ValueError("arXiv PDF is too large") + return _pdf(paper.title) + + cards = service.roundup_page_cards( + papers, heading="Top", span="Published", eyebrow="Top papers", fetch_pdf=fetch + ) + + assert fetched == [2, 3, 4] + assert len(cards) == 2 + assert Image.open(io.BytesIO(cards[0])).size == (1600, 2400) + + +def test_roundup_page_cards_stop_at_four(): + papers = [ + Paper(id=i, source="arxiv", arxiv_id=f"2611.0000{i}", title=f"P{i}", tldr="T.") + for i in range(1, 7) + ] + cards = service.roundup_page_cards( + papers, heading="Top", span="", eyebrow="", fetch_pdf=lambda p: _pdf(p.title) + ) + assert len(cards) == service.ROUNDUP_PAGE_CARDS + + +class _NoAuthors: + def scalars(self, query): + return [] + + +def test_paper_page_card_needs_an_arxiv_pdf(): + external = Paper(id=1, source="external", source_url="https://x.test", title="Ext") + assert service.paper_page_card(_NoAuthors(), external, rank=1) is None + + +def test_paper_page_card_renders_and_tolerates_a_bad_pdf(): + paper = Paper(id=2, source="arxiv", arxiv_id="2611.00002", title="Two", tldr="T.") + card = service.paper_page_card( + _NoAuthors(), paper, rank=3, fetch_pdf=lambda p: _pdf(p.title) + ) + assert card.startswith(b"\x89PNG") + broken = service.paper_page_card( + _NoAuthors(), paper, rank=3, fetch_pdf=lambda p: b"not a pdf" + ) + assert broken is None + + +def test_page_hero_stops_at_a_split_introduction_heading(): + hero = _first_page_hero(_pdf("Title"), 1000, 1) + assert hero.height > 300 diff --git a/deploy/cron_launcher.py b/deploy/cron_launcher.py index 14eea19ba..ea7131e67 100755 --- a/deploy/cron_launcher.py +++ b/deploy/cron_launcher.py @@ -709,7 +709,7 @@ def lock_name(job: str, spec: Job, extra: list[str]) -> str: "backend.scripts.x_post_candidates", timeout="30m", idempotency=( - "list is read-only; record inserts one x_insight_posts row per " + "list and card are read-only; record inserts one x_insight_posts row per " "posted subject, called once by the X agent after each post; " "requests closes requests for already-posted papers; " "resolve-request closes one x_post_requests row" From c3db9438c9d50c02fd9e80fb49c896265b565712 Mon Sep 17 00:00:00 2001 From: Niels Rogge Date: Mon, 23 Nov 2026 14:24:57 +0000 Subject: [PATCH 2/4] Keep the trending rank off single-paper cards A queued post can go out hours later, when the rank has moved. Co-Authored-By: Claude Opus 5.5 --- backend/scripts/x_post_candidates.py | 9 ++------- backend/services/x_post_candidates.py | 5 ++--- backend/tests/test_x_post_candidates.py | 6 +++--- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/backend/scripts/x_post_candidates.py b/backend/scripts/x_post_candidates.py index b7f990a3e..153c8008f 100644 --- a/backend/scripts/x_post_candidates.py +++ b/backend/scripts/x_post_candidates.py @@ -10,7 +10,7 @@ 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 [--rank 3 7] + 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. @@ -76,7 +76,6 @@ def main() -> int: "card", help="Print page-one PNG cards for single-paper posts as JSON" ) card_parser.add_argument("--paper-id", type=int, nargs="+", required=True) - card_parser.add_argument("--rank", type=int, nargs="*", default=[]) 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) @@ -101,12 +100,8 @@ def main() -> int: candidates.append(item) output = {"generated_at": now.isoformat(), "candidates": candidates} elif args.command == "card": - ranks = dict(zip(args.paper_id, args.rank)) papers = db.scalars(select(Paper).where(Paper.id.in_(args.paper_id))) - cards = { - str(paper.id): paper_page_card(db, paper, rank=ranks.get(paper.id)) - for paper in papers - } + 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 diff --git a/backend/services/x_post_candidates.py b/backend/services/x_post_candidates.py index 4cfed15af..14dd8eb46 100644 --- a/backend/services/x_post_candidates.py +++ b/backend/services/x_post_candidates.py @@ -819,7 +819,6 @@ def paper_page_card( db: Session, paper: Paper, *, - rank: int | None, fetch_pdf: Callable[[Paper], bytes] = _arxiv_pdf, ) -> bytes | None: """The 2:3 page-one card for a single-paper post, or None without an arXiv PDF.""" @@ -841,8 +840,8 @@ def paper_page_card( subtitle=f"Published {paper.date_published:%b %-d, %Y}" if paper.date_published else "", - eyebrow="Trending paper" if rank else "Paper", - counter=f"#{rank} this week" if rank else "", + eyebrow="New paper", + counter="", source=f"arxiv.org/abs/{paper.arxiv_id} · page 1 of the PDF", summary=paper.tldr or paper.abstract or "", ) diff --git a/backend/tests/test_x_post_candidates.py b/backend/tests/test_x_post_candidates.py index 337ad3ca0..3746a4366 100644 --- a/backend/tests/test_x_post_candidates.py +++ b/backend/tests/test_x_post_candidates.py @@ -503,17 +503,17 @@ def scalars(self, query): def test_paper_page_card_needs_an_arxiv_pdf(): external = Paper(id=1, source="external", source_url="https://x.test", title="Ext") - assert service.paper_page_card(_NoAuthors(), external, rank=1) is None + assert service.paper_page_card(_NoAuthors(), external) is None def test_paper_page_card_renders_and_tolerates_a_bad_pdf(): paper = Paper(id=2, source="arxiv", arxiv_id="2611.00002", title="Two", tldr="T.") card = service.paper_page_card( - _NoAuthors(), paper, rank=3, fetch_pdf=lambda p: _pdf(p.title) + _NoAuthors(), paper, fetch_pdf=lambda p: _pdf(p.title) ) assert card.startswith(b"\x89PNG") broken = service.paper_page_card( - _NoAuthors(), paper, rank=3, fetch_pdf=lambda p: b"not a pdf" + _NoAuthors(), paper, fetch_pdf=lambda p: b"not a pdf" ) assert broken is None From 8e13b20f7e4abdca5c10ee9d01c8e1544e1686c0 Mon Sep 17 00:00:00 2001 From: Niels Rogge Date: Mon, 23 Nov 2026 14:29:04 +0000 Subject: [PATCH 3/4] Number roundup cards by the listed papers and skip unreadable PDFs compose_list can drop entries to fit 280 characters, so the card counter now counts only the papers the post lists. A PDF with no pages or any MuPDF error now skips that card instead of failing the whole list run. Co-Authored-By: Claude Opus 5.5 --- backend/services/x_insight_cards.py | 2 ++ backend/services/x_insight_post_service.py | 3 ++- backend/services/x_post_candidates.py | 5 ++--- backend/tests/test_x_insight_post_service.py | 18 ++++++++++++++++++ backend/tests/test_x_post_candidates.py | 10 ++++++++++ 5 files changed, 34 insertions(+), 4 deletions(-) diff --git a/backend/services/x_insight_cards.py b/backend/services/x_insight_cards.py index 3d5c7090b..6619a4a65 100644 --- a/backend/services/x_insight_cards.py +++ b/backend/services/x_insight_cards.py @@ -119,6 +119,8 @@ def _first_page_hero(pdf: bytes, width: int, height: int) -> Image.Image: 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 = [ diff --git a/backend/services/x_insight_post_service.py b/backend/services/x_insight_post_service.py index bd7dc37c2..4f151936d 100644 --- a/backend/services/x_insight_post_service.py +++ b/backend/services/x_insight_post_service.py @@ -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, @@ -179,7 +180,7 @@ def top_papers(db: Session, *, period: str, now: datetime) -> Insight | None: ), facts={ "papers": [paper.title for paper in papers], - "paper_ids": [paper.id for paper in papers], + "paper_ids": [paper.id for paper in papers[:listed]], "heading": heading, "period": span, }, diff --git a/backend/services/x_post_candidates.py b/backend/services/x_post_candidates.py index 14dd8eb46..07924c02c 100644 --- a/backend/services/x_post_candidates.py +++ b/backend/services/x_post_candidates.py @@ -34,7 +34,6 @@ from datetime import UTC, datetime, timedelta from typing import Any, Callable -import fitz import httpx from sqlalchemy import func, select from sqlalchemy.orm import Session @@ -845,7 +844,7 @@ def paper_page_card( source=f"arxiv.org/abs/{paper.arxiv_id} · page 1 of the PDF", summary=paper.tldr or paper.abstract or "", ) - except (httpx.HTTPError, ValueError, fitz.FileDataError): + except (httpx.HTTPError, ValueError, RuntimeError): return None @@ -1046,7 +1045,7 @@ def roundup_page_cards( source=f"arxiv.org/abs/{paper.arxiv_id} · page 1 of the PDF", summary=paper.tldr or paper.abstract or "", ) - except (httpx.HTTPError, ValueError, fitz.FileDataError): + except (httpx.HTTPError, ValueError, RuntimeError): continue cards.append(card) if len(cards) == ROUNDUP_PAGE_CARDS: diff --git a/backend/tests/test_x_insight_post_service.py b/backend/tests/test_x_insight_post_service.py index 13ab7410e..396393e60 100644 --- a/backend/tests/test_x_insight_post_service.py +++ b/backend/tests/test_x_insight_post_service.py @@ -327,3 +327,21 @@ def scalar(self, query): assert not service.sota_posted(CaptureDb(), "191:Pass_1%:7") assert "/_" in captured["sql"] and "/%" in captured["sql"] + + +def test_top_papers_ids_match_the_listed_entries(monkeypatch): + papers = [ + SimpleNamespace( + id=i, + title=f"A rather long paper title about topic number {i} without colon", + ) + for i in range(1, 6) + ] + db = SimpleNamespace(scalars=lambda query: papers) + monkeypatch.setattr(service, "recently_posted", lambda *args, **kwargs: False) + insight = service.top_papers( + db, period="week", now=datetime(2026, 11, 23, 12, tzinfo=UTC) + ) + listed = insight.text.count("\n\n") + assert listed < len(papers) + assert insight.facts["paper_ids"] == [p.id for p in papers[:listed]] diff --git a/backend/tests/test_x_post_candidates.py b/backend/tests/test_x_post_candidates.py index 3746a4366..0061ba92a 100644 --- a/backend/tests/test_x_post_candidates.py +++ b/backend/tests/test_x_post_candidates.py @@ -521,3 +521,13 @@ def test_paper_page_card_renders_and_tolerates_a_bad_pdf(): def test_page_hero_stops_at_a_split_introduction_heading(): hero = _first_page_hero(_pdf("Title"), 1000, 1) assert hero.height > 300 + + +def test_roundup_page_cards_skip_a_pdf_with_no_pages(): + paper = Paper(id=1, source="arxiv", arxiv_id="2611.00001", title="P", tldr="T.") + with fitz.open() as empty: + pdf = empty.tobytes() if empty.page_count else b"%PDF-1.7\n%%EOF" + cards = service.roundup_page_cards( + [paper], heading="Top", span="", eyebrow="", fetch_pdf=lambda p: pdf + ) + assert cards == [] From 10e39b7f688e7be570bba9a3f113ebf813b58d50 Mon Sep 17 00:00:00 2001 From: Niels Rogge Date: Mon, 23 Nov 2026 14:32:31 +0000 Subject: [PATCH 4/4] Test the zero-page PDF check with a real empty document Co-Authored-By: Claude Opus 5.5 --- backend/tests/test_x_post_candidates.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/backend/tests/test_x_post_candidates.py b/backend/tests/test_x_post_candidates.py index 0061ba92a..976a0f910 100644 --- a/backend/tests/test_x_post_candidates.py +++ b/backend/tests/test_x_post_candidates.py @@ -8,6 +8,7 @@ from PIL import Image from backend.models.database import Dataset, Paper +from backend.services import x_insight_cards as cards_module from backend.services import x_post_candidates as service from backend.services.x_insight_cards import _first_page_hero from backend.services.x_post_candidates import ( @@ -523,11 +524,21 @@ def test_page_hero_stops_at_a_split_introduction_heading(): assert hero.height > 300 -def test_roundup_page_cards_skip_a_pdf_with_no_pages(): +def test_roundup_page_cards_skip_a_pdf_with_no_pages(monkeypatch): + empty = fitz.open + monkeypatch.setattr(cards_module.fitz, "open", lambda **kwargs: empty()) paper = Paper(id=1, source="arxiv", arxiv_id="2611.00001", title="P", tldr="T.") - with fitz.open() as empty: - pdf = empty.tobytes() if empty.page_count else b"%PDF-1.7\n%%EOF" cards = service.roundup_page_cards( - [paper], heading="Top", span="", eyebrow="", fetch_pdf=lambda p: pdf + [paper], heading="Top", span="", eyebrow="", fetch_pdf=lambda p: b"%PDF-" + ) + assert cards == [] + with pytest.raises(ValueError, match="no pages"): + _first_page_hero(b"%PDF-", 100, 100) + + +def test_roundup_page_cards_skip_a_malformed_pdf(): + paper = Paper(id=1, source="arxiv", arxiv_id="2611.00001", title="P", tldr="T.") + cards = service.roundup_page_cards( + [paper], heading="Top", span="", eyebrow="", fetch_pdf=lambda p: b"not a pdf" ) assert cards == []