greenpage 0.1.1__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.
greenpage/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """greenpage: estimate and budget the carbon footprint of web pages."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ from .model import Estimate, estimate, rating_for # noqa: E402
6
+ from .scan import PageScan, Resource, scan_directory, scan_file, scan_url # noqa: E402
7
+
8
+ __all__ = [
9
+ "Estimate", "PageScan", "Resource", "estimate", "rating_for",
10
+ "scan_directory", "scan_file", "scan_url", "__version__",
11
+ ]
greenpage/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
greenpage/advice.py ADDED
@@ -0,0 +1,34 @@
1
+ """Actionable suggestions for reducing a page's footprint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import PurePosixPath
6
+ from urllib.parse import urlparse
7
+
8
+ from .scan import PageScan
9
+
10
+ KB = 1000
11
+
12
+
13
+ def suggestions(scan: PageScan) -> list[str]:
14
+ tips: list[str] = []
15
+ by_kind: dict[str, int] = {}
16
+ for r in scan.resources:
17
+ by_kind[r.kind] = by_kind.get(r.kind, 0) + r.bytes
18
+
19
+ for r in scan.resources:
20
+ ext = PurePosixPath(urlparse(r.url).path).suffix.lower()
21
+ if r.kind == "image" and ext in {".png", ".jpg", ".jpeg", ".gif"} and r.bytes > 100 * KB:
22
+ tips.append(f"{r.url} is {r.bytes // KB} kB; serving it as AVIF or WebP typically saves 30-50%.")
23
+ elif r.kind == "font" and ext in {".ttf", ".otf"}:
24
+ tips.append(f"{r.url} uses {ext}; WOFF2 is much smaller and universally supported.")
25
+ elif r.kind == "media" and r.bytes > 1000 * KB:
26
+ tips.append(f"{r.url} is {r.bytes // KB} kB; use preload=\"none\" or a poster so it only loads on demand.")
27
+
28
+ if by_kind.get("script", 0) > 300 * KB:
29
+ tips.append(
30
+ f"JavaScript totals {by_kind['script'] // KB} kB; consider code-splitting or removing unused libraries."
31
+ )
32
+ if by_kind.get("font", 0) > 150 * KB:
33
+ tips.append(f"Web fonts total {by_kind['font'] // KB} kB; subset them or prefer system fonts.")
34
+ return tips
greenpage/cli.py ADDED
@@ -0,0 +1,136 @@
1
+ """Command-line interface: ``greenpage scan <path-or-url>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .advice import suggestions
12
+ from .model import GLOBAL_GRID_INTENSITY, estimate
13
+ from .scan import PageScan, scan_directory, scan_file, scan_url
14
+
15
+
16
+ def _human(n: int) -> str:
17
+ for unit in ("B", "kB", "MB"):
18
+ if n < 1000:
19
+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
20
+ n /= 1000
21
+ return f"{n:.1f} GB"
22
+
23
+
24
+ def _grams(g: float) -> str:
25
+ return "<0.001" if 0 < g < 0.001 else f"{g:.3f}"
26
+
27
+
28
+ def _collect(target: str) -> list[PageScan]:
29
+ if target.startswith(("http://", "https://")):
30
+ return [scan_url(target)]
31
+ path = Path(target)
32
+ if path.is_dir():
33
+ return scan_directory(path)
34
+ if path.is_file():
35
+ return [scan_file(path, path.parent)]
36
+ raise FileNotFoundError(f"no such file, directory or URL: {target}")
37
+
38
+
39
+ def _results(scans: list[PageScan], args: argparse.Namespace) -> list[dict]:
40
+ out = []
41
+ for s in scans:
42
+ est = estimate(s.total_bytes, green_hosting=args.green_host, grid_intensity=args.grid_intensity)
43
+ out.append({
44
+ "page": s.page,
45
+ "bytes": s.total_bytes,
46
+ "grams_co2e": round(est.grams_co2e, 6),
47
+ "rating": est.rating,
48
+ "over_budget": args.budget is not None and est.grams_co2e > args.budget,
49
+ "yearly_kg_co2e": round(est.grams_co2e * args.views * 12 / 1000, 2) if args.views else None,
50
+ "resources": [
51
+ {"url": r.url, "kind": r.kind, "bytes": r.bytes, **({"error": r.error} if r.error else {})}
52
+ for r in sorted(s.resources, key=lambda r: -r.bytes)
53
+ ],
54
+ "suggestions": suggestions(s),
55
+ })
56
+ return out
57
+
58
+
59
+ def _print_text(results: list[dict], args: argparse.Namespace) -> None:
60
+ for r in results:
61
+ flag = " OVER BUDGET" if r["over_budget"] else ""
62
+ print(f"\n{r['page']}")
63
+ grams = _grams(r["grams_co2e"])
64
+ print(f" {_human(r['bytes'])} transferred · {grams} g CO2e/view · rating {r['rating']}{flag}")
65
+ if r["yearly_kg_co2e"] is not None:
66
+ print(f" ≈ {r['yearly_kg_co2e']} kg CO2e/year at {args.views:,} views/month")
67
+ heaviest = [x for x in r["resources"] if x["bytes"]][: args.top]
68
+ if heaviest:
69
+ print(" Heaviest resources:")
70
+ for x in heaviest:
71
+ print(f" {_human(x['bytes']):>9} {x['kind']:<8} {x['url']}")
72
+ for x in r["resources"]:
73
+ if "error" in x:
74
+ print(f" {'?':>9} {x['kind']:<8} {x['url']} ({x['error']})")
75
+ for tip in r["suggestions"]:
76
+ print(f" → {tip}")
77
+
78
+
79
+ def _print_markdown(results: list[dict], args: argparse.Namespace) -> None:
80
+ print("## 🌱 greenpage carbon report\n")
81
+ if args.budget is not None:
82
+ print(f"Budget: **{args.budget} g CO2e** per page view\n")
83
+ print("| Page | Size | g CO2e/view | Rating | Status |")
84
+ print("|---|---:|---:|:---:|:---:|")
85
+ for r in results:
86
+ status = "❌ over" if r["over_budget"] else "✅"
87
+ print(f"| `{r['page']}` | {_human(r['bytes'])} | {_grams(r['grams_co2e'])} | {r['rating']} | {status} |")
88
+ tips = [t for r in results for t in r["suggestions"]]
89
+ if tips:
90
+ print("\n<details><summary>Suggestions</summary>\n")
91
+ for t in dict.fromkeys(tips):
92
+ print(f"- {t}")
93
+ print("\n</details>")
94
+
95
+
96
+ def build_parser() -> argparse.ArgumentParser:
97
+ p = argparse.ArgumentParser(prog="greenpage", description="Estimate and budget the carbon footprint of web pages.")
98
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
99
+ sub = p.add_subparsers(dest="command", required=True)
100
+
101
+ s = sub.add_parser("scan", help="scan an HTML file, a build directory, or a URL")
102
+ s.add_argument("target", help="path to an .html file, a site build directory, or an http(s) URL")
103
+ s.add_argument("--budget", type=float, help="fail (exit 1) if any page exceeds this many grams CO2e per view")
104
+ s.add_argument("--green-host", action="store_true", help="site is hosted on renewable energy")
105
+ s.add_argument("--grid-intensity", type=float, default=GLOBAL_GRID_INTENSITY,
106
+ help=f"grid carbon intensity in gCO2e/kWh (default: global average {GLOBAL_GRID_INTENSITY})")
107
+ s.add_argument("--views", type=int, help="monthly page views, to project yearly emissions")
108
+ s.add_argument("--top", type=int, default=5, help="number of heaviest resources to list (default: 5)")
109
+ s.add_argument("--format", choices=("text", "json", "markdown"), default="text")
110
+ return p
111
+
112
+
113
+ def main(argv: list[str] | None = None) -> int:
114
+ args = build_parser().parse_args(argv)
115
+ try:
116
+ scans = _collect(args.target)
117
+ except (OSError, ValueError) as exc:
118
+ print(f"greenpage: error: {exc}", file=sys.stderr)
119
+ return 2
120
+ if not scans:
121
+ print(f"greenpage: error: no HTML pages found in {args.target}", file=sys.stderr)
122
+ return 2
123
+
124
+ results = _results(scans, args)
125
+ if args.format == "json":
126
+ print(json.dumps(results, indent=2))
127
+ elif args.format == "markdown":
128
+ _print_markdown(results, args)
129
+ else:
130
+ _print_text(results, args)
131
+
132
+ return 1 if any(r["over_budget"] for r in results) else 0
133
+
134
+
135
+ if __name__ == "__main__":
136
+ sys.exit(main())
greenpage/model.py ADDED
@@ -0,0 +1,95 @@
1
+ """Carbon estimation based on the Sustainable Web Design Model (v4).
2
+
3
+ The SWD model converts bytes transferred into energy across three system
4
+ segments (data centres, networks, user devices), each split into
5
+ operational and embodied energy, then multiplies by grid carbon intensity.
6
+
7
+ Reference: https://sustainablewebdesign.org/estimating-digital-emissions/
8
+ All constants live here so they can be audited and updated in one place.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ BYTES_PER_GB = 1_000_000_000
16
+
17
+ # kWh per GB transferred, SWD v4.
18
+ OPERATIONAL_KWH_PER_GB = {
19
+ "data_centre": 0.055,
20
+ "network": 0.059,
21
+ "user_device": 0.080,
22
+ }
23
+ EMBODIED_KWH_PER_GB = {
24
+ "data_centre": 0.012,
25
+ "network": 0.013,
26
+ "user_device": 0.081,
27
+ }
28
+
29
+ # Global average grid intensity in gCO2e/kWh (Ember, used by SWD v4).
30
+ GLOBAL_GRID_INTENSITY = 494.0
31
+
32
+ # SWD v4 digital carbon rating: upper bound in grams CO2e per page view.
33
+ RATINGS = (
34
+ ("A+", 0.040),
35
+ ("A", 0.079),
36
+ ("B", 0.145),
37
+ ("C", 0.209),
38
+ ("D", 0.278),
39
+ ("E", 0.359),
40
+ )
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Estimate:
45
+ bytes: int
46
+ energy_kwh: float
47
+ grams_co2e: float
48
+
49
+ @property
50
+ def rating(self) -> str:
51
+ return rating_for(self.grams_co2e)
52
+
53
+
54
+ def rating_for(grams: float) -> str:
55
+ for label, upper in RATINGS:
56
+ if grams <= upper:
57
+ return label
58
+ return "F"
59
+
60
+
61
+ def estimate(
62
+ num_bytes: int,
63
+ *,
64
+ green_hosting: bool = False,
65
+ green_hosting_factor: float | None = None,
66
+ grid_intensity: float = GLOBAL_GRID_INTENSITY,
67
+ ) -> Estimate:
68
+ """Estimate the emissions of transferring ``num_bytes`` for one page view.
69
+
70
+ ``green_hosting_factor`` is the share (0-1) of hosting powered by renewable
71
+ or zero-carbon energy; ``green_hosting=True`` is shorthand for 1.0, which
72
+ SWD v4 prescribes for hosts verified by the Green Web Foundation.
73
+ """
74
+ if num_bytes < 0:
75
+ raise ValueError("num_bytes must be non-negative")
76
+ if grid_intensity < 0:
77
+ raise ValueError("grid_intensity must be non-negative")
78
+ if green_hosting_factor is None:
79
+ green_hosting_factor = 1.0 if green_hosting else 0.0
80
+ if not 0 <= green_hosting_factor <= 1:
81
+ raise ValueError("green_hosting_factor must be between 0 and 1")
82
+
83
+ gb = num_bytes / BYTES_PER_GB
84
+ total_kwh = 0.0
85
+ grams = 0.0
86
+ for segment in OPERATIONAL_KWH_PER_GB:
87
+ op_kwh = gb * OPERATIONAL_KWH_PER_GB[segment]
88
+ emb_kwh = gb * EMBODIED_KWH_PER_GB[segment]
89
+ op_grams = op_kwh * grid_intensity
90
+ if segment == "data_centre":
91
+ op_grams *= 1 - green_hosting_factor
92
+ total_kwh += op_kwh + emb_kwh
93
+ # Embodied emissions happened at manufacture, so use the global grid.
94
+ grams += op_grams + emb_kwh * GLOBAL_GRID_INTENSITY
95
+ return Estimate(bytes=num_bytes, energy_kwh=total_kwh, grams_co2e=grams)
greenpage/scan.py ADDED
@@ -0,0 +1,188 @@
1
+ """Discover a page's resources and measure their transfer size.
2
+
3
+ Works on local build output (e.g. ``dist/``) without any network access,
4
+ or on live URLs using only the standard library.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import gzip
10
+ import urllib.error
11
+ import urllib.request
12
+ from dataclasses import dataclass, field
13
+ from html.parser import HTMLParser
14
+ from pathlib import Path
15
+ from urllib.parse import unquote, urljoin, urlparse
16
+
17
+ USER_AGENT = "greenpage (+https://github.com/Amxr-tech/greenpage)"
18
+ TIMEOUT = 15
19
+
20
+ _LINK_RELS = {"stylesheet", "icon", "preload", "modulepreload", "manifest", "apple-touch-icon"}
21
+
22
+
23
+ @dataclass
24
+ class Resource:
25
+ url: str
26
+ bytes: int
27
+ kind: str
28
+ error: str | None = None
29
+
30
+
31
+ @dataclass
32
+ class PageScan:
33
+ page: str
34
+ resources: list[Resource] = field(default_factory=list)
35
+
36
+ @property
37
+ def total_bytes(self) -> int:
38
+ return sum(r.bytes for r in self.resources)
39
+
40
+ @property
41
+ def errors(self) -> list[Resource]:
42
+ return [r for r in self.resources if r.error]
43
+
44
+
45
+ class _ResourceParser(HTMLParser):
46
+ def __init__(self) -> None:
47
+ super().__init__()
48
+ self.refs: list[tuple[str, str]] = []
49
+
50
+ def _add(self, url: str | None, kind: str) -> None:
51
+ if url and not url.startswith(("data:", "javascript:", "#", "mailto:")):
52
+ self.refs.append((url.strip(), kind))
53
+
54
+ def _add_srcset(self, srcset: str | None, kind: str) -> None:
55
+ # Browsers fetch one candidate; count the first as a fair approximation.
56
+ if srcset:
57
+ self._add(srcset.split(",")[0].strip().split(" ")[0], kind)
58
+
59
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
60
+ a = dict(attrs)
61
+ if tag == "script":
62
+ self._add(a.get("src"), "script")
63
+ elif tag == "link":
64
+ rels = set((a.get("rel") or "").lower().split())
65
+ if rels & _LINK_RELS:
66
+ kind = "style" if "stylesheet" in rels else _kind_from_ext(a.get("href") or "")
67
+ self._add(a.get("href"), kind)
68
+ elif tag == "img":
69
+ if a.get("src"):
70
+ self._add(a.get("src"), "image")
71
+ else:
72
+ self._add_srcset(a.get("srcset"), "image")
73
+ elif tag == "source":
74
+ if a.get("src"):
75
+ self._add(a.get("src"), "media")
76
+ else:
77
+ self._add_srcset(a.get("srcset"), "image")
78
+ elif tag in ("video", "audio"):
79
+ self._add(a.get("poster"), "image")
80
+ if a.get("preload") != "none":
81
+ self._add(a.get("src"), "media")
82
+ elif tag in ("iframe", "embed"):
83
+ self._add(a.get("src"), "document")
84
+
85
+
86
+ def extract_resources(html: str) -> list[tuple[str, str]]:
87
+ """Return de-duplicated ``(url, kind)`` pairs referenced by ``html``."""
88
+ parser = _ResourceParser()
89
+ parser.feed(html)
90
+ seen: set[str] = set()
91
+ unique = []
92
+ for url, kind in parser.refs:
93
+ if url not in seen:
94
+ seen.add(url)
95
+ unique.append((url, kind))
96
+ return unique
97
+
98
+
99
+ def _kind_from_ext(url: str) -> str:
100
+ ext = Path(urlparse(url).path).suffix.lower()
101
+ if ext in {".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico"}:
102
+ return "image"
103
+ if ext in {".woff", ".woff2", ".ttf", ".otf", ".eot"}:
104
+ return "font"
105
+ if ext in {".js", ".mjs"}:
106
+ return "script"
107
+ if ext == ".css":
108
+ return "style"
109
+ if ext in {".mp4", ".webm", ".mp3", ".ogg"}:
110
+ return "media"
111
+ return "other"
112
+
113
+
114
+ def _gzip_size(data: bytes) -> int:
115
+ """Approximate transfer size for text assets, which servers compress."""
116
+ return len(gzip.compress(data, compresslevel=6))
117
+
118
+
119
+ _COMPRESSIBLE = {".html", ".htm", ".css", ".js", ".mjs", ".svg", ".json", ".txt", ".xml"}
120
+
121
+
122
+ def _local_size(path: Path) -> int:
123
+ data = path.read_bytes()
124
+ return _gzip_size(data) if path.suffix.lower() in _COMPRESSIBLE else len(data)
125
+
126
+
127
+ def scan_file(html_path: Path, site_root: Path) -> PageScan:
128
+ """Scan a local HTML file, resolving resources relative to ``site_root``."""
129
+ html_path = html_path.resolve()
130
+ site_root = site_root.resolve()
131
+ scan = PageScan(page=str(html_path.relative_to(site_root)))
132
+ scan.resources.append(Resource(scan.page, _local_size(html_path), "document"))
133
+ counted: set[Path] = {html_path}
134
+
135
+ for ref, kind in extract_resources(html_path.read_text(encoding="utf-8", errors="replace")):
136
+ parsed = urlparse(ref)
137
+ if parsed.scheme in ("http", "https") or ref.startswith("//"):
138
+ scan.resources.append(Resource(ref, 0, kind, "external (use URL mode to measure)"))
139
+ continue
140
+ rel = unquote(parsed.path)
141
+ target = (site_root / rel.lstrip("/")) if rel.startswith("/") else (html_path.parent / rel)
142
+ target = target.resolve()
143
+ if not target.is_relative_to(site_root) or not target.is_file():
144
+ scan.resources.append(Resource(ref, 0, kind, "not found"))
145
+ continue
146
+ if target in counted: # same file referenced via a different path
147
+ continue
148
+ counted.add(target)
149
+ scan.resources.append(Resource(ref, _local_size(target), kind if kind != "other" else _kind_from_ext(ref)))
150
+ return scan
151
+
152
+
153
+ def scan_directory(root: Path) -> list[PageScan]:
154
+ root = root.resolve()
155
+ pages = sorted(p for p in root.rglob("*") if p.suffix.lower() in (".html", ".htm") and p.is_file())
156
+ return [scan_file(p, root) for p in pages]
157
+
158
+
159
+ def _fetch(url: str) -> tuple[bytes, int, str]:
160
+ """Fetch ``url`` and return (body, bytes on the wire, content type)."""
161
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept-Encoding": "gzip"})
162
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: # noqa: S310 - user-supplied http(s) URL
163
+ raw = resp.read()
164
+ ctype = resp.headers.get("Content-Type", "")
165
+ if resp.headers.get("Content-Encoding") == "gzip":
166
+ return gzip.decompress(raw), len(raw), ctype
167
+ return raw, len(raw), ctype
168
+
169
+
170
+ def scan_url(url: str) -> PageScan:
171
+ """Scan a live page over HTTP(S)."""
172
+ if urlparse(url).scheme not in ("http", "https"):
173
+ raise ValueError(f"unsupported URL scheme: {url}")
174
+ body, wire, _ = _fetch(url)
175
+ scan = PageScan(page=url)
176
+ scan.resources.append(Resource(url, wire, "document"))
177
+ for ref, kind in extract_resources(body.decode("utf-8", errors="replace")):
178
+ absolute = urljoin(url, ref)
179
+ if urlparse(absolute).scheme not in ("http", "https"):
180
+ continue
181
+ try:
182
+ _, size, ctype = _fetch(absolute)
183
+ if kind == "other":
184
+ kind = _kind_from_ext(absolute)
185
+ scan.resources.append(Resource(absolute, size, kind))
186
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
187
+ scan.resources.append(Resource(absolute, 0, kind, str(exc)))
188
+ return scan
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: greenpage
3
+ Version: 0.1.1
4
+ Summary: Estimate and budget the carbon footprint of web pages, locally or in CI.
5
+ Author: greenpage contributors
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: carbon,ci,green-software,sustainability,web-performance
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
14
+ Classifier: Topic :: Software Development :: Quality Assurance
15
+ Requires-Python: >=3.10
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=8; extra == 'dev'
18
+ Requires-Dist: ruff>=0.6; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # 🌱 greenpage
22
+
23
+ **Estimate and budget the carbon footprint of web pages, locally or in CI.**
24
+
25
+ [![CI](https://github.com/Amxr-tech/greenpage/actions/workflows/ci.yml/badge.svg)](https://github.com/Amxr-tech/greenpage/actions/workflows/ci.yml)
26
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
27
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
28
+ ![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
29
+
30
+ The internet accounts for an estimated 3–4% of global greenhouse gas emissions,
31
+ about the same as the aviation industry. Every byte a page sends uses energy in data
32
+ centres, networks and on the visitor's device. Teams already set **performance budgets**;
33
+ greenpage adds a **carbon budget** that stops pages from quietly getting heavier.
34
+
35
+ - 📏 **Measures** every page in a static build (`dist/`, `public/`, `_site/`) offline, or any live URL
36
+ - 🧮 **Estimates** grams of CO₂e per page view using the open [Sustainable Web Design Model v4](https://sustainablewebdesign.org/estimating-digital-emissions/)
37
+ - 🏷️ **Rates** each page A+ to F on the SWD digital carbon rating scale
38
+ - 🚦 **Enforces** a budget: exits non-zero when a page goes over, so CI fails
39
+ - 💡 **Suggests** fixes: oversized images, legacy font formats, autoplaying media, heavy JS
40
+ - 📦 **No dependencies**: pure Python standard library
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install greenpage
46
+ # or from source
47
+ pip install git+https://github.com/Amxr-tech/greenpage
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ```bash
53
+ # A whole static-site build
54
+ greenpage scan ./dist
55
+
56
+ # A single live page
57
+ greenpage scan https://example.com
58
+
59
+ # Fail if any page emits more than 0.2 g CO2e per view
60
+ greenpage scan ./dist --budget 0.2
61
+
62
+ # Site runs on renewable energy, 50k views/month: project yearly impact
63
+ greenpage scan ./dist --green-host --views 50000
64
+
65
+ # Machine-readable or PR-comment-ready output
66
+ greenpage scan ./dist --format json
67
+ greenpage scan ./dist --format markdown
68
+ ```
69
+
70
+ Example output:
71
+
72
+ ```
73
+ index.html
74
+ 150.5 kB transferred · 0.022 g CO2e/view · rating A+
75
+ ≈ 2.68 kg CO2e/year at 10,000 views/month
76
+ Heaviest resources:
77
+ 150.0 kB image assets/hero.png
78
+ 280 B document index.html
79
+ → assets/hero.png is 150 kB; serving it as AVIF or WebP typically saves 30-50%.
80
+ ```
81
+
82
+ | Exit code | Meaning |
83
+ |---|---|
84
+ | `0` | All pages are within budget (or no budget set) |
85
+ | `1` | At least one page is over budget |
86
+ | `2` | Usage error, e.g. the target was not found |
87
+
88
+ ## GitHub Action
89
+
90
+ ```yaml
91
+ - uses: actions/checkout@v4
92
+ - run: npm ci && npm run build
93
+ - uses: Amxr-tech/greenpage@v0
94
+ with:
95
+ target: dist
96
+ budget: "0.2"
97
+ ```
98
+
99
+ The action writes a Markdown report to the job summary and fails the job when a page is over budget.
100
+
101
+ ## Python API
102
+
103
+ ```python
104
+ from greenpage import estimate, scan_directory
105
+
106
+ for page in scan_directory("dist"):
107
+ e = estimate(page.total_bytes, green_hosting=True)
108
+ print(page.page, f"{e.grams_co2e:.3f} g", e.rating)
109
+ ```
110
+
111
+ ## Methodology
112
+
113
+ greenpage implements the **Sustainable Web Design Model v4**:
114
+
115
+ 1. **Bytes.** Every resource a page references (HTML, CSS, JS, images, fonts, media, iframes) is counted.
116
+ Text assets are measured gzip-compressed, which is how servers deliver them.
117
+ 2. **Energy.** Bytes are converted to energy at 0.194 kWh/GB operational and 0.106 kWh/GB embodied,
118
+ split across data centres, networks and user devices.
119
+ 3. **Carbon.** Energy is multiplied by grid intensity: 494 gCO₂e/kWh global average by default, configurable
120
+ with `--grid-intensity`. Embodied energy always uses the global average.
121
+ 4. **Green hosting.** Data-centre operational emissions are multiplied by `1 - green hosting factor`.
122
+ `--green-host` sets the factor to 1, as SWD v4 prescribes for hosts verified by the
123
+ [Green Web Foundation](https://www.thegreenwebfoundation.org/). The Python API also accepts a partial
124
+ `green_hosting_factor` (0–1).
125
+
126
+ All constants live in [`src/greenpage/model.py`](src/greenpage/model.py).
127
+
128
+ **Limitations.** These are estimates, not measurements. Local mode doesn't count resources loaded
129
+ at runtime by JavaScript, or external URLs (it flags them instead). The model assumes a first-time
130
+ visit with no caching. Use the numbers to compare pages and spot regressions, not as audited figures.
131
+
132
+ ## Roadmap
133
+
134
+ - [ ] Count CSS `url()` references (background images, `@font-face`)
135
+ - [ ] Automatic green-host lookup via the Green Web Foundation API
136
+ - [ ] Headless-browser mode to capture runtime-loaded resources
137
+ - [ ] Per-country grid intensity presets
138
+ - [ ] Track history and chart trends across commits
139
+
140
+ Want to work on one of these? See [CONTRIBUTING.md](CONTRIBUTING.md).
141
+
142
+ ## License
143
+
144
+ [MIT](LICENSE)
@@ -0,0 +1,11 @@
1
+ greenpage/__init__.py,sha256=l_8smQDxWfSwSiTW3k4Bmpr95BFJMUMU3ZBjTxKGqDw,391
2
+ greenpage/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ greenpage/advice.py,sha256=R1riR-Hqyhwl2FST-C91ObnIaXUgTmwNRwHSB84kLjs,1390
4
+ greenpage/cli.py,sha256=aFmSF39-zIFJbtyywkrVvwlrytrjMcamxTCPttximWQ,5468
5
+ greenpage/model.py,sha256=jiOZX-rHjnrRFv8m2ftKpozbvao7ev-1mJlE0MOx30c,2892
6
+ greenpage/scan.py,sha256=__kP-8mvfn7WVxAOl-iXFkzEFFw37JBJF8INLqPFU9k,6915
7
+ greenpage-0.1.1.dist-info/METADATA,sha256=S7Eo4e7AjSzovbJWRzR4sjl6X1QUU91YavPHFZz12BE,5418
8
+ greenpage-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ greenpage-0.1.1.dist-info/entry_points.txt,sha256=_npYfoB5Tb8flKeA-L4atT2sLUt-5b7vtFwoUU58_lQ,49
10
+ greenpage-0.1.1.dist-info/licenses/LICENSE,sha256=qUJOTfuXaEUjI_ByBmtKlAsP_R4DGxqQZj_vQ-LiX1k,1079
11
+ greenpage-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ greenpage = greenpage.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 greenpage 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.