amagi-binder 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- amagi_binder/__init__.py +1 -0
- amagi_binder/__main__.py +3 -0
- amagi_binder/build.py +340 -0
- amagi_binder/cli.py +269 -0
- amagi_binder/index.py +340 -0
- amagi_binder/sheets.py +261 -0
- amagi_binder/sources.py +154 -0
- amagi_binder/stamp.py +169 -0
- amagi_binder-0.1.0.dist-info/METADATA +231 -0
- amagi_binder-0.1.0.dist-info/RECORD +14 -0
- amagi_binder-0.1.0.dist-info/WHEEL +5 -0
- amagi_binder-0.1.0.dist-info/entry_points.txt +2 -0
- amagi_binder-0.1.0.dist-info/licenses/LICENSE +21 -0
- amagi_binder-0.1.0.dist-info/top_level.txt +1 -0
amagi_binder/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
amagi_binder/__main__.py
ADDED
amagi_binder/build.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Plan and assemble the binder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
import pikepdf
|
|
13
|
+
from pikepdf import Name
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .index import PAPER_SIZES, SUPPORTED_EXTS, BinderError, Index, assign_labels, scan_folder
|
|
17
|
+
from .sheets import Slip, TocLayout, TocRow, render_slips, render_toc, toc_page_count
|
|
18
|
+
from .sources import Source, open_source
|
|
19
|
+
from .stamp import Stamper, StampText
|
|
20
|
+
|
|
21
|
+
LOG_COLUMNS = [
|
|
22
|
+
"exhibit", "title", "date", "files", "pages", "bates_begin", "bates_end",
|
|
23
|
+
"binder_page_begin", "binder_page_end", "sha256",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class PlannedExhibit:
|
|
29
|
+
label: str
|
|
30
|
+
title: str
|
|
31
|
+
date: str
|
|
32
|
+
description: str
|
|
33
|
+
sources: list
|
|
34
|
+
pages: int
|
|
35
|
+
bates_begin: Optional[int] = None # first Bates number on an exhibit page
|
|
36
|
+
bates_end: Optional[int] = None
|
|
37
|
+
slip_bates: Optional[int] = None # Bates number on the slip sheet, if stamped
|
|
38
|
+
slip_page: Optional[int] = None # 1-based binder page of the slip sheet
|
|
39
|
+
first_page: int = 0 # 1-based binder page of the exhibit's first page
|
|
40
|
+
last_page: int = 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Plan:
|
|
45
|
+
index: Index
|
|
46
|
+
exhibits: list
|
|
47
|
+
toc_pages: int
|
|
48
|
+
total_pages: int
|
|
49
|
+
next_bates: Optional[int]
|
|
50
|
+
warnings: list = field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
def bates_range(self, ex: PlannedExhibit) -> str:
|
|
53
|
+
return _bates_range(self.index.settings, ex)
|
|
54
|
+
|
|
55
|
+
def close(self) -> None:
|
|
56
|
+
"""Release the open exhibit files."""
|
|
57
|
+
for ex in self.exhibits:
|
|
58
|
+
for src in ex.sources:
|
|
59
|
+
src.pdf.close()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _bates_range(s, ex: PlannedExhibit) -> str:
|
|
63
|
+
if not s.bates:
|
|
64
|
+
return ""
|
|
65
|
+
first = ex.slip_bates if ex.slip_bates is not None else ex.bates_begin
|
|
66
|
+
if first == ex.bates_end:
|
|
67
|
+
return s.bates_label(first)
|
|
68
|
+
return f"{s.bates_label(first)} - {s.bates_label(ex.bates_end)}"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _resolve(index: Index, name: str) -> Path:
|
|
72
|
+
p = Path(name)
|
|
73
|
+
return p if p.is_absolute() else index.exhibits_dir / p
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def open_all(index: Index) -> tuple:
|
|
77
|
+
"""Open every exhibit. Returns (list of source lists, errors)."""
|
|
78
|
+
paper = PAPER_SIZES[index.settings.paper]
|
|
79
|
+
opened, errors = [], []
|
|
80
|
+
for ex in index.exhibits:
|
|
81
|
+
if ex.pages and len(ex.files) > 1:
|
|
82
|
+
errors.append(f"{index.settings.exhibit_word} {ex.label}: 'pages' only works with a single file")
|
|
83
|
+
opened.append([])
|
|
84
|
+
continue
|
|
85
|
+
group = []
|
|
86
|
+
for name in ex.files:
|
|
87
|
+
try:
|
|
88
|
+
group.append(open_source(_resolve(index, name), ex.pages, paper))
|
|
89
|
+
except BinderError as exc:
|
|
90
|
+
errors.append(f"{index.settings.exhibit_word} {ex.label}: {exc}")
|
|
91
|
+
opened.append(group)
|
|
92
|
+
return opened, errors
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_index(index: Index) -> tuple:
|
|
96
|
+
"""Problems that stop a build, and warnings that don't."""
|
|
97
|
+
errors, warnings = [], []
|
|
98
|
+
labels = Counter(ex.label for ex in index.exhibits)
|
|
99
|
+
for label, n in labels.items():
|
|
100
|
+
if n > 1:
|
|
101
|
+
errors.append(f"label {label!r} is used by {n} exhibits")
|
|
102
|
+
listed = Counter()
|
|
103
|
+
for ex in index.exhibits:
|
|
104
|
+
for name in ex.files:
|
|
105
|
+
listed[_resolve(index, name).resolve()] += 1
|
|
106
|
+
for path, n in listed.items():
|
|
107
|
+
if n > 1:
|
|
108
|
+
warnings.append(f"{path.name} is listed {n} times")
|
|
109
|
+
if index.exhibits_dir.is_dir():
|
|
110
|
+
for p in scan_folder(index.exhibits_dir):
|
|
111
|
+
if p.resolve() not in listed and (index.path is None or p.resolve() != index.path.resolve()):
|
|
112
|
+
warnings.append(f"{p.name} is in the folder but not in the index")
|
|
113
|
+
else:
|
|
114
|
+
errors.append(f"exhibits folder not found: {index.exhibits_dir}")
|
|
115
|
+
for ex in index.exhibits:
|
|
116
|
+
for name in ex.files:
|
|
117
|
+
ext = Path(name).suffix.lower()
|
|
118
|
+
if ext not in SUPPORTED_EXTS:
|
|
119
|
+
errors.append(f"{name}: unsupported file type {ext or '(none)'}")
|
|
120
|
+
return errors, warnings
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def make_plan(index: Index, opened: list) -> Plan:
|
|
124
|
+
s = index.settings
|
|
125
|
+
planned = []
|
|
126
|
+
for ex, group in zip(index.exhibits, opened):
|
|
127
|
+
planned.append(
|
|
128
|
+
PlannedExhibit(
|
|
129
|
+
label=ex.label, title=ex.title, date=ex.date, description=ex.description,
|
|
130
|
+
sources=group, pages=sum(len(src.page_indices) for src in group),
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
# Bates numbers do not depend on page positions, so assign them first.
|
|
134
|
+
n = s.start
|
|
135
|
+
for p in planned:
|
|
136
|
+
if s.bates and s.slips and s.stamp_slips:
|
|
137
|
+
p.slip_bates = n
|
|
138
|
+
n += 1
|
|
139
|
+
p.bates_begin = n if s.bates else None
|
|
140
|
+
n += p.pages
|
|
141
|
+
p.bates_end = n - 1 if s.bates else None
|
|
142
|
+
next_bates = n if s.bates else None
|
|
143
|
+
toc_pages = 0
|
|
144
|
+
if s.toc:
|
|
145
|
+
layout = _toc_layout(index, planned)
|
|
146
|
+
toc_pages = toc_page_count(layout)
|
|
147
|
+
page = toc_pages + 1
|
|
148
|
+
for p in planned:
|
|
149
|
+
if s.slips:
|
|
150
|
+
p.slip_page = page
|
|
151
|
+
page += 1
|
|
152
|
+
p.first_page = page
|
|
153
|
+
page += p.pages
|
|
154
|
+
p.last_page = page - 1
|
|
155
|
+
warnings = []
|
|
156
|
+
if s.bates and next_bates is not None and len(str(next_bates - 1)) > s.digits:
|
|
157
|
+
warnings.append(
|
|
158
|
+
f"Bates numbers go past {s.digits} digits (last is {next_bates - 1}); raise --digits"
|
|
159
|
+
)
|
|
160
|
+
return Plan(index, planned, toc_pages, page - 1, next_bates, warnings)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _toc_layout(index: Index, planned: list) -> TocLayout:
|
|
164
|
+
s = index.settings
|
|
165
|
+
rows = []
|
|
166
|
+
for p in planned:
|
|
167
|
+
bates = _bates_range(s, p)
|
|
168
|
+
target = p.slip_page if p.slip_page else p.first_page
|
|
169
|
+
rows.append(TocRow(p.label, p.title, p.date, bates, target or 0, p.pages))
|
|
170
|
+
return TocLayout(PAPER_SIZES[s.paper], s.title, s.caption, s.exhibit_word, s.bates, rows)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _stamp_items(index: Index, bates_no: Optional[int], exhibit_line: str = "") -> list:
|
|
174
|
+
s = index.settings
|
|
175
|
+
items = []
|
|
176
|
+
if bates_no is not None:
|
|
177
|
+
items.append(StampText(s.bates_label(bates_no), s.position, bold=True))
|
|
178
|
+
taken = {s.position} if bates_no is not None else set()
|
|
179
|
+
if s.legend:
|
|
180
|
+
pos = "bottom-left" if "bottom-left" not in taken else "bottom-right"
|
|
181
|
+
items.append(StampText(s.legend, pos, bold=True))
|
|
182
|
+
taken.add(pos)
|
|
183
|
+
if exhibit_line:
|
|
184
|
+
pos = "bottom-center" if "bottom-center" not in taken else "top-center"
|
|
185
|
+
items.append(StampText(exhibit_line, pos, bold=False))
|
|
186
|
+
return items
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _page_labels(plan: Plan) -> pikepdf.Array:
|
|
190
|
+
"""Viewer page labels: 'Contents 1', 'Ex. 3', then the Bates number."""
|
|
191
|
+
s = plan.index.settings
|
|
192
|
+
nums = []
|
|
193
|
+
if plan.toc_pages:
|
|
194
|
+
nums += [0, pikepdf.Dictionary(P=pikepdf.String("Contents "), S=Name.D)]
|
|
195
|
+
for p in plan.exhibits:
|
|
196
|
+
if p.slip_page:
|
|
197
|
+
text = s.bates_label(p.slip_bates) if p.slip_bates is not None else f"{s.exhibit_word} {p.label}"
|
|
198
|
+
nums += [p.slip_page - 1, pikepdf.Dictionary(P=pikepdf.String(text))]
|
|
199
|
+
if s.bates:
|
|
200
|
+
for i in range(p.pages):
|
|
201
|
+
nums += [p.first_page - 1 + i, pikepdf.Dictionary(P=pikepdf.String(s.bates_label(p.bates_begin + i)))]
|
|
202
|
+
else:
|
|
203
|
+
nums += [p.first_page - 1, pikepdf.Dictionary(P=pikepdf.String(f"{s.exhibit_word} {p.label}, p. "), S=Name.D)]
|
|
204
|
+
return pikepdf.Array(nums)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def assemble(plan: Plan, out_path: Path) -> None:
|
|
208
|
+
index = plan.index
|
|
209
|
+
s = index.settings
|
|
210
|
+
paper = PAPER_SIZES[s.paper]
|
|
211
|
+
out = pikepdf.new()
|
|
212
|
+
stamper = Stamper(out, font_size=s.font_size, box=s.box)
|
|
213
|
+
keep_open = []
|
|
214
|
+
|
|
215
|
+
toc_rows = []
|
|
216
|
+
if plan.toc_pages:
|
|
217
|
+
layout = _toc_layout(index, plan.exhibits)
|
|
218
|
+
toc_pdf = pikepdf.open(io.BytesIO(render_toc(layout)))
|
|
219
|
+
keep_open.append(toc_pdf)
|
|
220
|
+
if len(toc_pdf.pages) != plan.toc_pages: # pragma: no cover - layout is deterministic
|
|
221
|
+
raise BinderError("table of contents page count changed between passes")
|
|
222
|
+
out.pages.extend(toc_pdf.pages)
|
|
223
|
+
toc_rows = layout.rows
|
|
224
|
+
|
|
225
|
+
slips_pdf = None
|
|
226
|
+
if s.slips:
|
|
227
|
+
slips = [
|
|
228
|
+
Slip(s.exhibit_word, p.label, p.title, p.date, p.description, s.caption,
|
|
229
|
+
plan.bates_range(p), p.pages)
|
|
230
|
+
for p in plan.exhibits
|
|
231
|
+
]
|
|
232
|
+
slips_pdf = pikepdf.open(io.BytesIO(render_slips(slips, paper)))
|
|
233
|
+
keep_open.append(slips_pdf)
|
|
234
|
+
|
|
235
|
+
for i, p in enumerate(plan.exhibits):
|
|
236
|
+
if slips_pdf is not None:
|
|
237
|
+
out.pages.append(slips_pdf.pages[i])
|
|
238
|
+
if p.slip_bates is not None:
|
|
239
|
+
stamper.stamp(out.pages[-1], _stamp_items(index, p.slip_bates))
|
|
240
|
+
k = 0
|
|
241
|
+
for src in p.sources:
|
|
242
|
+
for idx in src.page_indices:
|
|
243
|
+
out.pages.append(src.pdf.pages[idx])
|
|
244
|
+
page = out.pages[-1]
|
|
245
|
+
bates_no = p.bates_begin + k if s.bates else None
|
|
246
|
+
line = f"{s.exhibit_word} {p.label}, page {k + 1} of {p.pages}" if s.exhibit_stamp else ""
|
|
247
|
+
stamper.stamp(page, _stamp_items(index, bates_no, line))
|
|
248
|
+
k += 1
|
|
249
|
+
|
|
250
|
+
if len(out.pages) != plan.total_pages: # pragma: no cover - guards the page math
|
|
251
|
+
raise BinderError(f"built {len(out.pages)} pages, planned {plan.total_pages}")
|
|
252
|
+
|
|
253
|
+
# Linked table of contents
|
|
254
|
+
for row in toc_rows:
|
|
255
|
+
pno, x0, y0, x1, y1 = row.link
|
|
256
|
+
target = out.pages[row.page - 1].obj
|
|
257
|
+
annot = out.make_indirect(
|
|
258
|
+
pikepdf.Dictionary(
|
|
259
|
+
Type=Name.Annot,
|
|
260
|
+
Subtype=Name.Link,
|
|
261
|
+
Rect=pikepdf.Array([x0, y0, x1, y1]),
|
|
262
|
+
Border=pikepdf.Array([0, 0, 0]),
|
|
263
|
+
Dest=pikepdf.Array([target, Name.Fit]),
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
toc_page = out.pages[pno].obj
|
|
267
|
+
if "/Annots" not in toc_page:
|
|
268
|
+
toc_page["/Annots"] = pikepdf.Array()
|
|
269
|
+
toc_page["/Annots"].append(annot)
|
|
270
|
+
|
|
271
|
+
# Bookmarks
|
|
272
|
+
with out.open_outline() as outline:
|
|
273
|
+
outline.root.clear()
|
|
274
|
+
if plan.toc_pages:
|
|
275
|
+
outline.root.append(pikepdf.OutlineItem("Table of Contents", 0))
|
|
276
|
+
for p in plan.exhibits:
|
|
277
|
+
title = f"{s.exhibit_word} {p.label} - {p.title}"
|
|
278
|
+
if s.bates:
|
|
279
|
+
title += f" ({plan.bates_range(p)})"
|
|
280
|
+
item = pikepdf.OutlineItem(title, (p.slip_page or p.first_page) - 1)
|
|
281
|
+
if len(p.sources) > 1:
|
|
282
|
+
start = p.first_page - 1
|
|
283
|
+
for src in p.sources:
|
|
284
|
+
item.children.append(pikepdf.OutlineItem(src.path.name, start))
|
|
285
|
+
start += len(src.page_indices)
|
|
286
|
+
outline.root.append(item)
|
|
287
|
+
|
|
288
|
+
out.Root.PageLabels = pikepdf.Dictionary(Nums=_page_labels(plan))
|
|
289
|
+
out.Root.PageMode = Name.UseOutlines
|
|
290
|
+
out.docinfo["/Title"] = s.title
|
|
291
|
+
out.docinfo["/Creator"] = f"amagi-binder {__version__}"
|
|
292
|
+
if "/Producer" in out.docinfo:
|
|
293
|
+
del out.docinfo["/Producer"]
|
|
294
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
295
|
+
out.save(out_path, deterministic_id=True)
|
|
296
|
+
for pdf in keep_open:
|
|
297
|
+
pdf.close()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def log_rows(plan: Plan) -> list:
|
|
301
|
+
s = plan.index.settings
|
|
302
|
+
rows = []
|
|
303
|
+
for p in plan.exhibits:
|
|
304
|
+
first = p.slip_bates if p.slip_bates is not None else p.bates_begin
|
|
305
|
+
rows.append({
|
|
306
|
+
"exhibit": p.label,
|
|
307
|
+
"title": p.title,
|
|
308
|
+
"date": p.date,
|
|
309
|
+
"files": "; ".join(src.path.name for src in p.sources),
|
|
310
|
+
"pages": p.pages,
|
|
311
|
+
"bates_begin": s.bates_label(first) if s.bates else "",
|
|
312
|
+
"bates_end": s.bates_label(p.bates_end) if s.bates else "",
|
|
313
|
+
"binder_page_begin": p.slip_page or p.first_page,
|
|
314
|
+
"binder_page_end": p.last_page,
|
|
315
|
+
"sha256": "; ".join(src.sha256 for src in p.sources),
|
|
316
|
+
})
|
|
317
|
+
return rows
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def write_log(plan: Plan, path: Path) -> None:
|
|
321
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
322
|
+
with open(path, "w", newline="", encoding="utf-8") as fh:
|
|
323
|
+
w = csv.DictWriter(fh, fieldnames=LOG_COLUMNS)
|
|
324
|
+
w.writeheader()
|
|
325
|
+
w.writerows(log_rows(plan))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def prepare(index: Index) -> tuple:
|
|
329
|
+
"""Label, check and open everything. Returns (plan or None, errors, warnings)."""
|
|
330
|
+
assign_labels(index)
|
|
331
|
+
errors, warnings = check_index(index)
|
|
332
|
+
opened, open_errors = open_all(index)
|
|
333
|
+
errors += open_errors
|
|
334
|
+
if errors:
|
|
335
|
+
for group in opened:
|
|
336
|
+
for src in group:
|
|
337
|
+
src.pdf.close()
|
|
338
|
+
return None, errors, warnings
|
|
339
|
+
plan = make_plan(index, opened)
|
|
340
|
+
return plan, errors, warnings + plan.warnings
|
amagi_binder/cli.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""amagi-binder command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .build import assemble, log_rows, prepare, write_log
|
|
12
|
+
from .index import (
|
|
13
|
+
LABEL_STYLES, PAPER_SIZES, POSITIONS, BinderError, load_index, scan_folder,
|
|
14
|
+
starter_index, validate_settings,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
EPILOG = """\
|
|
18
|
+
examples:
|
|
19
|
+
amagi-binder init exhibits/ -o exhibits/index.yaml
|
|
20
|
+
amagi-binder check exhibits/index.yaml
|
|
21
|
+
amagi-binder build exhibits/index.yaml -o binder.pdf --prefix DOE_ --legend CONFIDENTIAL
|
|
22
|
+
|
|
23
|
+
exit codes: 0 ok, 1 the index has problems, 2 usage error
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _add_layout_flags(p: argparse.ArgumentParser) -> None:
|
|
28
|
+
g = p.add_argument_group("overrides (these win over the index file)")
|
|
29
|
+
g.add_argument("--exhibits", metavar="DIR", help="folder the index's file names are relative to (default: the index's folder)")
|
|
30
|
+
g.add_argument("--title", help="binder title on the contents page")
|
|
31
|
+
g.add_argument("--caption", help="case caption line, e.g. 'Doe v. Roe, No. 1:26-cv-00001'")
|
|
32
|
+
g.add_argument("--prefix", help="Bates prefix, e.g. DOE or DOE_")
|
|
33
|
+
g.add_argument("--start", type=int, metavar="N", help="first Bates number (default 1)")
|
|
34
|
+
g.add_argument("--digits", type=int, metavar="N", help="zero-pad Bates numbers to N digits (default 6)")
|
|
35
|
+
g.add_argument("--position", choices=POSITIONS, help="where the Bates number goes (default bottom-right)")
|
|
36
|
+
g.add_argument("--font-size", type=float, metavar="PT", help="stamp size in points (default 10)")
|
|
37
|
+
g.add_argument("--box", action="store_true", default=None, help="draw a white box behind each stamp")
|
|
38
|
+
g.add_argument("--legend", metavar="TEXT", help="extra stamp at bottom-left, e.g. CONFIDENTIAL")
|
|
39
|
+
g.add_argument("--exhibit-stamp", action="store_true", default=None, help="also stamp 'Exhibit 3, page 2 of 5' at bottom-center")
|
|
40
|
+
g.add_argument("--stamp-slips", action="store_true", default=None, help="give slip sheets a Bates number too")
|
|
41
|
+
g.add_argument("--no-bates", action="store_true", help="no Bates numbers (slip sheets and contents only)")
|
|
42
|
+
g.add_argument("--no-slips", action="store_true", help="no exhibit slip sheets")
|
|
43
|
+
g.add_argument("--no-toc", action="store_true", help="no table of contents page")
|
|
44
|
+
g.add_argument("--labels", choices=LABEL_STYLES, help="auto labels: 1, 2, 3 or A, B, C")
|
|
45
|
+
g.add_argument("--label-start", type=int, metavar="N", help="first auto label (default 1, or A)")
|
|
46
|
+
g.add_argument("--exhibit-word", metavar="WORD", help="word on slip sheets (default Exhibit; e.g. Tab, Attachment)")
|
|
47
|
+
g.add_argument("--paper", choices=sorted(PAPER_SIZES), help="size of slip sheets, contents and image pages")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _load(args) -> "Index": # noqa: F821
|
|
51
|
+
index = load_index(Path(args.index), Path(args.exhibits) if args.exhibits else None)
|
|
52
|
+
s = index.settings
|
|
53
|
+
for attr in ("title", "caption", "prefix", "legend", "exhibit_word", "position", "labels", "paper"):
|
|
54
|
+
value = getattr(args, attr)
|
|
55
|
+
if value is not None:
|
|
56
|
+
setattr(s, attr, value)
|
|
57
|
+
if args.start is not None:
|
|
58
|
+
if args.start < 0:
|
|
59
|
+
raise BinderError("--start must be 0 or more")
|
|
60
|
+
s.start = args.start
|
|
61
|
+
if args.digits is not None:
|
|
62
|
+
if args.digits < 1:
|
|
63
|
+
raise BinderError("--digits must be 1 or more")
|
|
64
|
+
s.digits = args.digits
|
|
65
|
+
if args.label_start is not None:
|
|
66
|
+
if args.label_start < 1:
|
|
67
|
+
raise BinderError("--label-start must be 1 or more")
|
|
68
|
+
s.label_start = args.label_start
|
|
69
|
+
if args.font_size is not None:
|
|
70
|
+
s.font_size = args.font_size
|
|
71
|
+
for attr in ("box", "exhibit_stamp", "stamp_slips"):
|
|
72
|
+
if getattr(args, attr):
|
|
73
|
+
setattr(s, attr, True)
|
|
74
|
+
if args.no_bates:
|
|
75
|
+
s.bates = False
|
|
76
|
+
if args.no_slips:
|
|
77
|
+
s.slips = False
|
|
78
|
+
if args.no_toc:
|
|
79
|
+
s.toc = False
|
|
80
|
+
validate_settings(s)
|
|
81
|
+
return index
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _print_problems(errors, warnings) -> None:
|
|
85
|
+
for w in warnings:
|
|
86
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
87
|
+
for e in errors:
|
|
88
|
+
print(f"error: {e}", file=sys.stderr)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
TITLE_WIDTH = 44 # the summary is for a terminal; the PDF and CSV keep full titles
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _short(text: str, width: int = TITLE_WIDTH) -> str:
|
|
95
|
+
return text if len(text) <= width else text[: width - 3].rstrip() + "..."
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _summary_table(plan) -> list:
|
|
99
|
+
s = plan.index.settings
|
|
100
|
+
word = s.exhibit_word
|
|
101
|
+
rows = [(word, "Pages", "Bates range" if s.bates else "", "Binder pages", "Title")]
|
|
102
|
+
for p in plan.exhibits:
|
|
103
|
+
rows.append((
|
|
104
|
+
p.label, str(p.pages), plan.bates_range(p),
|
|
105
|
+
f"{p.slip_page or p.first_page}-{p.last_page}", _short(p.title),
|
|
106
|
+
))
|
|
107
|
+
widths = [max(len(r[i]) for r in rows) for i in range(4)]
|
|
108
|
+
out = []
|
|
109
|
+
for r in rows:
|
|
110
|
+
cells = [r[i].ljust(widths[i]) for i in range(4) if widths[i]]
|
|
111
|
+
out.append(" ".join(cells + [r[4]]).rstrip())
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cmd_init(args) -> int:
|
|
116
|
+
folder = Path(args.folder)
|
|
117
|
+
if not folder.is_dir():
|
|
118
|
+
print(f"error: not a folder: {folder}", file=sys.stderr)
|
|
119
|
+
return 2
|
|
120
|
+
files = scan_folder(folder)
|
|
121
|
+
if not files:
|
|
122
|
+
print(f"error: no PDF, JPG, PNG or TIFF files in {folder}", file=sys.stderr)
|
|
123
|
+
return 1
|
|
124
|
+
out = Path(args.output) if args.output else folder / "index.yaml"
|
|
125
|
+
if out.exists() and not args.force:
|
|
126
|
+
print(f"error: {out} already exists (use --force to overwrite)", file=sys.stderr)
|
|
127
|
+
return 1
|
|
128
|
+
if out.parent.resolve() != folder.resolve():
|
|
129
|
+
print(
|
|
130
|
+
f"note: file names in {out.name} are relative to {folder}; "
|
|
131
|
+
f"pass --exhibits {folder} when you build",
|
|
132
|
+
file=sys.stderr,
|
|
133
|
+
)
|
|
134
|
+
out.write_text(starter_index(folder, files, args.title), encoding="utf-8")
|
|
135
|
+
print(f"wrote {out} with {len(files)} exhibits (sorted by file name). Edit it, then run:")
|
|
136
|
+
print(f" amagi-binder build {out} -o binder.pdf")
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_check(args) -> int:
|
|
141
|
+
index = _load(args)
|
|
142
|
+
plan, errors, warnings = prepare(index)
|
|
143
|
+
if args.json:
|
|
144
|
+
payload = {"ok": not errors, "errors": errors, "warnings": warnings}
|
|
145
|
+
if plan is not None:
|
|
146
|
+
payload.update(
|
|
147
|
+
total_pages=plan.total_pages,
|
|
148
|
+
toc_pages=plan.toc_pages,
|
|
149
|
+
next_bates=index.settings.bates_label(plan.next_bates) if plan.next_bates is not None else None,
|
|
150
|
+
exhibits=log_rows(plan),
|
|
151
|
+
)
|
|
152
|
+
print(json.dumps(payload, indent=2))
|
|
153
|
+
if plan is not None:
|
|
154
|
+
plan.close()
|
|
155
|
+
return 0 if not errors else 1
|
|
156
|
+
_print_problems(errors, warnings)
|
|
157
|
+
if plan is None:
|
|
158
|
+
print(f"{len(errors)} problem(s); nothing built", file=sys.stderr)
|
|
159
|
+
return 1
|
|
160
|
+
for line in _summary_table(plan):
|
|
161
|
+
print(line)
|
|
162
|
+
print()
|
|
163
|
+
print(_totals(plan))
|
|
164
|
+
print("OK")
|
|
165
|
+
plan.close()
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _totals(plan) -> str:
|
|
170
|
+
s = plan.index.settings
|
|
171
|
+
parts = [f"{len(plan.exhibits)} exhibits", f"{plan.total_pages} binder pages"]
|
|
172
|
+
if plan.toc_pages:
|
|
173
|
+
parts.append(f"{plan.toc_pages} contents page" + ("" if plan.toc_pages == 1 else "s"))
|
|
174
|
+
text = ", ".join(parts)
|
|
175
|
+
if plan.next_bates is not None:
|
|
176
|
+
text += f". Next Bates number: {s.bates_label(plan.next_bates)}"
|
|
177
|
+
return text
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_build(args) -> int:
|
|
181
|
+
index = _load(args)
|
|
182
|
+
plan, errors, warnings = prepare(index)
|
|
183
|
+
_print_problems(errors, warnings)
|
|
184
|
+
if plan is None:
|
|
185
|
+
print(f"{len(errors)} problem(s); nothing built", file=sys.stderr)
|
|
186
|
+
return 1
|
|
187
|
+
out = Path(args.output)
|
|
188
|
+
if out.suffix.lower() != ".pdf":
|
|
189
|
+
print("error: -o must end in .pdf", file=sys.stderr)
|
|
190
|
+
plan.close()
|
|
191
|
+
return 2
|
|
192
|
+
for src_group in (p.sources for p in plan.exhibits):
|
|
193
|
+
for src in src_group:
|
|
194
|
+
if src.path.resolve() == out.resolve():
|
|
195
|
+
print(f"error: -o would overwrite exhibit {src.path.name}", file=sys.stderr)
|
|
196
|
+
plan.close()
|
|
197
|
+
return 2
|
|
198
|
+
try:
|
|
199
|
+
assemble(plan, out)
|
|
200
|
+
finally:
|
|
201
|
+
plan.close()
|
|
202
|
+
log = None
|
|
203
|
+
if not args.no_log:
|
|
204
|
+
log = Path(args.log) if args.log else out.with_name(out.stem + "_bates_log.csv")
|
|
205
|
+
write_log(plan, log)
|
|
206
|
+
if not args.quiet:
|
|
207
|
+
for line in _summary_table(plan):
|
|
208
|
+
print(line)
|
|
209
|
+
print()
|
|
210
|
+
print(f"wrote {out} ({_totals(plan)})")
|
|
211
|
+
if log:
|
|
212
|
+
print(f"wrote {log}")
|
|
213
|
+
return 0
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
217
|
+
parser = argparse.ArgumentParser(
|
|
218
|
+
prog="amagi-binder",
|
|
219
|
+
description=(
|
|
220
|
+
"Build one court-ready PDF from a folder of exhibits and a YAML or CSV index: "
|
|
221
|
+
"Bates stamps, exhibit slip sheets, a linked table of contents, bookmarks, "
|
|
222
|
+
"and a CSV Bates log."
|
|
223
|
+
),
|
|
224
|
+
epilog=EPILOG,
|
|
225
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
226
|
+
)
|
|
227
|
+
parser.add_argument("--version", action="version", version=f"amagi-binder {__version__}")
|
|
228
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
229
|
+
|
|
230
|
+
p = sub.add_parser("init", help="write a starter index.yaml for a folder of exhibits")
|
|
231
|
+
p.add_argument("folder", help="folder of exhibit files")
|
|
232
|
+
p.add_argument("-o", "--output", help="where to write the index (default: FOLDER/index.yaml)")
|
|
233
|
+
p.add_argument("--title", default="Exhibits", help="binder title (default: Exhibits)")
|
|
234
|
+
p.add_argument("--force", action="store_true", help="overwrite an existing index")
|
|
235
|
+
p.set_defaults(func=cmd_init)
|
|
236
|
+
|
|
237
|
+
p = sub.add_parser("check", help="validate the index and show the Bates plan without writing anything")
|
|
238
|
+
p.add_argument("index", help="index file (.yaml, .yml or .csv)")
|
|
239
|
+
p.add_argument("--json", action="store_true", help="print the plan as JSON")
|
|
240
|
+
_add_layout_flags(p)
|
|
241
|
+
p.set_defaults(func=cmd_check)
|
|
242
|
+
|
|
243
|
+
p = sub.add_parser("build", help="build the binder PDF and Bates log")
|
|
244
|
+
p.add_argument("index", help="index file (.yaml, .yml or .csv)")
|
|
245
|
+
p.add_argument("-o", "--output", required=True, help="output PDF path")
|
|
246
|
+
p.add_argument("--log", metavar="CSV", help="Bates log path (default: <output>_bates_log.csv)")
|
|
247
|
+
p.add_argument("--no-log", action="store_true", help="don't write the Bates log")
|
|
248
|
+
p.add_argument("-q", "--quiet", action="store_true", help="print only the output paths")
|
|
249
|
+
_add_layout_flags(p)
|
|
250
|
+
p.set_defaults(func=cmd_build)
|
|
251
|
+
return parser
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def main(argv=None) -> int:
|
|
255
|
+
for stream in (sys.stdout, sys.stderr):
|
|
256
|
+
try:
|
|
257
|
+
stream.reconfigure(encoding="utf-8")
|
|
258
|
+
except (AttributeError, ValueError):
|
|
259
|
+
pass
|
|
260
|
+
parser = build_parser()
|
|
261
|
+
args = parser.parse_args(argv)
|
|
262
|
+
if not getattr(args, "func", None):
|
|
263
|
+
parser.print_help()
|
|
264
|
+
return 2
|
|
265
|
+
try:
|
|
266
|
+
return args.func(args)
|
|
267
|
+
except BinderError as exc:
|
|
268
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
269
|
+
return 1
|