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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env python3
"""Render the dataset as a printable dimensional reference.

Everything on the page comes from containers.csv and listings.csv — nothing is
typed here — so the PDF cannot drift from the data. Per-vendor internal
dimensions come from container_stats, the same module build.py uses, so the
variance tables and the CSV's vendor_capacity_* columns are computed once.

Output: reference/storage-container-reference.pdf

Needs reportlab (pip install -r scripts/requirements.txt).
Run: python3 scripts/build_reference_pdf.py
"""

import csv
import sys
from datetime import date
from pathlib import Path

from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import (BaseDocTemplate, Frame, KeepTogether, NextPageTemplate,
                                PageBreak, PageTemplate, Paragraph, Spacer, Table,
                                TableStyle)

HERE = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(HERE))
import container_stats  # noqa: E402  (needs HERE on the path)

OUT = HERE / "reference" / "storage-container-reference.pdf"
DATASET_URL = "https://huggingface.co/datasets/danielrosehill/storage-container-dimensions"

INK = colors.HexColor("#1f2933")
MUTED = colors.HexColor("#6b7480")
RULE = colors.HexColor("#c9d1d9")
BAND = colors.HexColor("#f2f4f6")
HEAD_BG = colors.HexColor("#26323d")

FAMILY_ORDER = ["euro_stacking_container", "attached_lid_container", "vda_klt_container"]
FAMILY_TITLES = {
    "euro_stacking_container": "Euro stacking containers",
    "attached_lid_container": "Attached-lid containers (ALC)",
    "vda_klt_container": "VDA 4500 KLTs",
}
# One line each, so a reader who opens on this page knows what the family is.
FAMILY_BLURB = {
    "euro_stacking_container":
        "Open top, straight walls, lid a separate purchase. Stack when full; they do "
        "not nest when empty. No standard fixes the height series — it is whatever "
        "manufacturers converged on.",
    "attached_lid_container":
        "Integral hinged lid, walls sloping inward towards the base. Stack when full "
        "and nest to about 75 % of their height when empty. Capacities are the "
        "manufacturers' nominal figures: the taper means no single internal "
        "measurement is right at more than one height.",
    "vda_klt_container":
        "Returnable small load carriers for automotive supply chains. VDA 4500 fixes "
        "three external heights — 147.5, 213 and 280 mm — and thicker walls than a "
        "consumer eurobox, so the eurobox internal rule does not transfer.",
}


def styles():
    ss = getSampleStyleSheet()
    base = dict(fontName="Helvetica", textColor=INK, alignment=TA_LEFT)
    return {
        "title": ParagraphStyle("t", fontName="Helvetica-Bold", fontSize=26, leading=30,
                                textColor=INK, spaceAfter=2, alignment=TA_LEFT),
        "subtitle": ParagraphStyle("st", fontName="Helvetica", fontSize=12.5, leading=17,
                                   textColor=MUTED, spaceAfter=18, alignment=TA_LEFT),
        "h1": ParagraphStyle("h1", fontName="Helvetica-Bold", fontSize=16, leading=20,
                             textColor=INK, spaceBefore=2, spaceAfter=6),
        "h2": ParagraphStyle("h2", fontName="Helvetica-Bold", fontSize=11, leading=14,
                             textColor=INK, spaceBefore=12, spaceAfter=5),
        "body": ParagraphStyle("b", fontSize=9.2, leading=13, spaceAfter=7, **base),
        "note": ParagraphStyle("n", fontSize=8, leading=11, textColor=MUTED,
                               spaceAfter=9, fontName="Helvetica", alignment=TA_LEFT),
        "cell": ParagraphStyle("c", fontSize=7.6, leading=9.6, **base),
    }


S = styles()


def para(text, style="body"):
    return Paragraph(text, S[style])


