File size: 10,158 Bytes
ce8f04a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
303
304
305
306
307
308
309
"""
Unified document extraction pipeline for URLs / HTML / PDF bytes.

Cascade (ethical, rate-friendly):
  1. PDF URL → download + PyMuPDF/pypdf
  2. HTML URL → fetch (httpx/requests) → Trafilatura main content
  3. Optional Crawl4AI markdown if HTTP body is thin (caller may pass prefetched html)

Always attaches legal citation extraction for regulation grounding.
"""
from __future__ import annotations

import logging
import os
import re
import tempfile
from typing import Any, Dict, Optional
from urllib.parse import urlparse

from core.document_intel.html_extract import html_to_clean_text
from core.document_intel.legal_citations import extract_legal_citations
from core.document_intel.pdf_extract import extract_pdf_text

logger = logging.getLogger(__name__)

_PDF_EXT = re.compile(r"\.pdf($|\?)", re.I)


def extract_from_html(
    html: str,
    *,
    url: str = "",
    content_type: str = "",
) -> Dict[str, Any]:
    """Clean HTML + legal citations. Binary/ZIP URLs short-circuit without Trafilatura."""
    try:
        from core.document_intel.fetch_resilience import should_skip_html_extract

        if should_skip_html_extract(url, content_type=content_type or None):
            return {
                "text": "",
                "extractor": "skipped_binary",
                "chars": 0,
                "legal": extract_legal_citations(""),
                "content_type": "binary",
                "url": url,
                "ok": False,
                "skipped": True,
                "reason": "binary_or_archive",
            }
    except Exception:
        pass

    cleaned = html_to_clean_text(html or "", url=url, content_type=content_type)
    if cleaned.get("skipped"):
        return {
            "text": "",
            "extractor": cleaned.get("extractor") or "skipped_binary",
            "chars": 0,
            "legal": extract_legal_citations(""),
            "content_type": "binary",
            "url": url,
            "ok": False,
            "skipped": True,
            "reason": "binary_or_archive",
        }
    text = cleaned.get("text") or ""
    cites = extract_legal_citations(text)
    return {
        "text": text,
        "extractor": cleaned.get("extractor"),
        "chars": cleaned.get("chars") or len(text),
        "legal": cites,
        "content_type": "html",
        "url": url,
        "ok": bool(text and len(text) >= 40),
    }


def _looks_like_pdf_url(url: str) -> bool:
    if not url:
        return False
    path = urlparse(url).path or ""
    return bool(_PDF_EXT.search(path) or path.lower().endswith(".pdf"))


def _fetch_bytes(url: str, *, timeout: float = 45.0) -> Dict[str, Any]:
    """HTTP GET — prefer curl_cffi stealth on WAF domains, else requests."""
    try:
        from core.document_intel.stealth_fetch import should_use_stealth, stealth_get

        if should_use_stealth(url):
            stealth = stealth_get(url, timeout=timeout)
            if stealth.get("ok"):
                return {
                    "status_code": stealth.get("status_code") or 200,
                    "content": stealth.get("content") or b"",
                    "text": stealth.get("text") or "",
                    "headers": stealth.get("headers") or {},
                    "final_url": stealth.get("final_url") or url,
                    "via": f"stealth:{stealth.get('impersonate')}",
                }
            # fall through to plain requests
    except Exception as e:
        logger.debug("[DocIntel] stealth path skip: %s", e)

    import requests

    headers = {
        "User-Agent": (
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        ),
        "Accept": "text/html,application/xhtml+xml,application/pdf,*/*;q=0.8",
        "Accept-Language": "pl-PL,pl;q=0.9,en;q=0.8",
    }
    resp = requests.get(url, headers=headers, timeout=timeout, allow_redirects=True)
    return {
        "status_code": resp.status_code,
        "content": resp.content,
        "text": resp.text if resp.encoding or resp.apparent_encoding else "",
        "headers": {k.lower(): v for k, v in resp.headers.items()},
        "final_url": str(resp.url),
        "via": "requests",
    }


