File size: 9,787 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
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
from __future__ import annotations

import logging
import re
import time
from datetime import date
from html import unescape
from urllib.parse import urljoin

import requests
from dateutil import parser as dateutil_parser

from legex.models.base import Case
from legex.scrapers.base import BaseScraper

# Data source: https://juportal.be/zoekmachine/zoekformulier
# We submit the official search form with civil case-number prefix "C." and
# page through server-side "next_page" form actions.

log = logging.getLogger(__name__)

BASE_URL = "https://juportal.be"
SEARCH_FORM_URL = f"{BASE_URL}/zoekmachine/zoekformulier"
SEARCH_RESULTS_URL = f"{BASE_URL}/zoekmachine/zoekresultaten"
DELAY_SECONDS = 3
RETRY_DELAY_SECONDS = 30
MAX_PAGES_PER_QUERY = 300

_RE_FORM_TOKEN = re.compile(r'name=["\']TOKEN["\'][^>]*value=["\']([^"\']*)', re.IGNORECASE)
_RE_ACTION_VALUE = re.compile(
    r'<button[^>]*name=["\']action["\'][^>]*value=["\']([^"\']*)',
    re.IGNORECASE,
)
_RE_NEXT_VALUE = re.compile(
    r'<button[^>]*name=["\']next_page["\'][^>]*value=["\']([^"\']*)',
    re.IGNORECASE,
)
_RE_CONTENT_LINK = re.compile(r'href=["\'](/content/ECLI:BE:CASS:[^"\']+)["\']', re.IGNORECASE)
_RE_ROLE = re.compile(r"Rolnummer:\s*([A-Z]\.[0-9]{2}\.[0-9]{4}\.[A-Z])", re.IGNORECASE)
_RE_DATE = re.compile(r"Vonnis/arrest van\s+([0-9]{1,2}\s+[A-Za-z]+\s+[0-9]{4})", re.IGNORECASE)
_RE_ECLI = re.compile(r"(ECLI:BE:CASS:[A-Z0-9:.]+)")
_RE_RESULT_ROW_META = re.compile(
    r"Hof van Cassatie\s*-\s*([0-9]{1,2}\s+[A-Za-z]+\s+[0-9]{4})\s*-\s*([A-Z]\.[0-9]{2}\.[0-9]{4}\.[A-Z])",
    re.IGNORECASE,
)


def _parse_date(text: str | None) -> date | None:
    if not text:
        return None
    cleaned = text.strip()
    try:
        return date.fromisoformat(cleaned)
    except ValueError:
        pass
    try:
        return dateutil_parser.parse(cleaned, dayfirst=True).date()
    except (ValueError, OverflowError, dateutil_parser.ParserError):
        return None


def _extract_token(html: str) -> str | None:
    match = _RE_FORM_TOKEN.search(html)
    return match.group(1) if match else None


def _extract_action_value(html: str) -> str | None:
    match = _RE_ACTION_VALUE.search(html)
    return match.group(1) if match else None


def _extract_next_value(html: str) -> str | None:
    match = _RE_NEXT_VALUE.search(html)
    return match.group(1) if match else None


def _extract_result_links(html: str) -> list[str]:
    links = []
    seen: set[str] = set()
    for raw_link in _RE_CONTENT_LINK.findall(html):
        clean = raw_link.split("#", 1)[0]
        if ":ARR." not in clean:
            continue
        if clean in seen:
            continue
        seen.add(clean)
        links.append(urljoin(BASE_URL, clean))
    return links


def _extract_result_cases(html: str) -> list[Case]:
    cases: list[Case] = []
    seen: set[str] = set()
    chunks = html.split("<tr>")
    for chunk in chunks:
        link_match = _RE_CONTENT_LINK.search(chunk)
        if not link_match:
            continue
        rel = link_match.group(1).split("#", 1)[0]
        if ":ARR." not in rel:
            continue
        link = urljoin(BASE_URL, rel)
        if link in seen:
            continue
        seen.add(link)

        ecli_match = _RE_ECLI.search(chunk)
        meta_match = _RE_RESULT_ROW_META.search(unescape(re.sub(r"<[^>]+>", " ", chunk)))
        if not meta_match:
            continue
        decision_date = _parse_date(meta_match.group(1))
        case_id = meta_match.group(2).upper()
        if not case_id.startswith("C."):
            continue

        cases.append(
            Case(
                case_id=case_id,
                link=link,
                decision_date=decision_date,
                jurisdiction="be",
                language="nl",
                full_text=None,
                metadata={
                    "ecli": (ecli_match.group(1).upper() if ecli_match else None),
                    "source": "juportal.be",
                },
            )
        )
    return cases


def _extract_case_id(page_text: str) -> str | None:
    match = _RE_ROLE.search(page_text)
    return match.group(1).upper() if match else None


