scribble-video 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.
- scribble_video-0.1.0/LICENSE +21 -0
- scribble_video-0.1.0/PKG-INFO +132 -0
- scribble_video-0.1.0/README.md +117 -0
- scribble_video-0.1.0/pyproject.toml +28 -0
- scribble_video-0.1.0/pyproject.toml.orig +29 -0
- scribble_video-0.1.0/src/scribble/__init__.py +1 -0
- scribble_video-0.1.0/src/scribble/__main__.py +4 -0
- scribble_video-0.1.0/src/scribble/cli.py +212 -0
- scribble_video-0.1.0/src/scribble/download.py +46 -0
- scribble_video-0.1.0/src/scribble/ffmpeg_tools.py +121 -0
- scribble_video-0.1.0/src/scribble/sketch.py +119 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stephen Eidson
|
|
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.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: scribble-video
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Turn a video (or a YouTube link) into a pencil-and-ink sketch
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: imageio-ffmpeg
|
|
8
|
+
Requires-Dist: numpy
|
|
9
|
+
Requires-Dist: opencv-python-headless
|
|
10
|
+
Requires-Dist: yt-dlp
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Project-URL: Repository, https://github.com/rarrarrarr/scribble
|
|
13
|
+
Project-URL: Issues, https://github.com/rarrarrarr/scribble/issues
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# scribble
|
|
17
|
+
|
|
18
|
+
Turn a video (or a YouTube link) into a pencil-and-ink sketch: one drawing per shot, a contact sheet of every shot, and the whole video redrawn in sketch style with its original audio.
|
|
19
|
+
|
|
20
|
+

