"""Offline-only HTML projection and structural features.
This module never fetches resources, executes scripts, evaluates CSS, or starts
a browser. It parses a bounded string already supplied by the caller.
"""
from __future__ import annotations
import math
import re
from collections import Counter
from dataclasses import asdict, dataclass
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit
TEXT_TAGS = {"title", "label", "button", "a", "option", "textarea", "p", "h1", "h2", "h3"}
SKIP_TEXT_TAGS = {"script", "style", "noscript", "template", "svg"}
TRACKED_TAGS = {"form", "input", "button", "a", "script", "iframe", "img", "link"}
@dataclass(frozen=True)
class StaticPageFeatures:
html_chars_seen: int
html_truncated: bool
parse_errors: int
tag_count: int
max_depth: int
form_count: int
input_count: int
password_input_count: int
hidden_input_count: int
button_count: int
link_count: int
script_count: int
iframe_count: int
external_form_action_count: int
external_resource_count: int
javascript_url_count: int
data_url_count: int
event_handler_attribute_count: int
visible_text_chars: int
actionable_text_chars: int
url_length: int
host_length: int
url_entropy: float
def to_dict(self) -> dict[str, int | float | bool]:
return asdict(self)
def _origin(url: str) -> tuple[str, str, int | None]:
try:
parsed = urlsplit(url)
except ValueError:
return "", "", None
try:
port = parsed.port
except ValueError:
port = None
return parsed.scheme.lower(), (parsed.hostname or "").lower().rstrip("."), port
def _entropy(value: str) -> float:
if not value:
return 0.0
counts = Counter(value)
length = len(value)
return -sum((count / length) * math.log2(count / length) for count in counts.values())
def _clean_text(value: str) -> str:
return re.sub(r"\s+", " ", value).strip()
class _BoundedHTMLExtractor(HTMLParser):
def __init__(self, base_url: str, max_text_chars: int):
super().__init__(convert_charrefs=True)
self.base_url = base_url
try:
urlsplit(base_url)
except ValueError:
self.parse_errors = 1
else:
self.parse_errors = 0
self.base_origin = _origin(base_url)
self.max_text_chars = max_text_chars
self.depth = 0
self.max_depth = 0
self.skip_depth = 0
self.active_text_tags: list[str] = []
self.tag_counts: Counter[str] = Counter()
self.form_count = 0
self.input_count = 0
self.password_input_count = 0
self.hidden_input_count = 0
self.button_count = 0
self.link_count = 0
self.script_count = 0
self.iframe_count = 0
self.external_form_action_count = 0
self.external_resource_count = 0
self.javascript_url_count = 0
self.data_url_count = 0
self.event_handler_attribute_count = 0
self.visible_parts: list[str] = []
self.actionable_parts: list[str] = []
def error(self, message: str) -> None: # pragma: no cover - legacy hook
self.parse_errors += 1
def _add_text(self, value: str, actionable: bool) -> None:
value = _clean_text(value)
if not value:
return
if sum(map(len, self.visible_parts)) < self.max_text_chars:
self.visible_parts.append(value)
if actionable and sum(map(len, self.actionable_parts)) < self.max_text_chars:
self.actionable_parts.append(value)
def _inspect_reference(self, value: str, resource: bool = False) -> None:
lowered = value.strip().lower()
if lowered.startswith("javascript:"):
self.javascript_url_count += 1
return
if lowered.startswith("data:"):
self.data_url_count += 1
return
try:
absolute = urljoin(self.base_url, value)
except ValueError:
self.parse_errors += 1
return
origin = _origin(absolute)
if resource and origin[1] and origin != self.base_origin:
self.external_resource_count += 1
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
self.depth += 1
self.max_depth = max(self.max_depth, self.depth)
self.tag_counts[tag] += 1
if tag in SKIP_TEXT_TAGS:
self.skip_depth += 1
if tag in TEXT_TAGS:
self.active_text_tags.append(tag)
values = {str(k).lower(): "" if v is None else str(v) for k, v in attrs}
self.event_handler_attribute_count += sum(1 for key in values if key.startswith("on"))
for key in ("aria-label", "placeholder", "name", "value", "alt"):
if key in values and tag in TRACKED_TAGS:
self._add_text(values[key], actionable=True)
if tag == "form":
self.form_count += 1
action = values.get("action", "")
if action:
try:
absolute = urljoin(self.base_url, action)
except ValueError:
self.parse_errors += 1
else:
if _origin(absolute)[1] and _origin(absolute) != self.base_origin:
self.external_form_action_count += 1
self._inspect_reference(action)
elif tag == "input":
self.input_count += 1
input_type = values.get("type", "text").lower()
self.password_input_count += int(input_type == "password")
self.hidden_input_count += int(input_type == "hidden" or "hidden" in values)
elif tag == "button":
self.button_count += 1
elif tag == "a":
self.link_count += 1
self._inspect_reference(values.get("href", ""))
elif tag == "script":
self.script_count += 1
self._inspect_reference(values.get("src", ""), resource=True)
elif tag == "iframe":
self.iframe_count += 1
self._inspect_reference(values.get("src", ""), resource=True)
elif tag in {"img", "link"}:
self._inspect_reference(values.get("src", values.get("href", "")), resource=True)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in SKIP_TEXT_TAGS and self.skip_depth:
self.skip_depth -= 1
if tag in TEXT_TAGS and self.active_text_tags:
for index in range(len(self.active_text_tags) - 1, -1, -1):
if self.active_text_tags[index] == tag:
del self.active_text_tags[index]
break
self.depth = max(0, self.depth - 1)
def handle_data(self, data: str) -> None:
if self.skip_depth:
return
self._add_text(data, actionable=bool(self.active_text_tags))
def _bounded_html(html: str, max_html_chars: int, head_ratio: float = 0.8) -> tuple[str, bool]:
html = str(html or "")
if len(html) <= max_html_chars:
return html, False
head = int(max_html_chars * head_ratio)
tail = max_html_chars - head
return html[:head] + html[-tail:], True
def extract_static_page(
url: str,
html: str,
*,
max_html_chars: int = 524_288,
max_text_chars: int = 16_384,
) -> tuple[str, StaticPageFeatures]:
bounded, truncated = _bounded_html(html, max_html_chars)
parser = _BoundedHTMLExtractor(str(url), max_text_chars=max_text_chars)
try:
parser.feed(bounded)
parser.close()
except Exception:
parser.parse_errors += 1
visible = _clean_text(" ".join(parser.visible_parts))[:max_text_chars]
actionable = _clean_text(" ".join(parser.actionable_parts))[:max_text_chars]
projection = _clean_text(f"URL {url} ACTIONABLE {actionable} VISIBLE {visible}")
try:
parsed = urlsplit(str(url))
host_length = len(parsed.hostname or "")
except ValueError:
host_length = 0
features = StaticPageFeatures(
html_chars_seen=len(bounded),
html_truncated=truncated,
parse_errors=parser.parse_errors,
tag_count=sum(parser.tag_counts.values()),
max_depth=parser.max_depth,
form_count=parser.form_count,
input_count=parser.input_count,
password_input_count=parser.password_input_count,
hidden_input_count=parser.hidden_input_count,
button_count=parser.button_count,
link_count=parser.link_count,
script_count=parser.script_count,
iframe_count=parser.iframe_count,
external_form_action_count=parser.external_form_action_count,
external_resource_count=parser.external_resource_count,
javascript_url_count=parser.javascript_url_count,
data_url_count=parser.data_url_count,
event_handler_attribute_count=parser.event_handler_attribute_count,
visible_text_chars=len(visible),
actionable_text_chars=len(actionable),
url_length=len(str(url)),
host_length=host_length,
url_entropy=_entropy(str(url)),
)
return projection, features