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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@ follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Added: content-aware cropping

Served pages are now trimmed to their content bounds before framing
(`internal/crop`). The default `content-trim` detector removes whitespace
margins and steps over top-bleed printer's marks (registration / CMYK bars,
plate-ident codes) — safely: it only ever removes rows/columns with no content,
so it can never cut into the page. It does **not** yet remove ad or promo
skyboxes above the masthead; the crop seam is built so a smarter top-edge
detector plugs in later.

- On by default. `BROADSHEET_CROP=off` restores full, uncropped pages.
- The applied box is echoed in the `X-Broadsheet-Crop` response header and folded
into the ETag (so a re-crop invalidates caches). A stored per-source
`crop_overrides` box takes precedence over the auto-detector.
- **Behavior change:** existing deployments start serving cropped pages on
upgrade. It's safe (whitespace and printer's-marks only); set
`BROADSHEET_CROP=off` to keep full pages.

### Renamed: paperboy is now broadsheet

The project, module path (`github.com/kelchm/broadsheet`), binaries
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ Everything's an env var:
| `BROADSHEET_WIDTH` | `1600` | Master width — what we cache at. `?w=` resizes down from here. |
| `BROADSHEET_POLL_INTERVAL` | `30m` | How often the background loop checks upstream |
| `BROADSHEET_ARCHIVE_DAYS` | `14` | How many days of editions to keep |
| `BROADSHEET_CROP` | `auto` | `auto` trims each page to its content bounds (safe — whitespace and printer's marks only); `off` serves the full master |
Comment thread
coderabbitai[bot] marked this conversation as resolved.
| `BROADSHEET_ADMIN_TOKEN` | *(unset)* | When set, mutating `/api/v1` calls require `Authorization: Bearer <token>`. Set it before exposing the server beyond a trusted network. |
| `BROADSHEET_LOG_LEVEL` | `info` | `debug` / `info` / `warn` / `error` |

Expand All @@ -161,7 +162,7 @@ Worth knowing: Freedom Forum only keeps about two days live, so the archive fill

## Not done yet

Smart crop. Right now a front page is served whole, exactly as the PDF rasterizes. The plan is to detect each paper's masthead and content edges and frame it automatically. There's a per-source hint field (`CropHints`) carried through for it, but the detector that would use it isn't written.
Skybox removal. Pages are now trimmed to their content bounds automatically (see `BROADSHEET_CROP`) — that safely removes whitespace margins and top-bleed printer's marks. What's still unwritten is cropping away an ad or promo *skybox* above the masthead: that's a semantic call ("this band is an ad, not the paper") that a plain bounds scan can't make, so it needs a text-layer or learned detector. The crop seam's top edge is built to plug one in, and a per-source hint field (`CropHints`) is carried through for it.

## License

Expand Down
8 changes: 8 additions & 0 deletions cmd/broadsheet-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ type envConfig struct {
LogLevel string `env:"BROADSHEET_LOG_LEVEL" envDefault:"info"`
PollInterval time.Duration `env:"BROADSHEET_POLL_INTERVAL" envDefault:"30m"`
ArchiveDays int `env:"BROADSHEET_ARCHIVE_DAYS" envDefault:"14"`
// Crop trims each served page to its content bounds (safe: whitespace and
// printer's marks only). "auto" (default) is on; "off" serves full pages.
Crop string `env:"BROADSHEET_CROP" envDefault:"auto"`
// AdminToken, when set, gates mutating /api/v1 calls behind
// "Authorization: Bearer <token>". Empty = open (trusted-network default).
AdminToken string `env:"BROADSHEET_ADMIN_TOKEN"`
Expand Down Expand Up @@ -82,6 +85,7 @@ func main() {
Width: ec.Width,
PollInterval: ec.PollInterval,
ArchiveDays: ec.ArchiveDays,
DisableCrop: strings.EqualFold(ec.Crop, "off"),
Logger: logger,
})
if err != nil {
Expand Down Expand Up @@ -436,6 +440,10 @@ func writeImageBody(w http.ResponseWriter, res *broadsheet.Result) {
if res.Stale {
w.Header().Set("X-Broadsheet-Stale", "true")
}
if c := res.Crop; !c.IsEffectivelyFull() {
// Normalized crop applied before framing: x,y,w,h (2 decimals).
w.Header().Set("X-Broadsheet-Crop", fmt.Sprintf("%.2f,%.2f,%.2f,%.2f", c.X, c.Y, c.W, c.H))
}
_, _ = w.Write(res.Image) //nolint:gosec // G705: res.Image is server-rendered PNG bytes served as image/png, not user-controlled markup
}

Expand Down
36 changes: 35 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,36 @@ still the source of truth), so it can be added whenever without disruption.
Per-request `?w=` resizes down from the cached master (see [sizing](#sizing));
those per-width outputs are computed per request, not stored.

## Cropping

Cropping tightens a page before it's framed. It runs at serve time on the
decoded master — *after* rendering, *before* [framing](#sizing-and-framing) — so
the master render stays crop-agnostic. That's deliberate: a crop is metadata,
not a new artifact, so changing one never re-renders a PNG; it only mints a new
ETag (the crop identity folds into it, so caches invalidate correctly).

The Phase 1 detector is **content-trim** (`internal/crop`): it finds the
bounding box of ink and trims the blank margins to it. It also steps over a
*leading bleed strip* — the registration marks, CMYK bars, or plate/fold ident
code many press PDFs carry in the extreme-top bleed (the NYT's
`C M Y K … Nxxx,…,Bs-4C,E1`) — but only a band that is provably junk: thin,
faint, high on the page, and separated from the body by a clear whitespace gap.
Every rule is conservative enough that it can never cut real content; the worst
case is that it trims nothing.

What it deliberately does *not* do is remove an ad or promo *skybox* above the
masthead: that is thick content-grade ink, indistinguishable from a headline to
a bounds scan. Deciding "that band is an ad, not the paper" is a semantic call
that needs a text-layer or learned detector — a later phase. The seam is built
for it: the crop's *top edge* is the pluggable axis (a smarter masthead detector
drops in there), while content-trim keeps owning the sides, bottom, and a safe
fallback top.

Resolution order per source: a stored `crop_overrides` box (an operator edit — a
later feature) wins; otherwise the live auto-detector runs. Crop is on by default
(it is safe); `BROADSHEET_CROP=off` serves the full master. The applied box is
echoed in `X-Broadsheet-Crop`.

## HTTP API

Every *device-plane* handler is a pure read over the local archive/cache —
Expand Down Expand Up @@ -254,7 +284,8 @@ The image endpoints take framing params — `?w=` / `?h=` (target size),
`?sources=<ids>`, `?interval=<dur>`, `?phase=<n>`, `?slot=<n>`. Every response
sets `X-Broadsheet-Source`, `-Width`, `-Height`, and `-Days-Old`, plus
`X-Broadsheet-Stale: true` when a slot's source had nothing archived and the next
source with content was substituted. Rotation responses add `X-Broadsheet-Slot`
source with content was substituted, and `X-Broadsheet-Crop: x,y,w,h`
(normalized) when a crop was applied. Rotation responses add `X-Broadsheet-Slot`
and `X-Broadsheet-Next-Change` (seconds until the rotation advances).

`X-Broadsheet-Days-Old` is `floor(now − edition date)` in whole days — elapsed time
Expand Down Expand Up @@ -330,6 +361,7 @@ a TRMNL, a Home Assistant card, and a browser tab.
| `BROADSHEET_WIDTH` | `1600` | Master render width (quality ceiling) |
| `BROADSHEET_POLL_INTERVAL` | `30m` | Reconciler cadence |
| `BROADSHEET_ARCHIVE_DAYS` | `14` | PDF archive retention |
| `BROADSHEET_CROP` | `auto` | Crop stage: `auto` trims each page to its content bounds (safe); `off` serves the full master |
| `BROADSHEET_ADMIN_TOKEN` | *(unset)* | Bearer token gating mutating `/api/v1` calls |
| `BROADSHEET_LOG_LEVEL` | `info` | `debug` / `info` / `warn` / `error` |

Expand Down Expand Up @@ -385,6 +417,8 @@ internal/
archive/ durable PDF store: atomic Put, Newest, prune
render/ MediaType-aware "normalize to master PNG" (wraps rasterize)
rasterize/ PDF -> image (go-fitz / MuPDF)
crop/ content-trim detector: normalized Box + Detector seam

store/ broadsheet.db (SQLite): sources, provider ETags, health events
catalog/ embedded catalog.json: the browsable list of known papers
cache/ legacy state.json reader (one-time import only)
Expand Down
163 changes: 163 additions & 0 deletions internal/crop/crop.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Package crop trims a rendered newspaper front page to a tighter box.
//
// The engine renders every edition to a master-width PNG and then, at serve
// time, applies a crop before framing (see pkg/broadsheet). Crop is metadata,
// not a new artifact: a normalized [Box] is resolved per source/edition and
// applied to the decoded master. The master render stays crop-agnostic, so
// changing a crop never forces a re-render — only a new ETag.
//
// Two layers, mirroring the render/detect split:
//
// - [Detector] inspects a page image and proposes a [Box]. Phase 1 ships one
// detector, [ContentTrim], which is deterministic and provably safe: it
// only ever trims uniform whitespace margins, so it can never cut into
// real content. Smarter detectors (masthead / skybox removal) plug in
// behind the same interface once there's a trustworthy eval to judge them.
//
// - A [Box] is the resolved crop, in normalized coordinates so it's
// independent of the master width. [Box.Apply] realizes it against a
// concrete image.
//
// The package is deliberately independent of internal/source: the engine
// translates source.CropHints into [Hints] at the seam.
package crop

import (
"context"
"image"
"math"
)

// AlgoVersion identifies the auto-detection behavior. It is folded into the
// render ETag so a change to any detector's output invalidates cached crops
// derived from the old behavior. Bump it whenever a detector's geometry
// changes in a way that should re-crop already-cached editions.
const AlgoVersion = "1"

// minSpan is the smallest crop dimension (as a fraction of the image) treated as
// legitimate. Anything smaller is a corrupt/degenerate box, so Clamp collapses
// it to Full() rather than letting Apply emit a sliver crop.
const minSpan = 0.02

// Box is a crop rectangle in normalized coordinates: X, Y, W, H each in [0,1],
// as fractions of the source image's width/height. Normalizing keeps a box
// meaningful across master-width changes and across the master/downscaled
// variants of the same page.
//
// The zero Box has W==0/H==0 and is treated as "no crop" (see IsEffectivelyFull
// / Apply), so a Box that was never set is safe to apply.
type Box struct {
X, Y, W, H float64
}

// Full is the identity box covering the whole image.
func Full() Box { return Box{X: 0, Y: 0, W: 1, H: 1} }

// Clamp returns b with its coordinates constrained to a valid sub-rectangle of
// the unit square. An out-of-range or degenerate box collapses toward Full so
// a bad detector or a malformed override can never produce an empty or
// out-of-bounds crop.
func (b Box) Clamp() Box {
// A non-finite coordinate (a corrupted override, a NaN from bad math) would
// slip past every comparison below, so reject it up front.
for _, v := range [4]float64{b.X, b.Y, b.W, b.H} {
if math.IsNaN(v) || math.IsInf(v, 0) {
return Full()
}
}
if b.W < minSpan || b.H < minSpan {
return Full()
}
x, y, w, h := b.X, b.Y, b.W, b.H
if x < 0 {
w += x // pulling the left edge back in shrinks width
x = 0
}
Comment thread
kelchm marked this conversation as resolved.
if y < 0 {
h += y
y = 0
}
if x > 1 {
x = 1
}
if y > 1 {
y = 1
}
if x+w > 1 {
w = 1 - x
}
if y+h > 1 {
h = 1 - y
}
if w < minSpan || h < minSpan {
return Full()
}
return Box{X: x, Y: y, W: w, H: h}
}

// IsEffectivelyFull reports whether b, once clamped, covers essentially the
// whole image — within eps on every edge. Such a box isn't worth applying
// (the crop would be a no-op or shave a sub-pixel sliver), so callers skip it.
func (b Box) IsEffectivelyFull() bool {
const eps = 0.002 // ~3px on a 1600px master
c := b.Clamp()
return c.X <= eps && c.Y <= eps && c.X+c.W >= 1-eps && c.Y+c.H >= 1-eps
}

// Apply crops img to b (clamped). A box that's effectively full returns img
// unchanged. The returned image shares img's pixel storage where possible
// (image.Image sub-imaging), so callers must not mutate it.
func (b Box) Apply(img image.Image) image.Image {
if b.IsEffectivelyFull() {
return img
}
c := b.Clamp()
bnds := img.Bounds()
iw, ih := bnds.Dx(), bnds.Dy()
x0 := bnds.Min.X + int(c.X*float64(iw)+0.5)
y0 := bnds.Min.Y + int(c.Y*float64(ih)+0.5)
x1 := bnds.Min.X + int((c.X+c.W)*float64(iw)+0.5)
y1 := bnds.Min.Y + int((c.Y+c.H)*float64(ih)+0.5)
// Guard against rounding that collapses the rect.
if x1 <= x0 {
x1 = x0 + 1
}
if y1 <= y0 {
y1 = y0 + 1
}
rect := image.Rect(x0, y0, x1, y1).Intersect(bnds)
if sub, ok := img.(interface {
SubImage(image.Rectangle) image.Image
}); ok {
return sub.SubImage(rect)
}
// Fallback for images without SubImage: copy the region.
dst := image.NewNRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy()))
for y := rect.Min.Y; y < rect.Max.Y; y++ {
for x := rect.Min.X; x < rect.Max.X; x++ {
dst.Set(x-rect.Min.X, y-rect.Min.Y, img.At(x, y))
}
}
return dst
}

// Hints carry per-source detection inputs, translated from source.CropHints at
// the engine seam so this package stays independent of internal/source. Phase
// 1's ContentTrim ignores them; they exist for the masthead/skybox detectors
// that land in later phases.
type Hints struct {
// MastheadText is the visible nameplate string, an OCR/text-layer target.
MastheadText string
// PDFPath is the archived source PDF, for text-layer detectors. May be empty.
PDFPath string
}

// Detector inspects a page image and proposes a crop.
//
// found is false when the detector has no opinion (leave the page uncropped);
// a returned Box is only meaningful when found is true. err is reserved for
// real failures (a detector that shells out, etc.) — "nothing detected" is
// (Full, false, nil), not an error.
type Detector interface {
Detect(ctx context.Context, img image.Image, hints Hints) (box Box, found bool, err error)
}
Loading
Loading