Spaces:
Runtime error
Runtime error
Download src/core/source_evidence.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 8.86 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/source_evidence.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/core/source_evidence.py
-
curl -L -o source_evidence.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/source_evidence.py
8.86 kB
| """Utilities to fetch and normalize cited-source evidence for factuality.""" | |
| from __future__ import annotations | |
| import html | |
| import ipaddress | |
| import re | |
| import socket | |
| import time | |
| from dataclasses import dataclass | |
| from typing import Any, Dict, List, Tuple | |
| from urllib.parse import urlparse | |
| import httpx | |
| URL_RE = re.compile(r"(https?://[^\s)>\]]+)", re.IGNORECASE) | |
| SCRIPT_RE = re.compile(r"(?is)<script.*?>.*?</script>") | |
| STYLE_RE = re.compile(r"(?is)<style.*?>.*?</style>") | |
| TAG_RE = re.compile(r"(?is)<[^>]+>") | |
| WS_RE = re.compile(r"\s+") | |
| TITLE_RE = re.compile(r"(?is)<title[^>]*>(.*?)</title>") | |
| def _strip_html(raw: str) -> str: | |
| cleaned = SCRIPT_RE.sub(" ", raw or "") | |
| cleaned = STYLE_RE.sub(" ", cleaned) | |
| cleaned = TAG_RE.sub(" ", cleaned) | |
| cleaned = html.unescape(cleaned) | |
| return WS_RE.sub(" ", cleaned).strip() | |
| def _extract_title(raw_html: str) -> str: | |
| match = TITLE_RE.search(raw_html or "") | |
| if not match: | |
| return "" | |
| return WS_RE.sub(" ", html.unescape(match.group(1))).strip() | |
| def _parse_link_entry(entry: Any) -> Tuple[str, str]: | |
| """Return (url, title) from mixed link payloads.""" | |
| if isinstance(entry, dict): | |
| raw_url = str( | |
| entry.get("url") | |
| or entry.get("href") | |
| or entry.get("link") | |
| or "" | |
| ).strip() | |
| raw_title = str( | |
| entry.get("title") | |
| or entry.get("text") | |
| or entry.get("label") | |
| or entry.get("name") | |
| or "" | |
| ).strip() | |
| return raw_url, raw_title | |
| raw = str(entry or "").strip() | |
| if not raw: | |
| return "", "" | |
| match = URL_RE.search(raw) | |
| if not match: | |
| return "", raw[:120] | |
| url = match.group(1).strip() | |
| title = raw.replace(url, "").strip(" ()-:\t") | |
| return url, title[:120] | |
| def normalize_cited_links(link_entries: Any) -> List[Dict[str, str]]: | |
| """Normalize list of links into [{'url','title'}], deduplicated by URL.""" | |
| if not isinstance(link_entries, list): | |
| return [] | |
| normalized: List[Dict[str, str]] = [] | |
| seen = set() | |
| for entry in link_entries: | |
| url, title = _parse_link_entry(entry) | |
| if not url: | |
| continue | |
| parsed = urlparse(url) | |
| if parsed.scheme not in {"http", "https"}: | |
| continue | |
| clean_url = url.split("#", 1)[0].strip() | |
| if clean_url in seen: | |
| continue | |
| seen.add(clean_url) | |
| normalized.append( | |
| { | |
| "url": clean_url, | |
| "title": title or clean_url, | |
| } | |
| ) | |
| return normalized | |
| def _host_is_private(hostname: str) -> bool: | |
| host = (hostname or "").strip().lower() | |
| if not host: | |
| return True | |
| if host in {"localhost", "0.0.0.0"}: | |
| return True | |
| if host.endswith(".local") or host.endswith(".internal"): | |
| return True | |
| try: | |
| ip = ipaddress.ip_address(host) | |
| return bool( | |
| ip.is_private | |
| or ip.is_loopback | |
| or ip.is_link_local | |
| or ip.is_multicast | |
| or ip.is_reserved | |
| or ip.is_unspecified | |
| ) | |
| except ValueError: | |
| pass | |
| try: | |
| infos = socket.getaddrinfo(host, None) | |
| except Exception: | |
| # If resolution fails we let HTTP client decide; no immediate private-IP proof. | |
| return False | |
| for info in infos: | |
| addr = info[4][0] | |
| try: | |
| ip = ipaddress.ip_address(addr) | |
| except ValueError: | |
| continue | |
| if ( | |
| ip.is_private | |
| or ip.is_loopback | |
| or ip.is_link_local | |
| or ip.is_multicast | |
| or ip.is_reserved | |
| or ip.is_unspecified | |
| ): | |
| return True | |
| return False | |
| def _is_safe_public_url(url: str) -> bool: | |
| try: | |
| parsed = urlparse(url) | |
| except Exception: | |
| return False | |
| if parsed.scheme not in {"http", "https"}: | |
| return False | |
| if not parsed.hostname: | |
| return False | |
| return not _host_is_private(parsed.hostname) | |
| class SourceEvidenceFetcher: | |
| """Fetches source excerpts with bounded latency and simple SSRF guardrails.""" | |
| max_sources_per_turn: int = 3 | |
| per_source_timeout_seconds: float = 4.0 | |
| total_budget_seconds: float = 12.0 | |
| max_excerpt_chars: int = 1800 | |
| def __post_init__(self) -> None: | |
| self._cache: Dict[str, Dict[str, Any]] = {} | |
| def collect_from_links(self, link_entries: Any) -> List[Dict[str, Any]]: | |
| links = normalize_cited_links(link_entries) | |
| if not links: | |
| return [] | |
| results: List[Dict[str, Any]] = [] | |
| started = time.monotonic() | |
| for index, link in enumerate(links): | |
| url = link["url"] | |
| title = link["title"] | |
| if index >= max(self.max_sources_per_turn, 0): | |
| results.append( | |
| { | |
| "url": url, | |
| "title": title, | |
| "status": "skipped_limit", | |
| "excerpt": "", | |
| "error": f"Skipped: max sources per turn is {self.max_sources_per_turn}", | |
| } | |
| ) | |
| continue | |
| elapsed = time.monotonic() - started | |
| remaining = self.total_budget_seconds - elapsed | |
| if remaining <= 0: | |
| results.append( | |
| { | |
| "url": url, | |
| "title": title, | |
| "status": "budget_exceeded", | |
| "excerpt": "", | |
| "error": "Skipped: source evidence time budget exceeded", | |
| } | |
| ) | |
| continue | |
| cached = self._cache.get(url) | |
| if cached: | |
| cached_copy = dict(cached) | |
| cached_copy["cached"] = True | |
| results.append(cached_copy) | |
| continue | |
| timeout = max(1.0, min(self.per_source_timeout_seconds, remaining)) | |
| evidence = self._fetch_single(url=url, title=title, timeout=timeout) | |
| self._cache[url] = evidence | |
| results.append(dict(evidence)) | |
| return results | |
| def _fetch_single(self, url: str, title: str, timeout: float) -> Dict[str, Any]: | |
| base = { | |
| "url": url, | |
| "title": title or url, | |
| "status": "unknown", | |
| "excerpt": "", | |
| "error": "", | |
| "http_status": None, | |
| "elapsed_ms": None, | |
| "cached": False, | |
| } | |
| if not _is_safe_public_url(url): | |
| base["status"] = "unsafe_url" | |
| base["error"] = "URL blocked by safety policy (private/local host)" | |
| return base | |
| started = time.monotonic() | |
| try: | |
| with httpx.Client(timeout=timeout, follow_redirects=True) as client: | |
| response = client.get( | |
| url, | |
| headers={ | |
| "User-Agent": "AI-Tester-SourceEvidence/1.0 (+factuality-check)", | |
| "Accept": "text/html,application/json,text/plain;q=0.9,*/*;q=0.1", | |
| }, | |
| ) | |
| except httpx.TimeoutException: | |
| base["status"] = "timeout" | |
| base["error"] = f"Timeout after {timeout:.1f}s" | |
| base["elapsed_ms"] = int((time.monotonic() - started) * 1000) | |
| return base | |
| except Exception as exc: | |
| base["status"] = "fetch_error" | |
| base["error"] = str(exc)[:180] | |
| base["elapsed_ms"] = int((time.monotonic() - started) * 1000) | |
| return base | |
| base["elapsed_ms"] = int((time.monotonic() - started) * 1000) | |
| base["http_status"] = int(response.status_code) | |
| content_type = (response.headers.get("content-type") or "").lower() | |
| if response.status_code >= 400: | |
| base["status"] = "http_error" | |
| base["error"] = f"HTTP {response.status_code}" | |
| return base | |
| raw_text = response.text or "" | |
| if not raw_text.strip(): | |
| base["status"] = "empty_content" | |
| base["error"] = "Empty response body" | |
| return base | |
| if "application/json" in content_type: | |
| compact = WS_RE.sub(" ", raw_text).strip() | |
| excerpt = compact[: self.max_excerpt_chars] | |
| else: | |
| excerpt = _strip_html(raw_text)[: self.max_excerpt_chars] | |
| if not excerpt: | |
| base["status"] = "empty_content" | |
| base["error"] = "Could not extract readable text from source" | |
| return base | |
| extracted_title = _extract_title(raw_text) | |
| if extracted_title: | |
| base["title"] = extracted_title[:140] | |
| base["status"] = "ok" | |
| base["excerpt"] = excerpt | |
| return base | |