gitsaga 0.1.0__tar.gz

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.
@@ -0,0 +1,20 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ jobs:
7
+ test:
8
+ runs-on: ${{ matrix.os }}
9
+ strategy:
10
+ matrix:
11
+ os: [ubuntu-latest, macos-latest, windows-latest]
12
+ python-version: ["3.10", "3.12", "3.13"]
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: ${{ matrix.python-version }}
18
+ - run: pip install -e ".[dev]"
19
+ - run: ruff check .
20
+ - run: pytest -q
@@ -0,0 +1,28 @@
1
+ name: publish
2
+ on:
3
+ release:
4
+ types: [published]
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v4
10
+ - name: Refuse to publish with placeholder metadata
11
+ run: |
12
+ if grep -rn "YOUR-GITHUB-USERNAME" pyproject.toml README.md; then
13
+ echo "::error::Replace YOUR-GITHUB-USERNAME with your GitHub username before releasing"; exit 1
14
+ fi
15
+ - uses: astral-sh/setup-uv@v5
16
+ - run: uv build
17
+ - uses: actions/upload-artifact@v4
18
+ with: { name: dist, path: dist/ }
19
+ publish:
20
+ needs: build
21
+ runs-on: ubuntu-latest
22
+ environment: pypi
23
+ permissions:
24
+ id-token: write # required for PyPI trusted publishing
25
+ steps:
26
+ - uses: actions/download-artifact@v4
27
+ with: { name: dist, path: dist/ }
28
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ story.html
10
+ story.gif
11
+ story.mp4
12
+ *.stale*
13
+ docs/ownership.png
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - Ownership view (`--view ownership`, `o` key): owners per directory, bus factor, areas whose owner has left,
6
+ with captions for ownership handovers, lost owners and the bus factor falling to 1.
7
+
8
+ ## 0.1.0
9
+
10
+ - Self-contained HTML player: directory tree growing over time, contributors
11
+ flying in, language mix bar, scrubber with milestone ticks.
12
+ - Milestone detection with rule-based captions (releases, contributors, new
13
+ areas, refactors, busiest stretch, silences, language shifts).
14
+ - `--gif` / `--mp4` export through headless Chromium (`gitsaga[video]`).
15
+ - `--theme dark|light`, `--since`, `--rev`, `--list`.
gitsaga-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gitsaga 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.
gitsaga-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.5
2
+ Name: gitsaga
3
+ Version: 0.1.0
4
+ Summary: The story of your repo in 60 seconds: a narrated, animated timeline of a git history with automatic milestone detection. One self-contained HTML file, optional GIF/MP4.
5
+ Project-URL: Homepage, https://github.com/rampangeni/gitsaga
6
+ Project-URL: Issues, https://github.com/rampangeni/gitsaga/issues
7
+ Author: Ram Pangeni
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: animation,git,gource,history,repository,timeline,visualization
11
+ Classifier: Development Status :: 3 - Alpha
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 :: Multimedia :: Graphics
17
+ Classifier: Topic :: Software Development :: Version Control :: Git
18
+ Requires-Python: >=3.10
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Requires-Dist: ruff>=0.6; extra == 'dev'
22
+ Provides-Extra: video
23
+ Requires-Dist: pillow>=10; extra == 'video'
24
+ Requires-Dist: playwright>=1.45; extra == 'video'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # gitsaga
28
+
29
+ **The story of your repo in 60 seconds.** One command turns `git log` into a
30
+ self-contained, animated, *narrated* timeline: directories grow as a tree,
31
+ contributors fly in to touch files, and captions call out the moments that
32
+ mattered — first commit, releases, new contributors, big refactors, long
33
+ silences, the day the language mix flipped.
34
+
35
+ ![gitsaga on Flask](docs/demo.gif)
36
+
37
+ ```console
38
+ $ pip install gitsaga
39
+ $ cd my-project
40
+ $ gitsaga --open
41
+ ```
42
+
43
+ That writes `story.html`: a single file with no network access, no CDN and no
44
+ dependencies. Email it, attach it to a release, drop it in a PR.
45
+
46
+ ## Why not Gource?
47
+
48
+ Gource draws a beautiful swarm but never tells you *what happened*. gitsaga
49
+ detects milestones from the history and narrates them with a rule-based
50
+ caption track — no LLM, no API key, nothing leaves your machine.
51
+
52
+ | | gitsaga | Gource |
53
+ |---|---|---|
54
+ | Output | one HTML file, scrubbable | realtime OpenGL window |
55
+ | Narration of milestones | yes | no |
56
+ | Needs a GPU / desktop | no | yes |
57
+ | Share it | send the file | screen-record |
58
+ | GIF / MP4 | built in (optional extra) | via ffmpeg pipe |
59
+
60
+ ## What gets detected
61
+
62
+ First commit · semver releases (from tags) · the Nth contributor and the top
63
+ authors joining · new top-level areas · the biggest changes · refactors (25+
64
+ renames in one commit) · the busiest 30 days · silences of 6+ months ·
65
+ language leadership shifts · round commit counts · "Today".
66
+ Milestones are scored and spaced so 12 captions cover the whole arc.
67
+
68
+ ## Ownership view: who knows this code?
69
+
70
+ ```console
71
+ $ gitsaga --view ownership --open
72
+ ```
73
+
74
+ Same animation, but every directory is coloured by **who owns it right now**. Press `o` (or the button) to
75
+ flip between languages and owners at any moment.
76
+
77
+ ![ownership view](docs/ownership.gif)
78
+
79
+ - A **red ring** marks an area with a bus factor of 1 (one person accounts for most of its recent changes).
80
+ - A **dashed amber ring** marks an area whose owner has not committed anywhere for 12+ months.
81
+ - The HUD shows the repo-wide **bus factor** over time, and captions call out the moments that matter:
82
+ *"extreview/ loses its owner"*, *"Markus takes over tests/"*, *"The bus factor falls to 1"*.
83
+
84
+ Ownership is recency-weighted: a change counts for its directory and every parent, and its weight halves every
85
+ 18 months, so the owner is whoever worked there most *recently and often*, not whoever wrote it a decade ago.
86
+ The bus factor is the fewest people who account for half of that weight. No network, no blame, no file contents —
87
+ only who touched which directory and when.
88
+
89
+ ## Usage
90
+
91
+ ```console
92
+ gitsaga [REPO] [-o story.html] [--open]
93
+ [--gif FILE] [--mp4 FILE] [--duration SECS]
94
+ [--theme dark|light] [--view language|ownership] [--rev REV] [--since DATE] [--milestones N] [--title TEXT]
95
+ [--depth N] [--max-dirs N] [--max-commits N]
96
+ [--include-bots] [--include-vendor] [--list]
97
+ ```
98
+
99
+ - `gitsaga --since "1 year ago"` — just the last year.
100
+ - `gitsaga --rev v2.0.0` — the story up to a tag.
101
+ - `gitsaga --list` — print the detected milestones without rendering.
102
+ - Bots (dependabot, renovate…) and noise (lock files, vendored and minified
103
+ files) are skipped by default; `--include-bots` / `--include-vendor` keep them.
104
+
105
+ - `gitsaga --theme light` — light player (and light GIF/MP4); the URL also accepts `?theme=light`.
106
+
107
+ Player keys: `space` play/pause, `←`/`→` step, `n`/`p` next/previous caption,
108
+ click the scrubber to seek. Add `?t=12000` to the URL to open at 12 s.
109
+
110
+ ## GIF and MP4
111
+
112
+ ```console
113
+ $ pip install 'gitsaga[video]'
114
+ $ playwright install chromium
115
+ $ gitsaga --gif story.gif # 30 s, 800x450
116
+ $ gitsaga --mp4 story.mp4 # 60 s, 1280x720 (needs ffmpeg)
117
+ ```
118
+
119
+ Frames are rendered deterministically by stepping the player's clock in
120
+ headless Chromium, so output is identical run to run.
121
+
122
+ ## Privacy
123
+
124
+ gitsaga only runs `git log`/`git tag` locally. The HTML embeds commit
125
+ subjects, author names and file paths from the history — review it before
126
+ sharing a private repo's story publicly.
127
+
128
+ ## Notes
129
+
130
+ - Shallow clones lose history; gitsaga warns. Use `git fetch --unshallow`.
131
+ - Very large repos: use `--max-commits` or `--since`. Commits are bucketed
132
+ into at most 360 animation steps.
133
+
134
+ ## Development
135
+
136
+ ```console
137
+ pip install -e ".[dev]"
138
+ ruff check . && pytest
139
+ ```
140
+
141
+ MIT licensed.
@@ -0,0 +1,115 @@
1
+ # gitsaga
2
+
3
+ **The story of your repo in 60 seconds.** One command turns `git log` into a
4
+ self-contained, animated, *narrated* timeline: directories grow as a tree,
5
+ contributors fly in to touch files, and captions call out the moments that
6
+ mattered — first commit, releases, new contributors, big refactors, long
7
+ silences, the day the language mix flipped.
8
+
9
+ ![gitsaga on Flask](docs/demo.gif)
10
+
11
+ ```console
12
+ $ pip install gitsaga
13
+ $ cd my-project
14
+ $ gitsaga --open
15
+ ```
16
+
17
+ That writes `story.html`: a single file with no network access, no CDN and no
18
+ dependencies. Email it, attach it to a release, drop it in a PR.
19
+
20
+ ## Why not Gource?
21
+
22
+ Gource draws a beautiful swarm but never tells you *what happened*. gitsaga
23
+ detects milestones from the history and narrates them with a rule-based
24
+ caption track — no LLM, no API key, nothing leaves your machine.
25
+
26
+ | | gitsaga | Gource |
27
+ |---|---|---|
28
+ | Output | one HTML file, scrubbable | realtime OpenGL window |
29
+ | Narration of milestones | yes | no |
30
+ | Needs a GPU / desktop | no | yes |
31
+ | Share it | send the file | screen-record |
32
+ | GIF / MP4 | built in (optional extra) | via ffmpeg pipe |
33
+
34
+ ## What gets detected
35
+
36
+ First commit · semver releases (from tags) · the Nth contributor and the top
37
+ authors joining · new top-level areas · the biggest changes · refactors (25+
38
+ renames in one commit) · the busiest 30 days · silences of 6+ months ·
39
+ language leadership shifts · round commit counts · "Today".
40
+ Milestones are scored and spaced so 12 captions cover the whole arc.
41
+
42
+ ## Ownership view: who knows this code?
43
+
44
+ ```console
45
+ $ gitsaga --view ownership --open
46
+ ```
47
+
48
+ Same animation, but every directory is coloured by **who owns it right now**. Press `o` (or the button) to
49
+ flip between languages and owners at any moment.
50
+
51
+ ![ownership view](docs/ownership.gif)
52
+
53
+ - A **red ring** marks an area with a bus factor of 1 (one person accounts for most of its recent changes).
54
+ - A **dashed amber ring** marks an area whose owner has not committed anywhere for 12+ months.
55
+ - The HUD shows the repo-wide **bus factor** over time, and captions call out the moments that matter:
56
+ *"extreview/ loses its owner"*, *"Markus takes over tests/"*, *"The bus factor falls to 1"*.
57
+
58
+ Ownership is recency-weighted: a change counts for its directory and every parent, and its weight halves every
59
+ 18 months, so the owner is whoever worked there most *recently and often*, not whoever wrote it a decade ago.
60
+ The bus factor is the fewest people who account for half of that weight. No network, no blame, no file contents —
61
+ only who touched which directory and when.
62
+
63
+ ## Usage
64
+
65
+ ```console
66
+ gitsaga [REPO] [-o story.html] [--open]
67
+ [--gif FILE] [--mp4 FILE] [--duration SECS]
68
+ [--theme dark|light] [--view language|ownership] [--rev REV] [--since DATE] [--milestones N] [--title TEXT]
69
+ [--depth N] [--max-dirs N] [--max-commits N]
70
+ [--include-bots] [--include-vendor] [--list]
71
+ ```
72
+
73
+ - `gitsaga --since "1 year ago"` — just the last year.
74
+ - `gitsaga --rev v2.0.0` — the story up to a tag.
75
+ - `gitsaga --list` — print the detected milestones without rendering.
76
+ - Bots (dependabot, renovate…) and noise (lock files, vendored and minified
77
+ files) are skipped by default; `--include-bots` / `--include-vendor` keep them.
78
+
79
+ - `gitsaga --theme light` — light player (and light GIF/MP4); the URL also accepts `?theme=light`.
80
+
81
+ Player keys: `space` play/pause, `←`/`→` step, `n`/`p` next/previous caption,
82
+ click the scrubber to seek. Add `?t=12000` to the URL to open at 12 s.
83
+
84
+ ## GIF and MP4
85
+
86
+ ```console
87
+ $ pip install 'gitsaga[video]'
88
+ $ playwright install chromium
89
+ $ gitsaga --gif story.gif # 30 s, 800x450
90
+ $ gitsaga --mp4 story.mp4 # 60 s, 1280x720 (needs ffmpeg)
91
+ ```
92
+
93
+ Frames are rendered deterministically by stepping the player's clock in
94
+ headless Chromium, so output is identical run to run.
95
+
96
+ ## Privacy
97
+
98
+ gitsaga only runs `git log`/`git tag` locally. The HTML embeds commit
99
+ subjects, author names and file paths from the history — review it before
100
+ sharing a private repo's story publicly.
101
+
102
+ ## Notes
103
+
104
+ - Shallow clones lose history; gitsaga warns. Use `git fetch --unshallow`.
105
+ - Very large repos: use `--max-commits` or `--since`. Commits are bucketed
106
+ into at most 360 animation steps.
107
+
108
+ ## Development
109
+
110
+ ```console
111
+ pip install -e ".[dev]"
112
+ ruff check . && pytest
113
+ ```
114
+
115
+ MIT licensed.
Binary file
Binary file
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "gitsaga"
7
+ dynamic = ["version"]
8
+ description = "The story of your repo in 60 seconds: a narrated, animated timeline of a git history with automatic milestone detection. One self-contained HTML file, optional GIF/MP4."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Ram Pangeni" }]
13
+ dependencies = []
14
+ keywords = ["git", "visualization", "history", "animation", "gource", "timeline", "repository"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Software Development :: Version Control :: Git",
22
+ "Topic :: Multimedia :: Graphics",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=8", "ruff>=0.6"]
27
+ # GIF / MP4 export renders the player in headless Chromium (then run: playwright install chromium)
28
+ video = ["playwright>=1.45", "pillow>=10"]
29
+
30
+ [project.scripts]
31
+ gitsaga = "gitsaga.cli:main"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/rampangeni/gitsaga"
35
+ Issues = "https://github.com/rampangeni/gitsaga/issues"
36
+
37
+ [tool.hatch.version]
38
+ path = "src/gitsaga/__init__.py"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/gitsaga"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+
46
+ [tool.ruff]
47
+ line-length = 100
48
+ target-version = "py310"
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,97 @@
1
+ """gitsaga [REPO] -o story.html [--gif story.gif] [--mp4 story.mp4]"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ import webbrowser
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .export import ExportError, export_gif, export_mp4
12
+ from .history import GitError, git, read_commits, read_tags, repo_name
13
+ from .model import Options, build_story
14
+ from .render import player_html
15
+
16
+
17
+ def _err(msg: str) -> None:
18
+ print(msg, file=sys.stderr, flush=True)
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ p = argparse.ArgumentParser(prog="gitsaga", description="The story of your repo in 60 seconds: an animated, narrated timeline of its git history.")
23
+ p.add_argument("repo", nargs="?", default=".", help="path to a git repository (default: .)")
24
+ p.add_argument("-o", "--output", default="story.html", help="HTML player to write (default: story.html)")
25
+ p.add_argument("--open", action="store_true", help="open the result in a browser")
26
+ p.add_argument("--gif", metavar="FILE", help="also render a GIF (needs: pip install 'gitsaga[video]' && playwright install chromium)")
27
+ p.add_argument("--mp4", metavar="FILE", help="also render an MP4 (needs the video extra and ffmpeg)")
28
+ p.add_argument("--theme", choices=("dark", "light"), default="dark", help="colour theme of the player and exports (default dark)")
29
+ p.add_argument("--view", choices=("language", "ownership"), default="language", help="what the player opens with: language colours, or who owns which code (bus factor, orphaned areas)")
30
+ p.add_argument("--duration", type=float, help="length in seconds, captions included (default 60; 30 for --gif)")
31
+ p.add_argument("--milestones", type=int, default=12, metavar="N", help="captions to show (default 12)")
32
+ p.add_argument("--title", help="name shown in the player (default: the repository folder)")
33
+ p.add_argument("--rev", default="HEAD", help="branch, tag or commit to tell the story of (default HEAD)")
34
+ p.add_argument("--since", metavar="DATE", help="only history since this date, e.g. 2024-01-01 or '1 year ago'")
35
+ p.add_argument("--depth", type=int, default=3, help="directory depth shown (default 3)")
36
+ p.add_argument("--max-dirs", type=int, default=110, help="most directories drawn (default 110)")
37
+ p.add_argument("--max-commits", type=int, default=200_000, help="safety limit on commits read")
38
+ p.add_argument("--include-bots", action="store_true", help="keep commits by bots (dependabot, renovate, ...)")
39
+ p.add_argument("--include-vendor", action="store_true", help="keep lock files, vendored and generated files")
40
+ p.add_argument("--width", type=int, help="GIF/MP4 width in pixels (default 800 for GIF, 1280 for MP4)")
41
+ p.add_argument("--height", type=int, help="GIF/MP4 height in pixels (default 450 for GIF, 720 for MP4)")
42
+ p.add_argument("--fps", type=int, help="GIF/MP4 frames per second (default 10 for GIF, 30 for MP4)")
43
+ p.add_argument("--list", action="store_true", help="print the detected milestones instead of writing files")
44
+ p.add_argument("-q", "--quiet", action="store_true")
45
+ p.add_argument("-V", "--version", action="version", version=f"gitsaga {__version__}")
46
+ return p
47
+
48
+
49
+ def main(argv: list[str] | None = None) -> int:
50
+ a = build_parser().parse_args(argv)
51
+ say = (lambda *_: None) if a.quiet else _err
52
+ try:
53
+ commits = read_commits(a.repo, a.rev, a.include_bots, a.include_vendor, a.max_commits, a.since)
54
+ tags = read_tags(a.repo)
55
+ name = a.title or repo_name(a.repo)
56
+ shallow = git(a.repo, "rev-parse", "--is-shallow-repository").strip() == "true"
57
+ except GitError as e:
58
+ _err(f"gitsaga: {e}")
59
+ return 2
60
+ if not commits:
61
+ _err("gitsaga: no commits found (empty repository, or everything was filtered out)")
62
+ return 2
63
+ if shallow:
64
+ say("gitsaga: this is a shallow clone, so the story starts at its oldest available commit. Run `git fetch --unshallow` for the full history.")
65
+ duration = a.duration or (30.0 if a.gif and not a.mp4 else 60.0) # a GIF that is too long gets huge
66
+ story = build_story(commits, tags, name, Options(depth=a.depth, max_dirs=a.max_dirs, duration=duration, milestones=a.milestones, view=a.view))
67
+ if a.list:
68
+ for m in story["milestones"]:
69
+ print(f"{m['s']:>4} {m['k']:<12} {m['title']} | {m['detail']}")
70
+ return 0
71
+ html = player_html(story, a.theme)
72
+ out = Path(a.output)
73
+ out.write_text(html, encoding="utf-8")
74
+ meta = story["meta"]
75
+ say(f"gitsaga: {meta['commits']:,} commits, {meta['authors']:,} contributors, {len(story['milestones'])} milestones -> {out} ({len(html) // 1024} KB)")
76
+
77
+ def progress(k: int, n: int) -> None:
78
+ if not a.quiet and (k == n or k % 25 == 0):
79
+ print(f"\r rendering frames {k}/{n}", end="" if k < n else "\n", file=sys.stderr, flush=True)
80
+
81
+ try:
82
+ if a.gif:
83
+ size = export_gif(html, a.gif, a.width or 800, a.height or 450, a.fps or 10, progress)
84
+ say(f"gitsaga: wrote {a.gif} ({size / 1e6:.1f} MB)" + (" (large: try --duration 20 or --width 640)" if size > 10e6 else ""))
85
+ if a.mp4:
86
+ size = export_mp4(html, a.mp4, a.width or 1280, a.height or 720, a.fps or 30, progress)
87
+ say(f"gitsaga: wrote {a.mp4} ({size / 1e6:.1f} MB)")
88
+ except ExportError as e:
89
+ _err(f"gitsaga: {e}")
90
+ return 3
91
+ if a.open:
92
+ webbrowser.open(out.resolve().as_uri())
93
+ return 0
94
+
95
+
96
+ if __name__ == "__main__":
97
+ sys.exit(main())
@@ -0,0 +1,80 @@
1
+ """GIF / MP4 export: step the HTML player frame by frame in headless Chromium (needs the `video` extra)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+
12
+ HINT = "GIF/MP4 export needs the video extra and a browser: pip install 'gitsaga[video]' && playwright install chromium"
13
+
14
+
15
+ class ExportError(RuntimeError):
16
+ pass
17
+
18
+
19
+ def _frames(html: str, width: int, height: int, fps: int, progress: Callable[[int, int], None] | None) -> list[bytes]:
20
+ try:
21
+ from playwright.sync_api import sync_playwright
22
+ except ImportError as e:
23
+ raise ExportError(HINT) from e
24
+ out: list[bytes] = []
25
+ with tempfile.TemporaryDirectory() as tmp, sync_playwright() as pw:
26
+ page_path = Path(tmp) / "story.html"
27
+ page_path.write_text(html, encoding="utf-8")
28
+ try:
29
+ browser = pw.chromium.launch()
30
+ except Exception as e:
31
+ raise ExportError(f"could not start Chromium ({str(e).splitlines()[0]}). {HINT}") from e
32
+ page = browser.new_page(viewport={"width": width, "height": height})
33
+ page.goto(page_path.as_uri() + "?export=1")
34
+ page.wait_for_function("window.__gitsaga && window.__gitsaga.ready")
35
+ total_ms = page.evaluate("__gitsaga.total")
36
+ count = max(2, int(total_ms / 1000 * fps) + 1)
37
+ for k in range(count):
38
+ page.evaluate(f"__gitsaga.seek({min(total_ms, k * 1000 / fps)})")
39
+ out.append(page.screenshot(type="png"))
40
+ if progress:
41
+ progress(k + 1, count)
42
+ browser.close()
43
+ return out
44
+
45
+
46
+ def export_gif(html: str, path: str, width: int = 800, height: int = 450, fps: int = 10,
47
+ progress: Callable[[int, int], None] | None = None) -> int:
48
+ try:
49
+ from PIL import Image
50
+ except ImportError as e:
51
+ raise ExportError(HINT) from e
52
+ frames = [Image.open(io.BytesIO(b)).convert("RGB") for b in _frames(html, width, height, fps, progress)]
53
+ # one shared palette built from a sample of frames: smaller files and no colour flicker between frames
54
+ sample = frames[:: max(1, len(frames) // 24)]
55
+ sheet = Image.new("RGB", (width, height * len(sample)))
56
+ for k, im in enumerate(sample):
57
+ sheet.paste(im, (0, k * height))
58
+ pal = sheet.quantize(colors=128, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
59
+ q = [im.quantize(palette=pal, dither=Image.Dither.NONE) for im in frames]
60
+ q[0].save(path, save_all=True, append_images=q[1:], duration=round(1000 / fps), loop=0, optimize=True)
61
+ return Path(path).stat().st_size
62
+
63
+
64
+ def export_mp4(html: str, path: str, width: int = 1280, height: int = 720, fps: int = 30,
65
+ progress: Callable[[int, int], None] | None = None) -> int:
66
+ ff = shutil.which("ffmpeg")
67
+ if not ff:
68
+ raise ExportError("MP4 export needs ffmpeg on your PATH (https://ffmpeg.org/download.html)")
69
+ width, height = width - width % 2, height - height % 2 # h264 wants even sizes
70
+ frames = _frames(html, width, height, fps, progress)
71
+ p = subprocess.Popen([ff, "-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", str(fps), "-i", "-", "-pix_fmt", "yuv420p",
72
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-movflags", "+faststart", path],
73
+ stdin=subprocess.PIPE)
74
+ assert p.stdin
75
+ for b in frames:
76
+ p.stdin.write(b)
77
+ p.stdin.close()
78
+ if p.wait() != 0:
79
+ raise ExportError("ffmpeg failed to encode the video")
80
+ return Path(path).stat().st_size