dungscraper 0.6.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.
Files changed (69) hide show
  1. dungscraper/__init__.py +6 -0
  2. dungscraper/__main__.py +4 -0
  3. dungscraper/adapters/__init__.py +57 -0
  4. dungscraper/adapters/arxiv.py +80 -0
  5. dungscraper/adapters/github.py +86 -0
  6. dungscraper/adapters/hackernews.py +107 -0
  7. dungscraper/adapters/reddit.py +1679 -0
  8. dungscraper/adapters/wikipedia.py +60 -0
  9. dungscraper/adapters/youtube.py +271 -0
  10. dungscraper/api/__init__.py +1 -0
  11. dungscraper/api/app.py +197 -0
  12. dungscraper/api/auth.py +29 -0
  13. dungscraper/api/routes.py +380 -0
  14. dungscraper/api/usage.py +121 -0
  15. dungscraper/banner.py +65 -0
  16. dungscraper/cli.py +584 -0
  17. dungscraper/client.py +117 -0
  18. dungscraper/config.py +117 -0
  19. dungscraper/core/__init__.py +1 -0
  20. dungscraper/core/batch.py +69 -0
  21. dungscraper/core/cache.py +136 -0
  22. dungscraper/core/chunk.py +139 -0
  23. dungscraper/core/clip.py +90 -0
  24. dungscraper/core/contacts.py +474 -0
  25. dungscraper/core/content.py +522 -0
  26. dungscraper/core/crawl.py +264 -0
  27. dungscraper/core/crawl_scoring.py +126 -0
  28. dungscraper/core/css_extract.py +180 -0
  29. dungscraper/core/dedupe.py +62 -0
  30. dungscraper/core/diff.py +36 -0
  31. dungscraper/core/documents.py +54 -0
  32. dungscraper/core/escalate.py +362 -0
  33. dungscraper/core/extract.py +282 -0
  34. dungscraper/core/feeds.py +277 -0
  35. dungscraper/core/fetch.py +601 -0
  36. dungscraper/core/focus.py +156 -0
  37. dungscraper/core/joblinks.py +309 -0
  38. dungscraper/core/jobs.py +293 -0
  39. dungscraper/core/limiter.py +34 -0
  40. dungscraper/core/map.py +113 -0
  41. dungscraper/core/mx.py +47 -0
  42. dungscraper/core/pagetools.py +71 -0
  43. dungscraper/core/proxies.py +164 -0
  44. dungscraper/core/research.py +336 -0
  45. dungscraper/core/robots.py +99 -0
  46. dungscraper/core/scrape.py +507 -0
  47. dungscraper/core/search.py +295 -0
  48. dungscraper/core/sitemap.py +82 -0
  49. dungscraper/core/sites.py +462 -0
  50. dungscraper/core/structured.py +64 -0
  51. dungscraper/core/urls.py +157 -0
  52. dungscraper/core/watch.py +173 -0
  53. dungscraper/errors.py +29 -0
  54. dungscraper/install_claude.py +110 -0
  55. dungscraper/local.py +200 -0
  56. dungscraper/log.py +42 -0
  57. dungscraper/mcp_server.py +695 -0
  58. dungscraper/models.py +676 -0
  59. dungscraper/playground.py +278 -0
  60. dungscraper/py.typed +0 -0
  61. dungscraper/security.py +49 -0
  62. dungscraper/services.py +107 -0
  63. dungscraper/worker.py +33 -0
  64. dungscraper-0.6.0.dist-info/METADATA +181 -0
  65. dungscraper-0.6.0.dist-info/RECORD +69 -0
  66. dungscraper-0.6.0.dist-info/WHEEL +5 -0
  67. dungscraper-0.6.0.dist-info/entry_points.txt +2 -0
  68. dungscraper-0.6.0.dist-info/licenses/LICENSE +21 -0
  69. dungscraper-0.6.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,6 @@
