diff --git a/package.json b/package.json index 2f4eb2c..3d608fe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "2026.es.pycon.org", - "version": "1.17.30", + "version": "1.17.31", "description": "", "main": "index.js", "scripts": { @@ -9,6 +9,7 @@ "build": "astro build", "preview": "astro preview", "format": "prettier --write src", + "generate:programa-pdf": "node scripts/generate-programa-pdf.mjs", "prepare": "husky" }, "keywords": [], diff --git a/public/programa-pycones-2026.pdf b/public/programa-pycones-2026.pdf index d76bb1d..1f3a9fd 100644 Binary files a/public/programa-pycones-2026.pdf and b/public/programa-pycones-2026.pdf differ diff --git a/scripts/generate-programa-pdf.mjs b/scripts/generate-programa-pdf.mjs new file mode 100644 index 0000000..8bd33d8 --- /dev/null +++ b/scripts/generate-programa-pdf.mjs @@ -0,0 +1,354 @@ +#!/usr/bin/env node +/** + * Generates public/programa-pycones-2026.pdf from the Pretalx schedule. + * + * Usage: + * node scripts/generate-programa-pdf.mjs [--out ] [--dry-run] [--html ] + * + * The output mirrors the design of the previous artefact: one A4 landscape + * page per conference day, one column per room, cards with the track colour + * and full width bars for the accreditation window and the breaks. + * + * The vertical axis is proportional to real time, so card heights reflect + * session durations. Each page is scaled down (fonts, spacing and timeline + * together) when the day is too dense to fit on a single page, which is what + * the original generator did for the busiest day. + */ + +import { execFile } from 'node:child_process' +import { mkdtemp, readFile, rm, writeFile, mkdir, stat } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' + +import { fetchSchedule, normaliseSchedule, SCHEDULE_URL } from './programa-pdf/schedule.mjs' +import { buildHtmlDocument, buildTrackColors, renderPage, STYLES } from './programa-pdf/template.mjs' +import { evaluateInPage, findChrome } from './programa-pdf/chrome.mjs' + +const execFileAsync = promisify(execFile) + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = resolve(__dirname, '..') +const DEFAULT_OUT = join(REPO_ROOT, 'public', 'programa-pycones-2026.pdf') + +/** + * Pixels per minute of the conference day at scale 1. Combined with the + * available height this defines how dense the programme looks. + */ +const PX_PER_MINUTE = 1.32 +/** Space reserved at the top of every column for the room name. */ +const ROOM_HEAD_HEIGHT = 22 +/** Lower bound for the scale: below this the text stops being legible. */ +const MIN_SCALE = 0.68 +/** + * Minimum height of a card, in pixels, before the typography is scaled + * down. It has to hold the time chip, the title, the speakers and the + * footer. + */ +const MIN_CARD_HEIGHT = 62 + +/** + * How many times the generator re-renders the document to shrink the + * typography of the days whose cards do not fit their content. + */ +const MAX_FIT_ATTEMPTS = 8 + +/** + * Lower bound for the density of the timeline, in pixels per minute. Below + * this the cards of the shortest sessions would be unreadable. + */ +const MIN_DENSITY = 0.55 + +function parseArgs(argv) { + const args = { out: DEFAULT_OUT, dryRun: false, html: null } + for (let i = 0; i < argv.length; i++) { + if (argv[i] === '--out') args.out = resolve(argv[++i]) + else if (argv[i] === '--html') args.html = resolve(argv[++i]) + else if (argv[i] === '--dry-run') args.dryRun = true + } + return args +} + +function formatGeneratedDate(date = new Date()) { + const dd = String(date.getDate()).padStart(2, '0') + const mm = String(date.getMonth() + 1).padStart(2, '0') + return `${dd}/${mm}/${date.getFullYear()}` +} + +const toMin = (t) => { + const [h, m] = t.split(':').map(Number) + return h * 60 + m +} + +/** Returns the first and last time of a day, in minutes since midnight. */ +function daySpan(day) { + const times = [] + for (const s of day.sessions) times.push(toMin(s.start), toMin(s.end)) + for (const b of day.breaks) times.push(toMin(b.start), toMin(b.end)) + return { min: Math.min(...times), max: Math.max(...times) } +} + +/** + * Builds the geometry of a page for a given scale. + * + * `pxPerMinute` maps a minute of the conference day to pixels; the scale + * only affects the typography, so a dense day gets smaller fonts but keeps + * the same proportions. + */ +function buildGeometry(day, scale, pxPerMinute) { + const { min, max } = daySpan(day) + return { + min, + max, + height: (max - min) * pxPerMinute, + roomHeadHeight: ROOM_HEAD_HEIGHT * scale, + // The minimum height of a card is absolute: it is about the content + // fitting, not about the density of the day. + minCardHeight: MIN_CARD_HEIGHT, + pxPerMinute, + yOf: (t) => (toMin(t) - min) * pxPerMinute, + } +} + +/** + * Renders the pages for the given per-day scales. + */ +function renderPages(schedule, trackColors, generatedOn, scales, pxPerMinutes, contentHeights) { + return schedule.days.map((day, i) => { + const scale = scales[i] + const geo = buildGeometry(day, scale, pxPerMinutes[i]) + return renderPage(day, geo, { + version: schedule.version, + generatedOn, + trackColors, + scale, + contentHeights: contentHeights?.[i], + }) + }) +} + +/** + * Measures, in the real browser, the height available for the timeline of + * each page and the room header offset. + */ +const MEASURE_SCRIPT = `(() => { + const pages = [...document.querySelectorAll('.page')] + return pages.map((page) => { + const grid = page.querySelector('.grid') + const roomBody = page.querySelector('.room-body') + const head = page.querySelector('.room-head') + // The bottom of the lowest card of the page: the timeline has to be + // tall enough for it. + let contentBottom = 0 + for (const card of page.querySelectorAll('.card')) { + const bottom = card.getBoundingClientRect().bottom - roomBody.getBoundingClientRect().top + if (bottom > contentBottom) contentBottom = bottom + } + return { + gridHeight: grid ? grid.getBoundingClientRect().height : 0, + roomBodyHeight: roomBody ? roomBody.getBoundingClientRect().height : 0, + roomHeadHeight: head ? head.getBoundingClientRect().height : 0, + contentBottom, + } + }) +})()` + +/** + * Measures the natural height of the content of every card, so the layout + * can give each card the room its title, speakers and footer need. + */ +const CARD_HEIGHTS_SCRIPT = `(() => { + const pages = [...document.querySelectorAll('.page')] + const out = [] + for (const page of pages) { + const heights = [] + for (const card of page.querySelectorAll('.card')) { + const content = card.querySelector('.content') + const foot = card.querySelector('.foot') + if (!content) continue + // The natural height of the title and the speakers: the clone is not + // clipped, so it is as tall as the text needs. + const probe = content.cloneNode(true) + probe.style.position = 'absolute' + probe.style.visibility = 'hidden' + probe.style.height = 'auto' + probe.style.maxHeight = 'none' + probe.style.overflow = 'visible' + probe.style.flex = 'none' + content.parentElement.appendChild(probe) + const natural = probe.getBoundingClientRect().height + probe.remove() + heights.push(natural + (foot ? foot.getBoundingClientRect().height : 0) + 12) + } + out.push(heights) + } + return out +})()` + +async function main() { + const args = parseArgs(process.argv.slice(2)) + + console.log(`[programa-pdf] Fetching ${SCHEDULE_URL}`) + const payload = await fetchSchedule() + const schedule = normaliseSchedule(payload) + const trackColors = buildTrackColors(payload) + + const total = schedule.days.reduce((n, d) => n + d.sessions.length, 0) + console.log( + `[programa-pdf] Pretalx schedule version ${schedule.version} · ${schedule.days.length} day(s) · ${total} session(s)`, + ) + + const generatedOn = formatGeneratedDate() + + const workDir = await mkdtemp(join(tmpdir(), 'programa-pdf-')) + const htmlPath = join(workDir, 'programa.html') + const pdfPath = join(workDir, 'programa.pdf') + + try { + // The generator renders, measures and adjusts in a loop: + // + // 1. The timeline of a day is proportional to real time. + // 2. The slot of a card is always big enough for the title, the + // speakers and the footer of that card. + // 3. The whole day has to fit in the sheet: when it does not, the + // typography is reduced, so the content needs less room and the + // timeline can be compressed to fit. + const scales = schedule.days.map(() => 1) + const pxPerMinutes = schedule.days.map(() => PX_PER_MINUTE) + // The measured height of the content of each card, per day. + const contentHeights = schedule.days.map(() => new Map()) + + for (let attempt = 0; attempt < MAX_FIT_ATTEMPTS; attempt++) { + const pages = renderPages(schedule, trackColors, generatedOn, scales, pxPerMinutes, contentHeights) + await writeFile(htmlPath, buildHtmlDocument(pages, STYLES), 'utf8') + + const measurements = await evaluateInPage(htmlPath, MEASURE_SCRIPT) + const heights = await evaluateInPage(htmlPath, CARD_HEIGHTS_SCRIPT) + if (!Array.isArray(measurements) || !Array.isArray(heights)) { + throw new Error('Could not measure the rendered pages') + } + + let changed = false + + for (let i = 0; i < schedule.days.length; i++) { + const day = schedule.days[i] + const available = measurements[i].roomBodyHeight + + // 1. Measure the height the content of every card needs. + const map = new Map() + let k = 0 + for (const room of day.rooms) { + for (const session of day.sessions.filter((s) => s.room === room)) { + const h = heights[i]?.[k] + k++ + if (h == null) continue + const previous = map.get(session.code) + if (previous == null || Math.abs(previous - h) > 0.5) { + map.set(session.code, h) + changed = true + } + } + } + contentHeights[i] = map + + // 2. The density has to be high enough for the shortest slot of the + // day to hold the content of its card. + let required = 0 + for (const session of day.sessions) { + const needed = map.get(session.code) ?? 0 + const slot = toMin(session.end) - toMin(session.start) + if (slot > 0 && needed / slot > required) required = needed / slot + } + + // 3. The whole day has to fit in the sheet. When the density that + // the content needs is too high, the typography is reduced + // instead, so the content needs less room. + const { min, max } = daySpan(day) + const span = max - min + const maxDensity = available / span + + if (required > maxDensity) { + const factor = maxDensity / required + const next = Math.max(MIN_SCALE, scales[i] * factor) + if (next < scales[i] - 0.004) { + scales[i] = next + changed = true + continue + } + // The typography is at its floor: use the density that fits. + if (maxDensity > pxPerMinutes[i] + 0.005) { + pxPerMinutes[i] = maxDensity + changed = true + } + continue + } + + if (required > pxPerMinutes[i] + 0.005) { + pxPerMinutes[i] = required + changed = true + } + } + + if (!changed) break + } + + for (let i = 0; i < schedule.days.length; i++) { + const day = schedule.days[i] + console.log( + `[programa-pdf] ${day.date} · ${day.rooms.length} room(s) · ${day.sessions.length} session(s) · ${pxPerMinutes[i].toFixed(2)}px per min · scale ${scales[i].toFixed(3)}`, + ) + } + + // Final render with the resulting geometry. + const pages = renderPages(schedule, trackColors, generatedOn, scales, pxPerMinutes, contentHeights) + const html = buildHtmlDocument(pages, STYLES) + await writeFile(htmlPath, html, 'utf8') + + if (args.html) { + await writeFile(args.html, html, 'utf8') + console.log(`[programa-pdf] HTML written to ${args.html}`) + } + + if (args.dryRun) { + console.log('[programa-pdf] Dry run, no PDF generated') + return + } + + const chrome = findChrome() + console.log(`[programa-pdf] Rendering with ${chrome}`) + + await execFileAsync( + chrome, + [ + '--headless', + '--disable-gpu', + '--no-sandbox', + '--no-pdf-header-footer', + '--run-all-compositor-stages-before-draw', + '--virtual-time-budget=15000', + `--print-to-pdf=${pdfPath}`, + `file://${htmlPath}`, + ], + { maxBuffer: 1024 * 1024 * 32 }, + ) + + if (!existsSync(pdfPath)) { + throw new Error('Chrome did not produce a PDF') + } + + await mkdir(dirname(args.out), { recursive: true }) + await writeFile(args.out, await readFile(pdfPath)) + + const { size } = await stat(args.out) + console.log(`[programa-pdf] Wrote ${args.out} (${size} bytes)`) + } finally { + await rm(workDir, { recursive: true, force: true }) + } +} + +main().catch((err) => { + console.error('[programa-pdf] ERROR:', err.message) + process.exit(1) +}) diff --git a/scripts/programa-pdf/README.md b/scripts/programa-pdf/README.md new file mode 100644 index 0000000..2ea6bb5 --- /dev/null +++ b/scripts/programa-pdf/README.md @@ -0,0 +1,79 @@ +# Generador del PDF del programa + +`public/programa-pycones-2026.pdf` es la versión imprimible del programa que +se descarga desde `/es/programa/`. Se genera a partir del schedule export de +Pretalx: + +``` +https://pretalx.com/pycones-2026/schedule/export/schedule.json +``` + +Es el mismo endpoint que usa el sitio (ver `src/lib/schedule.ts`): la API REST +pública de Pretalx (`/api/events//`) no está disponible para este evento. + +## Uso + +```bash +pnpm generate:programa-pdf +``` + +Opciones: + +```bash +node scripts/generate-programa-pdf.mjs --out # otra ruta de salida +node scripts/generate-programa-pdf.mjs --html # guarda también el HTML +node scripts/generate-programa-pdf.mjs --dry-run # no genera el PDF +``` + +Se necesita **Google Chrome** o Chromium instalado. Si no está en las rutas +habituales, se puede indicar con la variable de entorno `CHROME_PATH`: + +```bash +CHROME_PATH=/ruta/a/chrome pnpm generate:programa-pdf +``` + +## Verificación + +```bash +node scripts/verify-programa-pdf.mjs +``` + +Comprueba que el PDF contiene todas las charlas del schedule, las barras de +descanso, la geometría A4 apaisada y los colores de los tracks. Necesita +`pymupdf` en el intérprete de Python: + +```bash +pip install pymupdf +PYTHON=/ruta/a/venv/bin/python node scripts/verify-programa-pdf.mjs +``` + +## Cómo funciona + +El generador reproduce el diseño del PDF anterior: + +- **Una página A4 apaisada por día**, con la cabecera (`PyConES 2026 · ` y + la versión con la fecha de generación), una columna por sala y un gutter con + las horas a la izquierda. +- **Cada charla es una tarjeta** con la franja del color de su track a la + izquierda, la hora de inicio y fin, el badge de idioma, el título, los + ponentes y el nombre del track. +- **Las barras horizontales** marcan la ventana de acreditaciones y las pausas. + Pretalx no las publica como sesiones, así que se deducen de los huecos entre + charlas. Las pausas largas (comida) se distinguen de las cortas (café) y las + sesiones largas que acompañan el programa (el Hackathon) se ignoran al + buscar los huecos. +- **Los colores de los tracks** se leen del propio schedule export, que es + donde Pretalx publica los mismos colores que usa en su widget. + +El eje vertical es proporcional al tiempo real, de forma que la altura de cada +tarjeta refleja la duración de la charla. Como un día más denso no cabe en una +hoja, el generador **renderiza, mide y ajusta** en un bucle: + +1. Mide en el navegador cuánto espacio necesita el contenido de cada tarjeta. +2. Ajusta la densidad de la línea de tiempo para que cada hueco tenga sitio + para su título, sus ponentes y su pie. +3. Si el día entero no cabe en la hoja, reduce la tipografía hasta que todo + el contenido se vea. + +El resultado es un PDF con el mismo aspecto que el anterior, con la tipografía +reducida en los días más densos (como hacía el generador original). diff --git a/scripts/programa-pdf/chrome.mjs b/scripts/programa-pdf/chrome.mjs new file mode 100644 index 0000000..7527709 --- /dev/null +++ b/scripts/programa-pdf/chrome.mjs @@ -0,0 +1,134 @@ +/** + * Minimal Chrome DevTools Protocol client. + * + * The generator needs to measure the real height available for the timeline + * before deciding the scale of each page, so it renders the document once, + * asks the browser for the computed layout and then re-renders with the + * final scale. + */ + +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +export const CHROME_PATHS = [ + process.env.CHROME_PATH, + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + '/usr/bin/google-chrome', + '/usr/bin/google-chrome-stable', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', +].filter(Boolean) + +export function findChrome() { + for (const candidate of CHROME_PATHS) { + if (existsSync(candidate)) return candidate + } + throw new Error('Could not find a Chrome/Chromium binary. Set CHROME_PATH to its location.') +} + +const DEBUG_PORT = 9333 + +/** + * Opens the given HTML file in a headless Chrome instance and evaluates + * `expression` in the page, returning its value. + */ +export async function evaluateInPage(htmlPath, expression, { timeout = 20000 } = {}) { + const chrome = findChrome() + const profileDir = await mkdtemp(join(tmpdir(), 'programa-pdf-profile-')) + + const proc = spawn( + chrome, + [ + '--headless', + '--disable-gpu', + '--no-sandbox', + '--no-first-run', + '--no-default-browser-check', + `--user-data-dir=${profileDir}`, + `--remote-debugging-port=${DEBUG_PORT}`, + '--window-size=1123,794', + 'about:blank', + ], + { stdio: 'ignore' }, + ) + + let target + try { + target = await waitForTarget(timeout) + } catch (err) { + proc.kill() + await rm(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch(() => {}) + throw err + } + + const ws = new WebSocket(target.webSocketDebuggerUrl) + let id = 0 + const pending = new Map() + + ws.onmessage = (event) => { + const msg = JSON.parse(event.data) + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg) + pending.delete(msg.id) + } + } + + await new Promise((resolve, reject) => { + ws.onopen = resolve + ws.onerror = reject + }) + + const send = (method, params = {}) => + new Promise((resolve) => { + const msgId = ++id + pending.set(msgId, resolve) + ws.send(JSON.stringify({ id: msgId, method, params })) + }) + + try { + await send('Page.enable') + await send('Page.navigate', { url: `file://${htmlPath}` }) + await new Promise((r) => setTimeout(r, 1500)) + const res = await send('Runtime.evaluate', { + expression, + returnByValue: true, + }) + if (res.error) throw new Error(res.error.message) + if (res.result?.exceptionDetails) { + throw new Error(res.result.exceptionDetails.text ?? 'Evaluation failed') + } + return res.result?.result?.value + } finally { + try { + ws.close() + } catch { + /* ignore */ + } + proc.kill() + // Chrome may still be writing to its profile directory; a failed cleanup + // must not break the generation. + await rm(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch(() => {}) + } +} + +async function waitForTarget(timeout) { + const deadline = Date.now() + timeout + let lastError + while (Date.now() < deadline) { + try { + const res = await fetch(`http://127.0.0.1:${DEBUG_PORT}/json/list`) + const tabs = await res.json() + const page = tabs.find((t) => t.type === 'page') + if (page) return page + } catch (err) { + lastError = err + } + await new Promise((r) => setTimeout(r, 200)) + } + throw new Error(`Chrome DevTools endpoint did not respond: ${lastError?.message}`) +} diff --git a/scripts/programa-pdf/schedule.mjs b/scripts/programa-pdf/schedule.mjs new file mode 100644 index 0000000..2bbe74b --- /dev/null +++ b/scripts/programa-pdf/schedule.mjs @@ -0,0 +1,256 @@ +/** + * Normalises the Pretalx schedule export into the flat, day-by-day structure + * used by the PDF generator. + * + * Source endpoint: https://pretalx.com/pycones-2026/schedule/export/schedule.json + * This is the same endpoint the website uses (see src/lib/schedule.ts) because + * the public REST API (/api/events//) is not available for this event. + */ + +export const PRETALX_EVENT = 'pycones-2026' +export const SCHEDULE_URL = `https://pretalx.com/${PRETALX_EVENT}/schedule/export/schedule.json` + +/** Fallback for the event timezone if Pretalx stops reporting it. */ +export const FALLBACK_TIMEZONE = 'Europe/Madrid' + +/** + * Start of the accreditation window per weekday. Pretalx does not publish + * accreditation as a session, so the original PDF generator hardcoded these. + * Keyed by ISO date (YYYY-MM-DD). + */ +export const ACCREDITATION_START = { + '2026-11-06': '14:00', + '2026-11-07': '08:30', + '2026-11-08': '09:30', +} + +/** Default accreditation window when the date is unknown: 60 minutes. */ +const DEFAULT_ACCREDITATION_MINUTES = 60 + +/** + * Minimum duration of a gap for it to be shown as a break. Shorter gaps are + * just the transition between two slots of the timetable. + */ +const MIN_BREAK_MINUTES = 20 + +/** + * Session types that run alongside the regular programme for a long time + * (the Hackathon). They are ignored when looking for the free slots of the + * timetable, so the breaks still show up. + */ +const LONG_RUNNING_TYPES = new Set(['Hackathon']) + +/** + * Weekday names, indexed by `Date#getUTCDay()` (0 = Sunday). + */ +const WEEKDAYS_ES = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'] + +const MONTHS_ES = [ + 'enero', + 'febrero', + 'marzo', + 'abril', + 'mayo', + 'junio', + 'julio', + 'agosto', + 'septiembre', + 'octubre', + 'noviembre', + 'diciembre', +] + +/** Formats an ISO date as "Viernes 6 de noviembre de 2026". */ +export function formatDayLabel(isoDate) { + const [y, m, d] = isoDate.split('-').map(Number) + const date = new Date(Date.UTC(y, m - 1, d)) + const weekday = WEEKDAYS_ES[date.getUTCDay()] + const month = MONTHS_ES[m - 1] + return `${weekday} ${d} de ${month} de ${y}` +} + +/** Converts "HH:MM" to minutes since midnight. */ +export function toMinutes(time) { + const [h, m] = time.split(':').map(Number) + return h * 60 + m +} + +/** Converts minutes since midnight back to "HH:MM". */ +export function fromMinutes(minutes) { + const h = Math.floor(minutes / 60) + const m = minutes % 60 + return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}` +} + +function pickRoomOrder(conference, days) { + // Prefer the canonical room order declared by the conference, then append + // any room that only shows up in the day payloads. + const declared = (conference.rooms ?? []).map((r) => r.name) + const seen = new Set() + const ordered = [] + for (const name of declared) { + if (!seen.has(name)) { + seen.add(name) + ordered.push(name) + } + } + for (const day of days) { + for (const name of Object.keys(day.rooms ?? {})) { + if (!seen.has(name)) { + seen.add(name) + ordered.push(name) + } + } + } + return ordered +} + +/** + * Infers the full-width bars (accreditation window, coffee breaks, lunch + * break) that live between sessions. Pretalx does not publish them as + * sessions, but they belong on the printed programme. + */ +function inferBreaks(date, sessions) { + const breaks = [] + if (sessions.length === 0) return breaks + + const sorted = [...sessions].sort((a, b) => toMinutes(a.start) - toMinutes(b.start)) + const firstStart = toMinutes(sorted[0].start) + + // Accreditation window: from the (known or default) accreditation start up + // to the first session of the day. + const accreditationStart = ACCREDITATION_START[date] + const credFrom = accreditationStart + ? toMinutes(accreditationStart) + : firstStart - DEFAULT_ACCREDITATION_MINUTES + if (credFrom < firstStart) { + breaks.push({ + label: 'Acreditaciones', + start: fromMinutes(credFrom), + end: fromMinutes(firstStart), + fullWidth: true, + }) + } + + // Gaps between consecutive sessions. + // + // Long running side events (the Hackathon) span the whole day and would + // otherwise swallow every break, so they are ignored when looking for the + // free slots of the regular programme. + const boundaries = new Set() + for (const s of sorted) { + boundaries.add(toMinutes(s.start)) + boundaries.add(toMinutes(s.end)) + } + const points = [...boundaries].sort((a, b) => a - b) + + for (let i = 0; i < points.length - 1; i++) { + const gapStart = points[i] + const gapEnd = points[i + 1] + const gap = gapEnd - gapStart + // Short gaps are just the transition between two slots of the + // timetable, not a break. + if (gap < MIN_BREAK_MINUTES) continue + + // A regular session overlaps this gap -> it is not a free slot. + const overlapping = sorted.some( + (s) => !LONG_RUNNING_TYPES.has(s.type) && toMinutes(s.start) < gapEnd && toMinutes(s.end) > gapStart, + ) + if (overlapping) continue + + breaks.push({ + label: breakLabel(gapStart, gapEnd, gap), + start: fromMinutes(gapStart), + end: fromMinutes(gapEnd), + fullWidth: true, + }) + } + + return breaks +} + +/** + * Labels a gap between two sessions. Long gaps around midday are lunch, short + * ones are coffee breaks. + */ +function breakLabel(startMin, endMin, gap) { + // Lunch: long gap that starts around midday. + if (gap >= 60 && startMin >= 11 * 60 + 30 && startMin <= 14 * 60) { + return 'Pausa para la comida' + } + if (gap >= 45 && startMin >= 11 * 60 + 30 && startMin <= 14 * 60) { + return 'Pausa para la comida' + } + if (gap <= 45) return 'Pausa para el café' + // Long gaps outside of lunch hours are generic breaks. + return 'Pausa' +} + +/** + * Normalises the raw Pretalx export payload. + */ +export function normaliseSchedule(payload) { + const schedule = payload?.schedule + if (!schedule?.conference) { + throw new Error('Unexpected Pretalx payload: missing schedule.conference') + } + + const conference = schedule.conference + const roomOrder = pickRoomOrder(conference, schedule.conference.days ?? []) + const timezone = conference.time_zone_name || FALLBACK_TIMEZONE + + const days = (conference.days ?? []) + .map((day) => { + const sessions = [] + for (const [room, roomSessions] of Object.entries(day.rooms ?? {})) { + for (const raw of roomSessions) { + sessions.push({ + code: raw.code ?? '', + title: raw.title ?? '', + start: (raw.date ?? '').slice(11, 16), + end: (raw.end ?? '').slice(11, 16), + duration: raw.duration ?? '', + room, + track: raw.track ?? null, + type: raw.type ?? '', + language: (raw.language ?? '').toLowerCase(), + speakers: (raw.persons ?? []).map((p) => p.public_name ?? p.name ?? ''), + }) + } + } + + const date = day.date + const sessionsWithTimes = sessions.filter((s) => s.start && s.end) + const breaks = inferBreaks(date, sessionsWithTimes) + + // Only keep the rooms that actually host something that day, but keep + // the canonical order. + const usedRooms = roomOrder.filter((room) => sessionsWithTimes.some((s) => s.room === room)) + + return { + date, + label: formatDayLabel(date), + rooms: usedRooms, + sessions: sessionsWithTimes.sort( + (a, b) => toMinutes(a.start) - toMinutes(b.start) || a.room.localeCompare(b.room), + ), + breaks, + } + }) + .filter((day) => day.sessions.length > 0) + + return { + version: schedule.version ?? '—', + timezone, + days, + } +} + +/** Downloads the Pretalx schedule export. */ +export async function fetchSchedule(url = SCHEDULE_URL) { + const res = await fetch(url) + if (!res.ok) { + throw new Error(`Pretalx returned ${res.status} for ${url}`) + } + return res.json() +} diff --git a/scripts/programa-pdf/template.mjs b/scripts/programa-pdf/template.mjs new file mode 100644 index 0000000..13ffd77 --- /dev/null +++ b/scripts/programa-pdf/template.mjs @@ -0,0 +1,462 @@ +/** + * HTML/CSS template for the programme PDF. + * + * The layout replicates the design of the original PDF (generated with + * headless Chrome from Pretalx data). Measurements were extracted from the + * previous artefact so the regenerated file keeps the same look: + * + * - A4 landscape (297mm x 210mm), one page per conference day. + * - Header: event title on the left, version + generation date on the right. + * - A time gutter on the left and one column per room. + * - Each session is a card with a coloured left stripe (the track colour), + * a time chip, a language badge, the title, the speakers and the track name. + * - Full width bars mark the accreditation window and the breaks. + * + * The vertical axis is proportional to real time: one minute of the + * conference day maps to a fixed number of pixels, so card heights reflect + * session durations and every day shares a consistent scale. + */ + +const TRACK_FALLBACK_COLOR = '#1d1d1b' + +/** + * Space a card needs on top of its content: the padding of the body and the + * height of the footer with the language badge and the track name. + */ +const CARD_CHROME_HEIGHT = 26 + +/** + * Gap left between a card and the next slot, in pixels, so consecutive + * cards and the break bars do not touch. + */ +const CARD_GAP = 3 + +/** Converts "HH:MM" to minutes since midnight. */ +function toMinutes(time) { + const [h, m] = time.split(':').map(Number) + return h * 60 + m +} + +export function escapeHtml(value) { + return String(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +/** + * Builds the track -> colour map from the Pretalx conference payload. + * These are the exact colours Pretalx uses in its own schedule widget. + */ +export function buildTrackColors(payload) { + const tracks = payload?.schedule?.conference?.tracks ?? [] + const map = new Map() + for (const track of tracks) { + if (track?.name) map.set(track.name, track.color || TRACK_FALLBACK_COLOR) + } + return map +} + +/** Renders the language badge (ES / EN / …). */ +function languageBadge(language) { + const label = language ? language.toUpperCase() : '—' + return `${escapeHtml(label)}` +} + +/** Renders a session card. */ +function sessionCard(session, trackColors) { + const color = (session.track && trackColors.get(session.track)) || TRACK_FALLBACK_COLOR + const speakers = session.speakers.filter(Boolean).join(', ') + const trackLabel = session.track + ? `
${escapeHtml(session.track)}
` + : '' + + return `
+
+ ${escapeHtml(session.start)} + ${escapeHtml(session.end)} +
+
+
+
${escapeHtml(session.title)}
+ ${speakers ? `
${escapeHtml(speakers)}
` : ''} +
+
+ ${languageBadge(session.language)} + ${trackLabel} +
+
+
` +} + +export const STYLES = ` + @page { size: 297mm 210mm; margin: 0; } + * { box-sizing: border-box; } + html, body { + margin: 0; + padding: 0; + background: #ffffff; + color: #1d1d1b; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + } + .page { + width: 297mm; + height: 210mm; + padding: 6.4mm 7.8mm 7mm 7.8mm; + position: relative; + overflow: hidden; + page-break-after: always; + display: flex; + flex-direction: column; + --scale: 1; + } + .page:last-child { page-break-after: auto; } + + .header { + display: flex; + justify-content: space-between; + align-items: baseline; + flex: 0 0 auto; + margin-bottom: 2.2mm; + } + .page-title { + font-size: calc(13pt * var(--scale)); + font-weight: 700; + color: #1d1d1b; + margin: 0; + white-space: nowrap; + } + .meta { + font-size: calc(6.49pt * var(--scale)); + color: #666666; + white-space: nowrap; + } + + .grid { + position: relative; + flex: 1 1 0; + display: flex; + gap: 4.7mm; + padding-left: 8mm; + min-height: 0; + } + .gutter { + position: absolute; + left: 0; + top: 0; + width: 8mm; + height: 100%; + } + .gutter-label { + position: absolute; + left: 0; + transform: translateY(-50%); + font-size: calc(7pt * var(--scale)); + color: #555555; + white-space: nowrap; + } + .columns { + display: flex; + gap: 4.7mm; + flex: 1 1 auto; + min-width: 0; + } + .column { + flex: 1 1 0; + min-width: 0; + position: relative; + } + .room-head { + position: absolute; + top: 0; + left: 0; + right: 0; + z-index: 3; + text-align: center; + font-size: calc(7.5pt * var(--scale)); + font-weight: 700; + color: #1d1d1b; + padding-bottom: 1mm; + border-bottom: 0.8pt solid #1d1d1b; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .room-body { + position: absolute; + top: var(--room-head-height); + left: 0; + right: 0; + bottom: 0; + z-index: 1; + } + .breaks { + position: absolute; + top: var(--room-head-height); + left: 0; + right: 0; + bottom: 0; + z-index: 2; + pointer-events: none; + } + + .card { + position: absolute; + left: 0; + right: 0; + display: flex; + align-items: stretch; + border: 0.75pt solid #cfd3da; + border-radius: 1.4mm; + background: #ffffff; + overflow: hidden; + } + .stripe { + width: 9.4mm; + flex: 0 0 9.4mm; + display: flex; + flex-direction: column; + align-items: center; + padding-top: 0.7mm; + } + .time-start { + font-size: calc(7.5pt * var(--scale)); + font-weight: 700; + color: #ffffff; + line-height: 1.15; + } + .time-end { + font-size: calc(5.5pt * var(--scale)); + font-weight: 700; + color: #ffffff; + opacity: 0.62; + line-height: 1.15; + } + .body { + position: relative; + flex: 1 1 auto; + min-width: 0; + padding: 0.7mm 1.1mm 1mm 1.2mm; + display: flex; + flex-direction: column; + overflow: hidden; + } + /* Holds the title and the speakers; it takes the space that is left + once the footer has been laid out, so nothing ever overlaps. The + title is the part that gives way when the card is too short. */ + .content { + flex: 0 1 auto; + min-height: 0; + overflow: hidden; + display: flex; + flex-direction: column; + } + .title { + font-size: calc(6.8pt * var(--scale)); + font-weight: 700; + color: #1d1d1b; + line-height: 1.28; + overflow: hidden; + overflow-wrap: break-word; + flex: 0 1 auto; + min-height: 0; + } + .speakers { + font-size: calc(6pt * var(--scale)); + font-weight: 400; + color: #444444; + line-height: 1.3; + margin-top: 0.4mm; + overflow: hidden; + overflow-wrap: break-word; + flex: 0 0 auto; + } + .foot { + margin-top: auto; + padding-top: 0.6mm; + display: flex; + align-items: flex-end; + gap: 1.4mm; + min-width: 0; + flex: 0 0 auto; + } + .lang { + flex: 0 0 auto; + display: inline-block; + background: #000000; + color: #ffffff; + font-size: calc(5.5pt * var(--scale)); + font-weight: 700; + border-radius: 0.8mm; + padding: 0.25mm 0.9mm; + line-height: 1.15; + } + .track { + font-size: calc(5.6pt * var(--scale)); + font-weight: 700; + line-height: 1.22; + overflow: hidden; + overflow-wrap: break-word; + } + + .break { + position: absolute; + left: 0; + right: 0; + background: #eef0f3; + border: 0.75pt solid #d3d7de; + border-radius: 1.2mm; + text-align: center; + font-size: calc(7pt * var(--scale)); + font-weight: 700; + color: #1d1d1b; + line-height: 1; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + } +` + +/** + * Computes the vertical geometry of a page: the timeline is proportional to + * real time, so a session card's height reflects its duration. + * + * `roomHeadHeight` is the space reserved at the top of every column for the + * room name; the timeline starts right below it. + */ +/** + * Computes the vertical geometry of a page. + * + * The vertical axis is proportional to real time, so a session card's height + * reflects its duration. Cards also have a minimum height, so the time chip, + * the title and the speakers always fit. + */ +export function buildGeometry(day, pxPerMinute, roomHeadHeight = 22, minCardHeight = 40) { + const toMin = (t) => { + const [h, m] = t.split(':').map(Number) + return h * 60 + m + } + const times = [] + for (const s of day.sessions) times.push(toMin(s.start), toMin(s.end)) + for (const b of day.breaks) times.push(toMin(b.start), toMin(b.end)) + const min = Math.min(...times) + const max = Math.max(...times) + return { + min, + max, + height: (max - min) * pxPerMinute, + roomHeadHeight, + minCardHeight, + pxPerMinute, + yOf: (t) => (toMin(t) - min) * pxPerMinute, + } +} + +/** + * Lays out the cards of a room. + * + * The height of a card is the height of its slot on the timeline, which the + * generator guarantees is big enough for the title, the speakers and the + * footer of the card. A small gap is left between the card and the slot, so + * consecutive cards do not touch. + */ +export function layoutRoom(sessions, geo, contentHeights = new Map()) { + const sorted = [...sessions].sort((a, b) => toMinutes(a.start) - toMinutes(b.start)) + return sorted.map((session) => { + const start = geo.yOf(session.start) + const end = geo.yOf(session.end) + const slot = end - start + const height = Math.max(Math.min(slot, geo.minCardHeight), slot - CARD_GAP) + return { ...session, top: start, height } + }) +} +/** + * Renders one page of the programme. + */ +export function renderPage(day, geo, opts) { + const { version, generatedOn, trackColors, scale = 1, contentHeights } = opts + + const header = `
+
PyConES 2026 · ${escapeHtml(day.label)}
+
Versión ${escapeHtml(version)} · generado el ${escapeHtml( + generatedOn, + )} · Programa siempre actualizado en 2026.es.pycon.org
+
` + + // Time gutter: one label per session start time, plus the break boundaries. + const gutterTimes = new Set() + for (const s of day.sessions) gutterTimes.add(s.start) + for (const b of day.breaks) gutterTimes.add(b.start) + const gutter = [...gutterTimes] + .sort((a, b) => (a < b ? -1 : 1)) + .map((t) => `
${escapeHtml(t)}
`) + .join('\n ') + + // Full width bars. + const bars = day.breaks + .map((b) => { + const top = geo.yOf(b.start) + const height = Math.max(geo.yOf(b.end) - geo.yOf(b.start), 10) + return `
${escapeHtml(b.label)} · ${escapeHtml(b.start)}–${escapeHtml(b.end)}
` + }) + .join('\n ') + + // One column per room; each card is absolutely positioned on the timeline. + const columns = day.rooms + .map((room) => { + const cards = layoutRoom( + day.sessions.filter((s) => s.room === room), + geo, + contentHeights, + ) + .map((s) => sessionCard(s, trackColors)) + .join('\n') + + return `
+
${escapeHtml(room)}
+
+${cards} +
+
` + }) + .join('\n') + + return `
+ ${header} +
+
+ ${gutter} +
+
+${columns} +
+
+ ${bars} +
+
+
` +} + +/** Wraps the rendered pages into a printable HTML document. */ +export function buildHtmlDocument(pages, styles) { + return ` + + + +Programa PyConES 2026 + + + +${pages.join('\n')} + +` +} diff --git a/scripts/verify-programa-pdf.mjs b/scripts/verify-programa-pdf.mjs new file mode 100644 index 0000000..67e6c35 --- /dev/null +++ b/scripts/verify-programa-pdf.mjs @@ -0,0 +1,184 @@ +#!/usr/bin/env node +/** + * Verifies the generated programme PDF against the Pretalx schedule. + * + * Usage: + * node scripts/verify-programa-pdf.mjs [--pdf ] + * + * It checks that every session of the schedule appears in the PDF, that the + * break bars are present, that the track colours match the ones Pretalx + * publishes and that the page geometry is the expected A4 landscape. + * + * Requires `pymupdf` (`pip install pymupdf`). + */ + +import { execFile } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' + +import { fetchSchedule, normaliseSchedule } from './programa-pdf/schedule.mjs' + +const execFileAsync = promisify(execFile) + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = resolve(__dirname, '..') +const DEFAULT_PDF = join(REPO_ROOT, 'public', 'programa-pycones-2026.pdf') + +const A4_LANDSCAPE = { width: 841.92, height: 594.96 } + +function parseArgs(argv) { + const args = { pdf: DEFAULT_PDF } + for (let i = 0; i < argv.length; i++) { + if (argv[i] === '--pdf') args.pdf = resolve(argv[++i]) + } + return args +} + +/** + * Extracts the text of every page with pymupdf. + * + * `PYTHON` can be used to point at a specific interpreter, for example a + * virtualenv that has `pymupdf` installed. + */ +async function extractPages(pdfPath) { + const script = ` +import sys, json +import pymupdf +doc = pymupdf.open(sys.argv[1]) +out = [] +for page in doc: + out.append({ + "text": page.get_text(), + "rect": [page.rect.width, page.rect.height], + "drawings": [ + {"fill": d.get("fill"), "rect": [d["rect"].x0, d["rect"].y0, d["rect"].x1, d["rect"].y1]} + for d in page.get_drawings() + ], + }) +print(json.dumps(out)) +` + const python = process.env.PYTHON || 'python3' + const { stdout } = await execFileAsync(python, ['-c', script, pdfPath], { + maxBuffer: 1024 * 1024 * 64, + }) + return JSON.parse(stdout) +} + +/** Normalises a string so it can be compared (no accents, no punctuation). */ +function normalise(text) { + return text + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[^\p{L}\p{N}]+/gu, ' ') + .toLowerCase() + .trim() +} + +async function main() { + const args = parseArgs(process.argv.slice(2)) + if (!existsSync(args.pdf)) { + throw new Error(`PDF not found: ${args.pdf}`) + } + + console.log('[verify] Fetching the Pretalx schedule') + const payload = await fetchSchedule() + const schedule = normaliseSchedule(payload) + const trackColors = new Map( + (payload?.schedule?.conference?.tracks ?? []).map((t) => [t.name, (t.color ?? '').toLowerCase()]), + ) + + console.log(`[verify] Reading ${args.pdf}`) + const pages = await extractPages(args.pdf) + + const errors = [] + const warnings = [] + + // --- Geometry ----------------------------------------------------------- + if (pages.length !== schedule.days.length) { + errors.push(`Expected ${schedule.days.length} pages, found ${pages.length}`) + } + for (const [i, page] of pages.entries()) { + const [w, h] = page.rect + if (Math.abs(w - A4_LANDSCAPE.width) > 1 || Math.abs(h - A4_LANDSCAPE.height) > 1) { + errors.push( + `Page ${i + 1}: expected A4 landscape (${A4_LANDSCAPE.width}x${A4_LANDSCAPE.height}), found ${w.toFixed(2)}x${h.toFixed(2)}`, + ) + } + } + + // --- Content ------------------------------------------------------------ + const allText = normalise(pages.map((p) => p.text).join(' ')) + + for (const day of schedule.days) { + const dayText = normalise(pages[schedule.days.indexOf(day)]?.text ?? '') + for (const session of day.sessions) { + const title = normalise(session.title) + // A title can be wrapped over several lines, so compare the first + // words and the last words of the title. + const words = title.split(' ').filter(Boolean) + if (words.length === 0) continue + const head = words.slice(0, 3).join(' ') + const tail = words.slice(-2).join(' ') + if (!dayText.includes(head) || !dayText.includes(tail)) { + errors.push(`Missing session on ${day.date}: "${session.title}"`) + } + for (const speaker of session.speakers) { + const name = normalise(speaker) + if (name && !dayText.includes(name)) { + warnings.push(`Speaker not found on ${day.date}: "${speaker}"`) + } + } + } + for (const br of day.breaks) { + const label = normalise(br.label) + if (!dayText.includes(label)) { + errors.push(`Missing break on ${day.date}: ${br.label}`) + } + } + } + + // --- Colours ------------------------------------------------------------ + const usedColors = new Set() + for (const page of pages) { + for (const d of page.drawings) { + if (!d.fill) continue + const hex = + '#' + + d.fill + .map((v) => + Math.round(v * 255) + .toString(16) + .padStart(2, '0'), + ) + .join('') + usedColors.add(hex) + } + } + for (const [name, color] of trackColors) { + if (!usedColors.has(color)) { + warnings.push(`Track colour not found in the PDF: ${name} (${color})`) + } + } + + // --- Report ------------------------------------------------------------- + console.log(`[verify] Pages: ${pages.length}`) + console.log(`[verify] Sessions checked: ${schedule.days.reduce((n, d) => n + d.sessions.length, 0)}`) + console.log(`[verify] Colours found: ${usedColors.size}`) + + for (const w of warnings) console.log(`[verify] WARN ${w}`) + for (const e of errors) console.log(`[verify] ERROR ${e}`) + + if (errors.length > 0) { + console.error(`[verify] Failed with ${errors.length} error(s)`) + process.exit(1) + } + console.log('[verify] OK') +} + +main().catch((err) => { + console.error('[verify] ERROR:', err.message) + process.exit(1) +})