|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
You need [uv](https://docs.astral.sh/uv/) (Windows, macOS or Linux). It also fetches Python 3.10+ if you don't have it.
|
|
25
|
+
|
|
26
|
+
```shell
|
|
27
|
+
uv tool install git+https://github.com/rarrarrarr/scribble
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
This puts a `scribble` command on your PATH. It has its own isolated environment, so nothing is installed into your global Python, and the repo isn't needed afterwards. The dependencies are OpenCV, NumPy, [yt-dlp](https://github.com/yt-dlp/yt-dlp) and [imageio-ffmpeg](https://github.com/imageio/imageio-ffmpeg), which downloads an ffmpeg binary for you. A system ffmpeg on your PATH is used as a fallback.
|
|
31
|
+
|
|
32
|
+
Upgrade with `uv tool upgrade scribble-video`, and remove it with `uv tool uninstall scribble-video`. The package is named `scribble-video` because `scribble` on PyPI is an unrelated project; the command is still `scribble`.
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```shell
|
|
37
|
+
scribble "https://www.youtube.com/watch?v=aqz-KE-bpKQ" # a link: downloaded first
|
|
38
|
+
scribble path/to/video.mp4 # a local file
|
|
39
|
+
scribble path/to/video.mp4 --no-video # just the drawings, much faster
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Quote links, since `&` is special to most shells.
|
|
43
|
+
|
|
44
|
+
### From source
|
|
45
|
+
|
|
46
|
+
```shell
|
|
47
|
+
git clone https://github.com/rarrarrarr/scribble
|
|
48
|
+
cd scribble
|
|
49
|
+
uv run scribble "https://www.youtube.com/watch?v=aqz-KE-bpKQ"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`uv run` creates a virtual environment in the repo (`.venv`) on first use, installs the versions pinned in `uv.lock`, and runs your working copy, so code changes take effect right away. It works from any folder inside the repo.
|
|
53
|
+
|
|
54
|
+
### Where files go
|
|
55
|
+
|
|
56
|
+
| Run as | Output and downloads |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| installed `scribble` | `~/scribble/`, with downloads in `~/scribble/source/` |
|
|
59
|
+
| `uv run scribble` in a clone | the repo's `scribble/` and `source/` folders, whichever folder you run it from |
|
|
60
|
+
|
|
61
|
+
To use another folder for both, set the `SCRIBBLE_HOME` environment variable. Outputs go in that folder and downloads in its `source/` subfolder. `-o` and `--download-dir` override this for a single run.
|
|
62
|
+
|
|
63
|
+
Each video gets its own folder, named after its title:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
<title-slug>/
|
|
67
|
+
frames/frame_001_0m01.63s.png one drawing per shot, from the middle of the shot
|
|
68
|
+
contact_sheet.png every shot on one page
|
|
69
|
+
<title-slug>_scribble.mp4 the full video in sketch style, with original audio
|
|
70
|
+
cuts.txt detected scene-cut times, in seconds
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Links are downloaded into the `source/` folder, and running again reuses that file.
|
|
74
|
+
|
|
75
|
+
### Options
|
|
76
|
+
|
|
77
|
+
| Option | Default | |
|
|
78
|
+
| --- | --- | --- |
|
|
79
|
+
| `-o, --out DIR` | `<title-slug>` in the output folder | output folder for this video |
|
|
80
|
+
| `--no-video` | | skip the sketch video; only make the drawings and contact sheet |
|
|
81
|
+
| `--threshold N` | `0.3` | scene-change sensitivity, 0 to 1; lower finds more shots |
|
|
82
|
+
| `--min-shot SECONDS` | `0.25` | ignore shots shorter than this |
|
|
83
|
+
| `--crf N` | `24` | video quality; lower is better and bigger |
|
|
84
|
+
| `--encoder NAME` | `auto` | `nvenc` encodes on an NVIDIA GPU (needs a recent driver), `x264` on the CPU; `auto` uses the GPU when it works |
|
|
85
|
+
| `--preset NAME` | `slow` | x264 speed preset; `veryfast` renders about 20% sooner |
|
|
86
|
+
| `--workers N` | CPU threads, at most 12 | frames sketched in parallel; `1` for one at a time |
|
|
87
|
+
| `--cols N` | `6` | contact sheet columns |
|
|
88
|
+
| `--title TEXT` | video title | contact sheet title (also sets the folder name) |
|
|
89
|
+
| `--download-dir DIR` | the `source/` folder | where links are downloaded |
|
|
90
|
+
| `--max-height N` | `1080` | highest resolution to download |
|
|
91
|
+
|
|
92
|
+
Each run replaces that folder's previous drawings.
|
|
93
|
+
|
|
94
|
+
## Troubleshooting
|
|
95
|
+
|
|
96
|
+
- **Downloads fail:** YouTube changes often and older yt-dlp versions stop working. Update it with `uv tool upgrade scribble-video`, or in a clone with `uv lock --upgrade-package yt-dlp` (the next run installs the new version).
|
|
97
|
+
- **yt-dlp warns about a JavaScript runtime:** install [deno](https://deno.com) to silence it and make more formats available.
|
|
98
|
+
|
|
99
|
+
## Code layout
|
|
100
|
+
|
|
101
|
+
All in `src/scribble/`:
|
|
102
|
+
|
|
103
|
+
- `cli.py`: the `scribble` command; runs each step in order
|
|
104
|
+
- `sketch.py`: the sketch look and the contact sheet layout; edit this to change the style
|
|
105
|
+
- `ffmpeg_tools.py`: scene detection and video encoding
|
|
106
|
+
- `download.py`: downloading links with yt-dlp
|
|
107
|
+
|
|
108
|
+
## Releasing
|
|
109
|
+
|
|
110
|
+
Publishing a GitHub release uploads the package to [PyPI](https://pypi.org/project/scribble-video/), using [.github/workflows/release.yml](.github/workflows/release.yml):
|
|
111
|
+
|
|
112
|
+
```shell
|
|
113
|
+
uv version --bump patch # or minor / major; updates pyproject.toml and uv.lock
|
|
114
|
+
git commit -am "release v$(uv version --short)"
|
|
115
|
+
git push
|
|
116
|
+
gh release create "v$(uv version --short)" --generate-notes
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The release tag must be `v` plus the version in `pyproject.toml`, or the workflow stops before publishing. To check that the package builds and installs without publishing anything, run the workflow by hand from the Actions tab.
|
|
120
|
+
|
|
121
|
+
PyPI trusts the workflow itself ([trusted publishing](https://docs.pypi.org/trusted-publishers/)), so no API token is stored. This takes a one-time setup:
|
|
122
|
+
|
|
123
|
+
1. On PyPI, open [Publishing](https://pypi.org/manage/account/publishing/) and add a pending publisher for GitHub: project `scribble-video`, owner `rarrarrarr`, repository `scribble`, workflow `release.yml`, environment `pypi`. The first release then creates the project.
|
|
124
|
+
2. On GitHub, under Settings > Environments, create an environment named `pypi`. Optionally add yourself as a required reviewer, so every upload waits for your approval.
|
|
125
|
+
|
|
126
|
+
## Use responsibly
|
|
127
|
+
|
|
128
|
+
Only download and process videos you have the right to use. YouTube's Terms of Service restrict downloading content without permission, and a sketched copy of someone else's video is still derived from their work.
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
[MIT](LICENSE). The sample image above is from *Big Buck Bunny*, © 2008 Blender Foundation, [www.bigbuckbunny.org](https://www.bigbuckbunny.org), used under [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# scribble
|
|
2
|
+
|
|
3
|
+
Turn a video (or a YouTube link) into a pencil-and-ink sketch: one drawing per shot, a contact sheet of every shot, and the whole video redrawn in sketch style with its original audio.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
You need [uv](https://docs.astral.sh/uv/) (Windows, macOS or Linux). It also fetches Python 3.10+ if you don't have it.
|
|
10
|
+
|
|
11
|
+
```shell
|
|
12
|
+
uv tool install git+https://github.com/rarrarrarr/scribble
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This puts a `scribble` command on your PATH. It has its own isolated environment, so nothing is installed into your global Python, and the repo isn't needed afterwards. The dependencies are OpenCV, NumPy, [yt-dlp](https://github.com/yt-dlp/yt-dlp) and [imageio-ffmpeg](https://github.com/imageio/imageio-ffmpeg), which downloads an ffmpeg binary for you. A system ffmpeg on your PATH is used as a fallback.
|
|
16
|
+
|
|
17
|
+
Upgrade with `uv tool upgrade scribble-video`, and remove it with `uv tool uninstall scribble-video`. The package is named `scribble-video` because `scribble` on PyPI is an unrelated project; the command is still `scribble`.
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```shell
|
|
22
|
+
scribble "https://www.youtube.com/watch?v=aqz-KE-bpKQ" # a link: downloaded first
|
|
23
|
+
scribble path/to/video.mp4 # a local file
|
|
24
|
+
scribble path/to/video.mp4 --no-video # just the drawings, much faster
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Quote links, since `&` is special to most shells.
|
|
28
|
+
|
|
29
|
+
### From source
|
|
30
|
+
|
|
31
|
+
```shell
|
|
32
|
+
git clone https://github.com/rarrarrarr/scribble
|
|
33
|
+
cd scribble
|
|
34
|
+
uv run scribble "https://www.youtube.com/watch?v=aqz-KE-bpKQ"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`uv run` creates a virtual environment in the repo (`.venv`) on first use, installs the versions pinned in `uv.lock`, and runs your working copy, so code changes take effect right away. It works from any folder inside the repo.
|
|
38
|
+
|
|
39
|
+
### Where files go
|
|
40
|
+
|
|
41
|
+
| Run as | Output and downloads |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| installed `scribble` | `~/scribble/`, with downloads in `~/scribble/source/` |
|
|
44
|
+
| `uv run scribble` in a clone | the repo's `scribble/` and `source/` folders, whichever folder you run it from |
|
|
45
|
+
|
|
46
|
+
To use another folder for both, set the `SCRIBBLE_HOME` environment variable. Outputs go in that folder and downloads in its `source/` subfolder. `-o` and `--download-dir` override this for a single run.
|
|
47
|
+
|
|
48
|
+
Each video gets its own folder, named after its title:
|
|
49
|
+
|
|
50
|
+
```text
|
|
51
|
+
<title-slug>/
|
|
52
|
+
frames/frame_001_0m01.63s.png one drawing per shot, from the middle of the shot
|
|
53
|
+
contact_sheet.png every shot on one page
|
|
54
|
+
<title-slug>_scribble.mp4 the full video in sketch style, with original audio
|
|
55
|
+
cuts.txt detected scene-cut times, in seconds
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Links are downloaded into the `source/` folder, and running again reuses that file.
|
|
59
|
+
|
|
60
|
+
### Options
|
|
61
|
+
|
|
62
|
+
| Option | Default | |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `-o, --out DIR` | `<title-slug>` in the output folder | output folder for this video |
|
|
65
|
+
| `--no-video` | | skip the sketch video; only make the drawings and contact sheet |
|
|
66
|
+
| `--threshold N` | `0.3` | scene-change sensitivity, 0 to 1; lower finds more shots |
|
|
67
|
+
| `--min-shot SECONDS` | `0.25` | ignore shots shorter than this |
|
|
68
|
+
| `--crf N` | `24` | video quality; lower is better and bigger |
|
|
69
|
+
| `--encoder NAME` | `auto` | `nvenc` encodes on an NVIDIA GPU (needs a recent driver), `x264` on the CPU; `auto` uses the GPU when it works |
|
|
70
|
+
| `--preset NAME` | `slow` | x264 speed preset; `veryfast` renders about 20% sooner |
|
|
71
|
+
| `--workers N` | CPU threads, at most 12 | frames sketched in parallel; `1` for one at a time |
|
|
72
|
+
| `--cols N` | `6` | contact sheet columns |
|
|
73
|
+
| `--title TEXT` | video title | contact sheet title (also sets the folder name) |
|
|
74
|
+
| `--download-dir DIR` | the `source/` folder | where links are downloaded |
|
|
75
|
+
| `--max-height N` | `1080` | highest resolution to download |
|
|
76
|
+
|
|
77
|
+
Each run replaces that folder's previous drawings.
|
|
78
|
+
|
|
79
|
+
## Troubleshooting
|
|
80
|
+
|
|
81
|
+
- **Downloads fail:** YouTube changes often and older yt-dlp versions stop working. Update it with `uv tool upgrade scribble-video`, or in a clone with `uv lock --upgrade-package yt-dlp` (the next run installs the new version).
|
|
82
|
+
- **yt-dlp warns about a JavaScript runtime:** install [deno](https://deno.com) to silence it and make more formats available.
|
|
83
|
+
|
|
84
|
+
## Code layout
|
|
85
|
+
|
|
86
|
+
All in `src/scribble/`:
|
|
87
|
+
|
|
88
|
+
- `cli.py`: the `scribble` command; runs each step in order
|
|
89
|
+
- `sketch.py`: the sketch look and the contact sheet layout; edit this to change the style
|
|
90
|
+
- `ffmpeg_tools.py`: scene detection and video encoding
|
|
91
|
+
- `download.py`: downloading links with yt-dlp
|
|
92
|
+
|
|
93
|
+
## Releasing
|
|
94
|
+
|
|
95
|
+
Publishing a GitHub release uploads the package to [PyPI](https://pypi.org/project/scribble-video/), using [.github/workflows/release.yml](.github/workflows/release.yml):
|
|
96
|
+
|
|
97
|
+
```shell
|
|
98
|
+
uv version --bump patch # or minor / major; updates pyproject.toml and uv.lock
|
|
99
|
+
git commit -am "release v$(uv version --short)"
|
|
100
|
+
git push
|
|
101
|
+
gh release create "v$(uv version --short)" --generate-notes
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The release tag must be `v` plus the version in `pyproject.toml`, or the workflow stops before publishing. To check that the package builds and installs without publishing anything, run the workflow by hand from the Actions tab.
|
|
105
|
+
|
|
106
|
+
PyPI trusts the workflow itself ([trusted publishing](https://docs.pypi.org/trusted-publishers/)), so no API token is stored. This takes a one-time setup:
|
|
107
|
+
|
|
108
|
+
1. On PyPI, open [Publishing](https://pypi.org/manage/account/publishing/) and add a pending publisher for GitHub: project `scribble-video`, owner `rarrarrarr`, repository `scribble`, workflow `release.yml`, environment `pypi`. The first release then creates the project.
|
|
109
|
+
2. On GitHub, under Settings > Environments, create an environment named `pypi`. Optionally add yourself as a required reviewer, so every upload waits for your approval.
|
|
110
|
+
|
|
111
|
+
## Use responsibly
|
|
112
|
+
|
|
113
|
+
Only download and process videos you have the right to use. YouTube's Terms of Service restrict downloading content without permission, and a sketched copy of someone else's video is still derived from their work.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
[MIT](LICENSE). The sample image above is from *Big Buck Bunny*, © 2008 Blender Foundation, [www.bigbuckbunny.org](https://www.bigbuckbunny.org), used under [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "scribble-video"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Turn a video (or a YouTube link) into a pencil-and-ink sketch"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.10"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"imageio-ffmpeg",
|
|
11
|
+
"numpy",
|
|
12
|
+
"opencv-python-headless",
|
|
13
|
+
"yt-dlp",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
scribble = "scribble.cli:main"
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Repository = "https://github.com/rarrarrarr/scribble"
|
|
21
|
+
Issues = "https://github.com/rarrarrarr/scribble/issues"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
[tool.uv.build-backend]
|
|
28
|
+
module-name = "scribble"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "scribble-video"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Turn a video (or a YouTube link) into a pencil-and-ink sketch"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.10"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"imageio-ffmpeg",
|
|
11
|
+
"numpy",
|
|
12
|
+
"opencv-python-headless",
|
|
13
|
+
"yt-dlp",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
scribble = "scribble.cli:main"
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Repository = "https://github.com/rarrarrarr/scribble"
|
|
21
|
+
Issues = "https://github.com/rarrarrarr/scribble/issues"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
# The package is src/scribble; without this, uv_build would look for src/scribble_video.
|
|
28
|
+
[tool.uv.build-backend]
|
|
29
|
+
module-name = "scribble"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""scribble: turn a video into a pencil-and-ink sketch."""
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""One command: video -> scribbled shot frames + contact sheet + sketch video with audio.
|
|
2
|
+
|
|
3
|
+
usage:
|
|
4
|
+
scribble VIDEO_OR_LINK [-o OUTDIR] [options] (installed as a tool)
|
|
5
|
+
uv run scribble VIDEO_OR_LINK ... (from a clone of the repo)
|
|
6
|
+
|
|
7
|
+
Where files go: run from the repo (`uv run scribble`), into the repo's scribble/
|
|
8
|
+
and source/ folders; installed as a tool, into ~/scribble/. Set SCRIBBLE_HOME to
|
|
9
|
+
use another folder instead (outputs in it, downloads in its source/ subfolder).
|
|
10
|
+
|
|
11
|
+
A link (e.g. https://www.youtube.com/watch?v=...) is downloaded with yt-dlp into
|
|
12
|
+
the source folder first ('<title> [<id>].mkv' + .info.json); later runs reuse that file.
|
|
13
|
+
|
|
14
|
+
Each video gets its own OUTDIR, named <slug>: the video's title in
|
|
15
|
+
lowercase-with-dashes (tags like "(Official Video)" dropped):
|
|
16
|
+
frames/frame_NNN_<m>m<ss.ss>s.png one sketch per shot (middle of the shot)
|
|
17
|
+
contact_sheet.png all shot sketches on one page
|
|
18
|
+
<slug>_scribble.mp4 the whole video in sketch style, original audio
|
|
19
|
+
cuts.txt detected scene-cut timestamps (seconds)
|
|
20
|
+
"""
|
|
21
|
+
import argparse
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
import unicodedata
|
|
28
|
+
from collections import deque
|
|
29
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
30
|
+
from contextlib import nullcontext
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
import cv2
|
|
34
|
+
|
|
35
|
+
from .download import download, is_url
|
|
36
|
+
from .ffmpeg_tools import VideoEncoder, detect_cuts, pick_encoder
|
|
37
|
+
from .sketch import Sketcher, contact_sheet, fmt_time
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def guess_title(video):
|
|
41
|
+
"""Title from a yt-dlp `<name>.info.json` beside the video, else the file name."""
|
|
42
|
+
info = video.with_suffix(".info.json")
|
|
43
|
+
if info.is_file():
|
|
44
|
+
try:
|
|
45
|
+
return json.loads(info.read_text(encoding="utf-8"))["title"]
|
|
46
|
+
except (ValueError, KeyError):
|
|
47
|
+
pass
|
|
48
|
+
return video.stem
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# Bracketed tags that add nothing to a folder name, e.g. "(Official Music Video)", "[HD]".
|
|
52
|
+
_TAG_RE = re.compile(r"[\(\[][^\)\]]*\b(official|video|audio|lyrics?|hd|hq|4k|remaster(ed)?|visualizer)\b[^\)\]]*[\)\]]", re.I)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def slugify(title, max_len=60):
|
|
56
|
+
"""'Coheed and Cambria - A Favor House Atlantic (Official Video)' -> 'coheed-and-cambria-a-favor-house-atlantic'."""
|
|
57
|
+
s = _TAG_RE.sub("", title)
|
|
58
|
+
s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
|
|
59
|
+
s = re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")
|
|
60
|
+
if len(s) > max_len:
|
|
61
|
+
s = s[:max_len].rsplit("-", 1)[0]
|
|
62
|
+
return s # may be "" for e.g. all-CJK titles; caller falls back
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def default_dirs():
|
|
66
|
+
"""(output root, download dir) when -o / --download-dir aren't given.
|
|
67
|
+
|
|
68
|
+
SCRIBBLE_HOME wins. Otherwise, running from this repo's own venv (`uv run scribble`)
|
|
69
|
+
writes into the repo, whatever the current folder; an installed tool (`uv tool
|
|
70
|
+
install`, which gets its own venv) writes into ~/scribble.
|
|
71
|
+
"""
|
|
72
|
+
home = os.environ.get("SCRIBBLE_HOME")
|
|
73
|
+
if home:
|
|
74
|
+
home = Path(home).expanduser()
|
|
75
|
+
return home, home / "source"
|
|
76
|
+
repo = Path(__file__).resolve().parents[2] # <repo>/src/scribble/cli.py
|
|
77
|
+
if (repo / "pyproject.toml").is_file() and repo in Path(sys.prefix).resolve().parents:
|
|
78
|
+
return repo / "scribble", repo / "source"
|
|
79
|
+
home = Path.home() / "scribble"
|
|
80
|
+
return home, home / "source"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def save_png(path, img):
|
|
84
|
+
# cv2.imwrite silently fails on non-ASCII paths on Windows; encode in memory instead.
|
|
85
|
+
ok, buf = cv2.imencode(".png", img)
|
|
86
|
+
if not ok:
|
|
87
|
+
raise RuntimeError(f"could not encode {path}")
|
|
88
|
+
Path(path).write_bytes(buf.tobytes())
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def shot_frames(cuts, duration, fps, min_shot):
|
|
92
|
+
"""{frame_index: shot_number} for the middle frame of every shot >= min_shot seconds."""
|
|
93
|
+
bounds = [0.0] + [c for c in cuts if 0 < c < duration] + [duration]
|
|
94
|
+
mids = [(a + b) / 2 for a, b in zip(bounds, bounds[1:]) if b - a >= min_shot]
|
|
95
|
+
return {int(m * fps): i + 1 for i, m in enumerate(mids)}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main(argv=None):
|
|
99
|
+
p = argparse.ArgumentParser(prog="scribble", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
100
|
+
p.add_argument("video", help="video file, or a link (e.g. YouTube) to download first")
|
|
101
|
+
p.add_argument("-o", "--out", type=Path,
|
|
102
|
+
help="output folder for this video (default: <output root>/<slug of title>, see above)")
|
|
103
|
+
p.add_argument("--download-dir", type=Path,
|
|
104
|
+
help="where links are downloaded to (default: the source folder, see above); re-runs reuse the file")
|
|
105
|
+
p.add_argument("--max-height", type=int, default=1080, help="max video height to download (default 1080)")
|
|
106
|
+
p.add_argument("--title", help="contact sheet title (default: from .info.json or file name)")
|
|
107
|
+
p.add_argument("--threshold", type=float, default=0.3, help="scene-change sensitivity 0-1; lower = more shots (default 0.3)")
|
|
108
|
+
p.add_argument("--min-shot", type=float, default=0.25, help="ignore shots shorter than this many seconds (default 0.25)")
|
|
109
|
+
p.add_argument("--cols", type=int, default=6, help="contact sheet columns (default 6)")
|
|
110
|
+
p.add_argument("--crf", type=int, default=24, help="video quality, lower = bigger/better (default 24)")
|
|
111
|
+
p.add_argument("--encoder", choices=("auto", "nvenc", "x264"), default="auto",
|
|
112
|
+
help="nvenc = NVIDIA GPU, x264 = CPU; auto uses the GPU when it works (default auto)")
|
|
113
|
+
p.add_argument("--preset", default="slow",
|
|
114
|
+
help="x264 speed preset, e.g. medium, fast, veryfast: faster files are a little bigger (default slow)")
|
|
115
|
+
p.add_argument("--no-video", action="store_true", help="only make frames + contact sheet (much faster)")
|
|
116
|
+
p.add_argument("--workers", type=int, default=0,
|
|
117
|
+
help="frames sketched in parallel (default: CPU threads, at most 12; 1 = serial)")
|
|
118
|
+
a = p.parse_args(argv)
|
|
119
|
+
out_root, download_dir = default_dirs()
|
|
120
|
+
a.download_dir = a.download_dir or download_dir
|
|
121
|
+
# Don't crash printing non-ASCII titles to a legacy console / redirected output.
|
|
122
|
+
for stream in (sys.stdout, sys.stderr):
|
|
123
|
+
if hasattr(stream, "reconfigure"):
|
|
124
|
+
stream.reconfigure(errors="replace")
|
|
125
|
+
|
|
126
|
+
if is_url(a.video):
|
|
127
|
+
print(f"downloading {a.video} ...")
|
|
128
|
+
a.video = download(a.video, a.download_dir, a.max_height)
|
|
129
|
+
print(f" -> {a.video}")
|
|
130
|
+
else:
|
|
131
|
+
a.video = Path(a.video)
|
|
132
|
+
if not a.video.is_file():
|
|
133
|
+
p.error(f"no such file: {a.video}")
|
|
134
|
+
title = a.title or guess_title(a.video)
|
|
135
|
+
# downloaded files are '<title> [<id>]', so a non-Latin title still yields the video id
|
|
136
|
+
slug = slugify(title) or slugify(a.video.stem) or "video"
|
|
137
|
+
a.out = a.out or out_root / slug
|
|
138
|
+
frames_dir = a.out / "frames"
|
|
139
|
+
frames_dir.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
for old in frames_dir.glob("frame_*.png"): # stale shots from an earlier run
|
|
141
|
+
old.unlink()
|
|
142
|
+
|
|
143
|
+
cap = cv2.VideoCapture(str(a.video))
|
|
144
|
+
if not cap.isOpened():
|
|
145
|
+
sys.exit(f"OpenCV could not open {a.video}")
|
|
146
|
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
147
|
+
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
148
|
+
W, H = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
|
149
|
+
duration = total / fps
|
|
150
|
+
print(f"{a.video.name}: {W}x{H} @ {fps:.3f} fps, {fmt_time(duration)}")
|
|
151
|
+
|
|
152
|
+
print("detecting scene cuts...")
|
|
153
|
+
cuts = detect_cuts(a.video, a.threshold)
|
|
154
|
+
(a.out / "cuts.txt").write_text("\n".join(f"{c:.3f}" for c in cuts) + "\n")
|
|
155
|
+
picks = shot_frames(cuts, duration, fps, a.min_shot)
|
|
156
|
+
print(f" {len(cuts)} cuts -> {len(picks)} shots")
|
|
157
|
+
|
|
158
|
+
workers = max(1, a.workers or min(12, os.cpu_count() or 1))
|
|
159
|
+
if workers > 1:
|
|
160
|
+
# parallelism comes from sketching whole frames side by side; OpenCV's own
|
|
161
|
+
# per-call threads on top of that only oversubscribe the cores
|
|
162
|
+
cv2.setNumThreads(1)
|
|
163
|
+
sketch = Sketcher(W, H)
|
|
164
|
+
video_out = a.out / f"{slug}_scribble.mp4"
|
|
165
|
+
if not a.no_video:
|
|
166
|
+
a.encoder = pick_encoder(a.encoder)
|
|
167
|
+
print(f"rendering with {workers} threads, encoding with {a.encoder}")
|
|
168
|
+
thumbs = []
|
|
169
|
+
start = time.time()
|
|
170
|
+
|
|
171
|
+
def finish(t, shot, s):
|
|
172
|
+
if encoder:
|
|
173
|
+
encoder.write(s)
|
|
174
|
+
if shot:
|
|
175
|
+
name = f"frame_{shot:03d}_{int(t // 60)}m{t % 60:05.2f}s.png"
|
|
176
|
+
save_png(frames_dir / name, s)
|
|
177
|
+
thumbs.append((t, s))
|
|
178
|
+
|
|
179
|
+
with (nullcontext() if a.no_video
|
|
180
|
+
else VideoEncoder(video_out, W, H, fps, audio_from=a.video, crf=a.crf,
|
|
181
|
+
preset=a.preset, encoder=a.encoder)) as encoder, \
|
|
182
|
+
ThreadPoolExecutor(workers) as pool:
|
|
183
|
+
# frames are sketched out of order on the pool and written back in order;
|
|
184
|
+
# `pending` caps how many decoded frames are held in memory at once
|
|
185
|
+
pending = deque()
|
|
186
|
+
i = 0
|
|
187
|
+
while True:
|
|
188
|
+
ok, frame = cap.read()
|
|
189
|
+
if not ok:
|
|
190
|
+
break
|
|
191
|
+
t = i / fps
|
|
192
|
+
shot = picks.get(i)
|
|
193
|
+
if encoder or shot:
|
|
194
|
+
pending.append((t, shot, pool.submit(sketch, frame, t)))
|
|
195
|
+
if len(pending) > 2 * workers:
|
|
196
|
+
t0, shot0, fut = pending.popleft()
|
|
197
|
+
finish(t0, shot0, fut.result())
|
|
198
|
+
i += 1
|
|
199
|
+
if i % 300 == 0:
|
|
200
|
+
print(f"\r rendering {i}/{total} ({time.time() - start:.0f}s)", end="", flush=True)
|
|
201
|
+
while pending:
|
|
202
|
+
t0, shot0, fut = pending.popleft()
|
|
203
|
+
finish(t0, shot0, fut.result())
|
|
204
|
+
elapsed = time.time() - start
|
|
205
|
+
print(f"\r read {i} frames in {elapsed:.0f}s ({i / max(elapsed, 1e-9):.0f} fps, {workers} threads)"
|
|
206
|
+
+ ("" if a.no_video else "; finishing encode..."))
|
|
207
|
+
cap.release()
|
|
208
|
+
|
|
209
|
+
save_png(a.out / "contact_sheet.png", contact_sheet(thumbs, title, cols=a.cols))
|
|
210
|
+
print(f"done -> {a.out.resolve()}")
|
|
211
|
+
print(f" {len(thumbs)} frames, contact_sheet.png" + ("" if a.no_video else f", {video_out.name}"))
|
|
212
|
+
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Download a video (e.g. a YouTube link) with yt-dlp."""
|
|
2
|
+
import re
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from .ffmpeg_tools import ffmpeg_exe
|
|
6
|
+
|
|
7
|
+
URL_RE = re.compile(r"^[a-z][a-z0-9+.-]*://", re.I)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def is_url(s):
|
|
11
|
+
return bool(URL_RE.match(str(s)))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def download(url, dest_dir, max_height=1080):
|
|
15
|
+
"""Download best video (<= max_height) + best audio, merged to .mkv, plus a
|
|
16
|
+
yt-dlp .info.json beside it. Returns the video's Path.
|
|
17
|
+
|
|
18
|
+
Files are named '<title> [<id>].mkv'; an already-downloaded video is reused.
|
|
19
|
+
"""
|
|
20
|
+
try:
|
|
21
|
+
import yt_dlp
|
|
22
|
+
except ImportError:
|
|
23
|
+
raise SystemExit("yt-dlp is needed for links: uv lock --upgrade-package yt-dlp")
|
|
24
|
+
|
|
25
|
+
dest_dir = Path(dest_dir)
|
|
26
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
opts = {
|
|
28
|
+
"format": f"bv*[height<={max_height}]+ba/b[height<={max_height}]/b",
|
|
29
|
+
"merge_output_format": "mkv",
|
|
30
|
+
"outtmpl": str(dest_dir / "%(title).80B [%(id)s].%(ext)s"),
|
|
31
|
+
"writeinfojson": True,
|
|
32
|
+
"noplaylist": True, # a watch?v=...&list=... link means just that one video
|
|
33
|
+
"ffmpeg_location": ffmpeg_exe(),
|
|
34
|
+
"quiet": True,
|
|
35
|
+
"no_warnings": True,
|
|
36
|
+
"noprogress": True,
|
|
37
|
+
}
|
|
38
|
+
with yt_dlp.YoutubeDL(opts) as ydl:
|
|
39
|
+
info = ydl.extract_info(url, download=True)
|
|
40
|
+
if info.get("_type") == "playlist":
|
|
41
|
+
raise SystemExit("that link is a playlist; pass a single video link")
|
|
42
|
+
downloads = info.get("requested_downloads") or []
|
|
43
|
+
path = Path(downloads[0]["filepath"]) if downloads else Path(ydl.prepare_filename(info))
|
|
44
|
+
if not path.is_file():
|
|
45
|
+
raise SystemExit(f"download finished but the file wasn't found: {path}")
|
|
46
|
+
return path
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Thin helpers around the ffmpeg binary (bundled by imageio-ffmpeg, or found on PATH)."""
|
|
2
|
+
import re
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
|
|
7
|
+
# Audio codecs that can be stream-copied into an .mp4 without re-encoding.
|
|
8
|
+
MP4_SAFE_AUDIO = {"aac", "mp3", "opus", "flac", "alac", "ac3", "eac3"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@lru_cache(maxsize=None)
|
|
12
|
+
def ffmpeg_exe():
|
|
13
|
+
try:
|
|
14
|
+
import imageio_ffmpeg
|
|
15
|
+
return imageio_ffmpeg.get_ffmpeg_exe()
|
|
16
|
+
except (ImportError, RuntimeError): # RuntimeError: no bundled binary for this platform
|
|
17
|
+
exe = shutil.which("ffmpeg")
|
|
18
|
+
if exe:
|
|
19
|
+
return exe
|
|
20
|
+
raise SystemExit("ffmpeg not found: run `uv sync`, or install ffmpeg on PATH")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _probe(video):
|
|
24
|
+
# `ffmpeg -i` with no output exits non-zero but prints stream info to stderr.
|
|
25
|
+
r = subprocess.run([ffmpeg_exe(), "-hide_banner", "-i", str(video)],
|
|
26
|
+
capture_output=True, text=True, errors="replace")
|
|
27
|
+
return r.stderr
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def audio_codec(video):
|
|
31
|
+
"""Name of the first audio stream's codec, or None if the file has no audio."""
|
|
32
|
+
m = re.search(r"Stream #\S+.*?: Audio: (\w+)", _probe(video))
|
|
33
|
+
return m.group(1) if m else None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def detect_cuts(video, threshold=0.3):
|
|
37
|
+
"""Timestamps (seconds) where ffmpeg's scene-change score exceeds `threshold`."""
|
|
38
|
+
cmd = [ffmpeg_exe(), "-hide_banner", "-nostats", "-i", str(video), "-an",
|
|
39
|
+
"-vf", f"select='gt(scene,{threshold})',showinfo", "-f", "null", "-"]
|
|
40
|
+
r = subprocess.run(cmd, capture_output=True, text=True, errors="replace")
|
|
41
|
+
if r.returncode != 0:
|
|
42
|
+
raise RuntimeError(f"scene detection failed:\n{r.stderr[-2000:]}")
|
|
43
|
+
return [float(t) for t in re.findall(r"pts_time:([0-9.]+)", r.stderr)]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@lru_cache(maxsize=None)
|
|
47
|
+
def nvenc_works():
|
|
48
|
+
"""True if ffmpeg can open NVIDIA's H.264 encoder here (needs an NVIDIA GPU and a
|
|
49
|
+
recent enough driver; ffmpeg lists the encoder even when it cannot use it)."""
|
|
50
|
+
cmd = [ffmpeg_exe(), "-v", "error", "-f", "lavfi", "-i", "color=black:s=256x256:d=0.1",
|
|
51
|
+
"-c:v", "h264_nvenc", "-f", "null", "-"]
|
|
52
|
+
try:
|
|
53
|
+
return subprocess.run(cmd, capture_output=True, timeout=30).returncode == 0
|
|
54
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pick_encoder(choice):
|
|
59
|
+
"""'auto' -> 'nvenc' when it works, else 'x264'; an explicit choice is checked."""
|
|
60
|
+
if choice == "auto":
|
|
61
|
+
return "nvenc" if nvenc_works() else "x264"
|
|
62
|
+
if choice == "nvenc" and not nvenc_works():
|
|
63
|
+
raise SystemExit("--encoder nvenc: ffmpeg could not open the NVIDIA encoder "
|
|
64
|
+
"(needs an NVIDIA GPU and an up-to-date driver)")
|
|
65
|
+
return choice
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class VideoEncoder:
|
|
69
|
+
"""Pipe raw BGR frames into ffmpeg (H.264), optionally taking audio from another file.
|
|
70
|
+
|
|
71
|
+
encoder is 'x264' (CPU; crf and preset apply) or 'nvenc' (NVIDIA GPU; crf maps
|
|
72
|
+
to about the same quality as x264's slow preset, and preset is ignored).
|
|
73
|
+
Audio is stream-copied when the codec fits in the container, otherwise encoded to AAC.
|
|
74
|
+
Use as a context manager, calling write(frame) for each frame.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, out, width, height, fps, audio_from=None, crf=24, preset="slow", encoder="x264"):
|
|
78
|
+
cmd = [ffmpeg_exe(), "-v", "error", "-y",
|
|
79
|
+
"-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{width}x{height}",
|
|
80
|
+
"-framerate", f"{fps:.6f}", "-i", "-"]
|
|
81
|
+
codec = audio_codec(audio_from) if audio_from else None
|
|
82
|
+
if codec:
|
|
83
|
+
copy = codec in MP4_SAFE_AUDIO or not str(out).lower().endswith((".mp4", ".m4v", ".mov"))
|
|
84
|
+
cmd += ["-i", str(audio_from), "-map", "0:v", "-map", "1:a:0", "-shortest"]
|
|
85
|
+
cmd += ["-c:a", "copy"] if copy else ["-c:a", "aac", "-b:a", "256k"]
|
|
86
|
+
if encoder == "nvenc":
|
|
87
|
+
# NVENC's -cq 21 measured the same size and PSNR as x264 -crf 24 -preset slow
|
|
88
|
+
# on sketch frames, so offset it to keep --crf meaning one quality on both
|
|
89
|
+
cmd += ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
|
|
90
|
+
"-rc", "vbr", "-cq", str(max(crf - 3, 0)), "-b:v", "0"]
|
|
91
|
+
else:
|
|
92
|
+
cmd += ["-c:v", "libx264", "-crf", str(crf), "-preset", preset]
|
|
93
|
+
cmd += ["-pix_fmt", "yuv420p", str(out)]
|
|
94
|
+
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
|
95
|
+
|
|
96
|
+
def write(self, frame):
|
|
97
|
+
try:
|
|
98
|
+
self.proc.stdin.write(frame.tobytes())
|
|
99
|
+
except (BrokenPipeError, OSError):
|
|
100
|
+
self.close() # surfaces ffmpeg's exit code
|
|
101
|
+
raise
|
|
102
|
+
|
|
103
|
+
def close(self):
|
|
104
|
+
if self.proc.stdin and not self.proc.stdin.closed:
|
|
105
|
+
try:
|
|
106
|
+
self.proc.stdin.close()
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
rc = self.proc.wait()
|
|
110
|
+
if rc != 0:
|
|
111
|
+
raise RuntimeError(f"ffmpeg encoder exited with code {rc}")
|
|
112
|
+
|
|
113
|
+
def __enter__(self):
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
def __exit__(self, exc_type, *_):
|
|
117
|
+
if exc_type is None:
|
|
118
|
+
self.close()
|
|
119
|
+
else: # don't mask the original error; just stop ffmpeg
|
|
120
|
+
self.proc.kill()
|
|
121
|
+
self.proc.wait()
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""The 'scribble' look: pencil shading + ink outlines + cross-hatching on paper.
|
|
2
|
+
|
|
3
|
+
Pure image code (OpenCV/numpy), no I/O. Used by cli.py.
|
|
4
|
+
"""
|
|
5
|
+
import math
|
|
6
|
+
import threading
|
|
7
|
+
|
|
8
|
+
import cv2
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Sketcher:
|
|
13
|
+
"""Converts BGR frames of a fixed size into sketch-style BGR frames.
|
|
14
|
+
|
|
15
|
+
Paper grain and hatch textures are generated once per instance so a video
|
|
16
|
+
doesn't "boil" from frame to frame. Safe to call from several threads at once.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, width, height, seed=7):
|
|
20
|
+
self.w, self.h = width, height
|
|
21
|
+
rng = np.random.default_rng(seed)
|
|
22
|
+
paper = cv2.GaussianBlur(rng.normal(0, 1, (height, width)).astype(np.float32), (0, 0), 0.8)
|
|
23
|
+
self.paper = 1.0 - 0.035 * (paper - paper.min()) / (paper.max() - paper.min())
|
|
24
|
+
# (texture, tone threshold): darker regions get more hatch layers
|
|
25
|
+
# hatch jitter seeds are fixed (1-3) to reproduce the original look
|
|
26
|
+
self.hatches = [(self._hatch(45, 6, 1), 0.55),
|
|
27
|
+
(self._hatch(-45, 6, 2), 0.35),
|
|
28
|
+
(self._hatch(0, 5, 3), 0.18)]
|
|
29
|
+
# how dark each hatch layer makes the paper where it is fully on
|
|
30
|
+
self.hatch_dark = [(((1.0 - tex) * 0.75).astype(np.float32), thr) for tex, thr in self.hatches]
|
|
31
|
+
# pencil (colour-dodge of gray with its blurred inverse, then a gamma) depends only
|
|
32
|
+
# on two uint8 values, so precompute it as a 256x256 table indexed gray*256 + blur
|
|
33
|
+
g = np.arange(256, dtype=np.float32)[:, None] / 255.0
|
|
34
|
+
b = np.arange(256, dtype=np.float32)[None, :] / 255.0
|
|
35
|
+
self.pencil_lut = (np.clip(g / np.maximum(1.0 - b, 1e-3), 0, 1) ** 1.6).astype(np.float32).ravel()
|
|
36
|
+
self._local = threading.local() # a CLAHE object keeps scratch buffers: one per thread
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def clahe(self):
|
|
40
|
+
c = getattr(self._local, "clahe", None)
|
|
41
|
+
if c is None:
|
|
42
|
+
c = self._local.clahe = cv2.createCLAHE(2.0, (8, 8))
|
|
43
|
+
return c
|
|
44
|
+
|
|
45
|
+
def _hatch(self, angle, spacing, seed):
|
|
46
|
+
r = np.random.default_rng(seed)
|
|
47
|
+
W, H = self.w, self.h
|
|
48
|
+
img = np.ones((H * 2, W * 2), np.float32)
|
|
49
|
+
for y in range(0, H * 2, spacing):
|
|
50
|
+
off = int(r.integers(-1, 2))
|
|
51
|
+
cv2.line(img, (0, y + off), (W * 2, y + off + int(r.integers(-3, 4))), 0.0, 1, cv2.LINE_AA)
|
|
52
|
+
M = cv2.getRotationMatrix2D((W, H), angle, 1.0)
|
|
53
|
+
img = cv2.warpAffine(img, M, (W * 2, H * 2), borderValue=1.0)
|
|
54
|
+
return img[H // 2:H // 2 + H, W // 2:W // 2 + W]
|
|
55
|
+
|
|
56
|
+
def __call__(self, bgr, t=0.0):
|
|
57
|
+
# Every factor below is in [0, 1], multiplied together in place into `out`;
|
|
58
|
+
# in-place float32 math keeps this fast (numpy temporaries dominated the time).
|
|
59
|
+
gray = self.clahe.apply(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY))
|
|
60
|
+
# pencil: table lookup on (gray, blurred inverse of gray)
|
|
61
|
+
idx = gray.astype(np.int32)
|
|
62
|
+
idx <<= 8
|
|
63
|
+
idx += cv2.GaussianBlur(255 - gray, (0, 0), 6)
|
|
64
|
+
out = self.pencil_lut.take(idx)
|
|
65
|
+
# ink outlines: 1 - 0.85 * soft edges
|
|
66
|
+
edges = cv2.Canny(cv2.bilateralFilter(gray, 7, 50, 7), 40, 110)
|
|
67
|
+
edges = cv2.dilate(edges, np.ones((2, 2), np.uint8))
|
|
68
|
+
ink = cv2.GaussianBlur(edges.astype(np.float32), (0, 0), 0.7)
|
|
69
|
+
ink *= np.float32(-0.85 / 255.0)
|
|
70
|
+
ink += 1.0
|
|
71
|
+
out *= ink
|
|
72
|
+
# cross-hatching in the shadows: each layer fades in below its tone threshold
|
|
73
|
+
tone = cv2.GaussianBlur(gray.astype(np.float32) * np.float32(1 / 255.0), (0, 0), 3)
|
|
74
|
+
dark = np.zeros_like(tone)
|
|
75
|
+
layer = np.empty_like(tone)
|
|
76
|
+
for weight, thr in self.hatch_dark:
|
|
77
|
+
np.multiply(tone, np.float32(-1 / 0.12), out=layer) # (thr - tone) / 0.12
|
|
78
|
+
layer += np.float32(thr / 0.12)
|
|
79
|
+
np.clip(layer, 0, 1, out=layer)
|
|
80
|
+
layer *= weight
|
|
81
|
+
np.maximum(dark, layer, out=dark)
|
|
82
|
+
np.subtract(1.0, dark, out=dark)
|
|
83
|
+
out *= dark
|
|
84
|
+
out *= self.paper
|
|
85
|
+
# slight hand wobble that drifts slowly over time
|
|
86
|
+
k = math.sin(t * 0.7) * 0.6
|
|
87
|
+
M = np.float32([[1, 0.004 * k, 0], [0.003 * k, 1, 0]])
|
|
88
|
+
out = cv2.warpAffine(out, M, (self.w, self.h), borderMode=cv2.BORDER_REFLECT)
|
|
89
|
+
# warm paper tint (BGR): scale each channel straight to uint8
|
|
90
|
+
return cv2.merge([(out * np.float32(255 * a) + np.float32(255 * b)).astype(np.uint8)
|
|
91
|
+
for a, b in ((0.93, 0.04), (0.96, 0.025), (1.0, 0.0))])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def contact_sheet(thumbs, title, cols=6, scale=1 / 3):
|
|
95
|
+
"""Grid of (timestamp_seconds, bgr_image) pairs with a title and time labels."""
|
|
96
|
+
if not thumbs:
|
|
97
|
+
raise ValueError("no frames for the contact sheet")
|
|
98
|
+
h, w = thumbs[0][1].shape[:2]
|
|
99
|
+
tw, th = int(w * scale), int(h * scale)
|
|
100
|
+
pad, lab, head = 14, 22, 50
|
|
101
|
+
rows = math.ceil(len(thumbs) / cols)
|
|
102
|
+
sheet = np.full((head + pad + rows * (th + lab + pad), pad + cols * (tw + pad), 3),
|
|
103
|
+
(235, 242, 246), np.uint8)
|
|
104
|
+
# Hershey fonts are ASCII-only
|
|
105
|
+
title = title.encode("ascii", "replace").decode()
|
|
106
|
+
cv2.putText(sheet, title, (pad, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (40, 40, 40), 2, cv2.LINE_AA)
|
|
107
|
+
for k, (t, img) in enumerate(thumbs):
|
|
108
|
+
r, c = divmod(k, cols)
|
|
109
|
+
x = pad + c * (tw + pad)
|
|
110
|
+
y = head + pad + r * (th + lab + pad)
|
|
111
|
+
sheet[y:y + th, x:x + tw] = cv2.resize(img, (tw, th), interpolation=cv2.INTER_AREA)
|
|
112
|
+
cv2.rectangle(sheet, (x - 1, y - 1), (x + tw, y + th), (60, 60, 60), 1)
|
|
113
|
+
cv2.putText(sheet, f"#{k + 1} {fmt_time(t)}", (x, y + th + 16),
|
|
114
|
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (50, 50, 50), 1, cv2.LINE_AA)
|
|
115
|
+
return sheet
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def fmt_time(t):
|
|
119
|
+
return f"{int(t // 60)}:{t % 60:05.2f}"
|