1
+ """DungScraper: self-hostable scraping and crawling for AI agents."""
2
+
3
+ from dungscraper.client import DungScraper, DungScraperAPIError
4
+
5
+ __version__ = "0.6.0"
6
+ __all__ = ["DungScraper", "DungScraperAPIError", "__version__"]
@@ -0,0 +1,4 @@
1
+ from dungscraper.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,57 @@
1
+ """API-backed site adapters.
2
+
3
+ Each adapter reads a public API or a documented page format instead of the
4
+ generic HTML fetch. Optional adapters return None when they cannot handle a
5
+ URL, and the normal fetch continues. Reddit always handles its own URLs:
6
+ the official API when credentials are set, otherwise public JSON, then RSS,
7
+ then old.reddit HTML. It does not fall through to the generic fetcher.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from urllib.parse import urlsplit
13
+
14
+ import httpx
15
+
16
+ from dungscraper.adapters.arxiv import ArxivAdapter
17
+ from dungscraper.adapters.github import GitHubAdapter
18
+ from dungscraper.adapters.hackernews import HackerNewsAdapter
19
+ from dungscraper.adapters.reddit import REDDIT_SETUP, RedditAdapter
20
+ from dungscraper.adapters.wikipedia import WikipediaAdapter
21
+ from dungscraper.adapters.youtube import YouTubeAdapter
22
+ from dungscraper.config import Settings
23
+ from dungscraper.models import ScrapeData, ScrapeRequest
24
+
25
+ ADAPTERS = (
26
+ RedditAdapter(),
27
+ YouTubeAdapter(),
28
+ WikipediaAdapter(),
29
+ GitHubAdapter(),
30
+ ArxivAdapter(),
31
+ HackerNewsAdapter(),
32
+ )
33
+
34
+
35
+ def adapter_for(url: str):
36
+ host = (urlsplit(url).hostname or "").lower()
37
+ if host.startswith("www."):
38
+ host = host[4:]
39
+ for adapter in ADAPTERS:
40
+ if adapter.matches(host, url):
41
+ return adapter
42
+ return None
43
+
44
+
45
+ async def fetch_via_adapter(
46
+ request: ScrapeRequest,
47
+ *,
48
+ settings: Settings,
49
+ client: httpx.AsyncClient,
50
+ ) -> ScrapeData | None:
51
+ adapter = adapter_for(request.url)
52
+ if adapter is None:
53
+ return None
54
+ return await adapter.fetch(request, settings=settings, client=client)
55
+
56
+
57
+ __all__ = ["ADAPTERS", "REDDIT_SETUP", "adapter_for", "fetch_via_adapter"]
@@ -0,0 +1,80 @@
1
+ """arXiv abstract pages via the public Atom API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import xml.etree.ElementTree as ET
6
+ from urllib.parse import urlsplit
7
+
8
+ import httpx
9
+
10
+ from dungscraper.config import Settings
11
+ from dungscraper.models import PageMetadata, ScrapeData, ScrapeRequest
12
+
13
+ ATOM = "{http://www.w3.org/2005/Atom}"
14
+
15
+
16
+ def arxiv_id(url: str) -> str | None:
17
+ parts = urlsplit(url)
18
+ host = (parts.hostname or "").lower()
19
+ if host.startswith("www."):
20
+ host = host[4:]
21
+ if host not in {"arxiv.org", "export.arxiv.org"}:
22
+ return None
23
+ segments = [segment for segment in parts.path.split("/") if segment]
24
+ if len(segments) >= 2 and segments[0] in {"abs", "pdf"}:
25
+ return segments[1].removesuffix(".pdf")
26
+ return None
27
+
28
+
29
+ def format_atom(xml_text: str) -> tuple[str, str] | None:
30
+ try:
31
+ root = ET.fromstring(xml_text)
32
+ except ET.ParseError:
33
+ return None
34
+ entry = root.find(f"{ATOM}entry")
35
+ if entry is None:
36
+ return None
37
+ title = " ".join((entry.findtext(f"{ATOM}title") or "").split())
38
+ summary = " ".join((entry.findtext(f"{ATOM}summary") or "").split())
39
+ authors = [
40
+ " ".join((node.findtext(f"{ATOM}name") or "").split())
41
+ for node in entry.findall(f"{ATOM}author")
42
+ ]
43
+ published = (entry.findtext(f"{ATOM}published") or "")[:10]
44
+ lines = [f"# {title}", "", f"Authors: {', '.join(authors)}"]
45
+ if published:
46
+ lines.append(f"Published: {published}")
47
+ lines.extend(["", summary])
48
+ return "\n".join(lines).strip(), title
49
+
50
+
51
+ class ArxivAdapter:
52
+ name = "arxiv"
53
+
54
+ def matches(self, host: str, url: str) -> bool:
55
+ return arxiv_id(url) is not None
56
+
57
+ async def fetch(self, request: ScrapeRequest, *, settings: Settings, client: httpx.AsyncClient) -> ScrapeData | None:
58
+ paper_id = arxiv_id(request.url)
59
+ if paper_id is None or urlsplit(request.url).path.startswith("/pdf/"):
60
+ return None
61
+ response = await client.get(
62
+ "https://export.arxiv.org/api/query",
63
+ params={"id_list": paper_id},
64
+ timeout=20,
65
+ )
66
+ if response.status_code >= 400:
67
+ return None
68
+ formatted = format_atom(response.text)
69
+ if formatted is None:
70
+ return None
71
+ markdown, title = formatted
72
+ return ScrapeData(
73
+ url=request.url,
74
+ markdown=markdown,
75
+ metadata=PageMetadata(title=title, description="arXiv via the public API"),
76
+ render_mode="api",
77
+ status_code=200,
78
+ content_type="application/atom+xml",
79
+ warnings=["arxiv_api"],
80
+ )
@@ -0,0 +1,86 @@
1
+ """GitHub repository and file reads via the public REST API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from urllib.parse import urlsplit
7
+
8
+ import httpx
9
+
10
+ from dungscraper.config import Settings
11
+ from dungscraper.models import PageMetadata, ScrapeData, ScrapeRequest
12
+
13
+
14
+ def parse_github(url: str) -> dict | None:
15
+ parts = urlsplit(url)
16
+ host = (parts.hostname or "").lower()
17
+ if host.startswith("www."):
18
+ host = host[4:]
19
+ if host != "github.com":
20
+ return None
21
+ segments = [segment for segment in parts.path.split("/") if segment]
22
+ if len(segments) < 2:
23
+ return None
24
+ owner, repo = segments[0], segments[1]
25
+ if owner in {"topics", "features", "settings", "marketplace"}:
26
+ return None
27
+ path = None
28
+ ref = None
29
+ if len(segments) >= 5 and segments[2] in {"blob", "tree"}:
30
+ ref = segments[3]
31
+ path = "/".join(segments[4:])
32
+ return {"owner": owner, "repo": repo, "ref": ref, "path": path}
33
+
34
+
35
+ class GitHubAdapter:
36
+ name = "github"
37
+
38
+ def matches(self, host: str, url: str) -> bool:
39
+ return host == "github.com" and parse_github(url) is not None
40
+
41
+ async def fetch(self, request: ScrapeRequest, *, settings: Settings, client: httpx.AsyncClient) -> ScrapeData | None:
42
+ parsed = parse_github(request.url)
43
+ if parsed is None:
44
+ return None
45
+ headers = {"Accept": "application/vnd.github+json", "User-Agent": settings.robots_user_agent}
46
+ if settings.github_token:
47
+ headers["Authorization"] = f"Bearer {settings.github_token}"
48
+ owner, repo = parsed["owner"], parsed["repo"]
49
+ repo_response = await client.get(f"https://api.github.com/repos/{owner}/{repo}", headers=headers, timeout=20)
50
+ if repo_response.status_code >= 400:
51
+ return None
52
+ info = repo_response.json()
53
+ if parsed["path"]:
54
+ content_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{parsed['path']}"
55
+ params = {"ref": parsed["ref"]} if parsed["ref"] else None
56
+ file_response = await client.get(content_url, headers=headers, params=params, timeout=20)
57
+ if file_response.status_code >= 400:
58
+ return None
59
+ payload = file_response.json()
60
+ encoded = payload.get("content") or ""
61
+ try:
62
+ text = base64.b64decode(encoded).decode("utf-8", "replace")
63
+ except Exception:
64
+ return None
65
+ language = parsed["path"].rsplit(".", 1)[-1] if "." in parsed["path"] else ""
66
+ markdown = f"# {owner}/{repo}/{parsed['path']}\n\n```{language}\n{text.rstrip()}\n```"
67
+ title = parsed["path"]
68
+ else:
69
+ readme = await client.get(
70
+ f"https://api.github.com/repos/{owner}/{repo}/readme",
71
+ headers={**headers, "Accept": "application/vnd.github.raw"},
72
+ timeout=20,
73
+ )
74
+ body = readme.text if readme.status_code < 400 else ""
75
+ description = info.get("description") or ""
76
+ markdown = f"# {info.get('full_name') or owner + '/' + repo}\n\n{description}\n\n{body}".strip()
77
+ title = info.get("full_name")
78
+ return ScrapeData(
79
+ url=request.url,
80
+ markdown=markdown,
81
+ metadata=PageMetadata(title=title, description=info.get("description")),
82
+ render_mode="api",
83
+ status_code=200,
84
+ content_type="application/json",
85
+ warnings=["github_api"],
86
+ )
@@ -0,0 +1,107 @@
1
+ """Hacker News via the public Firebase API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import parse_qs, urlsplit
6
+
7
+ import httpx
8
+
9
+ from dungscraper.config import Settings
10
+ from dungscraper.models import PageMetadata, ScrapeData, ScrapeRequest
11
+
12
+ API = "https://hacker-news.firebaseio.com/v0"
13
+
14
+
15
+ def hn_target(url: str) -> dict | None:
16
+ parts = urlsplit(url)
17
+ host = (parts.hostname or "").lower()
18
+ if host.startswith("www."):
19
+ host = host[4:]
20
+ if host not in {"news.ycombinator.com", "news.ycombinator.org"}:
21
+ return None
22
+ item_id = (parse_qs(parts.query).get("id") or [None])[0]
23
+ if parts.path.startswith("/item") and item_id and item_id.isdigit():
24
+ return {"kind": "item", "id": int(item_id)}
25
+ if parts.path in {"", "/"} or parts.path.startswith("/news"):
26
+ return {"kind": "top", "id": None}
27
+ return None
28
+
29
+
30
+ def format_item(item: dict, comments: list[str]) -> str:
31
+ title = item.get("title") or item.get("text") or "Hacker News"
32
+ by = item.get("by") or "?"
33
+ score = item.get("score", 0)
34
+ link = item.get("url") or f"https://news.ycombinator.com/item?id={item.get('id')}"
35
+ lines = [f"# {title}", "", f"{score} points · {by}", "", link]
36
+ text = (item.get("text") or "").strip()
37
+ if text and item.get("title"):
38
+ lines.extend(["", text])
39
+ if comments:
40
+ lines.extend(["", "## Comments", *comments])
41
+ return "\n".join(lines).strip()
42
+
43
+
44
+ def format_comment(item: dict, depth: int) -> str:
45
+ indent = " " * depth
46
+ author = item.get("by") or "[deleted]"
47
+ text = " ".join((item.get("text") or "").split())
48
+ return f"{indent}- **{author}**: {text}"
49
+
50
+
51
+ class HackerNewsAdapter:
52
+ name = "hackernews"
53
+
54
+ def matches(self, host: str, url: str) -> bool:
55
+ return hn_target(url) is not None
56
+
57
+ async def fetch(self, request: ScrapeRequest, *, settings: Settings, client: httpx.AsyncClient) -> ScrapeData | None:
58
+ target = hn_target(request.url)
59
+ if target is None:
60
+ return None
61
+ if target["kind"] == "top":
62
+ ids_response = await client.get(f"{API}/topstories.json", timeout=20)
63
+ if ids_response.status_code >= 400:
64
+ return None
65
+ lines = ["# Hacker News", ""]
66
+ for item_id in (ids_response.json() or [])[:30]:
67
+ item_response = await client.get(f"{API}/item/{item_id}.json", timeout=15)
68
+ if item_response.status_code >= 400:
69
+ continue
70
+ item = item_response.json() or {}
71
+ title = item.get("title") or "(untitled)"
72
+ link = item.get("url") or f"https://news.ycombinator.com/item?id={item_id}"
73
+ lines.append(f"- [{title}]({link}) · {item.get('score', 0)} points · {item.get('by') or '?'}")
74
+ markdown = "\n".join(lines)
75
+ title = "Hacker News"
76
+ else:
77
+ item_response = await client.get(f"{API}/item/{target['id']}.json", timeout=20)
78
+ if item_response.status_code >= 400:
79
+ return None
80
+ item = item_response.json() or {}
81
+ comments = await _comments(client, item.get("kids") or [], 0, request.max_comment_depth)
82
+ markdown = format_item(item, comments)
83
+ title = item.get("title") or "Hacker News"
84
+ return ScrapeData(
85
+ url=request.url,
86
+ markdown=markdown,
87
+ metadata=PageMetadata(title=title, description="Hacker News via the Firebase API"),
88
+ render_mode="api",
89
+ status_code=200,
90
+ content_type="application/json",
91
+ warnings=["hackernews_api"],
92
+ )
93
+
94
+
95
+ async def _comments(client: httpx.AsyncClient, kids: list, depth: int, max_depth: int) -> list[str]:
96
+ if depth > max_depth:
97
+ return []
98
+ lines: list[str] = []
99
+ for kid in kids[:20]:
100
+ response = await client.get(f"{API}/item/{kid}.json", timeout=15)
101
+ if response.status_code >= 400:
102
+ continue
103
+ item = response.json() or {}
104
+ if item.get("text"):
105
+ lines.append(format_comment(item, depth))
106
+ lines.extend(await _comments(client, item.get("kids") or [], depth + 1, max_depth))
107
+ return lines