File size: 7,740 Bytes
557f178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""Assemble the final report from authored text and remote figures; no analysis.

Usage: research-paper/bin/python code/build_report.py outputs/report_source.json
Optional second path writes a private layout preview instead of the final PDF.

The source is an object with title, subtitle, date and 4-5 pages. Each page is a
list of blocks: paragraph, heading, figure, model_table, callout or references.
Scientific numbers and figures must already exist in the remote results.
"""
from pathlib import Path
import json
import re
import sys
from xml.sax.saxutils import escape

from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, PageBreak, Image, Table, TableStyle,
    KeepTogether,
)
from reportlab.lib.utils import ImageReader
from pypdf import PdfReader


ROOT = Path(__file__).resolve().parents[1]
FONT_DIR = Path('/System/Library/Fonts/Supplemental')
INK = colors.HexColor('#162b39')
MUTED = colors.HexColor('#536570')
ACCENT = colors.HexColor('#176979')
PALE = colors.HexColor('#edf4f4')
RULE = colors.HexColor('#c8d6d9')

for name, filename in (
    ('Body', 'Arial.ttf'), ('BodyBold', 'Arial Bold.ttf'),
    ('BodyItalic', 'Arial Italic.ttf'), ('Title', 'Georgia.ttf'),
    ('TitleBold', 'Georgia Bold.ttf'),
):
    pdfmetrics.registerFont(TTFont(name, str(FONT_DIR / filename)))
pdfmetrics.registerFontFamily(
    'Body', normal='Body', bold='BodyBold', italic='BodyItalic', boldItalic='BodyBold'
)

STYLES = {
    'body': ParagraphStyle('body', fontName='Body', fontSize=10.4, leading=14.5,
                           textColor=INK, spaceAfter=8, alignment=TA_LEFT),
    'heading': ParagraphStyle('heading', fontName='TitleBold', fontSize=15.5,
                              leading=19, textColor=INK, spaceBefore=12, spaceAfter=8),
    'small': ParagraphStyle('small', fontName='Body', fontSize=8.4, leading=11.5,
                            textColor=MUTED, spaceAfter=6),
    'caption': ParagraphStyle('caption', fontName='Body', fontSize=8.5, leading=11.5,
                              textColor=MUTED, spaceBefore=5, spaceAfter=11),
    'callout': ParagraphStyle('callout', fontName='Body', fontSize=10.3, leading=14.5,
                              textColor=INK),
    'table': ParagraphStyle('table', fontName='Body', fontSize=8.7, leading=12,
                            textColor=INK),
    'title': ParagraphStyle('title', fontName='Title', fontSize=32, leading=38,
                            textColor=INK, spaceAfter=8),
    'subtitle': ParagraphStyle('subtitle', fontName='Body', fontSize=14, leading=19,
                               textColor=ACCENT, spaceAfter=13),
    'meta': ParagraphStyle('meta', fontName='Body', fontSize=8, leading=11,
                           textColor=MUTED, spaceAfter=14),
}


def rich(text):
    text = str(text).replace('\u2011', '-').replace('\u2013', '-').replace('\u2014', '-')
    text = escape(text)
    text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)
    text = re.sub(r'\[([^\]]+)\]\((https?://[^\s)]+)\)',
                  r'<link href="\2" color="#176979">\1</link>', text)
    return text


def para(text, kind='body'):
    return Paragraph(rich(text), STYLES[kind])


def block_flowables(block, width):
    kind = block['type']
    if kind in ('paragraph', 'heading'):
        return [para(block['text'], 'body' if kind == 'paragraph' else 'heading')]
    if kind == 'figure':
        path = ROOT / block['path']
        iw, ih = ImageReader(str(path)).getSize()
        scale = min(width / iw, block.get('max_height', 245) / ih)
        return [KeepTogether([
            Image(str(path), width=iw * scale, height=ih * scale, hAlign='CENTER'),
            para(block['caption'], 'caption'),
        ])]
    if kind == 'callout':
        panel = Table([[para(block['text'], 'callout')]], colWidths=[width])
        panel.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), PALE),
            ('BOX', (0, 0), (-1, -1), 0.4, RULE),
            ('LEFTPADDING', (0, 0), (-1, -1), 12),
            ('RIGHTPADDING', (0, 0), (-1, -1), 12),
            ('TOPPADDING', (0, 0), (-1, -1), 10),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ]))
        return [panel, Spacer(1, 10)]
    if kind == 'model_table':
        rows = [[para(cell, 'table') for cell in row] for row in block['rows']]
        fractions = block.get('column_widths', [0.35, 0.28, 0.37])
        table = Table(rows, colWidths=[width * x for x in fractions], repeatRows=1)
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), PALE),
            ('LINEBELOW', (0, 0), (-1, 0), 0.7, ACCENT),
            ('LINEBELOW', (0, -1), (-1, -1), 0.4, RULE),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('LEFTPADDING', (0, 0), (-1, -1), 8),
            ('RIGHTPADDING', (0, 0), (-1, -1), 8),
            ('TOPPADDING', (0, 0), (-1, -1), 7),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 7),
        ]))
        out = [table, Spacer(1, 8)]
        if block.get('note'):
            out.append(para(block['note'], 'small'))
        return out
    if kind == 'references':
        return [para(text, 'small') for text in block['items']]
    raise ValueError(f'Unknown report block: {kind}')


def build(source_path, output_path=None):
    source = json.loads(source_path.read_text())
    pages = source['pages']
    if len(pages) not in (4, 5):
        raise ValueError('The report source must contain four or five authored pages.')
    figures = [b for p in pages for b in p if b['type'] == 'figure']
    if len(figures) > 3:
        raise ValueError('Use at most three remote scientific figures.')
    output = output_path or ROOT / 'outputs/report.pdf'
    output.parent.mkdir(parents=True, exist_ok=True)
    doc = SimpleDocTemplate(str(output), pagesize=A4, leftMargin=52, rightMargin=52,
                            topMargin=48, bottomMargin=49, title=source['title'],
                            author=source.get('author', '0721alex'),
                            subject=source.get('subtitle', 'Liquidity in LLM opportunity planning'))
    story = [para(source['title'], 'title'), para(source['subtitle'], 'subtitle'),
             para(source.get('meta', source.get('date', '')), 'meta')]
    for i, page in enumerate(pages):
        if i:
            story.append(PageBreak())
        for block in page:
            story.extend(block_flowables(block, doc.width))

    def furniture(canvas, document):
        canvas.saveState()
        w, h = A4
        canvas.setStrokeColor(RULE)
        canvas.setLineWidth(0.4)
        canvas.line(52, 34, w - 52, 34)
        canvas.setFont('Body', 7.5)
        canvas.setFillColor(MUTED)
        canvas.drawString(52, 22, 'A Plan Is Not a Path | Controlled synthetic evaluation')
        canvas.drawRightString(w - 52, 22, str(document.page))
        if document.page > 1:
            canvas.setFont('Body', 7.5)
            canvas.drawString(52, h - 29, source.get('running_title', 'Liquidity in LLM opportunity planning'))
        canvas.restoreState()

    doc.build(story, onFirstPage=furniture, onLaterPages=furniture)
    actual_pages = len(PdfReader(output).pages)
    if actual_pages != len(pages):
        raise RuntimeError(f'Layout overflow: expected {len(pages)} pages, rendered {actual_pages}.')
    print(f'Assembled {output} ({actual_pages} pages); render and inspect every page.')


if __name__ == '__main__':
    build(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else None)