def table(data, widths, align_right=(), small=False):
    t = Table(data, colWidths=widths, repeatRows=1, hAlign="LEFT")
    size = 7.2 if small else 7.8
    cmds = [
        ("BACKGROUND", (0, 0), (-1, 0), HEAD_BG),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 0), (-1, -1), size),
        ("LEADING", (0, 0), (-1, -1), size + 2.6),
        ("TEXTCOLOR", (0, 1), (-1, -1), INK),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 3.2),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 3.2),
        ("LEFTPADDING", (0, 0), (-1, -1), 5),
        ("RIGHTPADDING", (0, 0), (-1, -1), 5),
        ("LINEBELOW", (0, 0), (-1, -1), 0.25, RULE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, BAND]),
    ]
    for col in align_right:
        cmds.append(("ALIGN", (col, 1), (col, -1), "RIGHT"))
    t.setStyle(TableStyle(cmds))
    return t


def load(name):
    with (HERE / name).open(encoding="utf-8") as f:
        return list(csv.DictReader(f))


def num(v, dp=1):
    """CSV cell -> display string. Empty stays empty; integers lose the .0."""
    if v in ("", None):
        return "—"
    f = float(v)
    return str(int(f)) if f == int(f) and dp == 1 else f"{f:.{dp}f}"


def group_by_footprint(rows):
    """Footprint -> its sizes, in the order the dataset lists them.

    Not sorted: the dataset leads with 600x400 because that is the footprint
    everything else is a fraction or multiple of, and a reference should open on
    the size the reader most likely came for.
    """
    out = {}
    for r in rows:
        out.setdefault((float(r["external_length_cm"]), float(r["external_width_cm"])), []).append(r)
    return out


# ---------------------------------------------------------------------------
# Page furniture
# ---------------------------------------------------------------------------

def page_decoration(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 7.2)
    canvas.setFillColor(MUTED)
    canvas.drawString(20 * mm, 12 * mm, "Industrial storage containers — dimensional reference")
    canvas.drawRightString(A4[0] - 20 * mm, 12 * mm, f"page {canvas.getPageNumber()}")
    canvas.setStrokeColor(RULE)
    canvas.setLineWidth(0.4)
    canvas.line(20 * mm, 15 * mm, A4[0] - 20 * mm, 15 * mm)
    canvas.restoreState()


def build_doc():
    doc = BaseDocTemplate(str(OUT), pagesize=A4,
                          leftMargin=20 * mm, rightMargin=20 * mm,
                          topMargin=18 * mm, bottomMargin=20 * mm,
                          title="Industrial storage containers — dimensional reference",
                          author="Daniel Rosehill", subject="Container dimensions and capacities")
    frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id="body")
    doc.addPageTemplates([
        PageTemplate(id="cover", frames=[frame]),
        PageTemplate(id="body", frames=[frame], onPage=page_decoration),
    ])
    return doc


# ---------------------------------------------------------------------------
# Content
# ---------------------------------------------------------------------------

def cover(containers, listings, verified):
    n_vendors = len({r["vendor"] for r in listings})
    markets = len({r["vendor_country"] for r in listings})
    return [
        Spacer(1, 40 * mm),
        para("Industrial storage containers", "title"),
        para("A dimensional reference: Euroboxes, attached-lid containers and VDA KLTs", "subtitle"),
        table([
            ["Container sizes", str(len(containers))],
            ["Vendor listings behind them", f"{len(listings)} from {n_vendors} vendors in {markets} markets"],
            ["Data verified", verified],
            ["Generated", date.today().isoformat()],
            ["Source", DATASET_URL],
            ["Licence", "CC BY 4.0"],
        ], [45 * mm, 125 * mm]),
        Spacer(1, 10 * mm),
        para(
            "Multiply a container's external dimensions and you will overstate what you are "
            "buying by roughly a quarter — and you will overstate a tapered attached-lid "
            "container by more than a straight-walled eurobox, which quietly corrupts any "
            "comparison between the two. Every capacity in this document is usable capacity. "
            "External volume is shown alongside so the gap stays visible."),
        para(
            "Nothing here is typed by hand: every figure is rendered from the published "
            "dataset. Where vendors disagree — and on internal dimensions they disagree a "
            "great deal — the disagreement is printed rather than averaged away."),
    ]


