File size: 4,064 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
import logging
import re
import time
from datetime import date, datetime
from typing import Any

import requests

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

log = logging.getLogger(__name__)

HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; LegalResearch/1.0)"}
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
DEFAULT_YEARS = list(range(2026, 2004, -1))
MAX_CANDIDATES = 500
DELAY_SECONDS = 0.3

_LINK_RE = re.compile(r"<a\s+href='[^']*showdocs/(\d+)/(\d+)'[^>]*>(.*?)</a>", re.DOTALL)
_CASE_NO_RE = re.compile(r"<STRONG>\s*(.*?)\s*</STRONG>", re.DOTALL)
_DATE_RE = re.compile(
    r"((?:January|February|March|April|May|June|July|August|September|October|November|December)"
    r"\s+\d{1,2},\s+\d{4})"
)


def _scrape_month(mon: str, year: int) -> tuple[list[dict[str, Any]], str | None]:
    """Scrape a single month's decisions page."""
    url = f"https://elibrary.judiciary.gov.ph/thebookshelf/docmonth/{mon}/{year}/1"
    cases: list[dict[str, Any]] = []
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.raise_for_status()
    except Exception as e:
        return cases, str(e)

    for doc_type, doc_id, inner_html in _LINK_RE.findall(r.text):
        cn_match = _CASE_NO_RE.search(inner_html)
        case_no = cn_match.group(1).strip() if cn_match else ""

        date_str = ""
        d_match = _DATE_RE.search(inner_html)
        if d_match:
            try:
                dt = datetime.strptime(d_match.group(1), "%B %d, %Y")
                date_str = dt.strftime("%Y-%m-%d")
            except ValueError:
                pass

        link = f"https://elibrary.judiciary.gov.ph/thebookshelf/showdocsfriendly/{doc_type}/{doc_id}"
        cases.append({"decision_date": date_str, "link": link, "case_id": case_no})
    return cases, None


class PHScraper(BaseScraper):
    country = "Philippinen"

    def scrape(
        self,
        start_date: date | None = None,
        end_date: date | None = None,
    ) -> list[Case]:
        years = DEFAULT_YEARS
        if end_date is not None:
            years = [y for y in years if y <= end_date.year]
        if start_date is not None:
            years = [y for y in years if y >= start_date.year]

        rows: list[dict[str, Any]] = []
        seen: set[str] = set()
        for year in years:
            if len(rows) >= MAX_CANDIDATES:
                break
            for mon in MONTHS:
                if len(rows) >= MAX_CANDIDATES:
                    break
                month_rows, err = _scrape_month(mon, year)
                if err:
                    log.warning("PH %s %s: %s", mon, year, err)
                else:
                    for row in month_rows:
                        if row["link"] in seen:
                            continue
                        seen.add(row["link"])
                        rows.append(row)
                    log.info("PH %s %s: %d new (running %d)", mon, year, len(month_rows), len(rows))
                time.sleep(DELAY_SECONDS)

        cases: list[Case] = []
        for row in rows:
            decision_date: date | None = None
            if row["decision_date"]:
                try:
                    decision_date = date.fromisoformat(row["decision_date"])
                except ValueError:
                    decision_date = None

            if start_date and decision_date and decision_date < start_date:
                continue
            if end_date and decision_date and decision_date > end_date:
                continue

            cases.append(Case(
                case_id=row["case_id"] or None,
                link=row["link"],
                decision_date=decision_date,
                jurisdiction="ph",
                language="en",
                full_text=None,
                metadata={},
            ))

        cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
        log.info("Collected %d Philippines cases", len(cases))
        return cases