BEN3 / ben3.py
MaxwellMeyer's picture
Upload 8 files
8fcb663 verified
Raw History Blame Contribute Delete
32.4 kB
from __future__ import annotations
import subprocess
from contextlib import nullcontext
from pathlib import Path
from typing import List, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageOps
from transformers import DINOv3ViTConfig, DINOv3ViTModel
import math
import os
torch.set_float32_matmul_precision("highest")
class BaseDPTSegmentation(nn.Module):
def __init__(self, num_classes=1, num_outputs: int=3, encoder_name: str='facebook/dinov3-vitb16-pretrain-lvd1689m', features: int=256, out_channels: Optional[List[int]]=None, use_bn: bool=True, use_clstoken: bool=False):
super().__init__()
self.patch_size = 16
self.encoder_name = encoder_name
if encoder_name != 'facebook/dinov3-vitb16-pretrain-lvd1689m':
raise ValueError(
'This BEN3 checkpoint is built for facebook/dinov3-vitb16-pretrain-lvd1689m.'
)
encoder_config = DINOv3ViTConfig(
patch_size=16,
hidden_size=768,
intermediate_size=3072,
num_hidden_layers=12,
num_attention_heads=12,
hidden_act='gelu',
attention_dropout=0.0,
initializer_range=0.02,
layer_norm_eps=1e-5,
rope_theta=100.0,
image_size=224,
num_channels=3,
query_bias=True,
key_bias=False,
value_bias=True,
proj_bias=True,
mlp_bias=True,
layerscale_value=1.0,
drop_path_rate=0.0,
use_gated_mlp=False,
num_register_tokens=4,
pos_embed_shift=None,
pos_embed_jitter=None,
pos_embed_rescale=2.0,
)
self.encoder = DINOv3ViTModel(encoder_config)
self.intermediate_layer_idx = {
'facebook/dinov3-vitb16-pretrain-lvd1689m': [2, 5, 8, 11]
}
dim = self.encoder.config.hidden_size
self.n_register_tokens = getattr(self.encoder.config, 'num_register_tokens', 4)
out_channels = out_channels or [256, 512, 1024, 1024]
self.seg_head = self._create_segmentation_head(
nclass=num_classes,
num_outputs=num_outputs,
in_channels=dim,
features=features,
use_bn=use_bn,
out_channels=out_channels,
use_clstoken=use_clstoken,
patch_size=self.patch_size,
)
def _create_segmentation_head(self, **kwargs):
raise NotImplementedError
def extract_intermediate_features(self, x):
layer_indices = self.intermediate_layer_idx.get(self.encoder_name, [2, 5, 8, 11])
outputs = self.encoder(pixel_values=x, output_hidden_states=True, return_dict=True)
hidden_states = outputs.hidden_states
features = []
for layer_idx in layer_indices:
hidden_state = hidden_states[layer_idx]
if self.seg_head.use_clstoken:
cls_token = hidden_state[:, 0]
patch_tokens = hidden_state[:, 1 + self.n_register_tokens:]
features.append((patch_tokens, cls_token))
else:
patch_tokens = hidden_state[:, 1 + self.n_register_tokens:]
features.append((patch_tokens,))
return features
class DPTSegmentation(BaseDPTSegmentation):
def _create_segmentation_head(self, **kwargs):
return DPTSegmentationHead(**kwargs)
def forward(self, x):
h, w = x.shape[-2:]
features = self.extract_intermediate_features(x)
patch_h, patch_w = (h // 16, w // 16)
outputs = self.seg_head(features, patch_h, patch_w)
return outputs
class BaseDPTSegmentationHead(nn.Module):
def __init__(self, nclass, in_channels, num_outputs: int=3, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False, patch_size=16):
super().__init__()
self.nclass = nclass
self.patch_size = patch_size
self.use_clstoken = use_clstoken
self._init_projections(in_channels, out_channels)
self._init_resize_layers(out_channels)
self._init_readout_projections(in_channels, use_clstoken)
self._init_dpt_components(out_channels, features, use_bn)
self._init_output_heads(features, num_outputs)
def _init_projections(self, in_channels, out_channels):
self.projects = nn.ModuleList([nn.Conv2d(in_channels, out_channel, kernel_size=1, stride=1, padding=0) for out_channel in out_channels])
def _init_resize_layers(self, out_channels):
self.resize_layers = nn.ModuleList([nn.ConvTranspose2d(out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0), nn.ConvTranspose2d(out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0), nn.Identity(), nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1)])
def _init_readout_projections(self, in_channels, use_clstoken):
if use_clstoken:
self.readout_projects = nn.ModuleList([nn.Sequential(nn.Linear(2 * in_channels, in_channels), nn.GELU()) for _ in range(4)])
else:
self.readout_projects = None
def _init_dpt_components(self, out_channels, features, use_bn):
self.scratch = _make_scratch(out_channels, features, groups=1, expand=False)
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
def _init_output_heads(self, features, num_outputs):
self.mask_head = MultiMaskHead(features, num_outputs, inter_features=32)
self.classifier_head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(features, 64), nn.ReLU(True), nn.Linear(64, num_outputs))
def process_encoder_features(self, out_features, patch_h, patch_w):
processed_features = []
for i, feature_tuple in enumerate(out_features):
if self.use_clstoken:
patch_tokens, cls_token = (feature_tuple[0], feature_tuple[1])
readout = cls_token.unsqueeze(1).expand_as(patch_tokens)
x = self.readout_projects[i](torch.cat((patch_tokens, readout), -1))
else:
patch_tokens = feature_tuple[0]
x = patch_tokens
x = x.permute(0, 2, 1).reshape(x.shape[0], x.shape[-1], patch_h, patch_w)
x = self.projects[i](x)
x = self.resize_layers[i](x)
processed_features.append(x)
return processed_features
class DPTSegmentationHead(BaseDPTSegmentationHead):
def forward(self, out_features, patch_h, patch_w):
processed_features = self.process_encoder_features(out_features, patch_h, patch_w)
layer_1_rn = self.scratch.layer1_rn(processed_features[0])
layer_2_rn = self.scratch.layer2_rn(processed_features[1])
layer_3_rn = self.scratch.layer3_rn(processed_features[2])
layer_4_rn = self.scratch.layer4_rn(processed_features[3])
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
aux_out = self.classifier_head(path_1)
pred_masks = self.mask_head(path_1, (int(patch_h * self.patch_size), int(patch_w * self.patch_size)))
return (pred_masks, aux_out)
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
out_shape4 = out_shape if len(in_shape) >= 4 else None
if expand:
out_shape1 = out_shape
out_shape2 = out_shape * 2
out_shape3 = out_shape * 4
out_shape4 = out_shape * 8 if len(in_shape) >= 4 else None
scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
if len(in_shape) >= 4:
scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
return scratch
class ResidualConvUnit(nn.Module):
def __init__(self, features, activation, bn):
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
if self.bn:
self.bn1 = nn.BatchNorm2d(features)
self.bn2 = nn.BatchNorm2d(features)
self.activation = activation
def forward(self, x):
out = self.activation(x)
out = self.conv1(out)
if self.bn:
out = self.bn1(out)
out = self.activation(out)
out = self.conv2(out)
if self.bn:
out = self.bn2(out)
return out + x
class FeatureFusionBlock(nn.Module):
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=False, size=None):
super().__init__()
self.deconv = deconv
self.align_corners = align_corners
self.groups = 1
self.expand = expand
self.size = size
out_features = features // 2 if expand else features
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
def forward(self, *xs, size=None):
output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = output + res
output = self.resConfUnit2(output)
if size is not None:
modifier = {'size': size}
elif self.size is not None:
modifier = {'size': self.size}
else:
modifier = {'scale_factor': 2}
output = F.interpolate(output, **modifier, mode='bilinear', align_corners=self.align_corners)
output = self.out_conv(output)
return output
def _make_fusion_block(features, use_bn, size=None):
return FeatureFusionBlock(features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=False, size=size)
class MultiMaskHead(nn.Module):
def __init__(self, in_features: int, n_masks: int, inter_features: int=32):
super().__init__()
self.output_conv1 = nn.Conv2d(in_features, in_features // 2, kernel_size=3, stride=1, padding=1)
self.upsample_2x = nn.Sequential(nn.ConvTranspose2d(in_features // 2, inter_features * 2, kernel_size=4, stride=2, padding=1), nn.ReLU(inplace=True), nn.Conv2d(inter_features * 2, inter_features * 2, kernel_size=3, padding=1), nn.ReLU(inplace=True))
self.mask_heads = nn.ModuleList([nn.Sequential(nn.Conv2d(inter_features * 2, inter_features, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(inter_features, 1, kernel_size=1, stride=1, padding=0)) for _ in range(n_masks)])
def forward(self, x, target_size):
feat = self.output_conv1(x)
feat = self.upsample_2x(feat)
feat = F.interpolate(feat, size=target_size, mode='bilinear', align_corners=False, antialias=False)
masks = []
for head in self.mask_heads:
mask = head(feat)
masks.append(mask)
return torch.cat(masks, dim=1)
PILInput = Union[Image.Image, Sequence[Image.Image]]
class BEN3:
def __init__(
self,
checkpoint_path: str,
image_size: int = 1024,
device: str = "cuda" if torch.cuda.is_available() else "cpu",
use_fp16: bool = True,
compile_model: bool = False,
compile_mode: str = "reduce-overhead",
):
self.image_size = int(image_size)
if self.image_size <= 0:
raise ValueError("image_size must be > 0")
self._requested_fp16 = bool(use_fp16)
self.device = torch.device(device)
self.use_fp16 = self._requested_fp16 and self.device.type == "cuda"
self.fp = torch.float16 if self.use_fp16 else torch.float32
self.amp_dtype = torch.float16
self.model = DPTSegmentation().to(
device=self.device,
dtype=self.fp,
).eval()
model_checkpoint = torch.load(
checkpoint_path,
map_location="cpu",
weights_only=True,
)
self.model.load_state_dict(model_checkpoint, strict=True)
self._imagenet_mean = torch.tensor(
[0.485, 0.456, 0.406],
dtype=torch.float32,
device=self.device,
).view(1, 3, 1, 1)
self._imagenet_std = torch.tensor(
[0.229, 0.224, 0.225],
dtype=torch.float32,
device=self.device,
).view(1, 3, 1, 1)
self._compiled = False
self._compile_mode = compile_mode
if compile_model:
self.compile(mode=compile_mode)
def eval(self):
self.model.eval()
return self
def train(self, mode: bool = True):
self.model.train(mode)
return self
def to(self, device: Union[str, torch.device]):
self.device = torch.device(device)
self.use_fp16 = self._requested_fp16 and self.device.type == "cuda"
self.fp = torch.float16 if self.use_fp16 else torch.float32
self.model = self.model.to(
device=self.device,
dtype=self.fp,
)
self._imagenet_mean = self._imagenet_mean.to(self.device)
self._imagenet_std = self._imagenet_std.to(self.device)
return self
def cuda(self, device: Optional[Union[int, str, torch.device]] = None):
if device is None:
target = torch.device("cuda")
elif isinstance(device, int):
target = torch.device(f"cuda:{device}")
else:
target = torch.device(device)
return self.to(target)
def cpu(self):
return self.to("cpu")
def compile(self, mode: str = "reduce-overhead"):
if not hasattr(torch, "compile"):
raise RuntimeError("torch.compile requires a supported PyTorch 2.x build")
if self._compiled:
return self
self.model = torch.compile(self.model, mode=mode)
self._compiled = True
self._compile_mode = mode
return self
def _autocast_context(self):
if self.use_fp16:
return torch.autocast(
device_type="cuda",
dtype=self.amp_dtype,
)
return nullcontext()
@torch.inference_mode()
def forward(self, image_batch: torch.Tensor) -> torch.Tensor:
if image_batch.ndim != 4:
raise ValueError(
f"Expected image_batch [B,3,H,W], got {tuple(image_batch.shape)}"
)
if image_batch.shape[1] != 3:
raise ValueError(
f"Expected 3 input channels, got {image_batch.shape[1]}"
)
image_batch = image_batch.to(
device=self.device,
dtype=torch.float32,
non_blocking=True,
)
base_batch = (
image_batch - self._imagenet_mean
) / self._imagenet_std
with self._autocast_context():
pred_masks, aux_out = self.model(base_batch)
pred_masks = torch.sigmoid(pred_masks)
best_idx = aux_out.argmax(dim=1)
batch_idx = torch.arange(
pred_masks.shape[0],
device=pred_masks.device,
)
best_mask = pred_masks[batch_idx, best_idx]
return best_mask
def _rgb_arrays_to_tensor(
self,
images_rgb: Sequence[np.ndarray],
) -> torch.Tensor:
if not images_rgb:
raise ValueError("images_rgb cannot be empty")
resized = []
for image in images_rgb:
if not isinstance(image, np.ndarray):
raise TypeError("Each RGB image must be a numpy.ndarray")
if image.ndim != 3 or image.shape[2] != 3:
raise ValueError(
f"Expected RGB image [H,W,3], got {image.shape}"
)
resized.append(
cv2.resize(
image,
(self.image_size, self.image_size),
interpolation=cv2.INTER_LANCZOS4,
)
)
batch_np = np.stack(resized, axis=0)
return (
torch.from_numpy(batch_np)
.permute(0, 3, 1, 2)
.contiguous()
.float()
.div_(255.0)
)
def _pil_to_tensor(
self,
image: Image.Image,
) -> Tuple[torch.Tensor, Image.Image, Tuple[int, int]]:
if not isinstance(image, Image.Image):
raise TypeError("image must be a PIL.Image.Image")
original = ImageOps.exif_transpose(image).copy()
width, height = original.size
rgb = np.asarray(original.convert("RGB"), dtype=np.uint8)
tensor = self._rgb_arrays_to_tensor([rgb])[0]
return tensor, original, (width, height)
def _rgb_batch_to_tensor(
self,
frames_rgb: Sequence[np.ndarray],
) -> torch.Tensor:
return self._rgb_arrays_to_tensor(frames_rgb)
@staticmethod
def _postprocess_batch_same_size(
refined: torch.Tensor,
output_hw: Tuple[int, int],
) -> np.ndarray:
if refined.ndim == 3:
refined = refined.unsqueeze(1)
if refined.ndim != 4 or refined.shape[1] != 1:
raise ValueError(
f"Expected refined [B,1,H,W], got {tuple(refined.shape)}"
)
refined = F.interpolate(
refined.float(),
size=output_hw,
mode="bilinear",
align_corners=False,
)
return (
refined[:, 0]
.clamp_(0.0, 1.0)
.mul_(255.0)
.round_()
.byte()
.cpu()
.numpy()
)
@staticmethod
def _postprocess_one(
refined_one: torch.Tensor,
output_hw: Tuple[int, int],
) -> np.ndarray:
return BEN3._postprocess_batch_same_size(
refined_one,
output_hw,
)[0]
def predict_masks(
self,
images: Sequence[Image.Image],
) -> List[np.ndarray]:
images = list(images)
if not images:
return []
tensors: List[torch.Tensor] = []
sizes_wh: List[Tuple[int, int]] = []
for image in images:
tensor, _, size_wh = self._pil_to_tensor(image)
tensors.append(tensor)
sizes_wh.append(size_wh)
batch_tensor = torch.stack(tensors, dim=0)
refined = self.forward(batch_tensor)
if all(size == sizes_wh[0] for size in sizes_wh):
out_w, out_h = sizes_wh[0]
masks = self._postprocess_batch_same_size(
refined,
output_hw=(out_h, out_w),
)
return [masks[i] for i in range(masks.shape[0])]
masks: List[np.ndarray] = []
for i, (out_w, out_h) in enumerate(sizes_wh):
masks.append(
self._postprocess_one(
refined[i:i + 1],
output_hw=(out_h, out_w),
)
)
return masks
def inference(self, images: PILInput):
single_input = isinstance(images, Image.Image)
image_list = [images] if single_input else list(images)
if not image_list:
return []
masks = self.predict_masks(image_list)
foregrounds: List[Image.Image] = []
mask_images: List[Image.Image] = []
for image, mask in zip(image_list, masks):
original = ImageOps.exif_transpose(image).convert("RGBA")
mask_pil = Image.fromarray(mask, mode="L")
original.putalpha(mask_pil)
foregrounds.append(original)
mask_images.append(mask_pil)
if single_input:
return foregrounds[0], mask_images[0]
return foregrounds, mask_images
def _predict_video_batch(
self,
frames_rgb: Sequence[np.ndarray],
output_hw: Tuple[int, int],
) -> np.ndarray:
batch_tensor = self._rgb_batch_to_tensor(frames_rgb)
refined = self.forward(batch_tensor)
return self._postprocess_batch_same_size(
refined,
output_hw=output_hw,
)
@staticmethod
def _resolve_video_output_path(
video_path: Union[str, os.PathLike],
output_path: Optional[Union[str, os.PathLike]],
webm: bool,
) -> Path:
suffix = ".webm" if webm else ".mp4"
video_path = Path(video_path)
if output_path is None:
return video_path.with_name(
f"{video_path.stem}_foreground{suffix}"
)
output_path = Path(output_path)
if output_path.exists() and output_path.is_dir():
return output_path / f"foreground{suffix}"
if output_path.suffix:
return output_path.with_suffix(suffix)
return output_path / f"foreground{suffix}"
def segment_video(
self,
video_path: Union[str, os.PathLike],
output_path: Optional[Union[str, os.PathLike]] = None,
fps: Optional[float] = None,
batch: int = 1,
print_frames_processed: bool = True,
webm: bool = False,
rgb_value: Tuple[int, int, int] = (0, 255, 0),
max_frames: Optional[int] = None,
add_audio: bool = True,
) -> str:
if batch < 1:
raise ValueError("batch must be >= 1")
if len(rgb_value) != 3 or any(
not 0 <= int(value) <= 255
for value in rgb_value
):
raise ValueError("rgb_value must contain three values in [0,255]")
video_path = Path(video_path)
final_output = self._resolve_video_output_path(
video_path,
output_path,
webm,
)
final_output.parent.mkdir(parents=True, exist_ok=True)
cap = cv2.VideoCapture(str(video_path))
if not cap.isOpened():
raise IOError(f"Cannot open video: {video_path}")
source_fps = float(cap.get(cv2.CAP_PROP_FPS))
if not math.isfinite(source_fps) or source_fps <= 0:
source_fps = 30.0
if fps in (None, 0):
output_fps = source_fps
else:
output_fps = float(fps)
if not math.isfinite(output_fps) or output_fps <= 0:
cap.release()
raise ValueError("fps must be > 0, None, or 0")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if width <= 0 or height <= 0:
cap.release()
raise ValueError("Could not determine input video dimensions")
if max_frames is not None:
max_frames = int(max_frames)
if max_frames < 0:
cap.release()
raise ValueError("max_frames must be >= 0 or None")
if add_audio:
raw_output = final_output.with_name(
f"{final_output.stem}.video_only{final_output.suffix}"
)
else:
raw_output = final_output
if webm:
writer = _RGBAWebMWriter(
str(raw_output),
width=width,
height=height,
fps=output_fps,
)
else:
writer = _MP4Writer(
str(raw_output),
width=width,
height=height,
fps=output_fps,
)
frame_batch: List[np.ndarray] = []
repeat_batch: List[int] = []
source_frames_read = 0
output_frames_written = 0
if total_frames > 0:
expected_source_frames = total_frames
if max_frames is not None:
expected_source_frames = min(
expected_source_frames,
max_frames,
)
else:
expected_source_frames = max_frames
def flush_batch():
nonlocal frame_batch
nonlocal repeat_batch
nonlocal output_frames_written
if not frame_batch:
return
masks = self._predict_video_batch(
frame_batch,
output_hw=(height, width),
)
if webm:
for rgb, alpha, repeats in zip(
frame_batch,
masks,
repeat_batch,
):
rgba = np.dstack((rgb, alpha))
for _ in range(repeats):
writer.write(rgba)
output_frames_written += 1
else:
rgb_batch = np.stack(frame_batch, axis=0).astype(
np.float32
)
alpha_batch = (
masks.astype(np.float32)[..., None] / 255.0
)
background = np.asarray(
rgb_value,
dtype=np.float32,
).reshape(1, 1, 1, 3)
composite_batch = (
rgb_batch * alpha_batch
+ background * (1.0 - alpha_batch)
).round().clip(0, 255).astype(np.uint8)
for frame_rgb, repeats in zip(
composite_batch,
repeat_batch,
):
for _ in range(repeats):
writer.write(frame_rgb)
output_frames_written += 1
frame_batch = []
repeat_batch = []
try:
while True:
if (
max_frames is not None
and source_frames_read >= max_frames
):
break
ret, frame_bgr = cap.read()
if not ret:
break
source_index = source_frames_read
source_frames_read += 1
output_before = math.floor(
source_index * output_fps / source_fps
)
output_after = math.floor(
(source_index + 1) * output_fps / source_fps
)
repeats = output_after - output_before
if repeats > 0:
frame_rgb = cv2.cvtColor(
frame_bgr,
cv2.COLOR_BGR2RGB,
)
frame_batch.append(frame_rgb)
repeat_batch.append(repeats)
if len(frame_batch) >= batch:
flush_batch()
if print_frames_processed:
if (
expected_source_frames is None
or expected_source_frames <= 0
):
total_text = "?"
else:
total_text = str(expected_source_frames)
print(
f"Processed {source_frames_read}/{total_text} "
f"source frames; wrote {output_frames_written} "
f"output frames",
end="\r",
flush=True,
)
flush_batch()
finally:
cap.release()
writer.close()
if print_frames_processed:
print()
if not add_audio:
return str(final_output)
audio_added = add_audio_to_video(
video_without_audio_path=str(raw_output),
original_video_path=str(video_path),
output_path=str(final_output),
)
if audio_added:
try:
raw_output.unlink()
except OSError:
pass
return str(final_output)
if raw_output != final_output:
raw_output.replace(final_output)
return str(final_output)
class _MP4Writer:
def __init__(
self,
path: str,
width: int,
height: int,
fps: float,
):
self.writer = cv2.VideoWriter(
path,
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(width, height),
)
if not self.writer.isOpened():
raise IOError(f"Could not open MP4 writer: {path}")
def write(self, frame_rgb: np.ndarray):
if frame_rgb.ndim != 3 or frame_rgb.shape[2] != 3:
raise ValueError(
f"Expected RGB [H,W,3], got {frame_rgb.shape}"
)
self.writer.write(
cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
)
def close(self):
self.writer.release()
class _RGBAWebMWriter:
def __init__(
self,
path: str,
width: int,
height: int,
fps: float,
):
command = [
"ffmpeg",
"-y",
"-loglevel",
"error",
"-f",
"rawvideo",
"-pix_fmt",
"rgba",
"-s:v",
f"{width}x{height}",
"-r",
str(fps),
"-i",
"-",
"-an",
"-c:v",
"libvpx-vp9",
"-pix_fmt",
"yuva420p",
"-auto-alt-ref",
"0",
path,
]
self.process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
)
def write(self, frame_rgba: np.ndarray):
if frame_rgba.ndim != 3 or frame_rgba.shape[2] != 4:
raise ValueError(
f"Expected RGBA [H,W,4], got {frame_rgba.shape}"
)
if self.process.stdin is None:
raise RuntimeError("ffmpeg stdin is closed")
frame_rgba = np.ascontiguousarray(
frame_rgba,
dtype=np.uint8,
)
self.process.stdin.write(frame_rgba.tobytes())
def close(self):
if self.process.stdin is not None:
self.process.stdin.close()
return_code = self.process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(
return_code,
self.process.args,
)
def add_audio_to_video(
video_without_audio_path: str,
original_video_path: str,
output_path: str,
) -> bool:
probe_command = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=index",
"-of",
"csv=p=0",
original_video_path,
]
result = subprocess.run(
probe_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
if not result.stdout.strip():
return False
output_suffix = Path(output_path).suffix.lower()
audio_codec = "libopus" if output_suffix == ".webm" else "aac"
command = [
"ffmpeg",
"-y",
"-loglevel",
"error",
"-i",
video_without_audio_path,
"-i",
original_video_path,
"-map",
"0:v:0",
"-map",
"1:a:0",
"-c:v",
"copy",
"-c:a",
audio_codec,
"-shortest",
output_path,
]
subprocess.run(command, check=True)
return True