cubecut 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cubecut/__init__.py +85 -0
- cubecut/_util.py +66 -0
- cubecut/analyze/__init__.py +38 -0
- cubecut/analyze/_sheets.py +115 -0
- cubecut/analyze/_survey.py +317 -0
- cubecut/analyze/boxes.py +241 -0
- cubecut/analyze/cuts.py +210 -0
- cubecut/analyze/events.py +1207 -0
- cubecut/analyze/motion.py +300 -0
- cubecut/analyze/moves.py +399 -0
- cubecut/analyze/style.py +361 -0
- cubecut/analyze/subtitles.py +460 -0
- cubecut/analyze/voice.py +100 -0
- cubecut/anim.py +134 -0
- cubecut/audio.py +162 -0
- cubecut/clean.py +289 -0
- cubecut/cli.py +275 -0
- cubecut/compose.py +147 -0
- cubecut/draw.py +398 -0
- cubecut/effects/__init__.py +37 -0
- cubecut/effects/_base.py +276 -0
- cubecut/effects/_draw.py +262 -0
- cubecut/effects/finish.py +160 -0
- cubecut/effects/library.py +87 -0
- cubecut/effects/light.py +318 -0
- cubecut/effects/marks.py +68 -0
- cubecut/effects/movement.py +205 -0
- cubecut/effects/parts.py +303 -0
- cubecut/effects/preview.py +175 -0
- cubecut/effects/transitions.py +86 -0
- cubecut/io.py +412 -0
- cubecut/layers.py +890 -0
- cubecut/measure.py +672 -0
- cubecut/project.py +93 -0
- cubecut/render.py +210 -0
- cubecut/skill/SKILL.md +170 -0
- cubecut/skill/references/cut.md +188 -0
- cubecut/skill/references/effects.md +128 -0
- cubecut/skill/references/measure.md +96 -0
- cubecut/skill/references/storyboard.md +147 -0
- cubecut/skill/references/teardown-commands.md +240 -0
- cubecut/skill/references/teardown.md +151 -0
- cubecut/skill/references/tools.md +74 -0
- cubecut/storyboard.py +1757 -0
- cubecut/teardown.py +482 -0
- cubecut/timeline.py +626 -0
- cubecut-0.2.0.dist-info/METADATA +176 -0
- cubecut-0.2.0.dist-info/RECORD +51 -0
- cubecut-0.2.0.dist-info/WHEEL +4 -0
- cubecut-0.2.0.dist-info/entry_points.txt +2 -0
- cubecut-0.2.0.dist-info/licenses/LICENSE +21 -0
cubecut/__init__.py
ADDED
|
@@ -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
|
cubecut/_util.py
ADDED
|
@@ -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)
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""One low-resolution pass over a whole video that the analysis functions share.
|
|
2
|
+
|
|
3
|
+
With the short side at 360 pixels: brightness, colour histograms, ORB features, a grey copy at half
|
|
4
|
+
that size, and a mask of text-like pixels (a pixel next to one much lighter or darker, the way
|
|
5
|
+
letters meet their outline or the picture behind them, whatever their colour). The subtitle bands come
|
|
6
|
+
out of that mask; features inside a band are then left out of registration on the frames it covers. A
|
|
7
|
+
survey is cached per file, so glance and teardown pay for it once (a few seconds for half a minute of
|
|
8
|
+
video).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import threading
|
|
13
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import cv2
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from .. import io
|
|
20
|
+
from .._util import CubecutError
|
|
21
|
+
|
|
22
|
+
SCAN = 360 # short side of the analysis pass
|
|
23
|
+
CHUNK = 120 # frames decoded at a time (each seek decodes 2 s before it)
|
|
24
|
+
CONTRAST = 100 # grey levels between a text pixel and a neighbour: letters against their edge
|
|
25
|
+
WHITE, BLACK = 200, 30 # mean grey a frame of a flash reaches (a flash to white, a dip to black)
|
|
26
|
+
FLASH = 0.67 # seconds: the longest a flash lasts
|
|
27
|
+
STANDOUT = 25 # grey levels a flash stands out from the frames around it
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def scan_width(size, short: int = SCAN) -> int:
|
|
31
|
+
"""The width to scan a video of ``size`` (w, h) at so that its short side is ``short`` pixels."""
|
|
32
|
+
w, h = size
|
|
33
|
+
return max(2, int(round(short * w / min(w, h) / 2)) * 2)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def tile_width(size, short: int) -> int:
|
|
37
|
+
"""The width of a picture of a frame of ``size`` (w, h) whose short side is ``short`` pixels, for sheets."""
|
|
38
|
+
w, h = size
|
|
39
|
+
return max(1, int(round(short * w / min(w, h))))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def frames_for(seconds: float, fps: float) -> int:
|
|
43
|
+
"""``seconds`` in whole frames, at least one."""
|
|
44
|
+
return max(1, int(round(seconds * fps)))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def as_video(video) -> io.Video:
|
|
48
|
+
"""A ``Video`` from a Video or a path."""
|
|
49
|
+
if isinstance(video, io.Video):
|
|
50
|
+
return video
|
|
51
|
+
return io.Video(video)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def span(shot) -> tuple[int, int]:
|
|
55
|
+
"""(first, last) frames, inclusive, of a Shot, a candidate or an (a, b) pair."""
|
|
56
|
+
frames = getattr(shot, 'frames', shot)
|
|
57
|
+
try:
|
|
58
|
+
a, b = (int(x) for x in frames)
|
|
59
|
+
except (TypeError, ValueError):
|
|
60
|
+
raise CubecutError(f'镜头要写成 sh["S06"],或 (起帧, 止帧),不是 {shot!r}。') from None
|
|
61
|
+
if b < a:
|
|
62
|
+
raise CubecutError(f'镜头的止帧 {b} 在起帧 {a} 前面。')
|
|
63
|
+
return a, b
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def dilate(mask: np.ndarray, radius: int = 1) -> np.ndarray:
|
|
67
|
+
"""Grow a boolean mask (..., h, w) by ``radius`` pixels in each direction (a square)."""
|
|
68
|
+
out = mask.copy()
|
|
69
|
+
for _ in range(radius):
|
|
70
|
+
grown = out.copy()
|
|
71
|
+
grown[..., 1:, :] |= out[..., :-1, :]
|
|
72
|
+
grown[..., :-1, :] |= out[..., 1:, :]
|
|
73
|
+
grown[..., :, 1:] |= grown[..., :, :-1]
|
|
74
|
+
grown[..., :, :-1] |= grown[..., :, 1:]
|
|
75
|
+
out = grown
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def text_pixels(rgb: np.ndarray, radius: int = 1) -> np.ndarray:
|
|
80
|
+
"""Text-like pixels, whatever the colour: the lighter side of a sharp step, a pixel within ``radius``
|
|
81
|
+
of one at least ``CONTRAST`` grey levels darker (letters against their outline, or against the picture
|
|
82
|
+
behind them). ``rgb`` uint8 (..., h, w, 3)."""
|
|
83
|
+
flat = rgb.reshape(-1, *rgb.shape[-3:])
|
|
84
|
+
out = np.empty(flat.shape[:3], bool)
|
|
85
|
+
kernel = np.ones((2 * radius + 1, 2 * radius + 1), np.uint8)
|
|
86
|
+
for k, frame in enumerate(flat):
|
|
87
|
+
grey = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
|
|
88
|
+
out[k] = grey.astype(np.int16) - cv2.erode(grey, kernel) >= CONTRAST
|
|
89
|
+
return out.reshape(rgb.shape[:-1])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def flash_runs(bright: np.ndarray, fps: float) -> list[tuple[int, int]]:
|
|
93
|
+
"""Flashes: short runs of frames that go near white (or near black), brighter (darker) than the
|
|
94
|
+
frames around them."""
|
|
95
|
+
n = len(bright)
|
|
96
|
+
gap, longest, near = frames_for(0.1, fps), frames_for(FLASH, fps), frames_for(0.1, fps)
|
|
97
|
+
found = []
|
|
98
|
+
for sign, hot in ((1, bright >= WHITE), (-1, bright <= BLACK)):
|
|
99
|
+
runs: list[list[int]] = []
|
|
100
|
+
for i in np.flatnonzero(hot):
|
|
101
|
+
if runs and i - runs[-1][1] <= gap:
|
|
102
|
+
runs[-1][1] = int(i)
|
|
103
|
+
else:
|
|
104
|
+
runs.append([int(i), int(i)])
|
|
105
|
+
for a, b in runs:
|
|
106
|
+
if b - a + 1 > longest:
|
|
107
|
+
continue
|
|
108
|
+
before = bright[max(a - near - 1, 0):max(a - 1, 0)]
|
|
109
|
+
after = bright[b + 2:b + near + 2]
|
|
110
|
+
around = np.concatenate([before, after]) if len(before) + len(after) else np.array([128.0])
|
|
111
|
+
level = sign * bright[a:b + 1]
|
|
112
|
+
if level.max() - (sign * around).max() >= STANDOUT or a == 0 or b == n - 1:
|
|
113
|
+
found.append((a, b))
|
|
114
|
+
return sorted(found)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def dark_flash(bright: np.ndarray, flash: tuple[int, int]) -> bool:
|
|
118
|
+
"""Whether a flash goes to black rather than to white."""
|
|
119
|
+
return float(bright[flash[0]:flash[1] + 1].mean()) < 128
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Survey:
|
|
123
|
+
"""What one pass over the video measured; see the module docstring."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, video: io.Video):
|
|
126
|
+
self.path = str(video.path)
|
|
127
|
+
self.fps = float(video.fps)
|
|
128
|
+
self.size = video.size
|
|
129
|
+
self.scan_width = scan_width(self.size)
|
|
130
|
+
small_width = self.scan_width // 4 * 2 # half the pass, so masks pool onto it
|
|
131
|
+
n = int(video.frames)
|
|
132
|
+
bright, hists, small, text, features = [], [], [], [], []
|
|
133
|
+
start = 0
|
|
134
|
+
pool = ThreadPoolExecutor(max_workers=4)
|
|
135
|
+
while start < n:
|
|
136
|
+
chunk = video.scan(self.scan_width, start=start, end=min(start + CHUNK, n))
|
|
137
|
+
grays = [cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) for frame in chunk]
|
|
138
|
+
found = pool.map(_orb, grays)
|
|
139
|
+
for k in range(0, len(chunk), 15):
|
|
140
|
+
text.append(np.packbits(text_pixels(chunk[k:k + 15]), axis=-1))
|
|
141
|
+
features.extend(found)
|
|
142
|
+
for frame, gray in zip(chunk, grays):
|
|
143
|
+
bright.append(float(gray.mean()))
|
|
144
|
+
half = cv2.resize(frame, (small_width, frame.shape[0] * small_width // frame.shape[1]), interpolation=cv2.INTER_AREA)
|
|
145
|
+
hsv = cv2.cvtColor(half, cv2.COLOR_RGB2HSV)
|
|
146
|
+
hist = cv2.calcHist([hsv], [0, 1], None, [30, 32], [0, 180, 0, 256])
|
|
147
|
+
hists.append(cv2.normalize(hist, hist).flatten())
|
|
148
|
+
small.append(cv2.cvtColor(half, cv2.COLOR_RGB2GRAY))
|
|
149
|
+
start += len(chunk)
|
|
150
|
+
if len(chunk) == 0:
|
|
151
|
+
break
|
|
152
|
+
pool.shutdown()
|
|
153
|
+
self.frames = len(bright)
|
|
154
|
+
self.bright = np.array(bright, np.float32)
|
|
155
|
+
self.hist = np.stack(hists)
|
|
156
|
+
self.small = np.stack(small)
|
|
157
|
+
self.scan_height = chunk.shape[1] if len(chunk) else int(round(self.size[1] * self.scan_width / self.size[0]))
|
|
158
|
+
self.scale = self.scan_width / self.size[0] # pass pixels per frame pixel
|
|
159
|
+
self._text = np.concatenate(text)
|
|
160
|
+
self._all_features = features
|
|
161
|
+
self._features = features
|
|
162
|
+
self.flashes = flash_runs(self.bright, self.fps)
|
|
163
|
+
self.flash = np.zeros(self.frames, bool)
|
|
164
|
+
for a, b in self.flashes:
|
|
165
|
+
self.flash[a:b + 1] = True
|
|
166
|
+
self.band: tuple[int, int] | None = None
|
|
167
|
+
self.bands: list[tuple[tuple[int, int], tuple[int, int]]] = []
|
|
168
|
+
self.band_info = None
|
|
169
|
+
self.candidates = None
|
|
170
|
+
|
|
171
|
+
def seconds(self, seconds: float) -> int:
|
|
172
|
+
"""``seconds`` in whole frames of this video, at least one."""
|
|
173
|
+
return frames_for(seconds, self.fps)
|
|
174
|
+
|
|
175
|
+
# ── text-like pixels at the pass's size ──
|
|
176
|
+
def text(self, start: int = 0, end: int | None = None, rows: tuple[int, int] | None = None) -> np.ndarray:
|
|
177
|
+
"""Text-like masks (n, h, w) at the pass's size for frames ``start``–``end``, optionally only ``rows`` (y0, y1)."""
|
|
178
|
+
packed = self._text[start:end] if rows is None else self._text[start:end, rows[0]:rows[1]]
|
|
179
|
+
return np.unpackbits(packed, axis=-1)[..., :self.scan_width].astype(bool)
|
|
180
|
+
|
|
181
|
+
def scan_rows(self, area: tuple[int, int]) -> tuple[int, int]:
|
|
182
|
+
"""Frame rows (y0, y1) as rows of the pass."""
|
|
183
|
+
f = self.scale
|
|
184
|
+
return int(area[0] * f), min(self.scan_height, int(np.ceil(area[1] * f)))
|
|
185
|
+
|
|
186
|
+
def small_rows(self, area: tuple[int, int]) -> tuple[int, int]:
|
|
187
|
+
f = self.small.shape[1] / self.size[1]
|
|
188
|
+
return int(area[0] * f), min(self.small.shape[1], int(np.ceil(area[1] * f)))
|
|
189
|
+
|
|
190
|
+
def clear(self, t: int, step: int) -> int:
|
|
191
|
+
"""The nearest frame from ``t`` in direction ``step`` that is not part of a flash."""
|
|
192
|
+
while 0 <= t < self.frames and self.flash[t]:
|
|
193
|
+
t += step
|
|
194
|
+
return min(max(t, 0), self.frames - 1)
|
|
195
|
+
|
|
196
|
+
def dark(self, flash: tuple[int, int]) -> bool:
|
|
197
|
+
"""Whether a flash goes to black rather than to white."""
|
|
198
|
+
return dark_flash(self.bright, flash)
|
|
199
|
+
|
|
200
|
+
def peak(self, flash: tuple[int, int]) -> int:
|
|
201
|
+
"""The frame a flash is furthest out on, brightest (darkest for a dip to black; the middle one when
|
|
202
|
+
several are): where a picture or a subtitle that is different after the flash than before it is
|
|
203
|
+
taken to change."""
|
|
204
|
+
a, b = flash
|
|
205
|
+
levels = -self.bright[a:b + 1] if self.dark(flash) else self.bright[a:b + 1]
|
|
206
|
+
top = np.flatnonzero(levels >= levels.max() - 2)
|
|
207
|
+
return a + int(top[len(top) // 2])
|
|
208
|
+
|
|
209
|
+
def set_bands(self, bands: list[tuple[tuple[int, int], tuple[int, int]]]) -> None:
|
|
210
|
+
"""Leave features inside the subtitle bands out of registration from now on, each band on the
|
|
211
|
+
frames it covers: ``bands`` [((first, last), (y0, y1)), …]; the first is the main one."""
|
|
212
|
+
self.bands = list(bands)
|
|
213
|
+
self.band = self.bands[0][1] if self.bands else None
|
|
214
|
+
kept = []
|
|
215
|
+
for t, (points, descriptors) in enumerate(self._all_features):
|
|
216
|
+
area = self.band_at(t)
|
|
217
|
+
if area is None or descriptors is None or not len(points):
|
|
218
|
+
kept.append((points, descriptors))
|
|
219
|
+
continue
|
|
220
|
+
y0, y1 = self.scan_rows(area)
|
|
221
|
+
keep = (points[:, 1] < y0) | (points[:, 1] >= y1)
|
|
222
|
+
kept.append((points[keep], descriptors[keep]))
|
|
223
|
+
self._features = kept
|
|
224
|
+
|
|
225
|
+
def band_at(self, t: int) -> tuple[int, int] | None:
|
|
226
|
+
"""The subtitle band (y0, y1) on frame ``t``, or None."""
|
|
227
|
+
return next((area for (a, b), area in self.bands if a <= t <= b), None)
|
|
228
|
+
|
|
229
|
+
def small_mask(self, *frames: int) -> np.ndarray:
|
|
230
|
+
"""The grey copy's pixels with the subtitle band of each of ``frames`` left out."""
|
|
231
|
+
h, w = self.small.shape[1:]
|
|
232
|
+
mask = np.ones((h, w), bool)
|
|
233
|
+
for t in frames:
|
|
234
|
+
area = self.band_at(t)
|
|
235
|
+
if area is not None:
|
|
236
|
+
y0, y1 = self.small_rows(area)
|
|
237
|
+
mask[y0:y1] = False
|
|
238
|
+
return mask
|
|
239
|
+
|
|
240
|
+
# ── registration ──
|
|
241
|
+
def register(self, a: int, b: int, rotate: bool = True) -> np.ndarray | None:
|
|
242
|
+
"""The similarity transform (2×3, in the pass's pixels) that lines frame ``a`` up with frame ``b``.
|
|
243
|
+
``rotate=False`` refits the inliers with scale and translation only when the rotation is under 1°."""
|
|
244
|
+
(pa, da), (pb, db) = self._features[a], self._features[b]
|
|
245
|
+
if da is None or db is None or len(pa) < 10 or len(pb) < 10:
|
|
246
|
+
return None
|
|
247
|
+
matches = _matcher().match(da, db)
|
|
248
|
+
if len(matches) < 10:
|
|
249
|
+
return None
|
|
250
|
+
src = pa[[m.queryIdx for m in matches]]
|
|
251
|
+
dst = pb[[m.trainIdx for m in matches]]
|
|
252
|
+
matrix, inliers = cv2.estimateAffinePartial2D(src, dst, method=cv2.RANSAC, ransacReprojThreshold=4)
|
|
253
|
+
if matrix is None or inliers is None or inliers.sum() < 12:
|
|
254
|
+
return None
|
|
255
|
+
if not rotate and abs(np.degrees(np.arctan2(matrix[1, 0], matrix[0, 0]))) < 1.0:
|
|
256
|
+
return zoom_fit(src[inliers.ravel() > 0], dst[inliers.ravel() > 0])
|
|
257
|
+
return matrix
|
|
258
|
+
|
|
259
|
+
def residual(self, a: int, b: int) -> float:
|
|
260
|
+
"""Share of the picture that still differs after the best camera move from frame ``a`` to ``b``
|
|
261
|
+
(subtitle band left out); 1 when no camera move lines them up."""
|
|
262
|
+
matrix = self.register(a, b)
|
|
263
|
+
if matrix is None:
|
|
264
|
+
return 1.0
|
|
265
|
+
m = matrix.copy()
|
|
266
|
+
h, w = self.small.shape[1:]
|
|
267
|
+
m[:, 2] *= w / self.scan_width
|
|
268
|
+
warped = cv2.warpAffine(self.small[a], m, (w, h))
|
|
269
|
+
valid = cv2.warpAffine(np.full((h, w), 255, np.uint8), m, (w, h)) > 0
|
|
270
|
+
valid &= self.small_mask(a, b)
|
|
271
|
+
if valid.mean() < 0.4:
|
|
272
|
+
return 1.0
|
|
273
|
+
diff = cv2.absdiff(warped, self.small[b])
|
|
274
|
+
return float((diff[valid] > 40).mean())
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def zoom_fit(src: np.ndarray, dst: np.ndarray) -> np.ndarray:
|
|
278
|
+
"""Least-squares scale and translation (no rotation) taking points ``src`` to ``dst``."""
|
|
279
|
+
p, q = src.astype(np.float64), dst.astype(np.float64)
|
|
280
|
+
pm, qm = p.mean(axis=0), q.mean(axis=0)
|
|
281
|
+
spread = ((p - pm) ** 2).sum()
|
|
282
|
+
scale = float(((p - pm) * (q - qm)).sum() / spread) if spread > 1e-9 else 1.0
|
|
283
|
+
tx, ty = qm - scale * pm
|
|
284
|
+
return np.array([[scale, 0.0, tx], [0.0, scale, ty]])
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
_MATCHER = None
|
|
288
|
+
_LOCAL = threading.local()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _orb(gray: np.ndarray):
|
|
292
|
+
detector = getattr(_LOCAL, 'orb', None)
|
|
293
|
+
if detector is None:
|
|
294
|
+
detector = _LOCAL.orb = cv2.ORB_create(700, scaleFactor=1.3, nlevels=5)
|
|
295
|
+
points, descriptors = detector.detectAndCompute(gray, None)
|
|
296
|
+
return np.float32([p.pt for p in points]).reshape(-1, 2), descriptors
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _matcher():
|
|
300
|
+
global _MATCHER
|
|
301
|
+
if _MATCHER is None:
|
|
302
|
+
_MATCHER = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
|
303
|
+
return _MATCHER
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
_SURVEYS: dict[tuple, Survey] = {}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def survey(video) -> Survey:
|
|
310
|
+
"""The cached pass for this video file."""
|
|
311
|
+
video = as_video(video)
|
|
312
|
+
path = Path(video.path).resolve()
|
|
313
|
+
key = (str(path), path.stat().st_mtime_ns)
|
|
314
|
+
if key not in _SURVEYS:
|
|
315
|
+
_SURVEYS.clear()
|
|
316
|
+
_SURVEYS[key] = Survey(video)
|
|
317
|
+
return _SURVEYS[key]
|