web-snapshot-cli 0.1.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.
snapshot/utils.py ADDED
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import mimetypes
5
+ import os
6
+ import re
7
+ from pathlib import Path, PurePosixPath
8
+ from urllib.parse import urljoin, urlparse, urlunparse
9
+
10
+ # Attributes that may contain fetchable URLs.
11
+ URL_ATTRS = ("href", "src", "poster", "data-src", "data-background")
12
+ SRCSET_ATTRS = ("srcset", "data-srcset")
13
+
14
+ # Tags treated as HTML pages when crawled.
15
+ PAGE_EXTENSIONS = {".html", ".htm", ".xhtml", ""}
16
+ ASSET_EXTENSIONS = {
17
+ ".css",
18
+ ".js",
19
+ ".mjs",
20
+ ".json",
21
+ ".xml",
22
+ ".svg",
23
+ ".png",
24
+ ".jpg",
25
+ ".jpeg",
26
+ ".gif",
27
+ ".webp",
28
+ ".avif",
29
+ ".ico",
30
+ ".woff",
31
+ ".woff2",
32
+ ".ttf",
33
+ ".eot",
34
+ ".mp4",
35
+ ".webm",
36
+ ".mp3",
37
+ ".pdf",
38
+ }
39
+
40
+ SKIP_SCHEMES = {"mailto", "tel", "javascript", "data", "blob", "about", "file"}
41
+
42
+
43
+ def normalize_url(url: str, base: str | None = None) -> str | None:
44
+ """Resolve and normalize a URL. Returns None for non-fetchable schemes."""
45
+ if not url or url.startswith("#"):
46
+ return None
47
+ url = url.strip()
48
+ if base:
49
+ url = urljoin(base, url)
50
+ parsed = urlparse(url)
51
+ if parsed.scheme and parsed.scheme.lower() in SKIP_SCHEMES:
52
+ return None
53
+ if not parsed.scheme:
54
+ return None
55
+ # Drop fragment; keep query for distinct resources.
56
+ normalized = parsed._replace(fragment="")
57
+ path = normalized.path or "/"
58
+ return urlunparse(normalized._replace(path=path))
59
+
60
+
61
+ def same_origin(a: str, b: str) -> bool:
62
+ pa, pb = urlparse(a), urlparse(b)
63
+ return (pa.scheme, pa.netloc) == (pb.scheme, pb.netloc)
64
+
65
+
66
+ def url_to_local_path(
67
+ url: str,
68
+ output_dir: Path,
69
+ page_url: str | None = None,
70
+ page_ext: str = ".html",
71
+ ) -> Path:
72
+ """Map a remote URL to a local filesystem path inside output_dir."""
73
+ parsed = urlparse(url)
74
+ host_dir = _safe_name(parsed.netloc)
75
+ path = PurePosixPath(parsed.path or "/")
76
+
77
+ if path.suffix:
78
+ rel = path.as_posix().lstrip("/")
79
+ elif _looks_like_page(url):
80
+ index_name = f"index{page_ext}"
81
+ posix = path.as_posix().lstrip("/")
82
+ if not posix or path.as_posix().endswith("/"):
83
+ rel = f"{posix}{index_name}" if posix else index_name
84
+ else:
85
+ rel = f"{posix}/{index_name}"
86
+ else:
87
+ digest = hashlib.sha1(url.encode()).hexdigest()[:10]
88
+ ext = _guess_extension(url) or ".bin"
89
+ rel = f"_assets/{digest}{ext}"
90
+
91
+ if parsed.query:
92
+ digest = hashlib.sha1(parsed.query.encode()).hexdigest()[:8]
93
+ stem = PurePosixPath(rel)
94
+ rel = str(stem.with_name(f"{stem.stem}_{digest}{stem.suffix}"))
95
+
96
+ return output_dir / host_dir / rel
97
+
98
+
99
+ def page_local_path(url: str, output_dir: Path, lang: str = "html") -> Path:
100
+ """Local path for a saved page."""
101
+ ext = ".md" if lang == "md" else ".html"
102
+ return url_to_local_path(url, output_dir, page_ext=ext)
103
+
104
+
105
+ def relative_href(from_path: Path, to_path: Path) -> str:
106
+ """POSIX-style relative path between two local files."""
107
+ rel = os.path.relpath(to_path, start=from_path.parent)
108
+ return PurePosixPath(rel).as_posix()
109
+
110
+
111
+ def _safe_name(value: str) -> str:
112
+ return re.sub(r"[^\w.\-]", "_", value)
113
+
114
+
115
+ def _looks_like_page(url: str) -> bool:
116
+ path = urlparse(url).path
117
+ ext = PurePosixPath(path).suffix.lower()
118
+ return ext in PAGE_EXTENSIONS
119
+
120
+
121
+ def _guess_extension(url: str) -> str | None:
122
+ path = urlparse(url).path
123
+ ext = PurePosixPath(path).suffix.lower()
124
+ if ext:
125
+ return ext
126
+ guessed = mimetypes.guess_extension(mimetypes.guess_type(path)[0] or "application/octet-stream")
127
+ return guessed
128
+
129
+
130
+ def parse_srcset(value: str) -> list[str]:
131
+ """Extract URLs from a srcset attribute."""
132
+ urls: list[str] = []
133
+ for part in value.split(","):
134
+ piece = part.strip().split()
135
+ if piece:
136
+ urls.append(piece[0])
137
+ return urls
138
+
139
+
140
+ def rewrite_css_urls(css: str, base_url: str, mapper) -> str:
141
+ """Rewrite url(...) references in CSS using mapper(url) -> local path or None."""
142
+
143
+ def repl(match: re.Match[str]) -> str:
144
+ raw = match.group(1).strip("'\"")
145
+ absolute = normalize_url(raw, base_url)
146
+ if not absolute:
147
+ return match.group(0)
148
+ local = mapper(absolute)
149
+ if local is None:
150
+ return match.group(0)
151
+ return f"url({local})"
152
+
153
+ return re.sub(r"url\(([^)]+)\)", repl, css)
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: web-snapshot-cli
3
+ Version: 0.1.0
4
+ Summary: Take offline snapshots of any website and restore them locally
5
+ Project-URL: Homepage, https://github.com/codingsushi79/Snapshot
6
+ Project-URL: Repository, https://github.com/codingsushi79/Snapshot
7
+ Author: snapshot contributors
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cli,crawler,offline,snapshot,web-archive
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Utilities
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: beautifulsoup4>=4.12
20
+ Requires-Dist: click>=8.1
21
+ Requires-Dist: httpx>=0.27
22
+ Requires-Dist: markdownify>=0.13
23
+ Requires-Dist: rich>=13.7
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
26
+ Requires-Dist: pytest>=8.0; extra == 'dev'
27
+ Requires-Dist: ruff>=0.8; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # snapshot — offline website snapshots
31
+
32
+ Take a fast offline copy of any public website, then serve it locally.
33
+
34
+ ## Install
35
+
36
+ **One-liner (macOS / Linux / WSL):**
37
+
38
+ ```bash
39
+ curl -fsSL https://raw.githubusercontent.com/codingsushi79/Snapshot/main/install.sh | bash
40
+ ```
41
+
42
+ **One-liner (Windows PowerShell):**
43
+
44
+ ```powershell
45
+ irm https://raw.githubusercontent.com/codingsushi79/Snapshot/main/install.ps1 | iex
46
+ ```
47
+
48
+ **Universal fallback** (requires Python 3.10+):
49
+
50
+ ```bash
51
+ python3 -m pip install --user git+https://github.com/codingsushi79/Snapshot.git
52
+ ```
53
+
54
+ **From PyPI** (once published):
55
+
56
+ ```bash
57
+ pip install web-snapshot-cli
58
+ ```
59
+
60
+ Then run:
61
+
62
+ ```bash
63
+ snapshot https://example.com ./mirror
64
+ ```
65
+
66
+ <details>
67
+ <summary>Other install methods</summary>
68
+
69
+ ```bash
70
+ # With pipx (recommended for CLI tools)
71
+ pipx install web-snapshot-cli
72
+ # or from git:
73
+ pipx install git+https://github.com/codingsushi79/Snapshot.git
74
+
75
+ # From a local clone
76
+ git clone https://github.com/codingsushi79/Snapshot.git
77
+ cd Snapshot
78
+ pip install -e .
79
+ ```
80
+
81
+ </details>
82
+
83
+ ## Usage
84
+
85
+ ### Snapshot a single page
86
+
87
+ ```bash
88
+ snapshot https://example.com ./mirror
89
+ ```
90
+
91
+ ### Crawl an entire site
92
+
93
+ ```bash
94
+ snapshot --crawl https://docs.example.com ./docs --max-pages 200 --depth 4
95
+ ```
96
+
97
+ ### Save pages as Markdown
98
+
99
+ ```bash
100
+ snapshot https://example.com ./mirror --lang md
101
+ ```
102
+
103
+ ### Crawl with filters and politeness
104
+
105
+ ```bash
106
+ snapshot --crawl --include '/docs/*' --exclude '/docs/drafts/*' \
107
+ --crawl-delay 1 --robots https://docs.example.com ./docs
108
+ ```
109
+
110
+ ### Authenticated pages
111
+
112
+ ```bash
113
+ snapshot --cookie session=abc123 --header "Authorization: Bearer TOKEN" \
114
+ https://app.example.com ./mirror
115
+ ```
116
+
117
+ ### Sitemap-based crawl
118
+
119
+ ```bash
120
+ snapshot --crawl --sitemap https://example.com ./mirror --max-pages 500
121
+ ```
122
+
123
+ ### Resume an interrupted snapshot
124
+
125
+ ```bash
126
+ snapshot --resume --crawl https://example.com ./mirror
127
+ ```
128
+
129
+ ### Dry run (no writes)
130
+
131
+ ```bash
132
+ snapshot --dry-run --verbose --crawl https://example.com ./mirror
133
+ ```
134
+
135
+ ### Extra args (positional)
136
+
137
+ Any `key=value` pairs after the output directory are merged into options:
138
+
139
+ ```bash
140
+ snapshot https://example.com ./mirror crawl=true max-pages=100 lang=html concurrency=32
141
+ ```
142
+
143
+ ### Restore locally
144
+
145
+ ```bash
146
+ snapshot -restore ./mirror
147
+ ```
148
+
149
+ This starts a local HTTP server (default `http://127.0.0.1:8080`) and opens your browser.
150
+
151
+ ```bash
152
+ snapshot -restore ./mirror --port 3000 --no-open
153
+ ```
154
+
155
+ ## Options
156
+
157
+ | Flag | Description |
158
+ |------|-------------|
159
+ | `--crawl`, `-c` | Follow same-origin links and download all pages |
160
+ | `--lang`, `-l` | Output format: `html` (default) or `md` |
161
+ | `--max-pages` | Max pages when crawling (default: 50) |
162
+ | `--depth` | Max crawl depth (default: 3) |
163
+ | `--no-assets` | Skip CSS, JS, images, fonts |
164
+ | `--timeout` | HTTP timeout in seconds (default: 15) |
165
+ | `--concurrency` | Parallel downloads (default: 16) |
166
+ | `--same-origin` / `--no-same-origin` | Restrict crawl to same origin (default: on) |
167
+ | `--user-agent` | Custom User-Agent header |
168
+ | `--cookie` | Cookie as `name=value` (repeatable) |
169
+ | `--header` | Extra HTTP header (repeatable) |
170
+ | `--include` | Only fetch URLs matching glob (repeatable) |
171
+ | `--exclude` | Skip URLs matching glob (repeatable) |
172
+ | `--robots` / `--no-robots` | Respect robots.txt (default: on) |
173
+ | `--crawl-delay` | Seconds to wait after each request (default: 0) |
174
+ | `--sitemap` | Seed crawl from sitemap.xml |
175
+ | `--resume` | Skip pages/assets already saved |
176
+ | `--verbose`, `-v` | Detailed log output |
177
+ | `--dry-run` | Fetch without writing files |
178
+ | `-restore DIR` | Serve a saved snapshot from `DIR` |
179
+ | `--port` | Port for restore (default: 8080) |
180
+ | `--host` | Host for restore (default: 127.0.0.1) |
181
+ | `--no-open` | Don't open a browser on restore |
182
+
183
+ ## How it works
184
+
185
+ 1. **snapshot** fetches pages with async HTTP (httpx), rewrites links to local paths, and downloads linked assets in parallel.
186
+ 2. A `.snapshot.json` manifest is written to the output folder with metadata for restore.
187
+ 3. **snapshot -restore** serves the saved files and maps `/` back to the original root page.
188
+
189
+ ## Output layout
190
+
191
+ ```
192
+ mirror/
193
+ .snapshot.json
194
+ example.com/
195
+ index.html
196
+ about/
197
+ index.html
198
+ _assets/
199
+ ...
200
+ ```
201
+
202
+ ## License
203
+
204
+ MIT
@@ -0,0 +1,13 @@
1
+ snapshot/__init__.py,sha256=8-ApU_fAzbIwD0S_dLk4H7rehrqbrgU4o6Ra_fUEsN0,69
2
+ snapshot/__main__.py,sha256=LXvMYduq7SUnoKWE6DENN8jA_01Aq_6-7Pw7KsLXBh4,69
3
+ snapshot/cli.py,sha256=qczb369TSoM6-bCI1RSpR75QMQT5LUhvMHFdZW6AMks,10398
4
+ snapshot/crawl_policy.py,sha256=aqKoL533VbQwROawqqc9w_mQSFtfUxzYxcs0KJ11iAo,4698
5
+ snapshot/downloader.py,sha256=jNOG6kfbG_8i13qEnlAAEnUpw4BZ1WcWzfNO4b2WGE8,18272
6
+ snapshot/manifest.py,sha256=WFfHJB0urB9n6hb9vFNM5j8QrnAQgOzezQXwzzNEPx4,1759
7
+ snapshot/restore.py,sha256=XIiS4W2xRaIHcdCkixiY14KS2yL_HrLy0WSPS6PvjtM,4193
8
+ snapshot/utils.py,sha256=SgW2CWFFwn9ugIj-5BKQGUySPJIf4pJzlIs2GeO81fU,4352
9
+ web_snapshot_cli-0.1.0.dist-info/METADATA,sha256=1Zeixh_UyLEoik3sFbqskIkwGddJqe0ueX6TgAbVaow,5232
10
+ web_snapshot_cli-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
11
+ web_snapshot_cli-0.1.0.dist-info/entry_points.txt,sha256=Mbqy6jJjTTn5JuLCnmV8G_eJbX5oPKAb7C5qCgnEiXM,47
12
+ web_snapshot_cli-0.1.0.dist-info/licenses/LICENSE,sha256=jkBcwqVvEh626gr4L1xJ5uGcRH0ER7-SwZv9PgW1MiU,1078
13
+ web_snapshot_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ snapshot = snapshot.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 snapshot contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.