def how_to_read():
    return [
        NextPageTemplate("body"), PageBreak(),
        para("How to read these tables", "h1"),
        para(
            "<b>The standards fix external dimensions. They do not fix internal ones.</b> "
            "ISO 3394 defines the 600 × 400 mm packaging module, EN 13199 caps a small load "
            "carrier at that footprint, and VDA 4500 additionally fixes three external "
            "heights. None of them specifies wall thickness, draft angle, rib design or base "
            "construction — and those are what determine what fits inside."),
        para("So each size carries three capacity figures, not one:"),
        table([
            ["Column", "What it is", "Use it for"],
            [para("<b>Typical usable</b>", "cell"),
             para("Computed from a conservative internal footprint: for a 600 × 400 box, "
                  "550 × 355 mm and 15 mm off the height. At or just below the least "
                  "generous vendor.", "cell"),
             para("Planning. A figure that overstates capacity fails silently — the pallet "
                  "does not fit, the shipment does not close.", "cell")],
            [para("<b>Vendor range</b>", "cell"),
             para("Capacity implied by each vendor's own published internal dimensions for "
                  "that footprint, lowest to highest. One vote per vendor, not per listing.", "cell"),
             para("Knowing what you will be quoted, and how much of a quoted difference is "
                  "real rather than measurement convention.", "cell")],
            [para("<b>External</b>", "cell"),
             para("L × W × H. What the box occupies on a shelf or in a container.", "cell"),
             para("Space planning, freight, pallet build.", "cell")],
        ], [26 * mm, 74 * mm, 70 * mm]),
        para("Why the vendor range is so wide", "h2"),
        para(
            "Because vendors measure at different heights. A euro crate is slightly tapered, "
            "so its top opening is larger than its base. Salesbridges publishes the top "
            "opening (570 × 370 mm inside a 600 × 400 box); Plastic Box Shop and Yosibox "
            "publish something close to the base (555 × 355 and 550 × 360). All three are "
            "honest, and the spread between them is about 11 % in litres on the same box. "
            "Each family section below prints the per-vendor figures it was drawn from."),
        para("A note on names", "h2"),
        para(
            "The trade has no agreed vocabulary. The same box is a Eurobox, a euro crate, a "
            "stacking tote, an industrial tote or a “KLT box” depending on the seller, and "
            "two of those mislead: “KLT” is widely applied to ordinary euroboxes that are "
            "nowhere near the VDA height grid, and “tote” means any industrial container in "
            "US usage but leans towards the attached-lid product in the UK. The last page "
            "lists the aliases by market. Identify a box by its walls, its lid and whether it "
            "nests — never by its name."),
    ]


def sizes_table(rows, family):
    """One row per height. External L x W is in the heading, so it is not repeated."""
    header = ["H (cm)", "Internal, typical\n(L × W × H cm)", "External\nvolume (L)",
              "Typical\nusable (L)", "Vendor range (L)", "Usable\n%", "Per EUR-1\nlayer",
              "Listings\nseen"]
    body = []
    for r in rows:
        lo, hi = r["vendor_capacity_low_l"], r["vendor_capacity_high_l"]
        rng = "—" if lo == "" else (num(lo) if lo == hi else f"{num(lo)}{num(hi)}")
        internal = "—" if not r["internal_length_cm"] else (
            f'{num(r["internal_length_cm"])} × {num(r["internal_width_cm"])} '
            f'× {num(r["internal_height_cm"])}')
        body.append([
            num(r["external_height_cm"]),
            internal,
            num(r["external_volume_l"]),
            num(r["typical_capacity_l"]),
            rng,
            f'{float(r["usable_ratio"]) * 100:.0f}',
            r["eur1_pallet_per_layer"],
            r["listings_observed"],
        ])
    widths = [16 * mm, 35 * mm, 21 * mm, 21 * mm, 26 * mm, 14 * mm, 19 * mm, 18 * mm]
    return table([header] + body, widths, align_right=(0, 2, 3, 4, 5, 6, 7))


