File size: 5,058 Bytes
6f5156a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Font download, sanitization, and FPDF writing."""

from __future__ import annotations

import hashlib
import re
import urllib.request
from pathlib import Path

from fpdf import FPDF
from fpdf.enums import Align, WrapMode

FONT_DIR = Path(__file__).resolve().parent / "_fonts"

FONT_URLS = {
    "NotoSans-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf",
    "SourceHanSansSC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/SimplifiedChinese/SourceHanSansSC-Regular.otf",
    "SourceHanSansK-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/Korean/SourceHanSansK-Regular.otf",
}

EXTRA_FONT_URLS = {
    "SourceHanSansTC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/TraditionalChinese/SourceHanSansTC-Regular.otf",
    "NotoSansDevanagari-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansDevanagari/NotoSansDevanagari-Regular.ttf",
    "NotoSansArmenian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansArmenian/NotoSansArmenian-Regular.ttf",
    "NotoSansGeorgian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansGeorgian/NotoSansGeorgian-Regular.ttf",
}


def ensure_fonts() -> None:
    FONT_DIR.mkdir(parents=True, exist_ok=True)
    all_fonts = {**FONT_URLS, **EXTRA_FONT_URLS}
    for name, url in all_fonts.items():
        dest = FONT_DIR / name
        if dest.exists() and dest.stat().st_size > 1000:
            continue
        print(f"Downloading font {name} …", flush=True)
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:
            f.write(r.read())


def sanitize_pdf_text(s: str) -> str:
    s = str(s).replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n")
    s = s.replace("\uf0b7", "•").replace("\uf0a7", "•").replace("\uf0d8", "•")
    s = s.replace("\uf02d", "–")
    return s


def safe_slug(case_id: str | None, link: str | None, row_idx: int) -> str:
    raw = (case_id or "").strip()
    if not raw:
        h = hashlib.sha256(((link or "") + str(row_idx)).encode("utf-8")).hexdigest()[:12]
        raw = f"decision_{row_idx}_{h}"
    raw = raw.replace("\n", " ").strip()
    raw = re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", raw)
    raw = re.sub(r"\s+", "_", raw)
    raw = raw.strip("._") or f"row_{row_idx}"
    if len(raw) > 120:
        raw = raw[:120].rstrip("_")
    return raw


class UnicodePDF(FPDF):
    pass


def pdf_font_setup(pdf: FPDF, key: str) -> str:
    if key == "han_sc":
        pdf.add_font("HanSC", "", str(FONT_DIR / "SourceHanSansSC-Regular.otf"))
        return "HanSC"
    if key == "han_tc":
        pdf.add_font("HanTC", "", str(FONT_DIR / "SourceHanSansTC-Regular.otf"))
        return "HanTC"
    if key == "han_k":
        pdf.add_font("HanK", "", str(FONT_DIR / "SourceHanSansK-Regular.otf"))
        return "HanK"
    if key == "deva":
        pdf.add_font("Deva", "", str(FONT_DIR / "NotoSansDevanagari-Regular.ttf"))
        return "Deva"
    if key == "arm":
        pdf.add_font("Arm", "", str(FONT_DIR / "NotoSansArmenian-Regular.ttf"))
        return "Arm"
    if key == "geo":
        pdf.add_font("Geo", "", str(FONT_DIR / "NotoSansGeorgian-Regular.ttf"))
        return "Geo"
    pdf.add_font("NotoSans", "", str(FONT_DIR / "NotoSans-Regular.ttf"))
    return "NotoSans"


def write_one_pdf(
    path: Path,
    case_id: str,
    link: str,
    body: str,
    font_key: str,
    *,
    text_source: str | None = None,
) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    pdf = UnicodePDF()
    pdf.set_auto_page_break(auto=True, margin=14)
    pdf.set_left_margin(14)
    pdf.set_right_margin(14)
    pdf.add_page()
    # Use one font for meta + body when the script is non-Latin: case_id often
    # contains Hangul etc., and NotoSans would miss those glyphs in the header.
    if font_key == "default":
        text_family = pdf_font_setup(pdf, "default")
    else:
        text_family = pdf_font_setup(pdf, font_key)
    pdf.set_font(text_family, size=11)
    head = [f"case_id: {case_id}", f"link: {link}"]
    if text_source:
        head.append(f"Quelle Text: {text_source}")
    head.append("")
    meta = sanitize_pdf_text("\n".join(head))
    # Latin header: WORD wrap; CJK header lines are short — WORD is fine with LEFT.
    pdf.multi_cell(0, 6, meta, align=Align.L, wrapmode=WrapMode.WORD)
    pdf.ln(2)
    pdf.set_font(text_family, size=10)
    text = body if (body and str(body).strip()) else "(kein Volltext in der Quelle)"
    body_txt = sanitize_pdf_text(text)
    if font_key == "default":
        pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.WORD)
    else:
        pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.CHAR)
    pdf.output(str(path))