loupe-scan 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loupe_scan/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Find text on web pages that human readers can't see but AI agents can.
2
+
3
+ from loupe_scan import scan
4
+
5
+ result = scan("https://example.com/")
6
+ print(result.verdict)
7
+
8
+ docs/python.md describes the API.
9
+ """
10
+
11
+ from loupe_scan._version import __version__
12
+ from loupe_scan.api import HiddenText, Scanner, ScanError, ScanResult, scan, scan_html
13
+ from loupe_scan.backend import Backend
14
+ from loupe_scan.errors import SetupError
15
+ from loupe_scan.report import FailOn, FailureKind
16
+ from loupe_scan.scan import Kind, ScanMode
17
+ from loupe_scan.stylesheets import StylesheetCheck
18
+
19
+ __all__ = [
20
+ "Backend",
21
+ "FailOn",
22
+ "FailureKind",
23
+ "HiddenText",
24
+ "Kind",
25
+ "ScanError",
26
+ "ScanMode",
27
+ "ScanResult",
28
+ "Scanner",
29
+ "SetupError",
30
+ "StylesheetCheck",
31
+ "__version__",
32
+ "scan",
33
+ "scan_html",
34
+ ]
loupe_scan/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """python -m loupe_scan runs the loupe command, for when its script isn't on PATH."""
2
+
3
+ import sys
4
+
5
+ from loupe_scan.cli import main
6
+
7
+ sys.exit(main())
loupe_scan/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """The installed loupe-scan version, kept apart so every module can import it without a cycle."""
2
+
3
+ __version__ = "0.2.0"
loupe_scan/api.py ADDED
@@ -0,0 +1,251 @@
1
+ """loupe from Python: scan a page and get back the text it hides from people.
2
+
3
+ from loupe_scan import scan
4
+
5
+ result = scan("https://example.com/")
6
+ print(result.verdict)
7
+
8
+ docs/python.md has the whole API and an example of checking a page before
9
+ handing it to a model.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass, field
18
+ from types import TracebackType
19
+ from typing import Literal
20
+
21
+ from loupe_scan.backend import Backend
22
+ from loupe_scan.report import (
23
+ DEFAULT_QUOTE_CHARACTERS,
24
+ CheckedFinding,
25
+ FailOn,
26
+ FailureKind,
27
+ PageReport,
28
+ findings_counted,
29
+ page_to_dict,
30
+ verdict,
31
+ )
32
+ from loupe_scan.render import open_renderer
33
+ from loupe_scan.scan import Kind, ScanMode
34
+ from loupe_scan.session import ScanSession, ScanSettings, endpoint_redactor, scan_supplied_html, scrub_strings
35
+ from loupe_scan.stylesheets import StylesheetCheck
36
+ from loupe_scan.urls import url_problem
37
+
38
+ BackendName = Literal["local", "brightdata"]
39
+ FailOnName = Literal["instructions", "hidden", "never"]
40
+
41
+
42
+ class ScanError(RuntimeError):
43
+ """The page couldn't be scanned. kind says why, as error.kind does in the JSON. The message is safe to print."""
44
+
45
+ def __init__(self, message: str, *, url: str, kind: FailureKind) -> None:
46
+ super().__init__(message)
47
+ self.url = url
48
+ self.kind = kind
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class HiddenText:
53
+ """One piece of text the page hides from people."""
54
+
55
+ # The whole text. Per-request meta values such as nonces are replaced with a placeholder.
56
+ text: str
57
+ kind: Kind
58
+ # How it was hidden, such as "display:none" or "alt".
59
+ detail: str
60
+ tag: str
61
+ # STATIC when the markup scan found it, RENDERED when the browser did.
62
+ mode: ScanMode
63
+ # The phrases that make it read like an instruction to an AI. Empty when there are none.
64
+ instruction_phrases: tuple[str, ...]
65
+ # Whether the text reaches the markdown. None when it wasn't compared.
66
+ in_markdown: bool | None
67
+
68
+ @property
69
+ def is_instruction_like(self) -> bool:
70
+ return bool(self.instruction_phrases)
71
+
72
+
73
+ def _hidden_text(item: CheckedFinding, redact: Callable[[str], str]) -> HiddenText:
74
+ finding = item.finding
75
+ return HiddenText(
76
+ text=redact(finding.text),
77
+ kind=finding.kind,
78
+ detail=redact(finding.detail),
79
+ tag=finding.tag,
80
+ mode=finding.mode,
81
+ instruction_phrases=finding.instruction_phrases,
82
+ in_markdown=item.in_markdown,
83
+ )
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class ScanResult:
88
+ """What loupe found on one page. scan() and Scanner.scan() make these."""
89
+
90
+ url: str
91
+ backend: Backend
92
+ mode: ScanMode
93
+ # The plain-English summary the command line prints first. Its wording can change between releases.
94
+ verdict: str
95
+ hidden_text: tuple[HiddenText, ...]
96
+ # The markdown's length, or None when no markdown was compared.
97
+ markdown_characters: int | None
98
+ # Why the markdown couldn't be compared. The page itself was still scanned.
99
+ markdown_error: str | None
100
+ # What the markup scan's partial stylesheet check read, or None for a rendered scan.
101
+ stylesheet_check: StylesheetCheck | None
102
+ _report: PageReport = field(repr=False, compare=False)
103
+ _redact: Callable[[str], str] = field(repr=False, compare=False)
104
+
105
+ @property
106
+ def instruction_like(self) -> tuple[HiddenText, ...]:
107
+ """The hidden text worded like an instruction to an AI."""
108
+ return tuple(item for item in self.hidden_text if item.is_instruction_like)
109
+
110
+ def fails(self, fail_on: FailOn | FailOnName = FailOn.INSTRUCTIONS) -> bool:
111
+ """True when the page has a finding fail_on counts, as loupe --fail-on does for exit code 1."""
112
+ return bool(findings_counted(self._report, FailOn(fail_on)))
113
+
114
+ def to_dict(self, *, quote_characters: int = DEFAULT_QUOTE_CHARACTERS) -> dict[str, object]:
115
+ """The page as one object of loupe --json's array, with text cut to quote_characters (0 keeps it whole)."""
116
+ if quote_characters < 0:
117
+ raise ValueError("quote_characters must be 0 or more")
118
+ document = scrub_strings(page_to_dict(self._report, quote_characters), self._redact)
119
+ if not isinstance(document, dict):
120
+ raise TypeError("a page should turn into a JSON object")
121
+ return document
122
+
123
+ def to_json(self, *, quote_characters: int = DEFAULT_QUOTE_CHARACTERS, indent: int | None = 2) -> str:
124
+ """to_dict() as JSON text, in the format docs/json.md describes."""
125
+ return json.dumps(self.to_dict(quote_characters=quote_characters), indent=indent, ensure_ascii=False)
126
+
127
+
128
+ def _result(report: PageReport, redact: Callable[[str], str]) -> ScanResult:
129
+ if report.html_error is not None:
130
+ kind = FailureKind.FETCH if report.failure is None else report.failure
131
+ raise ScanError(redact(report.html_error), url=report.url, kind=kind)
132
+ return ScanResult(
133
+ url=report.url,
134
+ backend=report.backend,
135
+ mode=report.mode,
136
+ verdict=redact(verdict(report)),
137
+ hidden_text=tuple(_hidden_text(item, redact) for item in report.findings),
138
+ markdown_characters=report.markdown_characters,
139
+ markdown_error=None if report.markdown_error is None else redact(report.markdown_error),
140
+ stylesheet_check=report.stylesheet_check,
141
+ _report=report,
142
+ _redact=redact,
143
+ )
144
+
145
+
146
+ class Scanner:
147
+ """Scans several pages with one browser, and one robots.txt and Crawl-delay per site.
148
+
149
+ with Scanner(render=True) as scanner:
150
+ for url in urls:
151
+ result = scanner.scan(url)
152
+
153
+ backend is "local", "brightdata", or None to use Bright Data when its
154
+ environment variables are set and this machine otherwise. Raises
155
+ SetupError when loupe can't scan at all: when created for a missing
156
+ Bright Data token, and on entering the with block for a missing browser.
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ *,
162
+ render: bool = False,
163
+ backend: Backend | BackendName | None = None,
164
+ markdown: bool = True,
165
+ respect_robots: bool = True,
166
+ ) -> None:
167
+ settings = ScanSettings(
168
+ render=render,
169
+ backend=None if backend is None else Backend(backend),
170
+ markdown=markdown,
171
+ respect_robots=respect_robots,
172
+ )
173
+ self._session = ScanSession(settings, environment=os.environ)
174
+ self.backend = self._session.backend
175
+
176
+ def __repr__(self) -> str:
177
+ return f"Scanner(backend={self.backend.value!r}, render={self._session.settings.render})"
178
+
179
+ def __enter__(self) -> Scanner:
180
+ self._session.__enter__()
181
+ return self
182
+
183
+ def __exit__(
184
+ self,
185
+ error_type: type[BaseException] | None,
186
+ error: BaseException | None,
187
+ traceback: TracebackType | None,
188
+ ) -> None:
189
+ self._session.__exit__(error_type, error, traceback)
190
+
191
+ def scan(self, url: str) -> ScanResult:
192
+ """Scan url. Raises ScanError when the page couldn't be scanned, so a page is never passed on unchecked."""
193
+ return _result(self._session.scan(url), self._session.redact)
194
+
195
+
196
+ def scan(
197
+ url: str,
198
+ *,
199
+ render: bool = False,
200
+ backend: Backend | BackendName | None = None,
201
+ markdown: bool = True,
202
+ respect_robots: bool = True,
203
+ ) -> ScanResult:
204
+ """Scan one page. For several, use a Scanner, which reads each site's robots.txt once and keeps its Crawl-delay.
205
+
206
+ render loads the page in Chromium (it needs the render extra and
207
+ playwright install chromium). markdown compares the hidden text with a
208
+ markdown version of the page. respect_robots obeys robots.txt on the
209
+ local backend; turn it off only for pages you own or may scan.
210
+
211
+ Raises ScanError when the page couldn't be scanned (blocked, kept out by
212
+ robots.txt, or not fetched or loaded) and SetupError when loupe can't
213
+ scan at all.
214
+ """
215
+ with Scanner(render=render, backend=backend, markdown=markdown, respect_robots=respect_robots) as scanner:
216
+ return scanner.scan(url)
217
+
218
+
219
+ def scan_html(html: str, url: str, *, render: bool = False, markdown: bool = True) -> ScanResult:
220
+ """Scan HTML you already have, as the page at url, without fetching anything.
221
+
222
+ Scan the HTML you're about to hand to a model, and a site that serves
223
+ agents something different from what loupe would have fetched can't slip
224
+ past. The markdown compared is made here from the same HTML.
225
+
226
+ url must be an http(s) URL. Without render it only names the page, and
227
+ the stylesheet check reads the HTML's <style> blocks but no linked
228
+ stylesheet. With
229
+ render, local Chromium is given the HTML as the page at url, so relative
230
+ links resolve against it, and its stylesheets and scripts load from the
231
+ network; docs/python.md says how that can differ from a live load. It
232
+ needs the render extra and playwright install chromium.
233
+
234
+ Raises ScanError when the browser couldn't load it, SetupError when
235
+ rendering can't run here, and ValueError for a url that isn't http(s).
236
+ """
237
+ if not isinstance(html, str):
238
+ raise TypeError("html must be a str; decode bytes first, for example with the page's charset")
239
+ _require_web_url(url)
240
+ redact = endpoint_redactor(os.environ)
241
+ if not render:
242
+ return _result(scan_supplied_html(html, url, backend=Backend.LOCAL, markdown=markdown), redact)
243
+ with open_renderer(None) as renderer:
244
+ report = scan_supplied_html(html, url, backend=Backend.LOCAL, markdown=markdown, renderer=renderer)
245
+ return _result(report, redact)
246
+
247
+
248
+ def _require_web_url(url: str) -> None:
249
+ problem = url_problem(url)
250
+ if problem is not None:
251
+ raise ValueError(problem)
loupe_scan/backend.py ADDED
@@ -0,0 +1,34 @@
1
+ """Where loupe gets pages from: this machine, or Bright Data's APIs.
2
+
3
+ The local backend needs no account: it loads pages itself. The Bright Data
4
+ backend fetches the HTML through Web Unlocker, renders through the Browser
5
+ API and gets the markdown from the Fetch API, which gets past sites that turn
6
+ away automated visitors.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from enum import Enum
13
+
14
+ from loupe_scan.fetch import TOKEN_ENVIRONMENT_VARIABLE
15
+ from loupe_scan.render import BROWSER_ENDPOINT_VARIABLE
16
+
17
+
18
+ class Backend(str, Enum):
19
+ LOCAL = "local"
20
+ BRIGHTDATA = "brightdata"
21
+
22
+ @property
23
+ def description(self) -> str:
24
+ return "local" if self is Backend.LOCAL else "Bright Data"
25
+
26
+
27
+ def choose_backend(requested: Backend | None, environment: Mapping[str, str]) -> Backend:
28
+ """The backend asked for, or else Bright Data when either of its credentials is set and local when neither is."""
29
+ if requested is not None:
30
+ return requested
31
+ for name in (TOKEN_ENVIRONMENT_VARIABLE, BROWSER_ENDPOINT_VARIABLE):
32
+ if environment.get(name, "").strip():
33
+ return Backend.BRIGHTDATA
34
+ return Backend.LOCAL
loupe_scan/blocking.py ADDED
@@ -0,0 +1,40 @@
1
+ """Recognise an answer that turns an automated visitor away.
2
+
3
+ Sites that block bots answer 403 or 429, or serve a challenge page in place
4
+ of the content. The checks here are deliberately narrow so a real page is
5
+ never mistaken for a block: two status codes, the header Cloudflare sets on
6
+ its challenges, and the exact titles of Cloudflare's challenge pages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Mapping
13
+ from typing import Final
14
+
15
+ _BLOCKING_STATUSES: Final[dict[int, str]] = {
16
+ 403: "HTTP 403, forbidden",
17
+ 429: "HTTP 429, too many requests",
18
+ }
19
+ # Cloudflare documents cf-mitigated: challenge on every challenge it serves.
20
+ _CHALLENGE_HEADER: Final[str] = "cf-mitigated"
21
+ _CHALLENGE_TITLES: Final[frozenset[str]] = frozenset({"just a moment...", "attention required! | cloudflare"})
22
+ _TITLE: Final[re.Pattern[str]] = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)
23
+ # A challenge page puts its title near the top, so only the start is searched.
24
+ _TITLE_SEARCH_CHARACTERS: Final[int] = 65_536
25
+
26
+
27
+ def blocked_by_answer(status: int, headers: Mapping[str, str]) -> str | None:
28
+ """Why the status line and headers look like a block, or None when they don't."""
29
+ if headers.get(_CHALLENGE_HEADER, "").strip().lower() == "challenge":
30
+ return "a Cloudflare challenge"
31
+ return _BLOCKING_STATUSES.get(status)
32
+
33
+
34
+ def blocked_by_content(html: str) -> str | None:
35
+ """Why the page itself looks like a challenge page, or None when it doesn't."""
36
+ match = _TITLE.search(html[:_TITLE_SEARCH_CHARACTERS])
37
+ if match is None:
38
+ return None
39
+ title = " ".join(match.group(1).split()).lower()
40
+ return "a Cloudflare challenge page" if title in _CHALLENGE_TITLES else None