def variance_block(kind, L, W, index, counts):
    """Per-vendor published internal dimensions for one footprint."""
    key = (kind, round(L * 10), round(W * 10))
    vendors = index.get(key)
    if not vendors:
        return [para(
            "No vendor in the captured listings publishes internal dimensions for this "
            "footprint, so no vendor range is shown above.", "note")]

    header = ["Vendor", "Listings", "Internal L × W (mm)", "Wall allowance\nper side (mm)",
              "External − internal\nheight (mm)", "Reading"]
    body = []
    for vendor in sorted(vendors, key=lambda v: -vendors[v][0]):
        il, iw, ded = vendors[vendor]
        per_side = ((L * 10 - il) / 2 + (W * 10 - iw) / 2) / 2
        # ~15 mm a side is a top-opening measurement; ~22 mm and up is near the base.
        reading = "top opening" if per_side < 20 else "near the base"
        body.append([vendor, str(counts.get(key, {}).get(vendor, 0)),
                     f"{il:.0f} × {iw:.0f}", f"{per_side:.0f}", f"{ded:.0f}", reading])
    widths = [34 * mm, 16 * mm, 30 * mm, 27 * mm, 32 * mm, 31 * mm]
    return [table([header] + body, widths, align_right=(1, 3, 4), small=True), Spacer(1, 4 * mm)]


VARIANCE_NOTE = (
    "Under each footprint: what each vendor publishes as the inside of that box. Wall "
    "allowance is (external − internal) ÷ 2, averaged over length and width. A figure near "
    "15 mm is a top-opening measurement; 22 mm and above is measured close to the base. The "
    "difference between those two conventions, not manufacturing variation, is most of the "
    "vendor range.")


def family_section(kind, containers, index, counts):
    rows = [r for r in containers if r["type"] == kind]
    flow = [NextPageTemplate("body"), PageBreak(),
            para(FAMILY_TITLES[kind], "h1"), para(FAMILY_BLURB[kind])]
    if any((kind, round(L * 10), round(W * 10)) in index
           for L, W in group_by_footprint(rows)):
        flow.append(para(VARIANCE_NOTE, "note"))
    for (L, W), sizes in group_by_footprint(rows).items():
        block = [para(f"{num(L)} × {num(W)} cm", "h2"), sizes_table(sizes, kind)]
        flow.append(KeepTogether(block))
        flow.append(Spacer(1, 3 * mm))
        flow.extend(variance_block(kind, L, W, index, counts))
    return flow


def sources_page(listings):
    by_vendor = {}
    for r in listings:
        v = by_vendor.setdefault(r["vendor"], {"n": 0, "internal": 0, "country": r["vendor_country"],
                                               "date": r["captured_date"], "cur": r["currency"]})
        v["n"] += 1
        v["internal"] += 1 if r["internal_length_cm"] else 0

    header = ["Vendor", "Market", "Listings", "With published\ninternals", "Currency", "Captured"]
    body = [[k, v["country"], str(v["n"]), str(v["internal"]), v["cur"], v["date"]]
            for k, v in sorted(by_vendor.items(), key=lambda kv: -kv[1]["n"])]

    ratios = {}
    for r in listings:
        if r["usable_ratio"]:
            ratios.setdefault(r["type"], []).append(float(r["usable_ratio"]))
    stat_rows = []
    for kind in FAMILY_ORDER:
        v = sorted(ratios.get(kind, []))
        if not v:
            continue
        stat_rows.append([FAMILY_TITLES[kind], str(len(v)), f"{min(v):.0%}",
                          f"{container_stats.median(v):.0%}", f"{max(v):.0%}"])

    return [
        NextPageTemplate("body"), PageBreak(),
        para("Where the numbers come from", "h1"),
        para(
            "Vendor catalogues captured on the dates below, plus VDA 4500 v3.1 for the KLT "
            "grid and secondary summaries of ISO 3394 and EN 13199, both of which are paid "
            "publications. Every listing is in listings.csv with its URL and SKU."),
        table([header] + body, [40 * mm, 22 * mm, 20 * mm, 30 * mm, 22 * mm, 26 * mm],
              align_right=(2, 3)),
        para("What each vendor claims, in its own words", "h2"),
        para(
            "Usable ratio computed from each listing's own stated capacity against its own "
            "external dimensions — what the vendor claims, not what this reference concluded:"),
        table([["Family", "Listings", "Min", "Median", "Max"]] + stat_rows,
              [58 * mm, 20 * mm, 20 * mm, 24 * mm, 20 * mm], align_right=(1, 2, 3, 4)),
        para(
            "The gap between the tapered and straight-walled medians is the single most "
            "important number in this document, and it holds across independent markets. The "
            "euro maximum is inflated by vendors who compute litres geometrically from the "
            "top opening rather than measuring a fill.", "note"),
    ]


