cubecut 0.2.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.
- cubecut-0.2.0/LICENSE +21 -0
- cubecut-0.2.0/PKG-INFO +176 -0
- cubecut-0.2.0/README.md +152 -0
- cubecut-0.2.0/cubecut/__init__.py +85 -0
- cubecut-0.2.0/cubecut/_util.py +66 -0
- cubecut-0.2.0/cubecut/analyze/__init__.py +38 -0
- cubecut-0.2.0/cubecut/analyze/_sheets.py +115 -0
- cubecut-0.2.0/cubecut/analyze/_survey.py +317 -0
- cubecut-0.2.0/cubecut/analyze/boxes.py +241 -0
- cubecut-0.2.0/cubecut/analyze/cuts.py +210 -0
- cubecut-0.2.0/cubecut/analyze/events.py +1207 -0
- cubecut-0.2.0/cubecut/analyze/motion.py +300 -0
- cubecut-0.2.0/cubecut/analyze/moves.py +399 -0
- cubecut-0.2.0/cubecut/analyze/style.py +361 -0
- cubecut-0.2.0/cubecut/analyze/subtitles.py +460 -0
- cubecut-0.2.0/cubecut/analyze/voice.py +100 -0
- cubecut-0.2.0/cubecut/anim.py +134 -0
- cubecut-0.2.0/cubecut/audio.py +162 -0
- cubecut-0.2.0/cubecut/clean.py +289 -0
- cubecut-0.2.0/cubecut/cli.py +275 -0
- cubecut-0.2.0/cubecut/compose.py +147 -0
- cubecut-0.2.0/cubecut/draw.py +398 -0
- cubecut-0.2.0/cubecut/effects/__init__.py +37 -0
- cubecut-0.2.0/cubecut/effects/_base.py +276 -0
- cubecut-0.2.0/cubecut/effects/_draw.py +262 -0
- cubecut-0.2.0/cubecut/effects/finish.py +160 -0
- cubecut-0.2.0/cubecut/effects/library.py +87 -0
- cubecut-0.2.0/cubecut/effects/light.py +318 -0
- cubecut-0.2.0/cubecut/effects/marks.py +68 -0
- cubecut-0.2.0/cubecut/effects/movement.py +205 -0
- cubecut-0.2.0/cubecut/effects/parts.py +303 -0
- cubecut-0.2.0/cubecut/effects/preview.py +175 -0
- cubecut-0.2.0/cubecut/effects/transitions.py +86 -0
- cubecut-0.2.0/cubecut/io.py +412 -0
- cubecut-0.2.0/cubecut/layers.py +890 -0
- cubecut-0.2.0/cubecut/measure.py +672 -0
- cubecut-0.2.0/cubecut/project.py +93 -0
- cubecut-0.2.0/cubecut/render.py +210 -0
- cubecut-0.2.0/cubecut/skill/SKILL.md +170 -0
- cubecut-0.2.0/cubecut/skill/references/cut.md +188 -0
- cubecut-0.2.0/cubecut/skill/references/effects.md +128 -0
- cubecut-0.2.0/cubecut/skill/references/measure.md +96 -0
- cubecut-0.2.0/cubecut/skill/references/storyboard.md +147 -0
- cubecut-0.2.0/cubecut/skill/references/teardown-commands.md +240 -0
- cubecut-0.2.0/cubecut/skill/references/teardown.md +151 -0
- cubecut-0.2.0/cubecut/skill/references/tools.md +74 -0
- cubecut-0.2.0/cubecut/storyboard.py +1757 -0
- cubecut-0.2.0/cubecut/teardown.py +482 -0
- cubecut-0.2.0/cubecut/timeline.py +626 -0
- cubecut-0.2.0/examples/minimal/timeline.py +19 -0
- cubecut-0.2.0/pyproject.toml +51 -0
- cubecut-0.2.0/tests/test_clean.py +289 -0
- cubecut-0.2.0/tests/test_core.py +559 -0
- cubecut-0.2.0/tests/test_effects.py +784 -0
- cubecut-0.2.0/tests/test_measure.py +244 -0
- cubecut-0.2.0/tests/test_teardown.py +1163 -0
- cubecut-0.2.0/uv.lock +427 -0
cubecut-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 psh
|
|
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.
|
cubecut-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cubecut
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Cut videos with code: a draft of tracks and shots renders to MP4, and an existing video tears down into one
|
|
5
|
+
Author: psh
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: compositing,editing,ffmpeg,timeline,video
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Natural Language :: Chinese (Simplified)
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Multimedia :: Video
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Requires-Dist: numpy>=2.0
|
|
20
|
+
Requires-Dist: opencv-python-headless>=4.10
|
|
21
|
+
Requires-Dist: pillow>=10.0
|
|
22
|
+
Requires-Dist: skia-python>=138.0
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# cubecut
|
|
26
|
+
|
|
27
|
+
用代码剪视频的轻量框架。一半是**拆**:把一条参考片拆成一张分镜表;一半是**剪**:一份草稿(`timeline.py`)按镜头叠层、加特效和转场、配字幕和声音,出成片。
|
|
28
|
+
|
|
29
|
+
cubecut 是给模型用的:代码抽帧、拼图、量数字、找候选,模型看图判断,把判断写进分镜表。
|
|
30
|
+
|
|
31
|
+
cubecut 不依赖 Cube,可以单独使用。Cube 的 Worker 运行环境里预装了它,Agent 写的脚本直接 `import cubecut`。
|
|
32
|
+
|
|
33
|
+
## 安装
|
|
34
|
+
|
|
35
|
+
需要 Python 3.11+,以及系统里的 `ffmpeg`、`ffprobe`(读写音视频都经过它们)。
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install cubecut
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
装进跑草稿的那个 Python:`cubecut` 命令和 `import cubecut` 都从这里来。`pipx`、`uv tool install` 只装出命令,`python3 timeline.py` 里 import 不到它。
|
|
42
|
+
|
|
43
|
+
依赖:numpy、OpenCV(headless)、Pillow、skia-python(文字和矢量)。Linux 上 skia-python 还要 `libegl1`、`libgl1`。
|
|
44
|
+
|
|
45
|
+
## 给 Agent 用:Skill
|
|
46
|
+
|
|
47
|
+
cubecut 带着一份 Skill(`SKILL.md` 加 `references/`),写的是怎么用 cubecut 拆片和剪片,不依赖 Cube。装好 cubecut 以后拷到 Agent 的 skills 目录:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
cubecut skill ~/.claude/skills # Claude Code
|
|
51
|
+
cubecut skill ~/.codex/skills # Codex
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
拷出来的是 `<目录>/cubecut/`,和装着的 cubecut 同一个版本;升级 cubecut 后再跑一次,换成新的。Skill 开头会让 Agent 先核对 `cubecut --version`;版本不够时它只提示升级,不会自己安装。
|
|
55
|
+
|
|
56
|
+
## 新建项目
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
cubecut new 我的项目 --size 720x1280 --fps 30 --ref 参考片.mp4
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
建出 `timeline.py`(空草稿)、`lib/`、`assets/`、`teardown/`、`out/`;给了 `--ref` 就把 `ref.mp4` 链接到参考片。其余命令都在项目根目录下跑。
|
|
63
|
+
|
|
64
|
+
## 一份草稿
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from cubecut import Timeline, background, video, image, text, keys, effects
|
|
68
|
+
|
|
69
|
+
tl = Timeline(size=(720, 1280), fps=30, loudness=-14)
|
|
70
|
+
|
|
71
|
+
tl.shot("S01", duration=3.0, layers=[
|
|
72
|
+
background("poster.png", box=keys({0: [0, 0, 720, 1280], 3: [-54, -96, 828, 1472]})),
|
|
73
|
+
text("每日签到送 888 金币", style="标题", at="top", enter=effects.pop(0.4)),
|
|
74
|
+
])
|
|
75
|
+
tl.shot("S02", duration=2.5, enter=effects.white_flash(0.2), layers=[
|
|
76
|
+
video("recording.mp4", trim=(1.0, 3.5)),
|
|
77
|
+
effects.zoom_blur(0.4, strength=0.6),
|
|
78
|
+
])
|
|
79
|
+
tl.subtitles("subtitles.json", style="黄字黑边")
|
|
80
|
+
tl.audio("music.mp3", duck=0.4, track="配乐")
|
|
81
|
+
tl.audio("voice.mp3", track="配音")
|
|
82
|
+
tl.adjust(grade="warm", bloom=0.3)
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
tl.check()
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
python3 timeline.py # 打印文字版的轨道视图和问题,写 out/timeline.json
|
|
90
|
+
cubecut render --draft # 半尺寸、15 帧的 out/draft.mp4
|
|
91
|
+
cubecut render --at 1.5,4.2 # 只算这几个时刻:out/check/sheet.jpg
|
|
92
|
+
cubecut render # out/video.mp4
|
|
93
|
+
cubecut render --shots S02,S03 # 只渲这几个镜头:out/shots/S02.mp4…
|
|
94
|
+
cubecut render --compare # 和分镜表的关键帧并排比:out/compare/<秒>.jpg
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## 概念
|
|
98
|
+
|
|
99
|
+
| 概念 | 代码 | 说明 |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| 草稿 | `Timeline` | 画布、帧率、出片设置,加上轨、段、标记 |
|
|
102
|
+
| 轨 | 主轨、字幕轨、覆盖轨、音频轨、调节轨 | 主轨先画,再是调节、覆盖、字幕 |
|
|
103
|
+
| 镜头 | `tl.shot` | 主轨上的片段,自动首尾相接,里面叠着层 |
|
|
104
|
+
| 层 | `background` `video` `image` `text` `typing` `number_roll`、特效 | 位置(`box=` 或 `at=` 加 `scale=`)、旋转、透明度、混合模式、进出场、只作用在这一层的特效(`fx=`);生成的素材是透明底的图,直接叠 |
|
|
105
|
+
| 片段 | `tl.subtitles` `tl.overlay` `tl.audio` `tl.adjust` | 其他轨上带起止时间的一段 |
|
|
106
|
+
| 动画 | `keys({时刻: 值}, ease=)` | 任何数值属性随时间变;运镜 `camera=` 是它的简写 |
|
|
107
|
+
| 转场 | 镜头的 `enter` / `exit` | `white_flash` `crossfade` `whip` `zoom_blur` |
|
|
108
|
+
| 特效 | `cubecut.effects`、`@effects.custom`、`@effects.motion` | 每帧画一次的函数,调用后是一层;`motion` 是层的进出场 |
|
|
109
|
+
| 开关 | 镜头和层的 `when=` | `False` 时去掉它,主轨自动接上 |
|
|
110
|
+
| 段、标记 | `tl.section` `tl.marker` | 把镜头归成钩子段、卖点段;时间点上的记号 |
|
|
111
|
+
|
|
112
|
+
## 拆
|
|
113
|
+
|
|
114
|
+
拆解产出一张分镜表:`teardown/` 下的四个文件。模型拿主意:判断写进表里,量什么也由它定;`cubecut measure` 照它的要求量,给数和画在原片上的对照图;模型看图认可的结果用 `--json` 原样存进 `teardown/measured/`,表里写引用。`cubecut build` 只检查和截图,不测量。
|
|
115
|
+
|
|
116
|
+
| 文件 | 内容 | 谁写 |
|
|
117
|
+
| --- | --- | --- |
|
|
118
|
+
| `materials.json` | 素材表 | 模型 |
|
|
119
|
+
| `shots.json` | 镜头:关键帧、图层、特效、转场 | 模型 |
|
|
120
|
+
| `script.json` | 片名、全片设置、字幕带、段落、台词 | 模型(`glance` 写好字幕带,`cubecut lines` 起台词) |
|
|
121
|
+
| `measured/*.json` | 模型认可的测量结果,表里用 `"measured": "measured/S03.json#飞入"` 引用 | 模型用 `cubecut measure … --json >` 原样存 |
|
|
122
|
+
| `derived.json` | 截图、关键帧合图、连续帧、清理标签、台词归哪个镜头 | `cubecut build`,每次整份重新生成 |
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
cubecut glance # 规格、响度、闪白闪黑、字幕带、总览图;抽音轨;头一次建空表
|
|
126
|
+
cubecut cuts # 切点候选和裁决图 → 模型把镜头写进 shots.json
|
|
127
|
+
cubecut look 2.4-3.0 # 逐帧看;--box 只看一块,--at 2.5,11.8 并排比,--full 原尺寸,--grid 坐标网格,--draw 画框
|
|
128
|
+
cubecut events S01 # 这段里发生了什么、在哪;小的变化加 --box 只看那一块
|
|
129
|
+
cubecut keyframes S01 # 停稳的时刻和理由;--box 是一块东西停稳、没被挡住的时刻
|
|
130
|
+
cubecut lines # 台词还空着时起到 script.json
|
|
131
|
+
cubecut measure ask.json # 照要求量:跟踪、运镜、明暗、变了的那块、格子、每格几时开始、字样式、换色、周期、转场
|
|
132
|
+
cubecut measure ask.json --json > teardown/measured/S03.json # 看图对了,原样存下来
|
|
133
|
+
cubecut build # 检查分镜表和引用、截图、出页面:只写 derived.json 和图
|
|
134
|
+
cubecut show S03 # 读表:一个镜头、一份素材(M6)或总览,带引用的数和对照图
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
时间段写 `起-止` 秒(止不含)或镜头号 `S01`;框是 `x,y,w,h`(原片像素)或素材号 `M6`。看、找、量的命令只读,每个打印几行字,图存在 `teardown/look/`、`teardown/measure/`。Python 里是同名的方法:`ref = cubecut.open("ref.mp4")`,`ref.events("6.1-7.3", box="M6")`、`ref.measure([...])`,返回的结果有 `.data` 和 `.show()`。
|
|
138
|
+
|
|
139
|
+
量到的数按剪辑那边的写法给(层的 `box=keys(…)`、`effects.tone`、`effects.bob`、`tl.subtitles(style=…)`),不用换算;每种量法没把握就说没量出来,不给数。模型看对照图不认可的不引用,自己看图定的写进 `does`。
|
|
140
|
+
|
|
141
|
+
字段和判断规则见 Skill 的 `references/teardown.md`(流程、怎么分素材、什么算录屏和实拍)、`teardown-commands.md`(每个命令、怎么切镜头)、`measure.md`(量法)、`storyboard.md`(四个文件的每个字段)。
|
|
142
|
+
|
|
143
|
+
模块:`cubecut.analyze`(量:切点候选、字幕带、事件、跟踪、停稳帧、找格子、切网格、运镜、定格、周期、转场、字的样式、明暗)、`cubecut.measure`(照要求量)、`cubecut.storyboard`(分镜表)、`cubecut.teardown`(命令和 `cubecut.open`)。
|
|
144
|
+
|
|
145
|
+
## 对着原片剪
|
|
146
|
+
|
|
147
|
+
- 层的 `box=[x, y, w, h]` 按屏幕上的框摆,`fx=[…]` 是只作用在这一层的特效;表里量到的数原样填。
|
|
148
|
+
- `cubecut render --compare`:草稿的帧和表里的关键帧并排,按素材的框分项列差多少,不给总分。
|
|
149
|
+
- `effects.preview(特效, 参数)`:单独渲一个特效,出连续帧图和 gif。
|
|
150
|
+
- `cubecut.clean`:素材截图的清理,`untext`(去字幕)、`fill`(补洞)、`key`(抠纯色底)、`unhighlight`(去高亮框)、`unback`(给一张干净的底,减掉画面底)。没有干净的底时的去背景、补全要用模型,cubecut 不做。
|
|
151
|
+
|
|
152
|
+
## 特效库
|
|
153
|
+
|
|
154
|
+
通用的手法在 `cubecut.effects` 里。带某种样子的特效跨项目留着用,放在特效库里:一个装特效文件夹的目录,路径由环境变量 `CUBECUT_EFFECTS` 给,一条特效一个文件夹(`effect.py`、`presets.json`、`README.md`、`preview.jpg`、`preview.gif`),`effects.index()` 生成 `INDEX.md`。用的时候把文件夹拷进项目的 `lib/<名字>/`。格式和入库标准见 Skill 的 `references/effects.md`。
|
|
155
|
+
|
|
156
|
+
## 文档
|
|
157
|
+
|
|
158
|
+
函数的说明就是它的 docstring:`python3 -m pydoc cubecut.analyze.events`。
|
|
159
|
+
|
|
160
|
+
## 开发
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
cd apps/cubecut
|
|
164
|
+
uv sync
|
|
165
|
+
uv run pytest -q
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
发布到 PyPI:版本号只写在 `cubecut/__init__.py` 的 `__version__`。构建工具用和 Cube SDK 同一份固定版本:
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
uv build --build-constraints ../../deploy/flow/sdk/build-constraints.txt --out-dir dist
|
|
172
|
+
uvx --from twine==6.2.0 twine check dist/*
|
|
173
|
+
uv publish dist/*
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
许可证:MIT。
|
cubecut-0.2.0/README.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# cubecut
|
|
2
|
+
|
|
3
|
+
用代码剪视频的轻量框架。一半是**拆**:把一条参考片拆成一张分镜表;一半是**剪**:一份草稿(`timeline.py`)按镜头叠层、加特效和转场、配字幕和声音,出成片。
|
|
4
|
+
|
|
5
|
+
cubecut 是给模型用的:代码抽帧、拼图、量数字、找候选,模型看图判断,把判断写进分镜表。
|
|
6
|
+
|
|
7
|
+
cubecut 不依赖 Cube,可以单独使用。Cube 的 Worker 运行环境里预装了它,Agent 写的脚本直接 `import cubecut`。
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
需要 Python 3.11+,以及系统里的 `ffmpeg`、`ffprobe`(读写音视频都经过它们)。
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install cubecut
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
装进跑草稿的那个 Python:`cubecut` 命令和 `import cubecut` 都从这里来。`pipx`、`uv tool install` 只装出命令,`python3 timeline.py` 里 import 不到它。
|
|
18
|
+
|
|
19
|
+
依赖:numpy、OpenCV(headless)、Pillow、skia-python(文字和矢量)。Linux 上 skia-python 还要 `libegl1`、`libgl1`。
|
|
20
|
+
|
|
21
|
+
## 给 Agent 用:Skill
|
|
22
|
+
|
|
23
|
+
cubecut 带着一份 Skill(`SKILL.md` 加 `references/`),写的是怎么用 cubecut 拆片和剪片,不依赖 Cube。装好 cubecut 以后拷到 Agent 的 skills 目录:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
cubecut skill ~/.claude/skills # Claude Code
|
|
27
|
+
cubecut skill ~/.codex/skills # Codex
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
拷出来的是 `<目录>/cubecut/`,和装着的 cubecut 同一个版本;升级 cubecut 后再跑一次,换成新的。Skill 开头会让 Agent 先核对 `cubecut --version`;版本不够时它只提示升级,不会自己安装。
|
|
31
|
+
|
|
32
|
+
## 新建项目
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
cubecut new 我的项目 --size 720x1280 --fps 30 --ref 参考片.mp4
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
建出 `timeline.py`(空草稿)、`lib/`、`assets/`、`teardown/`、`out/`;给了 `--ref` 就把 `ref.mp4` 链接到参考片。其余命令都在项目根目录下跑。
|
|
39
|
+
|
|
40
|
+
## 一份草稿
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from cubecut import Timeline, background, video, image, text, keys, effects
|
|
44
|
+
|
|
45
|
+
tl = Timeline(size=(720, 1280), fps=30, loudness=-14)
|
|
46
|
+
|
|
47
|
+
tl.shot("S01", duration=3.0, layers=[
|
|
48
|
+
background("poster.png", box=keys({0: [0, 0, 720, 1280], 3: [-54, -96, 828, 1472]})),
|
|
49
|
+
text("每日签到送 888 金币", style="标题", at="top", enter=effects.pop(0.4)),
|
|
50
|
+
])
|
|
51
|
+
tl.shot("S02", duration=2.5, enter=effects.white_flash(0.2), layers=[
|
|
52
|
+
video("recording.mp4", trim=(1.0, 3.5)),
|
|
53
|
+
effects.zoom_blur(0.4, strength=0.6),
|
|
54
|
+
])
|
|
55
|
+
tl.subtitles("subtitles.json", style="黄字黑边")
|
|
56
|
+
tl.audio("music.mp3", duck=0.4, track="配乐")
|
|
57
|
+
tl.audio("voice.mp3", track="配音")
|
|
58
|
+
tl.adjust(grade="warm", bloom=0.3)
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
tl.check()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
python3 timeline.py # 打印文字版的轨道视图和问题,写 out/timeline.json
|
|
66
|
+
cubecut render --draft # 半尺寸、15 帧的 out/draft.mp4
|
|
67
|
+
cubecut render --at 1.5,4.2 # 只算这几个时刻:out/check/sheet.jpg
|
|
68
|
+
cubecut render # out/video.mp4
|
|
69
|
+
cubecut render --shots S02,S03 # 只渲这几个镜头:out/shots/S02.mp4…
|
|
70
|
+
cubecut render --compare # 和分镜表的关键帧并排比:out/compare/<秒>.jpg
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 概念
|
|
74
|
+
|
|
75
|
+
| 概念 | 代码 | 说明 |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| 草稿 | `Timeline` | 画布、帧率、出片设置,加上轨、段、标记 |
|
|
78
|
+
| 轨 | 主轨、字幕轨、覆盖轨、音频轨、调节轨 | 主轨先画,再是调节、覆盖、字幕 |
|
|
79
|
+
| 镜头 | `tl.shot` | 主轨上的片段,自动首尾相接,里面叠着层 |
|
|
80
|
+
| 层 | `background` `video` `image` `text` `typing` `number_roll`、特效 | 位置(`box=` 或 `at=` 加 `scale=`)、旋转、透明度、混合模式、进出场、只作用在这一层的特效(`fx=`);生成的素材是透明底的图,直接叠 |
|
|
81
|
+
| 片段 | `tl.subtitles` `tl.overlay` `tl.audio` `tl.adjust` | 其他轨上带起止时间的一段 |
|
|
82
|
+
| 动画 | `keys({时刻: 值}, ease=)` | 任何数值属性随时间变;运镜 `camera=` 是它的简写 |
|
|
83
|
+
| 转场 | 镜头的 `enter` / `exit` | `white_flash` `crossfade` `whip` `zoom_blur` |
|
|
84
|
+
| 特效 | `cubecut.effects`、`@effects.custom`、`@effects.motion` | 每帧画一次的函数,调用后是一层;`motion` 是层的进出场 |
|
|
85
|
+
| 开关 | 镜头和层的 `when=` | `False` 时去掉它,主轨自动接上 |
|
|
86
|
+
| 段、标记 | `tl.section` `tl.marker` | 把镜头归成钩子段、卖点段;时间点上的记号 |
|
|
87
|
+
|
|
88
|
+
## 拆
|
|
89
|
+
|
|
90
|
+
拆解产出一张分镜表:`teardown/` 下的四个文件。模型拿主意:判断写进表里,量什么也由它定;`cubecut measure` 照它的要求量,给数和画在原片上的对照图;模型看图认可的结果用 `--json` 原样存进 `teardown/measured/`,表里写引用。`cubecut build` 只检查和截图,不测量。
|
|
91
|
+
|
|
92
|
+
| 文件 | 内容 | 谁写 |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| `materials.json` | 素材表 | 模型 |
|
|
95
|
+
| `shots.json` | 镜头:关键帧、图层、特效、转场 | 模型 |
|
|
96
|
+
| `script.json` | 片名、全片设置、字幕带、段落、台词 | 模型(`glance` 写好字幕带,`cubecut lines` 起台词) |
|
|
97
|
+
| `measured/*.json` | 模型认可的测量结果,表里用 `"measured": "measured/S03.json#飞入"` 引用 | 模型用 `cubecut measure … --json >` 原样存 |
|
|
98
|
+
| `derived.json` | 截图、关键帧合图、连续帧、清理标签、台词归哪个镜头 | `cubecut build`,每次整份重新生成 |
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
cubecut glance # 规格、响度、闪白闪黑、字幕带、总览图;抽音轨;头一次建空表
|
|
102
|
+
cubecut cuts # 切点候选和裁决图 → 模型把镜头写进 shots.json
|
|
103
|
+
cubecut look 2.4-3.0 # 逐帧看;--box 只看一块,--at 2.5,11.8 并排比,--full 原尺寸,--grid 坐标网格,--draw 画框
|
|
104
|
+
cubecut events S01 # 这段里发生了什么、在哪;小的变化加 --box 只看那一块
|
|
105
|
+
cubecut keyframes S01 # 停稳的时刻和理由;--box 是一块东西停稳、没被挡住的时刻
|
|
106
|
+
cubecut lines # 台词还空着时起到 script.json
|
|
107
|
+
cubecut measure ask.json # 照要求量:跟踪、运镜、明暗、变了的那块、格子、每格几时开始、字样式、换色、周期、转场
|
|
108
|
+
cubecut measure ask.json --json > teardown/measured/S03.json # 看图对了,原样存下来
|
|
109
|
+
cubecut build # 检查分镜表和引用、截图、出页面:只写 derived.json 和图
|
|
110
|
+
cubecut show S03 # 读表:一个镜头、一份素材(M6)或总览,带引用的数和对照图
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
时间段写 `起-止` 秒(止不含)或镜头号 `S01`;框是 `x,y,w,h`(原片像素)或素材号 `M6`。看、找、量的命令只读,每个打印几行字,图存在 `teardown/look/`、`teardown/measure/`。Python 里是同名的方法:`ref = cubecut.open("ref.mp4")`,`ref.events("6.1-7.3", box="M6")`、`ref.measure([...])`,返回的结果有 `.data` 和 `.show()`。
|
|
114
|
+
|
|
115
|
+
量到的数按剪辑那边的写法给(层的 `box=keys(…)`、`effects.tone`、`effects.bob`、`tl.subtitles(style=…)`),不用换算;每种量法没把握就说没量出来,不给数。模型看对照图不认可的不引用,自己看图定的写进 `does`。
|
|
116
|
+
|
|
117
|
+
字段和判断规则见 Skill 的 `references/teardown.md`(流程、怎么分素材、什么算录屏和实拍)、`teardown-commands.md`(每个命令、怎么切镜头)、`measure.md`(量法)、`storyboard.md`(四个文件的每个字段)。
|
|
118
|
+
|
|
119
|
+
模块:`cubecut.analyze`(量:切点候选、字幕带、事件、跟踪、停稳帧、找格子、切网格、运镜、定格、周期、转场、字的样式、明暗)、`cubecut.measure`(照要求量)、`cubecut.storyboard`(分镜表)、`cubecut.teardown`(命令和 `cubecut.open`)。
|
|
120
|
+
|
|
121
|
+
## 对着原片剪
|
|
122
|
+
|
|
123
|
+
- 层的 `box=[x, y, w, h]` 按屏幕上的框摆,`fx=[…]` 是只作用在这一层的特效;表里量到的数原样填。
|
|
124
|
+
- `cubecut render --compare`:草稿的帧和表里的关键帧并排,按素材的框分项列差多少,不给总分。
|
|
125
|
+
- `effects.preview(特效, 参数)`:单独渲一个特效,出连续帧图和 gif。
|
|
126
|
+
- `cubecut.clean`:素材截图的清理,`untext`(去字幕)、`fill`(补洞)、`key`(抠纯色底)、`unhighlight`(去高亮框)、`unback`(给一张干净的底,减掉画面底)。没有干净的底时的去背景、补全要用模型,cubecut 不做。
|
|
127
|
+
|
|
128
|
+
## 特效库
|
|
129
|
+
|
|
130
|
+
通用的手法在 `cubecut.effects` 里。带某种样子的特效跨项目留着用,放在特效库里:一个装特效文件夹的目录,路径由环境变量 `CUBECUT_EFFECTS` 给,一条特效一个文件夹(`effect.py`、`presets.json`、`README.md`、`preview.jpg`、`preview.gif`),`effects.index()` 生成 `INDEX.md`。用的时候把文件夹拷进项目的 `lib/<名字>/`。格式和入库标准见 Skill 的 `references/effects.md`。
|
|
131
|
+
|
|
132
|
+
## 文档
|
|
133
|
+
|
|
134
|
+
函数的说明就是它的 docstring:`python3 -m pydoc cubecut.analyze.events`。
|
|
135
|
+
|
|
136
|
+
## 开发
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
cd apps/cubecut
|
|
140
|
+
uv sync
|
|
141
|
+
uv run pytest -q
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
发布到 PyPI:版本号只写在 `cubecut/__init__.py` 的 `__version__`。构建工具用和 Cube SDK 同一份固定版本:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
uv build --build-constraints ../../deploy/flow/sdk/build-constraints.txt --out-dir dist
|
|
148
|
+
uvx --from twine==6.2.0 twine check dist/*
|
|
149
|
+
uv publish dist/*
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
许可证:MIT。
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""cubecut: cut videos with code.
|
|
2
|
+
|
|
3
|
+
Two halves. Tearing down: the ``cubecut`` commands (``glance``, ``cuts``, ``look``, ``events``,
|
|
4
|
+
``keyframes``) look at a reference video, ``cubecut measure`` measures what the model asks for, and the model
|
|
5
|
+
writes what it judges into a storyboard, four files under ``teardown/`` (``materials.json``,
|
|
6
|
+
``shots.json``, ``script.json``, pointing at the measured results it kept under ``teardown/measured/``;
|
|
7
|
+
``cubecut build`` checks them, crops the pictures into ``derived.json`` and draws the pages; ``cubecut
|
|
8
|
+
show`` reads them back). ``cubecut.open("ref.mp4")`` gives the same commands from Python; ``analyze`` is
|
|
9
|
+
what they measure with. Cutting: a draft (``timeline.py``: a ``Timeline``
|
|
10
|
+
with a main track of shots, plus subtitle, overlay, audio and adjustment tracks) renders to an MP4;
|
|
11
|
+
``clean`` clears a material's crop (subtitles off, holes painted in, a flat colour keyed out, a clean
|
|
12
|
+
background taken off).
|
|
13
|
+
|
|
14
|
+
from cubecut import Timeline, background, video, image, text, keys, effects
|
|
15
|
+
|
|
16
|
+
tl = Timeline(size=(720, 1280), fps=30)
|
|
17
|
+
tl.shot("S01", duration=3, layers=[background("bg.png", box=keys({0: [0, 0, 720, 1280], 3: [-54, -96, 828, 1472]})),
|
|
18
|
+
text("每日签到送 888", style="标题")])
|
|
19
|
+
tl.audio("music.mp3", track="配乐")
|
|
20
|
+
if __name__ == "__main__":
|
|
21
|
+
tl.check() # python3 timeline.py: the track view and any problems
|
|
22
|
+
|
|
23
|
+
Then ``cubecut render`` (``--draft``, ``--at 1.5``, ``--compare``). Look a function up with
|
|
24
|
+
``python3 -m pydoc cubecut.analyze.events``.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import sys
|
|
29
|
+
|
|
30
|
+
__version__ = '0.2.0'
|
|
31
|
+
|
|
32
|
+
from . import draw, effects, io # noqa: E402
|
|
33
|
+
from . import audio # noqa: E402
|
|
34
|
+
from ._util import CubecutError # noqa: E402
|
|
35
|
+
from .anim import keys # noqa: E402
|
|
36
|
+
from .layers import background, image, number_roll, text, typing, video # noqa: E402
|
|
37
|
+
from .timeline import Timeline # noqa: E402
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
'Timeline', 'background', 'video', 'image', 'text', 'typing', 'number_roll', 'keys', 'effects',
|
|
41
|
+
'io', 'draw', 'audio', 'analyze', 'clean', 'open', 'CubecutError', '__version__',
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def open(ref: str = 'ref.mp4'):
|
|
46
|
+
"""A reference video opened for looking and measuring from Python: the teardown commands as methods
|
|
47
|
+
(``ref.look(…)``, ``ref.events(…)``, ``ref.keyframes(…)``, ``ref.measure([…])``, ``ref.glance()``,
|
|
48
|
+
``ref.cuts()``), each returning what the command prints with ``.data`` and
|
|
49
|
+
``.show()``. See ``python3 -m pydoc cubecut.teardown.Ref``."""
|
|
50
|
+
from .teardown import Ref
|
|
51
|
+
|
|
52
|
+
return Ref(ref)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def __getattr__(name: str):
|
|
56
|
+
# The teardown half and material cleaning load on first use, so drafts import quickly.
|
|
57
|
+
if name in ('analyze', 'clean'):
|
|
58
|
+
import importlib
|
|
59
|
+
|
|
60
|
+
module = importlib.import_module(f'.{name}', __name__)
|
|
61
|
+
globals()[name] = module
|
|
62
|
+
return module
|
|
63
|
+
raise AttributeError(f"module 'cubecut' has no attribute {name!r}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _friendly_errors(kind, error, trace):
|
|
67
|
+
"""Run as a script (python3 timeline.py), cubecut's own errors print as one plain message."""
|
|
68
|
+
if isinstance(error, CubecutError):
|
|
69
|
+
print(f'错误:{error}', file=sys.stderr)
|
|
70
|
+
return
|
|
71
|
+
if isinstance(error, ModuleNotFoundError) and error.name == 'lib':
|
|
72
|
+
print("错误:No module named 'lib' → 项目里没有 lib/:建 lib/ 和空的 lib/__init__.py,再把要用的源码拷进去",
|
|
73
|
+
file=sys.stderr)
|
|
74
|
+
return
|
|
75
|
+
if isinstance(error, ModuleNotFoundError) and (error.name or '').startswith('lib.'):
|
|
76
|
+
module = error.name.split('.')[1]
|
|
77
|
+
print(f"错误:No module named '{error.name}' → lib/ 里没有 {module}:自己写的放 lib/{module}.py;"
|
|
78
|
+
f'特效库里的整个文件夹拷进来(cp -R "$CUBECUT_EFFECTS/{module}" lib/{module}),'
|
|
79
|
+
f'再 from lib.{module}.effect import {module}', file=sys.stderr)
|
|
80
|
+
return
|
|
81
|
+
_previous_hook(kind, error, trace)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
_previous_hook = sys.excepthook
|
|
85
|
+
sys.excepthook = _friendly_errors
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Shared helpers: errors that read well in a terminal, colours, ffmpeg calls."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
|
|
8
|
+
IMAGE_SUFFIXES = frozenset({'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tif', '.tiff', '.gif'})
|
|
9
|
+
VIDEO_SUFFIXES = frozenset({'.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi', '.gif'})
|
|
10
|
+
AUDIO_SUFFIXES = frozenset({'.mp3', '.wav', '.m4a', '.aac', '.ogg', '.oga', '.flac', '.opus'})
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CubecutError(ValueError):
|
|
14
|
+
"""A problem the person fixes: the message says what is wrong and what to do. A ValueError, so
|
|
15
|
+
``except ValueError`` around a call that was given something it cannot use catches it too."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def need(tool: str) -> str:
|
|
19
|
+
path = shutil.which(tool)
|
|
20
|
+
if path is None:
|
|
21
|
+
raise CubecutError(f'找不到 {tool}:cubecut 读写音视频要用系统里的 ffmpeg 和 ffprobe,先装上它们。')
|
|
22
|
+
return path
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run(command: Sequence[str], *, input: bytes | None = None) -> subprocess.CompletedProcess[bytes]:
|
|
26
|
+
"""Run ffmpeg or ffprobe; a failure raises with the last lines of its output."""
|
|
27
|
+
need(command[0])
|
|
28
|
+
result = subprocess.run(list(command), input=input, capture_output=True)
|
|
29
|
+
if result.returncode != 0:
|
|
30
|
+
tail = result.stderr.decode('utf-8', 'replace').strip().splitlines()[-6:]
|
|
31
|
+
raise CubecutError(f'{command[0]} 失败:' + ' / '.join(tail))
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_NAMED = {
|
|
36
|
+
'white': '#ffffff', 'black': '#000000', 'red': '#ff0000', 'green': '#00ff00', 'blue': '#0000ff',
|
|
37
|
+
'yellow': '#ffff00', 'gold': '#ffd54a', 'transparent': '#00000000',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def rgba(value) -> tuple[float, float, float, float]:
|
|
42
|
+
"""A colour as RGBA floats in 0–1: '#rgb', '#rrggbb', '#rrggbbaa', a few names, or a 3/4-tuple.
|
|
43
|
+
|
|
44
|
+
Tuples of ints are 0–255; tuples whose values are all floats no greater than 1 are 0–1.
|
|
45
|
+
"""
|
|
46
|
+
if isinstance(value, str):
|
|
47
|
+
text = _NAMED.get(value.strip().lower(), value.strip())
|
|
48
|
+
if not text.startswith('#') or len(text) not in (4, 7, 9):
|
|
49
|
+
raise CubecutError(f'颜色 {value!r} 看不懂:写成 #rrggbb、#rrggbbaa,或 (r, g, b)。')
|
|
50
|
+
digits = text[1:]
|
|
51
|
+
if len(digits) == 3:
|
|
52
|
+
digits = ''.join(ch * 2 for ch in digits)
|
|
53
|
+
try:
|
|
54
|
+
channels = [int(digits[i:i + 2], 16) / 255 for i in range(0, len(digits), 2)]
|
|
55
|
+
except ValueError:
|
|
56
|
+
raise CubecutError(f'颜色 {value!r} 看不懂:写成 #rrggbb、#rrggbbaa,或 (r, g, b)。') from None
|
|
57
|
+
return (*channels, 1.0)[:4] if len(channels) == 3 else tuple(channels) # type: ignore[return-value]
|
|
58
|
+
if isinstance(value, Sequence) and len(value) in (3, 4):
|
|
59
|
+
unit = all(isinstance(v, float) and v <= 1.0 for v in value)
|
|
60
|
+
channels = [float(v) if unit else float(v) / 255 for v in value]
|
|
61
|
+
return tuple(channels) if len(channels) == 4 else (*channels, 1.0) # type: ignore[return-value]
|
|
62
|
+
raise CubecutError(f'颜色 {value!r} 看不懂:写成 #rrggbb、#rrggbbaa,或 (r, g, b)。')
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def seconds(value: float) -> str:
|
|
66
|
+
return f'{value:.2f}'
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Finding what is in a video, where, and how it moves: what the teardown commands measure with.
|
|
2
|
+
|
|
3
|
+
shots(video, voice) cut candidates for a model to judge
|
|
4
|
+
voice(transcript, band) the voice track: a timed transcript lined up with the frames
|
|
5
|
+
subtitle_band(video) where the subtitles sit and when each line starts
|
|
6
|
+
subtitle_mask(frames) which pixels are subtitle text
|
|
7
|
+
events(video, first, last) what happens in a stretch: events, the change of every frame, what keeps moving
|
|
8
|
+
track(video, first, last, box) a block followed frame by frame: place and scale
|
|
9
|
+
keyframes(video, first, last) frames to take a keyframe from: settled, least covered
|
|
10
|
+
find(video, at, like) every copy of a sample (frame, box) on a frame
|
|
11
|
+
grid(video, at, box, r, c) a box cut into cells, each drawn in to what it holds
|
|
12
|
+
onsets(video, first, last, cells) when something starts in each of a set of boxes
|
|
13
|
+
track_keys(video, track) a tracked block's key moments (box, opacity) and the ease between them
|
|
14
|
+
camera_move(video, first, last) the whole picture's own frame before and after a move, and the ease
|
|
15
|
+
freezes(video, first, last) stretches that repeat one frame
|
|
16
|
+
cycle(video, first, last, box) what a part does again and again: period, how far, which way
|
|
17
|
+
transition(video, at, length) a flash between two pictures: its colour, how deep, how long
|
|
18
|
+
text_style(video, at, box) size, fill or gradient, outline of the text in a box, as draw.text takes them
|
|
19
|
+
tone(video, before, after) the gain and offset that turn one frame into another
|
|
20
|
+
camera(video, shot) the camera move, written as a camera file for background(…, camera=…)
|
|
21
|
+
scroll(video, shot) a scrolling page: offsets and the stitched long picture
|
|
22
|
+
|
|
23
|
+
``video`` is an ``io.Video`` or a path; ``shot`` is (first, last) frames.
|
|
24
|
+
"""
|
|
25
|
+
from .boxes import Onset, find, grid, onsets
|
|
26
|
+
from .cuts import Candidate, Candidates, shots
|
|
27
|
+
from .events import Alive, Event, Events, Keyframe, Step, Track, events, keyframes, track
|
|
28
|
+
from .motion import Camera, Scroll, camera, scroll
|
|
29
|
+
from .moves import Freeze, camera_move, cycle, freezes, track_keys, transition
|
|
30
|
+
from .style import Style, Tone, text_style, tone
|
|
31
|
+
from .subtitles import Band, subtitle_band, subtitle_mask
|
|
32
|
+
from .voice import Line, voice
|
|
33
|
+
|
|
34
|
+
__all__ = ['shots', 'voice', 'subtitle_band', 'subtitle_mask', 'events', 'track', 'keyframes', 'find', 'grid',
|
|
35
|
+
'onsets', 'track_keys', 'camera_move', 'freezes', 'cycle', 'transition', 'text_style', 'tone', 'Onset',
|
|
36
|
+
'Freeze', 'Style', 'Tone', 'camera', 'scroll',
|
|
37
|
+
'Band', 'Candidate', 'Candidates', 'Event', 'Events', 'Alive', 'Track', 'Step', 'Keyframe', 'Camera',
|
|
38
|
+
'Scroll', 'Line']
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Contact sheets with a caption above each picture (labels never cover what the model has to read)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .. import draw, io
|
|
11
|
+
|
|
12
|
+
BACKGROUND = 24
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _rgb(picture: np.ndarray) -> np.ndarray:
|
|
16
|
+
if picture.ndim == 2:
|
|
17
|
+
picture = np.repeat(picture[..., None], 3, axis=2)
|
|
18
|
+
if picture.shape[2] == 4:
|
|
19
|
+
alpha = picture[..., 3:4].astype(np.float32) / 255
|
|
20
|
+
picture = (picture[..., :3] * alpha + BACKGROUND * (1 - alpha)).astype(np.uint8)
|
|
21
|
+
return picture
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def paste(canvas: np.ndarray, rgba: np.ndarray, x: int, y: int) -> None:
|
|
25
|
+
"""Paste an RGBA (or RGB) picture onto an RGB canvas at (x, y), clipped to the canvas."""
|
|
26
|
+
h = min(rgba.shape[0], canvas.shape[0] - y)
|
|
27
|
+
w = min(rgba.shape[1], canvas.shape[1] - x)
|
|
28
|
+
if h <= 0 or w <= 0:
|
|
29
|
+
return
|
|
30
|
+
patch = rgba[:h, :w].astype(np.float32)
|
|
31
|
+
if patch.shape[2] == 3:
|
|
32
|
+
canvas[y:y + h, x:x + w] = patch.astype(np.uint8)
|
|
33
|
+
return
|
|
34
|
+
alpha = patch[..., 3:4] / 255
|
|
35
|
+
region = canvas[y:y + h, x:x + w].astype(np.float32)
|
|
36
|
+
canvas[y:y + h, x:x + w] = (patch[..., :3] * alpha + region * (1 - alpha)).astype(np.uint8)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def label(s: str, size: int, color: str = '#ffd54a') -> np.ndarray:
|
|
40
|
+
return draw.text(s, size=size, fill=color, weight='bold', align='left')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def marks(picture: np.ndarray, origin=(0, 0), *, grid: bool = False, boxes=(), base: int = 1, names=None) -> np.ndarray:
|
|
44
|
+
"""A picture (the frame, or the part of it starting at ``origin``) with a coordinate grid in video
|
|
45
|
+
pixels and boxes drawn on it, numbered from ``base`` (or labelled with ``names``, one a box)."""
|
|
46
|
+
if not grid and not boxes:
|
|
47
|
+
return picture
|
|
48
|
+
out = np.ascontiguousarray(picture[..., :3]).copy()
|
|
49
|
+
h, w = out.shape[:2]
|
|
50
|
+
x0, y0 = origin
|
|
51
|
+
thick = max(1, min(w, h) // 360)
|
|
52
|
+
if grid:
|
|
53
|
+
step = next(s for s in (10, 20, 50, 100, 200, 500) if max(w, h) / s <= 14)
|
|
54
|
+
size = max(11, min(w, h) // 36)
|
|
55
|
+
for x in range((x0 // step + 1) * step, x0 + w, step):
|
|
56
|
+
cv2.line(out, (x - x0, 0), (x - x0, h - 1), (90, 220, 255), thick)
|
|
57
|
+
paste(out, label(str(x), size, '#5adcff'), x - x0 + 2, 2)
|
|
58
|
+
for y in range((y0 // step + 1) * step, y0 + h, step):
|
|
59
|
+
cv2.line(out, (0, y - y0), (w - 1, y - y0), (90, 220, 255), thick)
|
|
60
|
+
paste(out, label(str(y), size, '#5adcff'), 2, y - y0 + 2)
|
|
61
|
+
for n, (bx, by, bw, bh) in enumerate(boxes, base):
|
|
62
|
+
cv2.rectangle(out, (bx - x0, by - y0), (bx - x0 + bw - 1, by - y0 + bh - 1), (255, 213, 74), max(2, thick * 2))
|
|
63
|
+
if len(boxes) > 1 or names:
|
|
64
|
+
paste(out, label(names[n - base] if names else str(n), max(13, min(w, h) // 30)), max(bx - x0 + 3, 0),
|
|
65
|
+
max(by - y0 + 3, 0))
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cards(groups: Sequence[tuple[str, Sequence[tuple[np.ndarray, str]]]], path: str | Path, *, cols: int,
|
|
70
|
+
tile_width: int, caption: int = 20, small: int = 15, gap: int = 8) -> str:
|
|
71
|
+
"""Cards in a grid. Each card has a caption and a row of tiles, each tile with a small label under it.
|
|
72
|
+
|
|
73
|
+
``groups``: [(caption, [(picture, tile label), …]), …]; every tile is scaled to ``tile_width``.
|
|
74
|
+
"""
|
|
75
|
+
rows_of_tiles = [[(_rgb(p), t) for p, t in tiles] for _, tiles in groups]
|
|
76
|
+
first = rows_of_tiles[0][0][0]
|
|
77
|
+
tile_h = max(1, int(round(tile_width * first.shape[0] / first.shape[1])))
|
|
78
|
+
per = max(len(r) for r in rows_of_tiles)
|
|
79
|
+
card_w = per * tile_width + (per - 1) * 4
|
|
80
|
+
card_h = caption + 8 + tile_h + small + 8
|
|
81
|
+
rows = (len(groups) + cols - 1) // cols
|
|
82
|
+
width = cols * card_w + (cols + 1) * gap * 2
|
|
83
|
+
canvas = np.full((rows * (card_h + gap) + gap, width, 3), BACKGROUND, np.uint8)
|
|
84
|
+
for k, ((title, _), tiles) in enumerate(zip(groups, rows_of_tiles)):
|
|
85
|
+
r, c = divmod(k, cols)
|
|
86
|
+
x0 = gap * 2 + c * (card_w + gap * 2)
|
|
87
|
+
y0 = gap + r * (card_h + gap)
|
|
88
|
+
paste(canvas, label(title, caption)[:, :card_w], x0, y0) # cut at its own card, never over the next
|
|
89
|
+
for j, (picture, tag) in enumerate(tiles):
|
|
90
|
+
x = x0 + j * (tile_width + 4)
|
|
91
|
+
h = int(round(tile_width * picture.shape[0] / picture.shape[1]))
|
|
92
|
+
tile = cv2.resize(picture, (tile_width, min(h, tile_h)), interpolation=cv2.INTER_AREA)
|
|
93
|
+
canvas[y0 + caption + 6:y0 + caption + 6 + tile.shape[0], x:x + tile_width] = tile
|
|
94
|
+
if tag:
|
|
95
|
+
paste(canvas, label(tag, small, '#ffffff')[:, :tile_width - 2], x + 2, y0 + caption + 6 + tile_h + 1)
|
|
96
|
+
return io.save(canvas, path, quality=85)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def strips(items: Sequence[tuple[np.ndarray, str]], path: str | Path, *, width: int = 1440, cols: int = 2,
|
|
100
|
+
caption: int = 18) -> str:
|
|
101
|
+
"""Wide pictures (subtitle bands) with a caption above each, ``cols`` per row."""
|
|
102
|
+
gap = 8
|
|
103
|
+
tile_w = (width - gap * (cols + 1)) // cols
|
|
104
|
+
pictures = [_rgb(p) for p, _ in items]
|
|
105
|
+
tile_h = max(int(round(tile_w * p.shape[0] / p.shape[1])) for p in pictures)
|
|
106
|
+
cell_h = caption + 6 + tile_h
|
|
107
|
+
rows = (len(items) + cols - 1) // cols
|
|
108
|
+
canvas = np.full((rows * (cell_h + gap) + gap, width, 3), BACKGROUND, np.uint8)
|
|
109
|
+
for k, (picture, (_, title)) in enumerate(zip(pictures, items)):
|
|
110
|
+
r, c = divmod(k, cols)
|
|
111
|
+
x0, y0 = gap + c * (tile_w + gap), gap + r * (cell_h + gap)
|
|
112
|
+
paste(canvas, label(title, caption)[:, :tile_w], x0, y0)
|
|
113
|
+
h = int(round(tile_w * picture.shape[0] / picture.shape[1]))
|
|
114
|
+
canvas[y0 + caption + 6:y0 + caption + 6 + h, x0:x0 + tile_w] = cv2.resize(picture, (tile_w, h), interpolation=cv2.INTER_AREA)
|
|
115
|
+
return io.save(canvas, path, quality=85)
|