File size: 2,220 Bytes
f5403c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from dataclasses import asdict, dataclass
from math import ceil

from .config import KDP_DEFAULTS, TRIM_SIZES_IN


@dataclass
class KdpBookSpec:
    trim_size: str
    width_in: float
    height_in: float
    bleed_in: float
    safe_margin_in: float
    page_count: int
    gutter_margin_in: float
    cover_width_in: float
    cover_height_in: float
    kdp_ready: bool

    def to_dict(self) -> dict:
        return asdict(self)


def gutter_margin_for_page_count(page_count: int) -> float:
    if page_count <= 150:
        return 0.375
    if page_count <= 300:
        return 0.5
    if page_count <= 500:
        return 0.625
    if page_count <= 700:
        return 0.75
    return 0.875


def estimate_spine_width(page_count: int, paper_type: str = "white_bw") -> float:
    if paper_type == "white_bw":
        return page_count * 0.002252
    return page_count * 0.0025


def build_book_spec(trim_size: str, page_count: int) -> KdpBookSpec:
    width_in, height_in = TRIM_SIZES_IN[trim_size]
    gutter = gutter_margin_for_page_count(page_count)
    cover_width = (width_in * 2) + (KDP_DEFAULTS.bleed_in * 2) + estimate_spine_width(page_count)
    cover_height = height_in + (KDP_DEFAULTS.bleed_in * 2)
    return KdpBookSpec(
        trim_size=trim_size,
        width_in=width_in,
        height_in=height_in,
        bleed_in=KDP_DEFAULTS.bleed_in,
        safe_margin_in=KDP_DEFAULTS.safe_margin_in,
        page_count=page_count,
        gutter_margin_in=gutter,
        cover_width_in=round(cover_width, 3),
        cover_height_in=round(cover_height, 3),
        kdp_ready=KDP_DEFAULTS.min_pages <= page_count <= KDP_DEFAULTS.max_pages_bw,
    )


def normalize_page_count(content_pages: int, minimum: int = KDP_DEFAULTS.min_pages) -> int:
    padded = max(content_pages, minimum)
    return int(ceil(padded / 2.0) * 2)


def page_pixels_for_trim(trim_size: str, dpi: int = 300) -> tuple[int, int]:
    width_in, height_in = TRIM_SIZES_IN[trim_size]
    return int(width_in * dpi), int(height_in * dpi)


def page_points_for_trim(trim_size: str) -> tuple[float, float]:
    width_in, height_in = TRIM_SIZES_IN[trim_size]
    return width_in * 72.0, height_in * 72.0