def _extract_ecli(page_text: str) -> str | None:
    match = _RE_ECLI.search(page_text)
    return match.group(1).upper() if match else None


def _extract_decision_date(page_text: str) -> date | None:
    match = _RE_DATE.search(page_text)
    return _parse_date(match.group(1) if match else None)


def _extract_text(page_html: str) -> str | None:
    text = unescape(re.sub(r"<[^>]+>", "\n", page_html))
    lines = [line.strip() for line in text.splitlines()]
    cleaned = [line for line in lines if line]
    return "\n".join(cleaned) if cleaned else None


class BEScraper(BaseScraper):
    country = "Belgium"

    def scrape(
        self,
        start_date: date | None = None,
        end_date: date | None = None,
    ) -> list[Case]:
        start = start_date or date(2015, 1, 1)
        end = end_date or date.today()
        cases: list[Case] = []
        seen: set[str] = set()
        session = requests.Session()

        for year in range(start.year, end.year + 1):
            year_start = max(start, date(year, 1, 1))
            year_end = min(end, date(year, 12, 31))
            if year_start > year_end:
                continue
            year_cases = self._scrape_year(session, year_start, year_end)
            for case in year_cases:
                if not case.link or case.link in seen:
                    continue
                seen.add(case.link)
                cases.append(case)

        return cases

    def _scrape_year(
        self,
        session: requests.Session,
        start_date: date,
        end_date: date,
    ) -> list[Case]:
        log.info("Belgium %s to %s", start_date.isoformat(), end_date.isoformat())
        form_html = self._fetch_text(session, SEARCH_FORM_URL)
        if form_html is None:
            return []
        token = _extract_token(form_html)
        action_value = _extract_action_value(form_html)
        if not token or not action_value:
            return []

        payload = {
            "TOKEN": token,
            "action": action_value,
            "TRECHNOROLE": "C.",
            "TRECHDECISIONDE": start_date.isoformat(),
            "TRECHDECISIONA": end_date.isoformat(),
            "TRECHNPPAGE": "50",
            "TRECHORDER": "DATEDEC",
            "TRECHDESCASC": "DESC",
            "TRECHOPER": "AND",
            "TRECHLIMIT": "25000",
            "TRECHMODE": "SIMPLE",
            "TRECHSCORE": "1",
            "TRECHSHOWFICHES": "fiches",
        }
        page_html = self._post_text(session, SEARCH_FORM_URL, payload)
        if page_html is None:
            return []

        results: list[Case] = []
        seen_links: set[str] = set()
        for page_idx in range(1, MAX_PAGES_PER_QUERY + 1):
            links = _extract_result_links(page_html)
            if not links:
                break
            log.info("Belgium page %d: %d decision links", page_idx, len(links))
            page_cases = _extract_result_cases(page_html)
            for case in page_cases:
                if not case.link or case.link in seen_links:
                    continue
                seen_links.add(case.link)
                results.append(case)

            next_value = _extract_next_value(page_html)
            next_token = _extract_token(page_html)
            if not next_value or not next_token:
                break
            time.sleep(DELAY_SECONDS)
            page_html = self._post_text(
                session,
                SEARCH_RESULTS_URL,
                {"TOKEN": next_token, "next_page": next_value},
            )
            if page_html is None:
                break

        return [
            c for c in results
            if c.decision_date is not None
            and start_date <= c.decision_date <= end_date
        ]

    def _fetch_case(self, link: str) -> Case | None:
        html = self._fetch_url_text(link)
        if html is None:
            return None
        text = _extract_text(html)
        if text is None:
            return None

        case_id = _extract_case_id(text)
        if not case_id or not case_id.startswith("C."):
            return None

        decision_date = _extract_decision_date(text)
        ecli = _extract_ecli(text)
        return Case(
            case_id=case_id,
            link=link,
            decision_date=decision_date,
            jurisdiction="be",
            language="nl",
            full_text=text,
            metadata={"ecli": ecli, "source": "juportal.be"} if ecli else {"source": "juportal.be"},
        )

    @staticmethod
    def civil_filter(cases: list[Case]) -> list[Case]:
        return [c for c in cases if (c.case_id or "").startswith("C.")]

    def _fetch_text(self, session: requests.Session, url: str) -> str | None:
        try:
            response = session.get(url, timeout=30)
            if response.status_code == 429:
                time.sleep(RETRY_DELAY_SECONDS)
                response = session.get(url, timeout=30)
            if not response.ok:
                return None
            return response.text
        except requests.RequestException:
            return None

    def _post_text(self, session: requests.Session, url: str, data: dict[str, str]) -> str | None:
        try:
            response = session.post(url, data=data, timeout=30)
            if response.status_code == 429:
                time.sleep(RETRY_DELAY_SECONDS)
                response = session.post(url, data=data, timeout=30)
            if not response.ok:
                return None
            return response.text
        except requests.RequestException:
            return None