File size: 6,063 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
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
"""Fetch document bodies from ``link`` and write PDFs (fallback: ``full_text``)."""

from __future__ import annotations

import io
import sys
import time
from pathlib import Path

import openpyxl
import requests
from bs4 import BeautifulSoup
from pypdf import PdfReader

from legex.pdf_export.core import safe_slug, write_one_pdf
from legex.pdf_export.font_keys import font_key_for_workbook
from legex.pdf_export.workbook import cell, discover_goldensets, header_map

UA = "Mozilla/5.0 (compatible; LegexPDFExport/1.0)"


def is_hf_dataset_stub_url(url: str) -> bool:
    u = url.lower()
    return "huggingface.co" in u and "/datasets/" in u


def effective_timeout(url: str, configured: float) -> float:
    u = url.lower()
    if "hcourt.gov.au" in u:
        return min(configured, 10.0)
    if "openlegaldata.io" in u:
        return min(configured, 12.0)
    return configured


def fetch_document_text(url: str, timeout: float = 28.0) -> str:
    url = (url or "").strip()
    if not url or not url.startswith("http"):
        return ""
    last_err: str | None = None
    for attempt in range(2):
        try:
            r = requests.get(
                url,
                timeout=timeout,
                headers={"User-Agent": UA, "Accept": "text/html,application/pdf;q=0.9,*/*;q=0.8"},
                allow_redirects=True,
            )
            r.raise_for_status()
            data = r.content
            if len(data) >= 4 and data[:4] == b"%PDF":
                reader = PdfReader(io.BytesIO(data))
                return "\n\n".join((p.extract_text() or "") for p in reader.pages)
            enc = r.encoding or "utf-8"
            try:
                html = data.decode(enc, errors="replace")
            except LookupError:
                html = data.decode("utf-8", errors="replace")
            soup = BeautifulSoup(html, "lxml")
            for tag in soup(["script", "style", "noscript"]):
                tag.decompose()
            text = soup.get_text("\n")
            lines = [ln.strip() for ln in text.splitlines()]
            return "\n".join(ln for ln in lines if ln)
        except Exception as e:
            last_err = str(e)
            if attempt < 1:
                time.sleep(1.2 * (attempt + 1))
    if last_err:
        return f"[Abruf fehlgeschlagen: {last_err}]\n"
    return ""


def pick_body(
    link_val: str,
    sheet_full: str | None,
    pause_s: float,
    req_timeout: float,
) -> tuple[str, str]:
    time.sleep(pause_s)
    link_val = (link_val or "").strip()
    sheet = (sheet_full or "").strip()

    if link_val and is_hf_dataset_stub_url(link_val):
        if sheet:
            return sheet, "full_text (HF-Dataset-Link)"
        return "(kein Volltext in der Zeile trotz HF-Link)", "leer"

    fetched = (
        fetch_document_text(link_val, timeout=effective_timeout(link_val, req_timeout))
        if link_val
        else ""
    )
    if fetched and not fetched.startswith("[Abruf fehlgeschlagen"):
        return fetched.strip(), "URL"
    if sheet:
        return sheet, "full_text (Fallback)"
    if fetched:
        return fetched.strip(), "URL (Fehlermeldung)"
    return "(kein Volltext — weder URL noch Tabellenfeld)", "leer"


def export_workbook(
    xlsx: Path,
    out_root: Path,
    *,
    pause_s: float,
    limit: int | None,
    req_timeout: float,
    resume: bool,
) -> int:
    label = xlsx.parent.name
    out_dir = out_root / label
    font_key = font_key_for_workbook(xlsx)

    wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True)
    if "GOLDENSET" not in wb.sheetnames:
        wb.close()
        print(f"  skip {xlsx.name}: kein Sheet GOLDENSET", flush=True)
        return 0
    ws = wb["GOLDENSET"]
    rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True)
    header_row = next(rows, None)
    if not header_row:
        wb.close()
        return 0
    h = header_map(header_row)
    idx_case = h.get("case_id")
    idx_link = h.get("link")
    idx_text = h.get("full_text")
    if idx_link is None:
        wb.close()
        print(f"  skip {xlsx.name}: keine Spalte 'link'", flush=True)
        return 0

    used_names: dict[str, int] = {}
    count = 0
    row_idx = 1
    for row in rows:
        row_idx += 1
        if not row:
            continue
        link_val = cell(row, idx_link) or ""
        case_id = cell(row, idx_case)
        sheet_full = cell(row, idx_text) if idx_text is not None else None
        if (
            not str(case_id or "").strip()
            and not link_val.strip()
            and not (sheet_full or "").strip()
        ):
            continue
        base = safe_slug(case_id, link_val or None, row_idx)
        used_names[base] = used_names.get(base, 0) + 1
        fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf"
        out_path = out_dir / fname
        if resume and out_path.exists() and out_path.stat().st_size > 80:
            count += 1
            if count % 25 == 0:
                print(f"  {label}: {count} (Bestand übersprungen) …", flush=True)
            if limit is not None and count >= limit:
                break
            continue

        body, prov = pick_body(link_val, sheet_full, pause_s, req_timeout)
        write_one_pdf(out_path, str(case_id or ""), link_val, body, font_key, text_source=prov)
        count += 1
        if count % 10 == 0:
            print(f"  {label}: {count} …", flush=True)
        if limit is not None and count >= limit:
            break
    wb.close()
    print(f"  {label}: fertig, {count} PDFs", flush=True)
    return count


def collect_workbooks(data_dir: Path, input_dirs: list[Path] | None) -> list[Path]:
    if input_dirs:
        files: list[Path] = []
        for d in input_dirs:
            if not d.is_dir():
                print("Ordner fehlt:", d, file=sys.stderr)
                continue
            files.extend(sorted(d.glob("Goldenset_*.xlsx")))
        return sorted(files, key=lambda p: (p.stem.lower(), str(p)))
    return discover_goldensets(data_dir)