Spaces:
Running
Running
fetch_document: readable errors, unverified-chain fallback with flag, first title only
Browse filesFiles changed (2)
- app.py+1-1
- src/fetch.py+46-15
380 unmodified lines381382383384385386387380 unmodified linesasync def fetch_document(url: str, offset: str = "0", max_chars: str = "12000") -> str:"""Read a public web page or PDF as plain text, e.g. a funding announcement (RFA, NOFO, solicitation), a policy page or a sponsor guide.Use when the user gives a link instead of pasting text. A grants.gov opportunity link returns theopportunity record (dates, ceiling, cost sharing, synopsis, attachment links) from the grants.gov API;380 unmodified lines381382383384385386387380 unmodified linesasync def fetch_document(url: str, offset: str = "0", max_chars: str = "12000") -> str:"""Read any public web page, PDF or grants.gov opportunity by its URL and return the text. Use it to look up a website the user names, a funding announcement (RFA, NOFO, solicitation), a policy page or a sponsor guide.Use when the user gives a link instead of pasting text. A grants.gov opportunity link returns theopportunity record (dates, ceiling, cost sharing, synopsis, attachment links) from the grants.gov API;
72 unmodified lines73747576777879122 unmodified lines20220320420520620711 unmodified lines21922022122222322422522622722822923023123223323423523623721 unmodified lines25926026126226326426572 unmodified linesdef handle_starttag(self, tag, attrs):if tag in self._SKIP:self._skip += 1elif tag == "title":self._in_title = Trueelif tag in self._BLOCK:self.parts.append("\n")122 unmodified linesreturn _grants_gov_text(data)async def fetch_document(url: str, offset: int = 0, max_chars: int = 12_000) -> dict:"""Fetch a public web page or PDF and return its text from `offset`, at most `max_chars` characters."""url = (url or "").strip()11 unmodified linesreturn {"error": f"grants.gov opportunity {opp_id} could not be read: {e}", "url": url}return _page(url, "grants.gov", title, text, offset, max_chars)async with httpx.AsyncClient(follow_redirects=False, timeout=TIMEOUT_S, headers={"User-Agent": USER_AGENT}) as client:current = urlfor _ in range(MAX_REDIRECTS + 1):resp = await client.get(current)if resp.is_redirect and resp.headers.get("location"):current = str(resp.next_request.url) if resp.next_request else resp.headers["location"]reason = _check_url(current)if reason:return {"error": f"refused after redirect: {reason}", "url": current}continuebreakelse:return {"error": "too many redirects", "url": current}if resp.status_code >= 400:return {"error": f"HTTP {resp.status_code}", "url": current}21 unmodified linesif not text:return {"error": "no readable text was found (an image-only PDF or a script-rendered page; for grants.gov, give the opportunity link, for NSF, the solicitation PDF)", "url": current, "kind": kind}return _page(current, kind, title, text, offset, max_chars)def _page(url: str, kind: str, title: str, text: str, offset: int, max_chars: int) -> dict:72 unmodified lines73747576777879122 unmodified lines20220320420520620720820921021121221321421521621721821922022122222322422522622722822911 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326421 unmodified lines28628728828929029129229329429529672 unmodified linesdef handle_starttag(self, tag, attrs):if tag in self._SKIP:self._skip += 1elif tag == "title" and not self._skip and not self.title: # the document's title, not an SVG icon'sself._in_title = Trueelif tag in self._BLOCK:self.parts.append("\n")122 unmodified linesreturn _grants_gov_text(data)class _Refused(Exception):def __init__(self, message: str, url: str):super().__init__(message)self.url = urlasync def _get_following_redirects(url: str, verify: bool):"""GET with each redirect target re-checked against the public-address rule. Returns (response, final url)."""async with httpx.AsyncClient(follow_redirects=False, timeout=TIMEOUT_S, headers={"User-Agent": USER_AGENT}, verify=verify) as client:current = urlfor _ in range(MAX_REDIRECTS + 1):resp = await client.get(current)if resp.is_redirect and resp.headers.get("location"):current = str(resp.next_request.url) if resp.next_request else resp.headers["location"]reason = _check_url(current)if reason:raise _Refused(f"refused after redirect: {reason}", current)continuereturn resp, currentraise _Refused("too many redirects", current)async def fetch_document(url: str, offset: int = 0, max_chars: int = 12_000) -> dict:"""Fetch a public web page or PDF and return its text from `offset`, at most `max_chars` characters."""url = (url or "").strip()11 unmodified linesreturn {"error": f"grants.gov opportunity {opp_id} could not be read: {e}", "url": url}return _page(url, "grants.gov", title, text, offset, max_chars)current = urltls_unverified = Falsetry:resp, current = await _get_following_redirects(url, verify=True)except httpx.ConnectError as e:if "CERTIFICATE_VERIFY_FAILED" not in str(e):return {"error": f"could not connect: {e}", "url": current}# The site's certificate chain does not verify against this server's trust store (a missing# intermediate, usually). Read it anyway for this public, read-only fetch, and say so in the result.try:resp, current = await _get_following_redirects(url, verify=False)tls_unverified = Trueexcept httpx.HTTPError as e2:return {"error": f"could not connect: {e2}", "url": current}except _Refused as e:return {"error": str(e), "url": e.url}except httpx.HTTPError as e:return {"error": f"could not fetch: {e}", "url": current}if resp.status_code >= 400:return {"error": f"HTTP {resp.status_code}", "url": current}21 unmodified linesif not text:return {"error": "no readable text was found (an image-only PDF or a script-rendered page; for grants.gov, give the opportunity link, for NSF, the solicitation PDF)", "url": current, "kind": kind}out = _page(current, kind, title, text, offset, max_chars)if tls_unverified:out["tls_unverified"] = Trueout["note"] = "The site's certificate could not be verified, so this text was read without TLS verification; treat it as unconfirmed."return outdef _page(url: str, kind: str, title: str, text: str, offset: int, max_chars: int) -> dict:
app.py+1-1
src/fetch.py+46-15