def names_page(containers):
    seen = {}
    for r in containers:
        seen.setdefault(r["type"], r["common_names"])
    rows = [[para(f'<b>{FAMILY_TITLES[k]}</b>', "cell"),
             para(seen[k].replace("; ", " · "), "cell")]
            for k in FAMILY_ORDER if k in seen]
    return [
        NextPageTemplate("body"), PageBreak(),
        para("What these boxes are called", "h1"),
        para(
            "Search terms, ordered from the most standard to the most colloquial, including "
            "regional trade names and one genericised vendor name. They are for finding a "
            "product, never for classifying one."),
        table([["Family", "Also called"]] + rows, [42 * mm, 128 * mm]),
        para("Two that mislead", "h2"),
        table([
            ["Term", "The trap"],
            [para("<b>“KLT box”</b>", "cell"),
             para("Applied by vendors to ordinary open-top euroboxes — 14 listings in these "
                  "captures do it, at eight heights and on three footprints, none of them on "
                  "the VDA 4500 grid of 147.5 / 213 / 280 mm. A real KLT is a thicker-walled "
                  "returnable carrier on that grid.", "cell")],
            [para("<b>“Tote”</b>", "cell"),
             para("In US usage any industrial container, tapered or straight, lidded or open. "
                  "In UK usage it leans towards the attached-lid product. “Industrial tote” "
                  "therefore applies to two different families and discriminates nothing.", "cell")],
        ], [30 * mm, 140 * mm]),
        para("Telling them apart without the names", "h2"),
        table([
            ["", "Euro stacking container", "Attached-lid container", "VDA KLT"],
            ["Walls", "straight", "sloping", "straight"],
            ["Lid", "separate purchase", "integral, hinged", "separate"],
            ["Nests when empty", "no", "~75 % of its height", "no"],
            ["Height grid", "manufacturer's choice", "manufacturer's choice", "147.5 / 213 / 280 mm"],
            ["Typical usable ratio", "76–78 %", "73–75 %", "~71 %"],
        ], [34 * mm, 46 * mm, 46 * mm, 44 * mm]),
        Spacer(1, 8 * mm),
        para(
            f"Full dataset, per-listing evidence and the notes behind every figure: "
            f"<link href='{DATASET_URL}' color='#26323d'><u>{DATASET_URL}</u></link>", "note"),
    ]


def main():
    containers = load("containers.csv")
    listings = load("listings.csv")
    index = container_stats.internal_index(listings)
    counts = container_stats.vendor_listing_counts(listings)
    verified = max(r["captured_date"] for r in listings)

    story = cover(containers, listings, verified)
    story += how_to_read()
    for kind in FAMILY_ORDER:
        story += family_section(kind, containers, index, counts)
    story += sources_page(listings)
    story += names_page(containers)

    OUT.parent.mkdir(exist_ok=True)
    build_doc().build(story)
    print(f"{OUT.relative_to(HERE)}{len(containers)} sizes, {len(listings)} listings")


if __name__ == "__main__":
    main()