def _process_fetched(
    url: str,
    fetched: Dict[str, Any],
    *,
    is_pdf: bool,
) -> Dict[str, Any]:
    status = int(fetched.get("status_code") or 0)
    if status >= 400 or status == 0:
        return {
            "ok": False,
            "reason": f"http_{status}",
            "text": "",
            "url": url,
            "status_code": status,
        }

    ctype = (fetched.get("headers") or {}).get("content-type", "")
    content: bytes = fetched.get("content") or b""
    final_url = fetched.get("final_url") or url

    if is_pdf or "application/pdf" in ctype or content[:4] == b"%PDF":
        fd, path = tempfile.mkstemp(suffix=".pdf")
        try:
            with os.fdopen(fd, "wb") as f:
                f.write(content)
            pdf = extract_pdf_text(path)
            text = pdf.get("text") or ""
            cites = extract_legal_citations(text)
            return {
                "ok": bool(text and len(text) >= 40),
                "text": text,
                "extractor": pdf.get("parser"),
                "chars": pdf.get("chars") or len(text),
                "legal": cites,
                "content_type": "pdf",
                "url": final_url,
                "status_code": status,
                "source": "pdf_bytes",
            }
        finally:
            try:
                os.unlink(path)
            except Exception:
                pass

    html = fetched.get("text") or ""
    if not html and content:
        try:
            html = content.decode("utf-8", errors="replace")
        except Exception:
            html = ""
    out = extract_from_html(html, url=final_url)
    out["status_code"] = status
    out["url"] = final_url
    out["source"] = "http_html"
    return out


def extract_document_from_url(
    url: str,
    *,
    prefer_pdf: Optional[bool] = None,
    html_hint: Optional[str] = None,
    timeout: float = 45.0,
) -> Dict[str, Any]:
    """
    Fetch URL and extract clean text + legal citations (sync).
    Soft-fails with ok=False (never raises for network issues).
    """
    if not url or not str(url).startswith(("http://", "https://")):
        return {"ok": False, "reason": "invalid_url", "text": "", "url": url}

    try:
        from core.document_intel.fetch_resilience import (
            is_binary_or_archive_url,
            path_extension,
        )

        # ZIP/archives: never fetch into Trafilatura (P2)
        if is_binary_or_archive_url(url) and path_extension(url) != ".pdf":
            return {
                "ok": False,
                "reason": "skipped_binary_archive",
                "text": "",
                "url": url,
                "skipped": True,
                "extractor": "skipped_binary",
            }
    except Exception:
        pass

    if html_hint:
        out = extract_from_html(html_hint, url=url)
        out["source"] = "html_hint"
        return out

    is_pdf = prefer_pdf if prefer_pdf is not None else _looks_like_pdf_url(url)

    try:
        fetched = _fetch_bytes(url, timeout=timeout)
    except Exception as e:
        logger.warning("[DocIntel] fetch failed %s: %s", url[:80], e)
        return {"ok": False, "reason": f"fetch_error:{e}"[:120], "text": "", "url": url}

    return _process_fetched(url, fetched, is_pdf=is_pdf)


async def extract_document_from_url_async(
    url: str,
    *,
    prefer_pdf: Optional[bool] = None,
    html_hint: Optional[str] = None,
    timeout: float = 45.0,
    use_crawl4ai_fallback: bool = True,
) -> Dict[str, Any]:
    """
    Async variant: same cascade + optional Crawl4AI when HTML is thin.
    """
    import asyncio

    if not url or not str(url).startswith(("http://", "https://")):
        return {"ok": False, "reason": "invalid_url", "text": "", "url": url}

    try:
        from core.document_intel.fetch_resilience import (
            is_binary_or_archive_url,
            path_extension,
        )

        if is_binary_or_archive_url(url) and path_extension(url) != ".pdf":
            return {
                "ok": False,
                "reason": "skipped_binary_archive",
                "text": "",
                "url": url,
                "skipped": True,
                "extractor": "skipped_binary",
            }
    except Exception:
        pass

    if html_hint:
        out = extract_from_html(html_hint, url=url)
        out["source"] = "html_hint"
        return out

    is_pdf = prefer_pdf if prefer_pdf is not None else _looks_like_pdf_url(url)

    try:
        fetched = await asyncio.to_thread(_fetch_bytes, url, timeout=timeout)
    except Exception as e:
        logger.warning("[DocIntel] async fetch failed %s: %s", url[:80], e)
        return {"ok": False, "reason": f"fetch_error:{e}"[:120], "text": "", "url": url}

    out = _process_fetched(url, fetched, is_pdf=is_pdf)
    min_chars = int(os.environ.get("DOC_INTEL_MIN_CHARS", "120"))
    if (
        use_crawl4ai_fallback
        and out.get("content_type") != "pdf"
        and (not out.get("ok") or (out.get("chars") or 0) < min_chars)
    ):
        try:
            from core.crawl4ai_client import scrape_url_to_markdown

            md = await scrape_url_to_markdown(out.get("url") or url)
            if md and len(md.strip()) > (out.get("chars") or 0):
                cites = extract_legal_citations(md)
                return {
                    "ok": True,
                    "text": md.strip(),
                    "extractor": "crawl4ai",
                    "chars": len(md.strip()),
                    "legal": cites,
                    "content_type": "markdown",
                    "url": out.get("url") or url,
                    "status_code": out.get("status_code"),
                    "source": "crawl4ai_fallback",
                }
        except Exception as e:
            logger.debug("[DocIntel] crawl4ai fallback skip: %s", e)
    return out