Upload 7 files
Browse files- nodes/color_match.py +191 -0
- nodes/load_video_batch.py +359 -0
- nodes/openpose_smoother.py +1837 -0
- nodes/preview_image_metadata.py +95 -0
- nodes/rename_files.py +200 -0
- nodes/save_load_pose.py +128 -0
- nodes/video_combine_metadata.py +1311 -0
nodes/color_match.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import shutil
|
| 4 |
+
import cv2
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import folder_paths
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TSColorMatchSequentialBias:
|
| 12 |
+
|
| 13 |
+
@classmethod
|
| 14 |
+
def INPUT_TYPES(cls):
|
| 15 |
+
return {
|
| 16 |
+
"required": {
|
| 17 |
+
"images": ("IMAGE",),
|
| 18 |
+
"chunk_size": ("INT", {"default": 81, "min": 1, "max": 99999, "step": 1}),
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
RETURN_TYPES = ("IMAGE",)
|
| 23 |
+
RETURN_NAMES = ("IMAGE",)
|
| 24 |
+
FUNCTION = "process"
|
| 25 |
+
CATEGORY = "TS_Nodes/Video"
|
| 26 |
+
|
| 27 |
+
EPS = 1e-6
|
| 28 |
+
|
| 29 |
+
FPS = 30
|
| 30 |
+
HEAD_WIN = 1
|
| 31 |
+
TAIL_WIN = 1
|
| 32 |
+
SAVE_TEMP_CHUNKS = True
|
| 33 |
+
DEBUG = False
|
| 34 |
+
|
| 35 |
+
@staticmethod
|
| 36 |
+
def _rgb01_to_bgr8(rgb01: np.ndarray) -> np.ndarray:
|
| 37 |
+
out = np.clip(rgb01 * 255.0, 0.0, 255.0).astype(np.uint8)
|
| 38 |
+
return cv2.cvtColor(out, cv2.COLOR_RGB2BGR)
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def _bgr8_to_rgb01(bgr8: np.ndarray) -> np.ndarray:
|
| 42 |
+
rgb = cv2.cvtColor(bgr8, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
|
| 43 |
+
return rgb
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def _sample_rgb01_all_pixels_from_bgr8(frame_bgr8: np.ndarray) -> np.ndarray:
|
| 47 |
+
small = cv2.resize(frame_bgr8, (480, 270), interpolation=cv2.INTER_AREA)
|
| 48 |
+
rgb01 = cv2.cvtColor(small, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
|
| 49 |
+
return rgb01.reshape(-1, 3)
|
| 50 |
+
|
| 51 |
+
def _compute_stats(self, frames_bgr8: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
| 52 |
+
pxs = [self._sample_rgb01_all_pixels_from_bgr8(fr) for fr in frames_bgr8]
|
| 53 |
+
px = np.concatenate(pxs, axis=0)
|
| 54 |
+
mean = px.mean(axis=0).astype(np.float32)
|
| 55 |
+
std = px.std(axis=0).astype(np.float32)
|
| 56 |
+
return mean, std
|
| 57 |
+
|
| 58 |
+
def _apply_color_transfer_rgb01(
|
| 59 |
+
self,
|
| 60 |
+
frame_bgr8: np.ndarray,
|
| 61 |
+
target_mean: np.ndarray,
|
| 62 |
+
target_std: np.ndarray,
|
| 63 |
+
source_mean: np.ndarray,
|
| 64 |
+
source_std: np.ndarray,
|
| 65 |
+
) -> np.ndarray:
|
| 66 |
+
rgb01 = self._bgr8_to_rgb01(frame_bgr8)
|
| 67 |
+
scale = target_std / (source_std + self.EPS)
|
| 68 |
+
out = (rgb01 - source_mean) * scale + target_mean
|
| 69 |
+
return np.clip(out, 0.0, 1.0)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def _ensure_mp4v_writer(path: str, fps: int, w: int, h: int) -> cv2.VideoWriter:
|
| 73 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 74 |
+
vw = cv2.VideoWriter(path, fourcc, float(fps), (w, h))
|
| 75 |
+
if not vw.isOpened():
|
| 76 |
+
raise RuntimeError(f"Can't open VideoWriter for: {path}")
|
| 77 |
+
return vw
|
| 78 |
+
|
| 79 |
+
def process(self, images, chunk_size: int):
|
| 80 |
+
images_np = images.detach().cpu().numpy()
|
| 81 |
+
n = int(images_np.shape[0]) if images_np is not None else 0
|
| 82 |
+
if n <= 0:
|
| 83 |
+
return (images,)
|
| 84 |
+
|
| 85 |
+
h = int(images_np.shape[1])
|
| 86 |
+
w = int(images_np.shape[2])
|
| 87 |
+
|
| 88 |
+
out_dir = folder_paths.get_output_directory()
|
| 89 |
+
run_id = uuid.uuid4().hex[:10]
|
| 90 |
+
base_name = f"matched_sequential_transfer_{run_id}"
|
| 91 |
+
|
| 92 |
+
tmp_dir = os.path.join(out_dir, f".tmp_{base_name}")
|
| 93 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 94 |
+
|
| 95 |
+
final_path_tmp = os.path.join(tmp_dir, f"{base_name}.mp4")
|
| 96 |
+
final_path = os.path.join(out_dir, f"{base_name}.mp4")
|
| 97 |
+
|
| 98 |
+
out_final = None
|
| 99 |
+
out_frames_rgb01: list[np.ndarray] = []
|
| 100 |
+
|
| 101 |
+
fps = int(self.FPS)
|
| 102 |
+
head_win = int(self.HEAD_WIN)
|
| 103 |
+
tail_win = int(self.TAIL_WIN)
|
| 104 |
+
save_temp_chunks = bool(self.SAVE_TEMP_CHUNKS)
|
| 105 |
+
debug = bool(self.DEBUG)
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
if debug:
|
| 109 |
+
print("Processing images chunk by chunk and building final video directly...")
|
| 110 |
+
print(f" N={n}, chunk_size={chunk_size}, fps={fps}, size={w}x{h}")
|
| 111 |
+
print(f" save_temp_chunks={save_temp_chunks}, head_win={head_win}, tail_win={tail_win}")
|
| 112 |
+
|
| 113 |
+
out_final = self._ensure_mp4v_writer(final_path_tmp, fps, w, h)
|
| 114 |
+
|
| 115 |
+
ci = 0
|
| 116 |
+
prev_modified_tail_bgr8: list[np.ndarray] = []
|
| 117 |
+
|
| 118 |
+
for start in range(0, n, chunk_size):
|
| 119 |
+
end = min(start + chunk_size, n)
|
| 120 |
+
length = end - start
|
| 121 |
+
|
| 122 |
+
raw_frames_bgr8: list[np.ndarray] = []
|
| 123 |
+
for i in range(start, end):
|
| 124 |
+
raw_rgb01 = images_np[i].astype(np.float32)
|
| 125 |
+
raw_frames_bgr8.append(self._rgb01_to_bgr8(raw_rgb01))
|
| 126 |
+
|
| 127 |
+
processed_frames_bgr8: list[np.ndarray] = []
|
| 128 |
+
|
| 129 |
+
if ci == 0:
|
| 130 |
+
processed_frames_bgr8 = raw_frames_bgr8
|
| 131 |
+
if debug:
|
| 132 |
+
print(f"Chunk {ci}: Keep original (base for next)")
|
| 133 |
+
else:
|
| 134 |
+
target_m, target_s = self._compute_stats(prev_modified_tail_bgr8)
|
| 135 |
+
|
| 136 |
+
h1 = min(head_win, length)
|
| 137 |
+
raw_head_frames_bgr8 = raw_frames_bgr8[:h1]
|
| 138 |
+
source_m, source_s = self._compute_stats(raw_head_frames_bgr8)
|
| 139 |
+
|
| 140 |
+
if debug:
|
| 141 |
+
print(f"Chunk {ci-1}->{ci}:")
|
| 142 |
+
print(f" Target Mean: {target_m}, Std: {target_s}")
|
| 143 |
+
print(f" Source Mean: {source_m}, Std: {source_s}")
|
| 144 |
+
|
| 145 |
+
for fr_bgr8 in raw_frames_bgr8:
|
| 146 |
+
rgb01 = self._apply_color_transfer_rgb01(fr_bgr8, target_m, target_s, source_m, source_s)
|
| 147 |
+
res_bgr8 = self._rgb01_to_bgr8(rgb01)
|
| 148 |
+
processed_frames_bgr8.append(res_bgr8)
|
| 149 |
+
|
| 150 |
+
for fr_bgr8 in processed_frames_bgr8:
|
| 151 |
+
out_final.write(fr_bgr8)
|
| 152 |
+
out_frames_rgb01.append(self._bgr8_to_rgb01(fr_bgr8))
|
| 153 |
+
|
| 154 |
+
tw = min(tail_win, length)
|
| 155 |
+
tail_start = max(0, length - tw)
|
| 156 |
+
prev_modified_tail_bgr8 = processed_frames_bgr8[tail_start:]
|
| 157 |
+
|
| 158 |
+
if save_temp_chunks:
|
| 159 |
+
chunk_filename_tmp = os.path.join(tmp_dir, f"chunk_{ci:03d}.mp4")
|
| 160 |
+
out_chunk = self._ensure_mp4v_writer(chunk_filename_tmp, fps, w, h)
|
| 161 |
+
for fr_bgr8 in processed_frames_bgr8:
|
| 162 |
+
out_chunk.write(fr_bgr8)
|
| 163 |
+
out_chunk.release()
|
| 164 |
+
if debug:
|
| 165 |
+
print(f"Saved TEMP chunk_{ci:03d}.mp4 with {length} frames.")
|
| 166 |
+
|
| 167 |
+
ci += 1
|
| 168 |
+
|
| 169 |
+
out_final.release()
|
| 170 |
+
out_final = None
|
| 171 |
+
|
| 172 |
+
shutil.move(final_path_tmp, final_path)
|
| 173 |
+
|
| 174 |
+
if debug:
|
| 175 |
+
print("\nDONE. Saved final video:", final_path)
|
| 176 |
+
|
| 177 |
+
finally:
|
| 178 |
+
if out_final is not None:
|
| 179 |
+
try:
|
| 180 |
+
out_final.release()
|
| 181 |
+
except Exception:
|
| 182 |
+
pass
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
if os.path.isdir(tmp_dir):
|
| 186 |
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
| 187 |
+
except Exception:
|
| 188 |
+
pass
|
| 189 |
+
|
| 190 |
+
out_tensor = torch.from_numpy(np.stack(out_frames_rgb01, axis=0).astype(np.float32))
|
| 191 |
+
return (out_tensor,)
|
nodes/load_video_batch.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import shutil
|
| 4 |
+
import subprocess
|
| 5 |
+
import time
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import cv2
|
| 13 |
+
|
| 14 |
+
_has_cv2 = True
|
| 15 |
+
except Exception:
|
| 16 |
+
_has_cv2 = False
|
| 17 |
+
|
| 18 |
+
ENCODE_ARGS = ("utf-8", "backslashreplace")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _pick_ffmpeg_path():
|
| 22 |
+
if "VHS_FORCE_FFMPEG_PATH" in os.environ:
|
| 23 |
+
p = os.environ.get("VHS_FORCE_FFMPEG_PATH")
|
| 24 |
+
if p:
|
| 25 |
+
return p
|
| 26 |
+
|
| 27 |
+
system_ffmpeg = shutil.which("ffmpeg")
|
| 28 |
+
if system_ffmpeg is not None:
|
| 29 |
+
return system_ffmpeg
|
| 30 |
+
|
| 31 |
+
if os.path.isfile("ffmpeg"):
|
| 32 |
+
return os.path.abspath("ffmpeg")
|
| 33 |
+
if os.path.isfile("ffmpeg.exe"):
|
| 34 |
+
return os.path.abspath("ffmpeg.exe")
|
| 35 |
+
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
ffmpeg_path = _pick_ffmpeg_path()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_audio(file, start_time=0, duration=0):
|
| 43 |
+
if ffmpeg_path is None:
|
| 44 |
+
raise Exception("ffmpeg not found. Put ffmpeg in PATH, or set VHS_FORCE_FFMPEG_PATH env var.")
|
| 45 |
+
|
| 46 |
+
args = [ffmpeg_path, "-i", file]
|
| 47 |
+
if start_time > 0:
|
| 48 |
+
args += ["-ss", str(start_time)]
|
| 49 |
+
if duration > 0:
|
| 50 |
+
args += ["-t", str(duration)]
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
# как в utils: вытаскиваем raw f32le в stdout
|
| 54 |
+
res = subprocess.run(args + ["-f", "f32le", "-"], capture_output=True, check=True)
|
| 55 |
+
audio = torch.frombuffer(bytearray(res.stdout), dtype=torch.float32)
|
| 56 |
+
match = re.search(r", (\d+) Hz, (\w+), ", res.stderr.decode(*ENCODE_ARGS))
|
| 57 |
+
except subprocess.CalledProcessError as e:
|
| 58 |
+
raise Exception(f"Failed to extract audio from {file}:\n" + e.stderr.decode(*ENCODE_ARGS))
|
| 59 |
+
|
| 60 |
+
if match:
|
| 61 |
+
ar = int(match.group(1))
|
| 62 |
+
ac = {"mono": 1, "stereo": 2}.get(match.group(2), 2)
|
| 63 |
+
else:
|
| 64 |
+
ar = 44100
|
| 65 |
+
ac = 2
|
| 66 |
+
|
| 67 |
+
if audio.numel() == 0:
|
| 68 |
+
empty = torch.zeros((1, 1, 0), dtype=torch.float32)
|
| 69 |
+
return {"waveform": empty, "sample_rate": ar}
|
| 70 |
+
|
| 71 |
+
audio = audio.reshape((-1, ac)).transpose(0, 1).unsqueeze(0)
|
| 72 |
+
return {"waveform": audio, "sample_rate": ar}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class LazyAudioMap(Mapping):
|
| 76 |
+
def __init__(self, file, start_time, duration):
|
| 77 |
+
self.file = file
|
| 78 |
+
self.start_time = start_time
|
| 79 |
+
self.duration = duration
|
| 80 |
+
self._dict = None
|
| 81 |
+
|
| 82 |
+
def _ensure(self):
|
| 83 |
+
if self._dict is None:
|
| 84 |
+
self._dict = get_audio(self.file, self.start_time, self.duration)
|
| 85 |
+
|
| 86 |
+
def __getitem__(self, key):
|
| 87 |
+
self._ensure()
|
| 88 |
+
return self._dict[key]
|
| 89 |
+
|
| 90 |
+
def __iter__(self):
|
| 91 |
+
self._ensure()
|
| 92 |
+
return iter(self._dict)
|
| 93 |
+
|
| 94 |
+
def __len__(self):
|
| 95 |
+
self._ensure()
|
| 96 |
+
return len(self._dict)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def lazy_get_audio(file, start_time=0, duration=0, **kwargs):
|
| 100 |
+
return LazyAudioMap(file, start_time, duration)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def extract_first_number(s):
|
| 104 |
+
match = re.search(r"\d+", s)
|
| 105 |
+
return int(match.group()) if match else float("inf")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
sort_methods = [
|
| 109 |
+
"None",
|
| 110 |
+
"Alphabetical (ASC)",
|
| 111 |
+
"Alphabetical (DESC)",
|
| 112 |
+
"Numerical (ASC)",
|
| 113 |
+
"Numerical (DESC)",
|
| 114 |
+
"Datetime (ASC)",
|
| 115 |
+
"Datetime (DESC)",
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def sort_by(items, base_path=".", method=None):
|
| 120 |
+
def fullpath(x):
|
| 121 |
+
return os.path.join(base_path, x)
|
| 122 |
+
|
| 123 |
+
def get_timestamp(path):
|
| 124 |
+
try:
|
| 125 |
+
return os.path.getmtime(path)
|
| 126 |
+
except FileNotFoundError:
|
| 127 |
+
return float("-inf")
|
| 128 |
+
|
| 129 |
+
if method == "Alphabetical (ASC)":
|
| 130 |
+
return sorted(items)
|
| 131 |
+
elif method == "Alphabetical (DESC)":
|
| 132 |
+
return sorted(items, reverse=True)
|
| 133 |
+
elif method == "Numerical (ASC)":
|
| 134 |
+
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]))
|
| 135 |
+
elif method == "Numerical (DESC)":
|
| 136 |
+
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]), reverse=True)
|
| 137 |
+
elif method == "Datetime (ASC)":
|
| 138 |
+
return sorted(items, key=lambda x: get_timestamp(fullpath(x)))
|
| 139 |
+
elif method == "Datetime (DESC)":
|
| 140 |
+
return sorted(items, key=lambda x: get_timestamp(fullpath(x)), reverse=True)
|
| 141 |
+
else:
|
| 142 |
+
return items
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def target_size(width, height, custom_width, custom_height, downscale_ratio=8):
|
| 146 |
+
if downscale_ratio is None:
|
| 147 |
+
downscale_ratio = 8
|
| 148 |
+
|
| 149 |
+
if custom_width == 0 and custom_height == 0:
|
| 150 |
+
new_w, new_h = width, height
|
| 151 |
+
elif custom_height == 0:
|
| 152 |
+
new_h = int(height * (custom_width / width))
|
| 153 |
+
new_w = int(custom_width)
|
| 154 |
+
elif custom_width == 0:
|
| 155 |
+
new_w = int(width * (custom_height / height))
|
| 156 |
+
new_h = int(custom_height)
|
| 157 |
+
else:
|
| 158 |
+
new_w, new_h = int(custom_width), int(custom_height)
|
| 159 |
+
|
| 160 |
+
new_w = int(new_w / downscale_ratio + 0.5) * downscale_ratio
|
| 161 |
+
new_h = int(new_h / downscale_ratio + 0.5) * downscale_ratio
|
| 162 |
+
return new_w, new_h
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _read_frames_vhs_like(
|
| 166 |
+
video_path: str,
|
| 167 |
+
force_rate: float = 0,
|
| 168 |
+
custom_width: int = 0,
|
| 169 |
+
custom_height: int = 0,
|
| 170 |
+
downscale_ratio: int = 8,
|
| 171 |
+
frame_load_cap: int = 0,
|
| 172 |
+
select_every_nth: int = 1,
|
| 173 |
+
):
|
| 174 |
+
|
| 175 |
+
if select_every_nth is None or select_every_nth < 1:
|
| 176 |
+
select_every_nth = 1
|
| 177 |
+
|
| 178 |
+
if not _has_cv2:
|
| 179 |
+
raise RuntimeError("OpenCV (cv2) not available. Install opencv-python.")
|
| 180 |
+
|
| 181 |
+
cap = cv2.VideoCapture(video_path)
|
| 182 |
+
if not cap.isOpened() or not cap.grab():
|
| 183 |
+
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
| 184 |
+
|
| 185 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 186 |
+
if fps is None or fps <= 0:
|
| 187 |
+
fps = 30.0
|
| 188 |
+
|
| 189 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 190 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 191 |
+
|
| 192 |
+
ok0, frame0 = cap.retrieve()
|
| 193 |
+
if not ok0 or frame0 is None:
|
| 194 |
+
cap.release()
|
| 195 |
+
raise RuntimeError(f"Cannot retrieve first frame from: {video_path}")
|
| 196 |
+
|
| 197 |
+
if width <= 0 or height <= 0:
|
| 198 |
+
height, width = frame0.shape[:2]
|
| 199 |
+
|
| 200 |
+
base_dt = 1.0 / float(fps)
|
| 201 |
+
target_dt = base_dt if force_rate == 0 else (1.0 / float(force_rate))
|
| 202 |
+
|
| 203 |
+
effective_dt = target_dt * float(select_every_nth)
|
| 204 |
+
loaded_fps = 1.0 / effective_dt if effective_dt > 0 else float(fps)
|
| 205 |
+
|
| 206 |
+
new_w, new_h = target_size(width, height, custom_width, custom_height, downscale_ratio)
|
| 207 |
+
do_resize = (new_w != width) or (new_h != height)
|
| 208 |
+
|
| 209 |
+
def _process_frame(bgr):
|
| 210 |
+
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 211 |
+
if do_resize:
|
| 212 |
+
rgb = cv2.resize(rgb, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4)
|
| 213 |
+
return rgb
|
| 214 |
+
|
| 215 |
+
frames = []
|
| 216 |
+
|
| 217 |
+
evaluated = -1
|
| 218 |
+
|
| 219 |
+
def _maybe_add(bgr):
|
| 220 |
+
nonlocal evaluated
|
| 221 |
+
evaluated += 1
|
| 222 |
+
if (evaluated % select_every_nth) != 0:
|
| 223 |
+
return
|
| 224 |
+
frames.append(_process_frame(bgr))
|
| 225 |
+
|
| 226 |
+
_maybe_add(frame0)
|
| 227 |
+
|
| 228 |
+
if frame_load_cap > 0 and len(frames) >= frame_load_cap:
|
| 229 |
+
cap.release()
|
| 230 |
+
arr = np.stack(frames, axis=0).astype(np.float32) / 255.0
|
| 231 |
+
t = torch.from_numpy(arr)
|
| 232 |
+
loaded_duration = float(len(t) * effective_dt)
|
| 233 |
+
start_time = 0.0
|
| 234 |
+
return t, float(fps), float(loaded_fps), loaded_duration, start_time
|
| 235 |
+
|
| 236 |
+
time_offset = target_dt
|
| 237 |
+
time_offset -= target_dt
|
| 238 |
+
|
| 239 |
+
while cap.isOpened():
|
| 240 |
+
if time_offset < target_dt:
|
| 241 |
+
ok = cap.grab()
|
| 242 |
+
if not ok:
|
| 243 |
+
break
|
| 244 |
+
time_offset += base_dt
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
ok, frame_bgr = cap.retrieve()
|
| 248 |
+
if not ok or frame_bgr is None:
|
| 249 |
+
break
|
| 250 |
+
|
| 251 |
+
_maybe_add(frame_bgr)
|
| 252 |
+
|
| 253 |
+
if frame_load_cap > 0 and len(frames) >= frame_load_cap:
|
| 254 |
+
break
|
| 255 |
+
|
| 256 |
+
time_offset -= target_dt
|
| 257 |
+
|
| 258 |
+
cap.release()
|
| 259 |
+
|
| 260 |
+
if len(frames) == 0:
|
| 261 |
+
raise RuntimeError(f"No frames could be read from: {video_path}")
|
| 262 |
+
|
| 263 |
+
arr = np.stack(frames, axis=0).astype(np.float32) / 255.0
|
| 264 |
+
t = torch.from_numpy(arr)
|
| 265 |
+
|
| 266 |
+
loaded_duration = float(len(t) * effective_dt)
|
| 267 |
+
start_time = 0.0
|
| 268 |
+
return t, float(fps), float(loaded_fps), loaded_duration, start_time
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class LoadVideoBatchListFromDir:
|
| 272 |
+
@classmethod
|
| 273 |
+
def INPUT_TYPES(s):
|
| 274 |
+
return {
|
| 275 |
+
"required": {
|
| 276 |
+
"directory": ("STRING", {"default": ""}),
|
| 277 |
+
"force_rate": ("FLOAT", {"default": 0, "min": 0, "max": 120, "step": 1}),
|
| 278 |
+
"width": ("INT", {"default": 720, "min": 0, "max": 8192, "step": 1}),
|
| 279 |
+
"height": ("INT", {"default": 1280, "min": 0, "max": 8192, "step": 1}),
|
| 280 |
+
},
|
| 281 |
+
"optional": {
|
| 282 |
+
"video_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}),
|
| 283 |
+
"frame_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}),
|
| 284 |
+
"select_every_nth": ("INT", {"default": 1, "min": 1, "max": 0xFFFFFFFF, "step": 1}),
|
| 285 |
+
"start_index": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF, "step": 1}),
|
| 286 |
+
"load_always": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}),
|
| 287 |
+
"sort_method": (sort_methods,),
|
| 288 |
+
},
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
RETURN_TYPES = ("IMAGE", "AUDIO", "INT")
|
| 292 |
+
RETURN_NAMES = ("IMAGE", "audio", "COUNT")
|
| 293 |
+
OUTPUT_IS_LIST = (True, True, False)
|
| 294 |
+
|
| 295 |
+
FUNCTION = "load_videos"
|
| 296 |
+
CATEGORY = "video"
|
| 297 |
+
|
| 298 |
+
@classmethod
|
| 299 |
+
def IS_CHANGED(cls, **kwargs):
|
| 300 |
+
if kwargs.get("load_always"):
|
| 301 |
+
return float("NaN")
|
| 302 |
+
return hash(frozenset(kwargs.items()))
|
| 303 |
+
|
| 304 |
+
def load_videos(
|
| 305 |
+
self,
|
| 306 |
+
directory: str,
|
| 307 |
+
force_rate: float = 0,
|
| 308 |
+
width: int = 0,
|
| 309 |
+
height: int = 0,
|
| 310 |
+
video_load_cap: int = 0,
|
| 311 |
+
frame_load_cap: int = 0,
|
| 312 |
+
select_every_nth: int = 1,
|
| 313 |
+
start_index: int = 0,
|
| 314 |
+
load_always: bool = False,
|
| 315 |
+
sort_method=None,
|
| 316 |
+
):
|
| 317 |
+
if not os.path.isdir(directory):
|
| 318 |
+
raise FileNotFoundError(f"Directory '{directory}' cannot be found.")
|
| 319 |
+
|
| 320 |
+
files = os.listdir(directory)
|
| 321 |
+
if len(files) == 0:
|
| 322 |
+
raise FileNotFoundError(f"No files in directory '{directory}'.")
|
| 323 |
+
|
| 324 |
+
valid_ext = {".mp4", ".mov", ".mkv", ".webm", ".avi", ".m4v"}
|
| 325 |
+
files = [
|
| 326 |
+
f
|
| 327 |
+
for f in files
|
| 328 |
+
if os.path.isfile(os.path.join(directory, f)) and os.path.splitext(f)[1].lower() in valid_ext
|
| 329 |
+
]
|
| 330 |
+
if len(files) == 0:
|
| 331 |
+
raise FileNotFoundError(f"No video files in directory '{directory}' (expected: {sorted(valid_ext)}).")
|
| 332 |
+
|
| 333 |
+
files = sort_by(files, directory, sort_method)
|
| 334 |
+
files = files[start_index:]
|
| 335 |
+
if video_load_cap > 0:
|
| 336 |
+
files = files[:video_load_cap]
|
| 337 |
+
|
| 338 |
+
images_list = []
|
| 339 |
+
audios_list = []
|
| 340 |
+
|
| 341 |
+
for fname in files:
|
| 342 |
+
path = os.path.join(directory, fname)
|
| 343 |
+
|
| 344 |
+
vid, source_fps, loaded_fps, loaded_duration, start_time = _read_frames_vhs_like(
|
| 345 |
+
path,
|
| 346 |
+
force_rate=force_rate,
|
| 347 |
+
custom_width=width,
|
| 348 |
+
custom_height=height,
|
| 349 |
+
downscale_ratio=8,
|
| 350 |
+
frame_load_cap=frame_load_cap,
|
| 351 |
+
select_every_nth=select_every_nth,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
images_list.append(vid)
|
| 355 |
+
|
| 356 |
+
audio = lazy_get_audio(path, start_time, loaded_duration)
|
| 357 |
+
audios_list.append(audio)
|
| 358 |
+
|
| 359 |
+
return (images_list, audios_list, len(images_list))
|
nodes/openpose_smoother.py
ADDED
|
@@ -0,0 +1,1837 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import math
|
| 5 |
+
import pickle
|
| 6 |
+
import threading
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import cv2
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ============================================================
|
| 16 |
+
# ComfyUI Node (pose_data + PKL)
|
| 17 |
+
# ============================================================
|
| 18 |
+
|
| 19 |
+
_GLOBAL_LOCK = threading.Lock()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class KPSSmoothPoseDataAndRender:
|
| 23 |
+
|
| 24 |
+
@classmethod
|
| 25 |
+
def INPUT_TYPES(cls):
|
| 26 |
+
return {
|
| 27 |
+
"required": {
|
| 28 |
+
"pose_data": ("POSEDATA",),
|
| 29 |
+
"filter_extra_people": ("BOOLEAN", {"default": True}),
|
| 30 |
+
"smooth_alpha": ("FLOAT", {"default": 0.7, "min": 0.01, "max": 0.99, "step": 0.01}),
|
| 31 |
+
"gap_frames": ("INT", {"default": 12, "min": 0, "max": 100, "step": 1}),
|
| 32 |
+
"min_run_frames": ("INT", {"default": 3, "min": 1, "max": 60, "step": 1}),
|
| 33 |
+
"conf_thresh_body": ("FLOAT", {"default": 0.35, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 34 |
+
"conf_thresh_hands": ("FLOAT", {"default": 0.60, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
RETURN_TYPES = ("IMAGE", "POSEDATA")
|
| 39 |
+
RETURN_NAMES = ("IMAGE", "pose_data")
|
| 40 |
+
FUNCTION = "run"
|
| 41 |
+
CATEGORY = "posedata"
|
| 42 |
+
|
| 43 |
+
def run(self, pose_data, **kwargs):
|
| 44 |
+
filter_extra_people = bool(kwargs.get("filter_extra_people", True))
|
| 45 |
+
|
| 46 |
+
smooth_alpha = float(kwargs.get("smooth_alpha", 0.7))
|
| 47 |
+
gap_frames = int(kwargs.get("gap_frames", 12))
|
| 48 |
+
min_run_frames = int(kwargs.get("min_run_frames", 2))
|
| 49 |
+
|
| 50 |
+
conf_thresh_body = float(kwargs.get("conf_thresh_body", 0.20))
|
| 51 |
+
conf_thresh_hands = float(kwargs.get("conf_thresh_hands", 0.50))
|
| 52 |
+
conf_thresh_face = 0.20
|
| 53 |
+
|
| 54 |
+
force_body_18 = bool(kwargs.get("force_body_18", False))
|
| 55 |
+
|
| 56 |
+
pose_data = _coerce_pose_data_to_obj(pose_data)
|
| 57 |
+
frames_json_like, meta_ref = _pose_data_to_kps_frames(pose_data, force_body_18=force_body_18)
|
| 58 |
+
|
| 59 |
+
with _GLOBAL_LOCK:
|
| 60 |
+
old = _snapshot_tunable_globals()
|
| 61 |
+
try:
|
| 62 |
+
globals()["CONF_GATE_BODY"] = conf_thresh_body
|
| 63 |
+
globals()["CONF_GATE_HAND"] = conf_thresh_hands
|
| 64 |
+
globals()["CONF_GATE_FACE"] = conf_thresh_face
|
| 65 |
+
|
| 66 |
+
globals()["ALPHA_BODY"] = smooth_alpha
|
| 67 |
+
globals()["SUPER_SMOOTH_ALPHA"] = smooth_alpha
|
| 68 |
+
globals()["MAX_GAP_FRAMES"] = gap_frames
|
| 69 |
+
globals()["MIN_RUN_FRAMES"] = min_run_frames
|
| 70 |
+
globals()["DENSE_SUPER_SMOOTH_ALPHA"] = smooth_alpha
|
| 71 |
+
globals()["DENSE_MAX_GAP_FRAMES"] = gap_frames
|
| 72 |
+
globals()["DENSE_MIN_RUN_FRAMES"] = min_run_frames
|
| 73 |
+
globals()["FILTER_EXTRA_PEOPLE"] = filter_extra_people
|
| 74 |
+
|
| 75 |
+
smoothed_frames = smooth_KPS_json_obj(
|
| 76 |
+
frames_json_like,
|
| 77 |
+
keep_face_untouched=False,
|
| 78 |
+
keep_hands_untouched=False,
|
| 79 |
+
filter_extra_people=filter_extra_people,
|
| 80 |
+
)
|
| 81 |
+
finally:
|
| 82 |
+
_restore_tunable_globals(old)
|
| 83 |
+
|
| 84 |
+
out_pose_data = _kps_frames_to_pose_data(pose_data, smoothed_frames, meta_ref, force_body_18=force_body_18)
|
| 85 |
+
|
| 86 |
+
w, h = _extract_canvas_wh(smoothed_frames, default_w=720, default_h=1280)
|
| 87 |
+
frames_np = []
|
| 88 |
+
for fr in smoothed_frames:
|
| 89 |
+
if isinstance(fr, dict) and fr.get("people"):
|
| 90 |
+
img = _draw_pose_frame_full(
|
| 91 |
+
w,
|
| 92 |
+
h,
|
| 93 |
+
fr["people"][0],
|
| 94 |
+
conf_thresh_body=conf_thresh_body,
|
| 95 |
+
conf_thresh_hands=conf_thresh_hands,
|
| 96 |
+
conf_thresh_face=conf_thresh_face,
|
| 97 |
+
)
|
| 98 |
+
else:
|
| 99 |
+
img = np.zeros((h, w, 3), dtype=np.uint8)
|
| 100 |
+
frames_np.append(img)
|
| 101 |
+
|
| 102 |
+
frames_t = torch.from_numpy(np.stack(frames_np, axis=0)).float() / 255.0
|
| 103 |
+
return (frames_t, out_pose_data)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ============================================================
|
| 107 |
+
# PKL / pose_data IO
|
| 108 |
+
# ============================================================
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class _PoseDummyObj:
|
| 112 |
+
def __init__(self, *a, **k):
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
def __setstate__(self, state):
|
| 116 |
+
if isinstance(state, dict):
|
| 117 |
+
self.__dict__.update(state)
|
| 118 |
+
elif isinstance(state, (list, tuple)) and len(state) == 2 and isinstance(state[0], dict):
|
| 119 |
+
self.__dict__.update(state[0])
|
| 120 |
+
if isinstance(state[1], dict):
|
| 121 |
+
self.__dict__.update(state[1])
|
| 122 |
+
else:
|
| 123 |
+
self.__dict__["_slotstate"] = state[1]
|
| 124 |
+
else:
|
| 125 |
+
self.__dict__["_state"] = state
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class _SafeUnpickler(pickle.Unpickler):
|
| 129 |
+
def find_class(self, module, name):
|
| 130 |
+
if module.startswith("numpy._core"):
|
| 131 |
+
module = module.replace("numpy._core", "numpy.core", 1)
|
| 132 |
+
if module.startswith("numpy._globals"):
|
| 133 |
+
module = module.replace("numpy._globals", "numpy", 1)
|
| 134 |
+
if name in {"AAPoseMeta"}:
|
| 135 |
+
return _PoseDummyObj
|
| 136 |
+
try:
|
| 137 |
+
return super().find_class(module, name)
|
| 138 |
+
except Exception:
|
| 139 |
+
return _PoseDummyObj
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _load_pose_data_pkl(path: str) -> Any:
|
| 143 |
+
with open(path, "rb") as f:
|
| 144 |
+
return _SafeUnpickler(f).load()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _coerce_pose_data_to_obj(pd: Any) -> Any:
|
| 148 |
+
if isinstance(pd, str):
|
| 149 |
+
return _load_pose_data_pkl(pd)
|
| 150 |
+
if isinstance(pd, dict) and "pose_data" in pd:
|
| 151 |
+
return pd["pose_data"]
|
| 152 |
+
return pd
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _as_attr(x: Any, key: str, default=None):
|
| 156 |
+
if isinstance(x, dict):
|
| 157 |
+
return x.get(key, default)
|
| 158 |
+
return getattr(x, key, default)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _set_attr(x: Any, key: str, value: Any):
|
| 162 |
+
if isinstance(x, dict):
|
| 163 |
+
x[key] = value
|
| 164 |
+
else:
|
| 165 |
+
setattr(x, key, value)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _xy_p_to_flat(xy: Optional[np.ndarray], p: Optional[np.ndarray]) -> Optional[List[float]]:
|
| 169 |
+
if xy is None:
|
| 170 |
+
return None
|
| 171 |
+
arr = np.asarray(xy)
|
| 172 |
+
if arr.ndim != 2 or arr.shape[1] < 2:
|
| 173 |
+
return None
|
| 174 |
+
N = arr.shape[0]
|
| 175 |
+
if p is None:
|
| 176 |
+
pp = np.ones((N,), dtype=np.float32)
|
| 177 |
+
else:
|
| 178 |
+
pp = np.asarray(p).reshape(-1)
|
| 179 |
+
if pp.shape[0] != N:
|
| 180 |
+
pp = np.ones((N,), dtype=np.float32)
|
| 181 |
+
out: List[float] = []
|
| 182 |
+
for i in range(N):
|
| 183 |
+
out.extend([float(arr[i, 0]), float(arr[i, 1]), float(pp[i])])
|
| 184 |
+
return out
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _flat_to_xy_p(flat: Optional[List[float]]) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
|
| 188 |
+
if not isinstance(flat, list) or len(flat) % 3 != 0:
|
| 189 |
+
return None, None
|
| 190 |
+
N = len(flat) // 3
|
| 191 |
+
xy = np.zeros((N, 2), dtype=np.float32)
|
| 192 |
+
p = np.zeros((N,), dtype=np.float32)
|
| 193 |
+
for i in range(N):
|
| 194 |
+
xy[i, 0] = float(flat[3 * i + 0])
|
| 195 |
+
xy[i, 1] = float(flat[3 * i + 1])
|
| 196 |
+
p[i] = float(flat[3 * i + 2])
|
| 197 |
+
return xy, p
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _pose_data_to_kps_frames(pose_data: Any, *, force_body_18: bool) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
|
| 201 |
+
pose_metas = _as_attr(pose_data, "pose_metas", None)
|
| 202 |
+
if pose_metas is None:
|
| 203 |
+
pose_metas = _as_attr(pose_data, "frames", None)
|
| 204 |
+
if pose_metas is None or not isinstance(pose_metas, list):
|
| 205 |
+
raise ValueError("pose_data does not contain 'pose_metas' list.")
|
| 206 |
+
frames: List[Dict[str, Any]] = []
|
| 207 |
+
for meta in pose_metas:
|
| 208 |
+
h = _as_attr(meta, "height", 1280)
|
| 209 |
+
w = _as_attr(meta, "width", 720)
|
| 210 |
+
kps_body = _as_attr(meta, "kps_body", None)
|
| 211 |
+
kps_body_p = _as_attr(meta, "kps_body_p", None)
|
| 212 |
+
kps_face = _as_attr(meta, "kps_face", None)
|
| 213 |
+
kps_face_p = _as_attr(meta, "kps_face_p", None)
|
| 214 |
+
kps_lhand = _as_attr(meta, "kps_lhand", None)
|
| 215 |
+
kps_lhand_p = _as_attr(meta, "kps_lhand_p", None)
|
| 216 |
+
kps_rhand = _as_attr(meta, "kps_rhand", None)
|
| 217 |
+
kps_rhand_p = _as_attr(meta, "kps_rhand_p", None)
|
| 218 |
+
|
| 219 |
+
pose_flat = _xy_p_to_flat(kps_body, kps_body_p)
|
| 220 |
+
face_flat = _xy_p_to_flat(kps_face, kps_face_p)
|
| 221 |
+
lh_flat = _xy_p_to_flat(kps_lhand, kps_lhand_p)
|
| 222 |
+
rh_flat = _xy_p_to_flat(kps_rhand, kps_rhand_p)
|
| 223 |
+
|
| 224 |
+
if force_body_18 and isinstance(pose_flat, list) and len(pose_flat) >= 18 * 3:
|
| 225 |
+
pose_flat = pose_flat[: 18 * 3]
|
| 226 |
+
|
| 227 |
+
person = {
|
| 228 |
+
"pose_keypoints_2d": pose_flat if pose_flat is not None else [],
|
| 229 |
+
"face_keypoints_2d": face_flat if face_flat is not None else [],
|
| 230 |
+
"hand_left_keypoints_2d": lh_flat,
|
| 231 |
+
"hand_right_keypoints_2d": rh_flat,
|
| 232 |
+
}
|
| 233 |
+
frame = {"people": [person], "canvas_height": int(h), "canvas_width": int(w)}
|
| 234 |
+
frames.append(frame)
|
| 235 |
+
|
| 236 |
+
meta_ref = {"pose_metas": pose_metas, "len": len(pose_metas)}
|
| 237 |
+
return frames, meta_ref
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _kps_frames_to_pose_data(
|
| 241 |
+
pose_data_in: Any, frames_kps: List[Dict[str, Any]], meta_ref: Dict[str, Any], *, force_body_18: bool
|
| 242 |
+
) -> Any:
|
| 243 |
+
out_pd = copy.deepcopy(pose_data_in)
|
| 244 |
+
pose_metas_out = _as_attr(out_pd, "pose_metas", None)
|
| 245 |
+
if pose_metas_out is None:
|
| 246 |
+
pose_metas_out = meta_ref.get("pose_metas")
|
| 247 |
+
if pose_metas_out is None or not isinstance(pose_metas_out, list):
|
| 248 |
+
raise ValueError("Failed to locate pose_metas in output pose_data.")
|
| 249 |
+
|
| 250 |
+
T = min(len(pose_metas_out), len(frames_kps))
|
| 251 |
+
for t in range(T):
|
| 252 |
+
meta = pose_metas_out[t]
|
| 253 |
+
fr = frames_kps[t]
|
| 254 |
+
people = fr.get("people", []) if isinstance(fr, dict) else []
|
| 255 |
+
p0 = people[0] if people else None
|
| 256 |
+
if not isinstance(p0, dict):
|
| 257 |
+
continue
|
| 258 |
+
|
| 259 |
+
pose_flat = p0.get("pose_keypoints_2d")
|
| 260 |
+
face_flat = p0.get("face_keypoints_2d")
|
| 261 |
+
lh_flat = p0.get("hand_left_keypoints_2d")
|
| 262 |
+
rh_flat = p0.get("hand_right_keypoints_2d")
|
| 263 |
+
|
| 264 |
+
if force_body_18 and isinstance(pose_flat, list) and len(pose_flat) >= 18 * 3:
|
| 265 |
+
pose_flat = pose_flat[: 18 * 3]
|
| 266 |
+
|
| 267 |
+
body_xy, body_p = _flat_to_xy_p(pose_flat if isinstance(pose_flat, list) else None)
|
| 268 |
+
face_xy, face_p = _flat_to_xy_p(face_flat if isinstance(face_flat, list) else None)
|
| 269 |
+
lh_xy, lh_p = _flat_to_xy_p(lh_flat if isinstance(lh_flat, list) else None)
|
| 270 |
+
rh_xy, rh_p = _flat_to_xy_p(rh_flat if isinstance(rh_flat, list) else None)
|
| 271 |
+
|
| 272 |
+
if body_xy is not None and body_p is not None:
|
| 273 |
+
_set_attr(meta, "kps_body", body_xy.astype(np.float32, copy=False))
|
| 274 |
+
_set_attr(meta, "kps_body_p", body_p.astype(np.float32, copy=False))
|
| 275 |
+
if face_xy is not None and face_p is not None:
|
| 276 |
+
_set_attr(meta, "kps_face", face_xy.astype(np.float32, copy=False))
|
| 277 |
+
_set_attr(meta, "kps_face_p", face_p.astype(np.float32, copy=False))
|
| 278 |
+
if lh_xy is not None and lh_p is not None:
|
| 279 |
+
_set_attr(meta, "kps_lhand", lh_xy.astype(np.float32, copy=False))
|
| 280 |
+
_set_attr(meta, "kps_lhand_p", lh_p.astype(np.float32, copy=False))
|
| 281 |
+
if rh_xy is not None and rh_p is not None:
|
| 282 |
+
_set_attr(meta, "kps_rhand", rh_xy.astype(np.float32, copy=False))
|
| 283 |
+
_set_attr(meta, "kps_rhand_p", rh_p.astype(np.float32, copy=False))
|
| 284 |
+
|
| 285 |
+
if isinstance(fr, dict):
|
| 286 |
+
if "canvas_width" in fr:
|
| 287 |
+
_set_attr(meta, "width", int(fr["canvas_width"]))
|
| 288 |
+
if "canvas_height" in fr:
|
| 289 |
+
_set_attr(meta, "height", int(fr["canvas_height"]))
|
| 290 |
+
|
| 291 |
+
_set_attr(out_pd, "pose_metas", pose_metas_out)
|
| 292 |
+
return out_pd
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _extract_canvas_wh(data: Any, default_w: int, default_h: int) -> Tuple[int, int]:
|
| 296 |
+
w, h = int(default_w), int(default_h)
|
| 297 |
+
if isinstance(data, list):
|
| 298 |
+
for fr in data:
|
| 299 |
+
if isinstance(fr, dict) and "canvas_width" in fr and "canvas_height" in fr:
|
| 300 |
+
try:
|
| 301 |
+
w = int(fr["canvas_width"])
|
| 302 |
+
h = int(fr["canvas_height"])
|
| 303 |
+
break
|
| 304 |
+
except Exception:
|
| 305 |
+
pass
|
| 306 |
+
return w, h
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# ============================================================
|
| 310 |
+
# === START: smooth_KPS_json.py logic (ported as-is)
|
| 311 |
+
# ============================================================
|
| 312 |
+
|
| 313 |
+
ROOTSCALE_CARRY_ENABLED = True
|
| 314 |
+
CARRY_MAX_FRAMES = 48
|
| 315 |
+
CARRY_MIN_ANCHORS = 2
|
| 316 |
+
CARRY_ANCHOR_JOINTS = [0, 1, 2, 5, 3, 6, 4, 7]
|
| 317 |
+
CARRY_CONF_GATE = 0.20
|
| 318 |
+
|
| 319 |
+
FILTER_EXTRA_PEOPLE = True
|
| 320 |
+
MAIN_PERSON_MODE = "longest_track"
|
| 321 |
+
TRACK_MATCH_MIN_PX = 80.0
|
| 322 |
+
TRACK_MATCH_FACTOR = 3.0
|
| 323 |
+
TRACK_MAX_FRAME_GAP = 32
|
| 324 |
+
|
| 325 |
+
SPATIAL_OUTLIER_FIX = True
|
| 326 |
+
BONE_MAX_FACTOR = 2.3
|
| 327 |
+
TORSO_RADIUS_FACTOR = 4.0
|
| 328 |
+
|
| 329 |
+
ALPHA_BODY = 0.70
|
| 330 |
+
MAX_STEP_BODY = 60.0
|
| 331 |
+
VEL_ALPHA = 0.45
|
| 332 |
+
EPS = 0.3
|
| 333 |
+
CONF_GATE_BODY = 0.20
|
| 334 |
+
CONF_FLOOR_BODY = 0.00
|
| 335 |
+
|
| 336 |
+
TRACK_DIST_PENALTY = 1.5
|
| 337 |
+
FACE_WEIGHT_IN_SCORE = 0.15
|
| 338 |
+
HAND_WEIGHT_IN_SCORE = 0.35
|
| 339 |
+
|
| 340 |
+
ALLOW_DISAPPEAR_JOINTS = {3, 4, 6, 7}
|
| 341 |
+
|
| 342 |
+
GAP_FILL_ENABLED = True
|
| 343 |
+
MAX_GAP_FRAMES = 12
|
| 344 |
+
MIN_RUN_FRAMES = 2
|
| 345 |
+
|
| 346 |
+
TORSO_SYNC_ENABLED = True
|
| 347 |
+
TORSO_JOINTS = {1, 2, 5, 8, 11}
|
| 348 |
+
TORSO_LOOKAHEAD_FRAMES = 32
|
| 349 |
+
|
| 350 |
+
SUPER_SMOOTH_ENABLED = True
|
| 351 |
+
SUPER_SMOOTH_ALPHA = 0.7
|
| 352 |
+
SUPER_SMOOTH_MIN_CONF = 0.20
|
| 353 |
+
|
| 354 |
+
MEDIAN3_ENABLED = True
|
| 355 |
+
FACE_SMOOTH_ENABLED = True
|
| 356 |
+
HANDS_SMOOTH_ENABLED = False
|
| 357 |
+
|
| 358 |
+
CONF_GATE_FACE = 0.20
|
| 359 |
+
CONF_GATE_HAND = 0.50
|
| 360 |
+
|
| 361 |
+
HAND_MIN_POINTS_PRESENT = 7
|
| 362 |
+
MIN_HAND_RUN_FRAMES = 6
|
| 363 |
+
|
| 364 |
+
DENSE_GAP_FILL_ENABLED = False
|
| 365 |
+
DENSE_MAX_GAP_FRAMES = 8
|
| 366 |
+
DENSE_MIN_RUN_FRAMES = 2
|
| 367 |
+
DENSE_MEDIAN3_ENABLED = False
|
| 368 |
+
DENSE_SUPER_SMOOTH_ENABLED = False
|
| 369 |
+
DENSE_SUPER_SMOOTH_ALPHA = 0.7
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _snapshot_tunable_globals() -> Dict[str, Any]:
|
| 373 |
+
keys = [
|
| 374 |
+
"FILTER_EXTRA_PEOPLE",
|
| 375 |
+
"SUPER_SMOOTH_ALPHA",
|
| 376 |
+
"MAX_GAP_FRAMES",
|
| 377 |
+
"MIN_RUN_FRAMES",
|
| 378 |
+
"DENSE_SUPER_SMOOTH_ALPHA",
|
| 379 |
+
"DENSE_MAX_GAP_FRAMES",
|
| 380 |
+
"DENSE_MIN_RUN_FRAMES",
|
| 381 |
+
"ALPHA_BODY",
|
| 382 |
+
"CONF_GATE_BODY",
|
| 383 |
+
"CONF_GATE_HAND",
|
| 384 |
+
"CONF_GATE_FACE",
|
| 385 |
+
]
|
| 386 |
+
return {k: globals().get(k) for k in keys}
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _restore_tunable_globals(old: Dict[str, Any]) -> None:
|
| 390 |
+
for k, v in old.items():
|
| 391 |
+
globals()[k] = v
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _is_valid_xyc(x: float, y: float, c: float) -> bool:
|
| 395 |
+
if c is None or c <= 0:
|
| 396 |
+
return False
|
| 397 |
+
if x == 0 and y == 0:
|
| 398 |
+
return False
|
| 399 |
+
if math.isnan(x) or math.isnan(y) or math.isnan(c):
|
| 400 |
+
return False
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _reshape_keypoints_2d(arr: List[float]) -> List[Tuple[float, float, float]]:
|
| 405 |
+
if arr is None:
|
| 406 |
+
return []
|
| 407 |
+
out = []
|
| 408 |
+
for i in range(0, len(arr), 3):
|
| 409 |
+
out.append((float(arr[i]), float(arr[i + 1]), float(arr[i + 2])))
|
| 410 |
+
return out
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _flatten_keypoints_2d(kps: List[Tuple[float, float, float]]) -> List[float]:
|
| 414 |
+
out: List[float] = []
|
| 415 |
+
for x, y, c in kps:
|
| 416 |
+
out.extend([float(x), float(y), float(c)])
|
| 417 |
+
return out
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _sum_conf(arr: Optional[List[float]], sample_step: int = 1) -> float:
|
| 421 |
+
if not arr:
|
| 422 |
+
return 0.0
|
| 423 |
+
s = 0.0
|
| 424 |
+
for i in range(2, len(arr), 3 * sample_step):
|
| 425 |
+
try:
|
| 426 |
+
c = float(arr[i])
|
| 427 |
+
except Exception:
|
| 428 |
+
c = 0.0
|
| 429 |
+
if c > 0:
|
| 430 |
+
s += c
|
| 431 |
+
return s
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _body_center_from_pose(pose_arr: Optional[List[float]]) -> Optional[Tuple[float, float]]:
|
| 435 |
+
if not pose_arr:
|
| 436 |
+
return None
|
| 437 |
+
kps = _reshape_keypoints_2d(pose_arr)
|
| 438 |
+
idxs = [2, 5, 8, 11, 1]
|
| 439 |
+
pts = []
|
| 440 |
+
for idx in idxs:
|
| 441 |
+
if idx < len(kps) and _is_valid_xyc(*kps[idx]):
|
| 442 |
+
pts.append((kps[idx][0], kps[idx][1]))
|
| 443 |
+
if not pts:
|
| 444 |
+
for x, y, c in kps:
|
| 445 |
+
if _is_valid_xyc(x, y, c):
|
| 446 |
+
pts.append((x, y))
|
| 447 |
+
if not pts:
|
| 448 |
+
return None
|
| 449 |
+
return (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _dist(a: Tuple[float, float], b: Tuple[float, float]) -> float:
|
| 453 |
+
return math.hypot(a[0] - b[0], a[1] - b[1])
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _choose_single_person(
|
| 457 |
+
people: List[Dict[str, Any]], prev_center: Optional[Tuple[float, float]]
|
| 458 |
+
) -> Optional[Dict[str, Any]]:
|
| 459 |
+
if not people:
|
| 460 |
+
return None
|
| 461 |
+
best = None
|
| 462 |
+
best_score = -1e18
|
| 463 |
+
for p in people:
|
| 464 |
+
pose = p.get("pose_keypoints_2d")
|
| 465 |
+
score = _sum_conf(pose)
|
| 466 |
+
score += FACE_WEIGHT_IN_SCORE * _sum_conf(p.get("face_keypoints_2d"), 4)
|
| 467 |
+
score += HAND_WEIGHT_IN_SCORE * (
|
| 468 |
+
_sum_conf(p.get("hand_left_keypoints_2d"), 2) + _sum_conf(p.get("hand_right_keypoints_2d"), 2)
|
| 469 |
+
)
|
| 470 |
+
center = _body_center_from_pose(pose)
|
| 471 |
+
if prev_center is not None and center is not None:
|
| 472 |
+
score -= TRACK_DIST_PENALTY * _dist(prev_center, center)
|
| 473 |
+
if score > best_score:
|
| 474 |
+
best_score = score
|
| 475 |
+
best = p
|
| 476 |
+
return best
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@dataclass
|
| 480 |
+
class _Track:
|
| 481 |
+
frames: Dict[int, Dict[str, Any]]
|
| 482 |
+
centers: Dict[int, Tuple[float, float]]
|
| 483 |
+
last_t: int
|
| 484 |
+
last_center: Tuple[float, float]
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _estimate_torso_scale(pose: List[Tuple[float, float, float]]) -> Optional[float]:
|
| 488 |
+
def dist(i, k):
|
| 489 |
+
if i >= len(pose) or k >= len(pose):
|
| 490 |
+
return None
|
| 491 |
+
if not _is_valid_xyc(*pose[i]) or not _is_valid_xyc(*pose[k]):
|
| 492 |
+
return None
|
| 493 |
+
return math.hypot(pose[i][0] - pose[k][0], pose[i][1] - pose[k][1])
|
| 494 |
+
|
| 495 |
+
cand = [c for c in [dist(2, 5), dist(8, 11), dist(1, 8), dist(1, 11)] if c is not None and c > 1e-3]
|
| 496 |
+
if not cand:
|
| 497 |
+
return None
|
| 498 |
+
return float(sum(cand) / len(cand))
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def _track_match_threshold_from_pose(pose_arr: Optional[List[float]]) -> float:
|
| 502 |
+
if isinstance(pose_arr, list):
|
| 503 |
+
s = _estimate_torso_scale(_reshape_keypoints_2d(pose_arr))
|
| 504 |
+
if s is not None:
|
| 505 |
+
return max(float(TRACK_MATCH_MIN_PX), float(TRACK_MATCH_FACTOR) * float(s))
|
| 506 |
+
return float(max(TRACK_MATCH_MIN_PX, 120.0))
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _build_tracks_over_video(frames_data: List[Any]) -> List[_Track]:
|
| 510 |
+
tracks: List[_Track] = []
|
| 511 |
+
for t, frame in enumerate(frames_data):
|
| 512 |
+
if not isinstance(frame, dict):
|
| 513 |
+
continue
|
| 514 |
+
people = frame.get("people", [])
|
| 515 |
+
if not isinstance(people, list) or not people:
|
| 516 |
+
continue
|
| 517 |
+
|
| 518 |
+
cand = []
|
| 519 |
+
for i, p in enumerate(people):
|
| 520 |
+
if not isinstance(p, dict):
|
| 521 |
+
continue
|
| 522 |
+
c = _body_center_from_pose(p.get("pose_keypoints_2d"))
|
| 523 |
+
if c is not None:
|
| 524 |
+
cand.append((i, p, c))
|
| 525 |
+
if not cand:
|
| 526 |
+
continue
|
| 527 |
+
|
| 528 |
+
used = set()
|
| 529 |
+
track_order = sorted(range(len(tracks)), key=lambda k: tracks[k].last_t, reverse=True)
|
| 530 |
+
for k in track_order:
|
| 531 |
+
tr = tracks[k]
|
| 532 |
+
if (t - tr.last_t) > int(TRACK_MAX_FRAME_GAP):
|
| 533 |
+
continue
|
| 534 |
+
best_idx, best_d = None, 1e18
|
| 535 |
+
for i, p, cc in cand:
|
| 536 |
+
if i in used:
|
| 537 |
+
continue
|
| 538 |
+
thr = _track_match_threshold_from_pose(p.get("pose_keypoints_2d"))
|
| 539 |
+
d = _dist(tr.last_center, cc)
|
| 540 |
+
if d <= thr and d < best_d:
|
| 541 |
+
best_d = d
|
| 542 |
+
best_idx = i
|
| 543 |
+
if best_idx is not None:
|
| 544 |
+
i, p, cc = next(x for x in cand if x[0] == best_idx)
|
| 545 |
+
used.add(i)
|
| 546 |
+
tr.frames[t], tr.centers[t], tr.last_t, tr.last_center = p, cc, t, cc
|
| 547 |
+
for i, p, cc in cand:
|
| 548 |
+
if i not in used:
|
| 549 |
+
tracks.append(_Track(frames={t: p}, centers={t: cc}, last_t=t, last_center=cc))
|
| 550 |
+
return tracks
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def _track_presence_score(tr: _Track) -> Tuple[int, float, float]:
|
| 554 |
+
face_sum, body_sum = 0.0, 0.0
|
| 555 |
+
for p in tr.frames.values():
|
| 556 |
+
face_sum += _sum_conf(p.get("face_keypoints_2d"), 4)
|
| 557 |
+
body_sum += _sum_conf(p.get("pose_keypoints_2d"), 1)
|
| 558 |
+
return (len(tr.frames), face_sum, body_sum)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _pick_main_track(tracks: List[_Track]) -> Optional[_Track]:
|
| 562 |
+
if not tracks:
|
| 563 |
+
return None
|
| 564 |
+
best, best_key = None, (-1, -1e18, -1e18)
|
| 565 |
+
for tr in tracks:
|
| 566 |
+
key = _track_presence_score(tr)
|
| 567 |
+
if key > best_key:
|
| 568 |
+
best_key, best = key, tr
|
| 569 |
+
return best
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
@dataclass
|
| 573 |
+
class BodyState:
|
| 574 |
+
last_xy: List[Optional[Tuple[float, float]]]
|
| 575 |
+
last_v: List[Tuple[float, float]]
|
| 576 |
+
|
| 577 |
+
def __init__(self, joints: int):
|
| 578 |
+
self.last_xy = [None] * joints
|
| 579 |
+
self.last_v = [(0.0, 0.0)] * joints
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _smooth_body_pose(pose_arr: Optional[List[float]], state: BodyState) -> Optional[List[float]]:
|
| 583 |
+
if pose_arr is None:
|
| 584 |
+
return None
|
| 585 |
+
kps = _reshape_keypoints_2d(pose_arr)
|
| 586 |
+
J = len(kps)
|
| 587 |
+
if len(state.last_xy) != J:
|
| 588 |
+
state.last_xy = [None] * J
|
| 589 |
+
state.last_v = [(0.0, 0.0)] * J
|
| 590 |
+
|
| 591 |
+
out: List[Tuple[float, float, float]] = []
|
| 592 |
+
for j in range(J):
|
| 593 |
+
x, y, c = kps[j]
|
| 594 |
+
last = state.last_xy[j]
|
| 595 |
+
vx_last, vy_last = state.last_v[j]
|
| 596 |
+
valid_in = _is_valid_xyc(x, y, c) and (c >= CONF_GATE_BODY)
|
| 597 |
+
|
| 598 |
+
if valid_in:
|
| 599 |
+
if last is None:
|
| 600 |
+
state.last_xy[j] = (x, y)
|
| 601 |
+
state.last_v[j] = (0.0, 0.0)
|
| 602 |
+
out.append((x, y, float(c)))
|
| 603 |
+
continue
|
| 604 |
+
|
| 605 |
+
dx_raw, dy_raw = x - last[0], y - last[1]
|
| 606 |
+
if abs(dx_raw) < EPS:
|
| 607 |
+
dx_raw = 0.0
|
| 608 |
+
if abs(dy_raw) < EPS:
|
| 609 |
+
dy_raw = 0.0
|
| 610 |
+
|
| 611 |
+
vx = VEL_ALPHA * dx_raw + (1.0 - VEL_ALPHA) * vx_last
|
| 612 |
+
vy = VEL_ALPHA * dy_raw + (1.0 - VEL_ALPHA) * vy_last
|
| 613 |
+
nx = ALPHA_BODY * x + (1.0 - ALPHA_BODY) * (last[0] + vx)
|
| 614 |
+
ny = ALPHA_BODY * y + (1.0 - ALPHA_BODY) * (last[1] + vy)
|
| 615 |
+
|
| 616 |
+
d = math.hypot(nx - last[0], ny - last[1])
|
| 617 |
+
if d > MAX_STEP_BODY and d > 1e-6:
|
| 618 |
+
scale = MAX_STEP_BODY / d
|
| 619 |
+
nx = last[0] + (nx - last[0]) * scale
|
| 620 |
+
ny = last[1] + (ny - last[1]) * scale
|
| 621 |
+
vx, vy = nx - last[0], ny - last[1]
|
| 622 |
+
|
| 623 |
+
state.last_xy[j], state.last_v[j] = (nx, ny), (vx, vy)
|
| 624 |
+
out.append((nx, ny, float(c)))
|
| 625 |
+
else:
|
| 626 |
+
state.last_xy[j] = None
|
| 627 |
+
state.last_v[j] = (0.0, 0.0)
|
| 628 |
+
out.append((0.0, 0.0, 0.0))
|
| 629 |
+
|
| 630 |
+
return _flatten_keypoints_2d(out)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
COCO18_EDGES = [
|
| 634 |
+
(1, 2),
|
| 635 |
+
(2, 3),
|
| 636 |
+
(3, 4),
|
| 637 |
+
(1, 5),
|
| 638 |
+
(5, 6),
|
| 639 |
+
(6, 7),
|
| 640 |
+
(1, 8),
|
| 641 |
+
(8, 9),
|
| 642 |
+
(9, 10),
|
| 643 |
+
(1, 11),
|
| 644 |
+
(11, 12),
|
| 645 |
+
(12, 13),
|
| 646 |
+
(8, 11),
|
| 647 |
+
(1, 0),
|
| 648 |
+
(0, 14),
|
| 649 |
+
(14, 16),
|
| 650 |
+
(0, 15),
|
| 651 |
+
(15, 17),
|
| 652 |
+
]
|
| 653 |
+
HAND21_EDGES = [
|
| 654 |
+
(0, 1),
|
| 655 |
+
(1, 2),
|
| 656 |
+
(2, 3),
|
| 657 |
+
(3, 4),
|
| 658 |
+
(0, 5),
|
| 659 |
+
(5, 6),
|
| 660 |
+
(6, 7),
|
| 661 |
+
(7, 8),
|
| 662 |
+
(0, 9),
|
| 663 |
+
(9, 10),
|
| 664 |
+
(10, 11),
|
| 665 |
+
(11, 12),
|
| 666 |
+
(0, 13),
|
| 667 |
+
(13, 14),
|
| 668 |
+
(14, 15),
|
| 669 |
+
(15, 16),
|
| 670 |
+
(0, 17),
|
| 671 |
+
(17, 18),
|
| 672 |
+
(18, 19),
|
| 673 |
+
(19, 20),
|
| 674 |
+
]
|
| 675 |
+
|
| 676 |
+
_NEIGHBORS = None
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _build_neighbors():
|
| 680 |
+
global _NEIGHBORS
|
| 681 |
+
if _NEIGHBORS is not None:
|
| 682 |
+
return
|
| 683 |
+
_NEIGHBORS = {}
|
| 684 |
+
for a, b in COCO18_EDGES:
|
| 685 |
+
_NEIGHBORS.setdefault(a, set()).add(b)
|
| 686 |
+
_NEIGHBORS.setdefault(b, set()).add(a)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def _suppress_spatial_outliers_in_pose_arr(
|
| 690 |
+
pose_arr: Optional[List[float]], *, conf_gate: float
|
| 691 |
+
) -> Optional[List[float]]:
|
| 692 |
+
if not isinstance(pose_arr, list) or len(pose_arr) % 3 != 0:
|
| 693 |
+
return pose_arr
|
| 694 |
+
pose = _reshape_keypoints_2d(pose_arr)
|
| 695 |
+
J = len(pose)
|
| 696 |
+
center = _body_center_from_pose(pose_arr)
|
| 697 |
+
scale = _estimate_torso_scale(pose)
|
| 698 |
+
if center is None or scale is None:
|
| 699 |
+
return pose_arr
|
| 700 |
+
|
| 701 |
+
max_r, max_bone = TORSO_RADIUS_FACTOR * scale, BONE_MAX_FACTOR * scale
|
| 702 |
+
out = [list(p) for p in pose]
|
| 703 |
+
|
| 704 |
+
def visible(j):
|
| 705 |
+
return j < J and out[j][2] >= conf_gate and not (out[j][0] == 0 and out[j][1] == 0)
|
| 706 |
+
|
| 707 |
+
for j in range(J):
|
| 708 |
+
if visible(j) and math.hypot(out[j][0] - center[0], out[j][1] - center[1]) > max_r:
|
| 709 |
+
out[j] = [0.0, 0.0, 0.0]
|
| 710 |
+
|
| 711 |
+
for a, b in COCO18_EDGES:
|
| 712 |
+
if a >= J or b >= J:
|
| 713 |
+
continue
|
| 714 |
+
if not visible(a) or not visible(b):
|
| 715 |
+
continue
|
| 716 |
+
if math.hypot(out[a][0] - out[b][0], out[a][1] - out[b][1]) > max_bone:
|
| 717 |
+
if out[a][2] <= out[b][2]:
|
| 718 |
+
out[a] = [0.0, 0.0, 0.0]
|
| 719 |
+
else:
|
| 720 |
+
out[b] = [0.0, 0.0, 0.0]
|
| 721 |
+
|
| 722 |
+
flat = []
|
| 723 |
+
for p in out:
|
| 724 |
+
flat.extend(p)
|
| 725 |
+
return flat
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def _suppress_isolated_joints_in_pose_arr(
|
| 729 |
+
pose_arr: Optional[List[float]], *, conf_gate: float, keep: set[int] = None
|
| 730 |
+
) -> Optional[List[float]]:
|
| 731 |
+
if not isinstance(pose_arr, list) or len(pose_arr) % 3 != 0:
|
| 732 |
+
return pose_arr
|
| 733 |
+
_build_neighbors()
|
| 734 |
+
pose = _reshape_keypoints_2d(pose_arr)
|
| 735 |
+
J, out = len(pose), [list(p) for p in pose]
|
| 736 |
+
keep = keep or set()
|
| 737 |
+
|
| 738 |
+
def vis(j):
|
| 739 |
+
return j < J and out[j][2] >= conf_gate and not (out[j][0] == 0 and out[j][1] == 0)
|
| 740 |
+
|
| 741 |
+
for j in range(J):
|
| 742 |
+
if j in keep or not vis(j):
|
| 743 |
+
continue
|
| 744 |
+
if not any(n < J and vis(n) for n in _NEIGHBORS.get(j, set())):
|
| 745 |
+
out[j] = [0.0, 0.0, 0.0]
|
| 746 |
+
|
| 747 |
+
flat = []
|
| 748 |
+
for p in out:
|
| 749 |
+
flat.extend(p)
|
| 750 |
+
return flat
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def _denoise_and_fill_gaps_pose_seq(
|
| 754 |
+
pose_arr_seq: List[Optional[List[float]]], *, conf_gate: float, min_run: int, max_gap: int
|
| 755 |
+
) -> List[Optional[List[float]]]:
|
| 756 |
+
if not pose_arr_seq:
|
| 757 |
+
return pose_arr_seq
|
| 758 |
+
J = next(
|
| 759 |
+
(len(arr) // 3 for arr in pose_arr_seq if isinstance(arr, list) and len(arr) % 3 == 0 and len(arr) > 0), None
|
| 760 |
+
)
|
| 761 |
+
if J is None:
|
| 762 |
+
return pose_arr_seq
|
| 763 |
+
T = len(pose_arr_seq)
|
| 764 |
+
out_seq = [list(arr) if isinstance(arr, list) and len(arr) == J * 3 else arr for arr in pose_arr_seq]
|
| 765 |
+
|
| 766 |
+
def is_vis(arr, j):
|
| 767 |
+
return float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j + 0]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 768 |
+
|
| 769 |
+
for j in range(J):
|
| 770 |
+
start = None
|
| 771 |
+
for t in range(T + 1):
|
| 772 |
+
cur = t < T and isinstance(out_seq[t], list) and is_vis(out_seq[t], j)
|
| 773 |
+
if cur and start is None:
|
| 774 |
+
start = t
|
| 775 |
+
if not cur and start is not None:
|
| 776 |
+
if (t - start) < min_run:
|
| 777 |
+
for k in range(start, t):
|
| 778 |
+
if isinstance(out_seq[k], list):
|
| 779 |
+
out_seq[k][3 * j : 3 * j + 3] = [0.0, 0.0, 0.0]
|
| 780 |
+
start = None
|
| 781 |
+
|
| 782 |
+
for j in range(J):
|
| 783 |
+
t = 0
|
| 784 |
+
while t < T:
|
| 785 |
+
arr = out_seq[t]
|
| 786 |
+
if isinstance(arr, list) and is_vis(arr, j):
|
| 787 |
+
last_vis_t = t
|
| 788 |
+
t += 1
|
| 789 |
+
while t < T:
|
| 790 |
+
if isinstance(out_seq[t], list) and is_vis(out_seq[t], j):
|
| 791 |
+
break
|
| 792 |
+
t += 1
|
| 793 |
+
if t < T and (t - last_vis_t - 1) > 0 and (t - last_vis_t - 1) <= max_gap:
|
| 794 |
+
a, b = out_seq[last_vis_t], out_seq[t]
|
| 795 |
+
ax, ay, ac = float(a[3 * j]), float(a[3 * j + 1]), float(a[3 * j + 2])
|
| 796 |
+
bx, by, bc = float(b[3 * j]), float(b[3 * j + 1]), float(b[3 * j + 2])
|
| 797 |
+
for k in range(last_vis_t + 1, t):
|
| 798 |
+
if isinstance(out_seq[k], list):
|
| 799 |
+
r = (k - last_vis_t) / (t - last_vis_t)
|
| 800 |
+
out_seq[k][3 * j : 3 * j + 3] = [ax + (bx - ax) * r, ay + (by - ay) * r, min(ac, bc)]
|
| 801 |
+
else:
|
| 802 |
+
t += 1
|
| 803 |
+
return out_seq
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def _zero_lag_ema_pose_seq(
|
| 807 |
+
pose_seq: List[Optional[List[float]]], *, alpha: float, conf_gate: float
|
| 808 |
+
) -> List[Optional[List[float]]]:
|
| 809 |
+
if not pose_seq:
|
| 810 |
+
return pose_seq
|
| 811 |
+
J = next((len(arr) // 3 for arr in pose_seq if isinstance(arr, list) and len(arr) % 3 == 0 and len(arr) > 0), None)
|
| 812 |
+
if J is None:
|
| 813 |
+
return pose_seq
|
| 814 |
+
T = len(pose_seq)
|
| 815 |
+
|
| 816 |
+
def is_vis(arr, j):
|
| 817 |
+
return float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j + 0]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 818 |
+
|
| 819 |
+
fwd, last = [None] * T, [None] * J
|
| 820 |
+
for t in range(T):
|
| 821 |
+
if not isinstance(pose_seq[t], list) or len(pose_seq[t]) != J * 3:
|
| 822 |
+
fwd[t] = pose_seq[t]
|
| 823 |
+
continue
|
| 824 |
+
out = list(pose_seq[t])
|
| 825 |
+
for j in range(J):
|
| 826 |
+
if is_vis(pose_seq[t], j):
|
| 827 |
+
x, y = float(pose_seq[t][3 * j]), float(pose_seq[t][3 * j + 1])
|
| 828 |
+
sx, sy = (
|
| 829 |
+
(x, y)
|
| 830 |
+
if last[j] is None
|
| 831 |
+
else (alpha * x + (1 - alpha) * last[j][0], alpha * y + (1 - alpha) * last[j][1])
|
| 832 |
+
)
|
| 833 |
+
last[j], out[3 * j], out[3 * j + 1] = (sx, sy), float(sx), float(sy)
|
| 834 |
+
else:
|
| 835 |
+
last[j] = None
|
| 836 |
+
fwd[t] = out
|
| 837 |
+
|
| 838 |
+
bwd, last = [None] * T, [None] * J
|
| 839 |
+
for t in range(T - 1, -1, -1):
|
| 840 |
+
if not isinstance(fwd[t], list) or len(fwd[t]) != J * 3:
|
| 841 |
+
bwd[t] = fwd[t]
|
| 842 |
+
continue
|
| 843 |
+
out = list(fwd[t])
|
| 844 |
+
for j in range(J):
|
| 845 |
+
if is_vis(fwd[t], j):
|
| 846 |
+
x, y = float(fwd[t][3 * j]), float(fwd[t][3 * j + 1])
|
| 847 |
+
sx, sy = (
|
| 848 |
+
(x, y)
|
| 849 |
+
if last[j] is None
|
| 850 |
+
else (alpha * x + (1 - alpha) * last[j][0], alpha * y + (1 - alpha) * last[j][1])
|
| 851 |
+
)
|
| 852 |
+
last[j], out[3 * j], out[3 * j + 1] = (sx, sy), float(sx), float(sy)
|
| 853 |
+
else:
|
| 854 |
+
last[j] = None
|
| 855 |
+
bwd[t] = out
|
| 856 |
+
return bwd
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def _apply_root_scale(
|
| 860 |
+
pose_arr: Optional[List[float]], *, src_root, src_scale, dst_root, dst_scale
|
| 861 |
+
) -> Optional[List[float]]:
|
| 862 |
+
if not isinstance(pose_arr, list) or len(pose_arr) % 3 != 0 or src_scale <= 1e-6 or dst_scale <= 1e-6:
|
| 863 |
+
return pose_arr
|
| 864 |
+
kps = _reshape_keypoints_2d(pose_arr)
|
| 865 |
+
s = dst_scale / src_scale
|
| 866 |
+
out = [
|
| 867 |
+
(
|
| 868 |
+
(dst_root[0] + (x - src_root[0]) * s, dst_root[1] + (y - src_root[1]) * s, c)
|
| 869 |
+
if c > 0 and not (x == 0 and y == 0)
|
| 870 |
+
else (x, y, c)
|
| 871 |
+
)
|
| 872 |
+
for x, y, c in kps
|
| 873 |
+
]
|
| 874 |
+
return _flatten_keypoints_2d(out)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def _carry_pose_when_torso_missing(
|
| 878 |
+
pose_seq: List[Optional[List[float]]], *, conf_gate, max_carry, anchor_joints, min_anchors
|
| 879 |
+
) -> List[Optional[List[float]]]:
|
| 880 |
+
if not pose_seq:
|
| 881 |
+
return pose_seq
|
| 882 |
+
J = next((len(a) // 3 for a in pose_seq if isinstance(a, list) and len(a) % 3 == 0 and len(a) > 0), None)
|
| 883 |
+
if J is None:
|
| 884 |
+
return pose_seq
|
| 885 |
+
out = [a if a is None else list(a) for a in pose_seq]
|
| 886 |
+
FILL = {1, 8, 9, 10, 11, 12, 13} - set(ALLOW_DISAPPEAR_JOINTS)
|
| 887 |
+
|
| 888 |
+
def is_vis(arr, j):
|
| 889 |
+
return float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 890 |
+
|
| 891 |
+
def rs_anchors(arr):
|
| 892 |
+
pts = [(float(arr[3 * j]), float(arr[3 * j + 1])) for j in anchor_joints if j < J and is_vis(arr, j)]
|
| 893 |
+
if len(pts) < min_anchors:
|
| 894 |
+
return None
|
| 895 |
+
xs, ys = [p[0] for p in pts], [p[1] for p in pts]
|
| 896 |
+
s = max(max(xs) - min(xs), max(ys) - min(ys))
|
| 897 |
+
if s <= 1e-3:
|
| 898 |
+
return None
|
| 899 |
+
return (sum(xs) / len(pts), sum(ys) / len(pts)), float(s)
|
| 900 |
+
|
| 901 |
+
last_good, last_rs, carry = None, None, 0
|
| 902 |
+
for t, arr in enumerate(out):
|
| 903 |
+
if not isinstance(arr, list) or len(arr) != J * 3:
|
| 904 |
+
continue
|
| 905 |
+
rs = rs_anchors(arr)
|
| 906 |
+
if (
|
| 907 |
+
sum(1 for j in anchor_joints if j < J and is_vis(arr, j)) >= min_anchors
|
| 908 |
+
and rs
|
| 909 |
+
and sum(1 for j in FILL if j < J and is_vis(arr, j)) >= 2
|
| 910 |
+
):
|
| 911 |
+
last_good, last_rs, carry = list(arr), rs, max_carry
|
| 912 |
+
continue
|
| 913 |
+
if rs and last_good and last_rs and carry > 0:
|
| 914 |
+
carried = _apply_root_scale(
|
| 915 |
+
last_good, src_root=last_rs[0], src_scale=last_rs[1], dst_root=rs[0], dst_scale=rs[1]
|
| 916 |
+
)
|
| 917 |
+
if isinstance(carried, list) and len(carried) == J * 3:
|
| 918 |
+
for j in FILL:
|
| 919 |
+
if (
|
| 920 |
+
j < J
|
| 921 |
+
and not is_vis(arr, j)
|
| 922 |
+
and (float(carried[3 * j]) != 0 or float(carried[3 * j + 1]) != 0)
|
| 923 |
+
and float(carried[3 * j + 2]) > 0
|
| 924 |
+
):
|
| 925 |
+
arr[3 * j : 3 * j + 3] = [
|
| 926 |
+
float(carried[3 * j]),
|
| 927 |
+
float(carried[3 * j + 1]),
|
| 928 |
+
max(min(float(carried[3 * j + 2]), 0.60), conf_gate),
|
| 929 |
+
]
|
| 930 |
+
out[t], carry = arr, carry - 1
|
| 931 |
+
continue
|
| 932 |
+
carry = max(carry - 1, 0)
|
| 933 |
+
return out
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def _force_full_torso_pair(
|
| 937 |
+
pose_seq: List[Optional[List[float]]],
|
| 938 |
+
*,
|
| 939 |
+
conf_gate,
|
| 940 |
+
anchor_joints,
|
| 941 |
+
min_anchors,
|
| 942 |
+
max_lookback=240,
|
| 943 |
+
fill_legs_with_hip=True,
|
| 944 |
+
always_fill_if_one_hip=True,
|
| 945 |
+
) -> List[Optional[List[float]]]:
|
| 946 |
+
if not pose_seq:
|
| 947 |
+
return pose_seq
|
| 948 |
+
J = next((len(a) // 3 for a in pose_seq if isinstance(a, list) and len(a) % 3 == 0 and len(a) > 0), None)
|
| 949 |
+
if J is None:
|
| 950 |
+
return pose_seq
|
| 951 |
+
out = [a if a is None else list(a) for a in pose_seq]
|
| 952 |
+
|
| 953 |
+
def is_vis(arr, j):
|
| 954 |
+
return (
|
| 955 |
+
j < J and float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
def rs_anchors(arr):
|
| 959 |
+
pts = [(float(arr[3 * j]), float(arr[3 * j + 1])) for j in anchor_joints if j < J and is_vis(arr, j)]
|
| 960 |
+
if len(pts) < min_anchors:
|
| 961 |
+
return None
|
| 962 |
+
xs, ys = [p[0] for p in pts], [p[1] for p in pts]
|
| 963 |
+
s = max(max(xs) - min(xs), max(ys) - min(ys))
|
| 964 |
+
return ((sum(xs) / len(pts), sum(ys) / len(pts)), float(s)) if s > 1e-3 else None
|
| 965 |
+
|
| 966 |
+
last_idx, last_f, last_rs = None, None, None
|
| 967 |
+
for t, arr in enumerate(out):
|
| 968 |
+
if not isinstance(arr, list) or len(arr) != J * 3:
|
| 969 |
+
continue
|
| 970 |
+
rs = rs_anchors(arr)
|
| 971 |
+
r_ok, l_ok = is_vis(arr, 8), is_vis(arr, 11)
|
| 972 |
+
if rs and sum(1 for j in anchor_joints if is_vis(arr, j)) >= min_anchors and r_ok and l_ok:
|
| 973 |
+
last_idx, last_f, last_rs = t, list(arr), rs
|
| 974 |
+
continue
|
| 975 |
+
if (
|
| 976 |
+
not last_f
|
| 977 |
+
or not last_rs
|
| 978 |
+
or (t - last_idx) > max_lookback
|
| 979 |
+
or not rs
|
| 980 |
+
or (r_ok and l_ok)
|
| 981 |
+
or (not r_ok and not l_ok and not always_fill_if_one_hip)
|
| 982 |
+
):
|
| 983 |
+
continue
|
| 984 |
+
carried = _apply_root_scale(last_f, src_root=last_rs[0], src_scale=last_rs[1], dst_root=rs[0], dst_scale=rs[1])
|
| 985 |
+
if not isinstance(carried, list) or len(carried) != J * 3:
|
| 986 |
+
continue
|
| 987 |
+
|
| 988 |
+
def cp(j):
|
| 989 |
+
if (
|
| 990 |
+
j < J
|
| 991 |
+
and not is_vis(arr, j)
|
| 992 |
+
and (float(carried[3 * j]) != 0 or float(carried[3 * j + 1]) != 0)
|
| 993 |
+
and float(carried[3 * j + 2]) > 0
|
| 994 |
+
):
|
| 995 |
+
arr[3 * j : 3 * j + 3] = [
|
| 996 |
+
float(carried[3 * j]),
|
| 997 |
+
float(carried[3 * j + 1]),
|
| 998 |
+
max(min(float(carried[3 * j + 2]), 0.60), conf_gate),
|
| 999 |
+
]
|
| 1000 |
+
|
| 1001 |
+
if not r_ok:
|
| 1002 |
+
cp(8)
|
| 1003 |
+
if fill_legs_with_hip:
|
| 1004 |
+
cp(9)
|
| 1005 |
+
cp(10)
|
| 1006 |
+
if not l_ok:
|
| 1007 |
+
cp(11)
|
| 1008 |
+
if fill_legs_with_hip:
|
| 1009 |
+
cp(12)
|
| 1010 |
+
cp(13)
|
| 1011 |
+
out[t] = arr
|
| 1012 |
+
return out
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def _median3_pose_seq(pose_seq: List[Optional[List[float]]], *, conf_gate: float) -> List[Optional[List[float]]]:
|
| 1016 |
+
if not pose_seq:
|
| 1017 |
+
return pose_seq
|
| 1018 |
+
J = next((len(a) // 3 for a in pose_seq if isinstance(a, list) and len(a) % 3 == 0 and len(a) > 0), None)
|
| 1019 |
+
if J is None:
|
| 1020 |
+
return pose_seq
|
| 1021 |
+
T = len(pose_seq)
|
| 1022 |
+
|
| 1023 |
+
def is_vis(arr, j):
|
| 1024 |
+
return float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 1025 |
+
|
| 1026 |
+
out_seq = []
|
| 1027 |
+
for t in range(T):
|
| 1028 |
+
if not isinstance(pose_seq[t], list) or len(pose_seq[t]) != J * 3:
|
| 1029 |
+
out_seq.append(pose_seq[t])
|
| 1030 |
+
continue
|
| 1031 |
+
out = list(pose_seq[t])
|
| 1032 |
+
a0, a1, a2 = pose_seq[max(0, t - 1)], pose_seq[t], pose_seq[min(T - 1, t + 1)]
|
| 1033 |
+
for j in range(J):
|
| 1034 |
+
if not is_vis(pose_seq[t], j):
|
| 1035 |
+
continue
|
| 1036 |
+
xs, ys = [], []
|
| 1037 |
+
for aa in (a0, a1, a2):
|
| 1038 |
+
if isinstance(aa, list) and len(aa) == J * 3 and is_vis(aa, j):
|
| 1039 |
+
xs.append(float(aa[3 * j]))
|
| 1040 |
+
ys.append(float(aa[3 * j + 1]))
|
| 1041 |
+
if len(xs) >= 2:
|
| 1042 |
+
xs.sort()
|
| 1043 |
+
ys.sort()
|
| 1044 |
+
out[3 * j], out[3 * j + 1] = float(xs[len(xs) // 2]), float(ys[len(ys) // 2])
|
| 1045 |
+
out_seq.append(out)
|
| 1046 |
+
return out_seq
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
def _sync_group_appearances(
|
| 1050 |
+
pose_arr_seq: List[Optional[List[float]]], *, group: set[int], conf_gate: float, lookahead: int
|
| 1051 |
+
) -> List[Optional[List[float]]]:
|
| 1052 |
+
if not pose_arr_seq:
|
| 1053 |
+
return pose_arr_seq
|
| 1054 |
+
J = next((len(a) // 3 for a in pose_arr_seq if isinstance(a, list) and len(a) % 3 == 0 and len(a) > 0), None)
|
| 1055 |
+
if J is None:
|
| 1056 |
+
return pose_arr_seq
|
| 1057 |
+
T = len(pose_arr_seq)
|
| 1058 |
+
out = [list(a) if isinstance(a, list) and len(a) == J * 3 else a for a in pose_arr_seq]
|
| 1059 |
+
|
| 1060 |
+
def is_vis(arr, j):
|
| 1061 |
+
return float(arr[3 * j + 2]) >= conf_gate and not (float(arr[3 * j]) == 0 and float(arr[3 * j + 1]) == 0)
|
| 1062 |
+
|
| 1063 |
+
for t in range(T):
|
| 1064 |
+
arr = out[t]
|
| 1065 |
+
if not isinstance(arr, list):
|
| 1066 |
+
continue
|
| 1067 |
+
vis = {j for j in group if j < J and is_vis(arr, j)}
|
| 1068 |
+
if not vis:
|
| 1069 |
+
continue
|
| 1070 |
+
for j in list({j for j in group if j < J and j not in vis}):
|
| 1071 |
+
t2 = next(
|
| 1072 |
+
(
|
| 1073 |
+
tt
|
| 1074 |
+
for tt in range(t + 1, min(T, t + 1 + lookahead))
|
| 1075 |
+
if isinstance(out[tt], list) and is_vis(out[tt], j)
|
| 1076 |
+
),
|
| 1077 |
+
None,
|
| 1078 |
+
)
|
| 1079 |
+
if t2 is None:
|
| 1080 |
+
continue
|
| 1081 |
+
last_t = next((tb for tb in range(t - 1, -1, -1) if isinstance(out[tb], list) and is_vis(out[tb], j)), None)
|
| 1082 |
+
b = out[t2]
|
| 1083 |
+
if last_t is None:
|
| 1084 |
+
for k in range(t, t2):
|
| 1085 |
+
if isinstance(out[k], list):
|
| 1086 |
+
out[k][3 * j : 3 * j + 3] = b[3 * j : 3 * j + 3]
|
| 1087 |
+
else:
|
| 1088 |
+
a = out[last_t]
|
| 1089 |
+
if float(a[3 * j]) == 0 and float(a[3 * j + 1]) == 0:
|
| 1090 |
+
continue
|
| 1091 |
+
c_fill = min(float(a[3 * j + 2]), float(b[3 * j + 2]))
|
| 1092 |
+
for tt in range(t, t2):
|
| 1093 |
+
if isinstance(out[tt], list):
|
| 1094 |
+
r = (tt - last_t) / (t2 - last_t)
|
| 1095 |
+
out[tt][3 * j : 3 * j + 3] = [
|
| 1096 |
+
float(a[3 * j]) + (float(b[3 * j]) - float(a[3 * j])) * r,
|
| 1097 |
+
float(a[3 * j + 1]) + (float(b[3 * j + 1]) - float(a[3 * j + 1])) * r,
|
| 1098 |
+
float(c_fill),
|
| 1099 |
+
]
|
| 1100 |
+
return out
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
def _count_valid_points(arr: Optional[List[float]], *, conf_gate: float) -> int:
|
| 1104 |
+
if not isinstance(arr, list) or len(arr) % 3 != 0:
|
| 1105 |
+
return 0
|
| 1106 |
+
return sum(
|
| 1107 |
+
1
|
| 1108 |
+
for i in range(0, len(arr), 3)
|
| 1109 |
+
if float(arr[i + 2]) >= conf_gate and not (float(arr[i]) == 0 and float(arr[i + 1]) == 0)
|
| 1110 |
+
)
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
def _zero_out_kps(arr: Optional[List[float]]) -> Optional[List[float]]:
|
| 1114 |
+
if not isinstance(arr, list) or len(arr) % 3 != 0:
|
| 1115 |
+
return arr
|
| 1116 |
+
out = list(arr)
|
| 1117 |
+
for i in range(0, len(out), 3):
|
| 1118 |
+
out[i : i + 3] = [0.0, 0.0, 0.0]
|
| 1119 |
+
return out
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
def _pin_body_wrist_to_hand(
|
| 1123 |
+
p_out: Dict[str, Any], *, side: str, conf_gate_body: float, conf_gate_hand: float, blend: float
|
| 1124 |
+
) -> None:
|
| 1125 |
+
bw, hk = (4, "hand_right_keypoints_2d") if side == "right" else (7, "hand_left_keypoints_2d")
|
| 1126 |
+
pose, hand = p_out.get("pose_keypoints_2d"), p_out.get(hk)
|
| 1127 |
+
if not isinstance(pose, list) or not isinstance(hand, list) or len(pose) < (bw * 3 + 3) or len(hand) < 3:
|
| 1128 |
+
return
|
| 1129 |
+
hx, hy, hc = float(hand[0]), float(hand[1]), float(hand[2])
|
| 1130 |
+
if hc < conf_gate_hand or (hx == 0.0 and hy == 0.0):
|
| 1131 |
+
return
|
| 1132 |
+
bx, by, bc = float(pose[bw * 3]), float(pose[bw * 3 + 1]), float(pose[bw * 3 + 2])
|
| 1133 |
+
if bc < conf_gate_body or (bx == 0.0 and by == 0.0):
|
| 1134 |
+
pose[bw * 3 : bw * 3 + 3] = [hx, hy, float(max(bc, min(hc, 0.9)))]
|
| 1135 |
+
else:
|
| 1136 |
+
pose[bw * 3 : bw * 3 + 3] = [
|
| 1137 |
+
bx * (1.0 - blend) + hx * blend,
|
| 1138 |
+
by * (1.0 - blend) + hy * blend,
|
| 1139 |
+
float(min(bc, hc)),
|
| 1140 |
+
]
|
| 1141 |
+
p_out["pose_keypoints_2d"] = pose
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
def _fix_elbow_using_wrist(p_out: Dict[str, Any], *, side: str, conf_gate: float) -> None:
|
| 1145 |
+
pose = p_out.get("pose_keypoints_2d")
|
| 1146 |
+
if not isinstance(pose, list) or len(pose) % 3 != 0:
|
| 1147 |
+
return
|
| 1148 |
+
sh, el, wr = (2, 3, 4) if side == "right" else (5, 6, 7)
|
| 1149 |
+
|
| 1150 |
+
def vis(x, y, c):
|
| 1151 |
+
return c >= conf_gate and not (x == 0.0 and y == 0.0)
|
| 1152 |
+
|
| 1153 |
+
sx, sy, sc = float(pose[3 * sh]), float(pose[3 * sh + 1]), float(pose[3 * sh + 2])
|
| 1154 |
+
ex, ey, ec = float(pose[3 * el]), float(pose[3 * el + 1]), float(pose[3 * el + 2])
|
| 1155 |
+
wx, wy, wc = float(pose[3 * wr]), float(pose[3 * wr + 1]), float(pose[3 * wr + 2])
|
| 1156 |
+
if not vis(sx, sy, sc) or not vis(wx, wy, wc):
|
| 1157 |
+
return
|
| 1158 |
+
if vis(ex, ey, ec):
|
| 1159 |
+
Lse, Lew = math.hypot(ex - sx, ey - sy), math.hypot(wx - ex, wy - ey)
|
| 1160 |
+
else:
|
| 1161 |
+
dsw = math.hypot(wx - sx, wy - sy)
|
| 1162 |
+
if dsw < 1e-3:
|
| 1163 |
+
return
|
| 1164 |
+
Lse, Lew = 0.55 * dsw, 0.45 * dsw
|
| 1165 |
+
dx, dy = wx - sx, wy - sy
|
| 1166 |
+
d = math.hypot(dx, dy)
|
| 1167 |
+
if d < 1e-6:
|
| 1168 |
+
return
|
| 1169 |
+
d2 = max(min(d, (Lse + Lew) - 1e-3), abs(Lse - Lew) + 1e-3)
|
| 1170 |
+
a = (Lse * Lse - Lew * Lew + d2 * d2) / (2.0 * d2)
|
| 1171 |
+
h = math.sqrt(max(Lse * Lse - a * a, 0.0))
|
| 1172 |
+
px, py = sx + a * (dx / d), sy + a * (dy / d)
|
| 1173 |
+
rx, ry = -dy / d, dx / d
|
| 1174 |
+
e1x, e1y, e2x, e2y = px + h * rx, py + h * ry, px - h * rx, py - h * ry
|
| 1175 |
+
nx, ny = (
|
| 1176 |
+
(e1x, e1y)
|
| 1177 |
+
if not vis(ex, ey, ec) or math.hypot(e1x - ex, e1y - ey) <= math.hypot(e2x - ex, e2y - ey)
|
| 1178 |
+
else (e2x, e2y)
|
| 1179 |
+
)
|
| 1180 |
+
pose[3 * el : 3 * el + 3] = [float(nx), float(ny), float(max(min(ec, 0.8), conf_gate))]
|
| 1181 |
+
p_out["pose_keypoints_2d"] = pose
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
def _remove_short_presence_runs_kps_seq(
|
| 1185 |
+
seq: List[Optional[List[float]]], *, conf_gate: float, min_points_present: int, min_run: int
|
| 1186 |
+
) -> List[Optional[List[float]]]:
|
| 1187 |
+
if not seq:
|
| 1188 |
+
return seq
|
| 1189 |
+
out = [None if a is None else list(a) for a in seq]
|
| 1190 |
+
start = None
|
| 1191 |
+
for t in range(len(seq) + 1):
|
| 1192 |
+
cur = t < len(seq) and _count_valid_points(seq[t], conf_gate=conf_gate) >= min_points_present
|
| 1193 |
+
if cur and start is None:
|
| 1194 |
+
start = t
|
| 1195 |
+
if not cur and start is not None:
|
| 1196 |
+
if (t - start) < min_run:
|
| 1197 |
+
for k in range(start, t):
|
| 1198 |
+
out[k] = _zero_out_kps(out[k])
|
| 1199 |
+
start = None
|
| 1200 |
+
return out
|
| 1201 |
+
|
| 1202 |
+
|
| 1203 |
+
def _zero_sparse_frames_kps_seq(
|
| 1204 |
+
seq: List[Optional[List[float]]], *, conf_gate: float, min_points_present: int
|
| 1205 |
+
) -> List[Optional[List[float]]]:
|
| 1206 |
+
if not seq:
|
| 1207 |
+
return seq
|
| 1208 |
+
return [
|
| 1209 |
+
(
|
| 1210 |
+
_zero_out_kps(a)
|
| 1211 |
+
if isinstance(a, list) and _count_valid_points(a, conf_gate=conf_gate) < min_points_present
|
| 1212 |
+
else a
|
| 1213 |
+
)
|
| 1214 |
+
for a in seq
|
| 1215 |
+
]
|
| 1216 |
+
|
| 1217 |
+
|
| 1218 |
+
def _suppress_spatial_outliers_in_hand_arr(
|
| 1219 |
+
hand_arr: Optional[List[float]], *, conf_gate: float, max_bone_factor: float = 3.0
|
| 1220 |
+
) -> Optional[List[float]]:
|
| 1221 |
+
if not isinstance(hand_arr, list) or len(hand_arr) % 3 != 0:
|
| 1222 |
+
return hand_arr
|
| 1223 |
+
pts = _reshape_keypoints_2d(hand_arr)
|
| 1224 |
+
J = len(pts)
|
| 1225 |
+
if J < 21:
|
| 1226 |
+
return hand_arr
|
| 1227 |
+
out = [list(p) for p in pts]
|
| 1228 |
+
|
| 1229 |
+
def vis(j):
|
| 1230 |
+
return out[j][2] >= conf_gate and not (out[j][0] == 0 and out[j][1] == 0)
|
| 1231 |
+
|
| 1232 |
+
vv = [(x, y) for x, y, c in out if c >= conf_gate and not (x == 0 and y == 0)]
|
| 1233 |
+
if len(vv) < 6:
|
| 1234 |
+
return hand_arr
|
| 1235 |
+
xs, ys = [p[0] for p in vv], [p[1] for p in vv]
|
| 1236 |
+
s = max(max(xs) - min(xs), max(ys) - min(ys))
|
| 1237 |
+
if s <= 1e-3:
|
| 1238 |
+
return hand_arr
|
| 1239 |
+
max_bone = max_bone_factor * s
|
| 1240 |
+
for a, b in HAND21_EDGES:
|
| 1241 |
+
if a >= J or b >= J or not vis(a) or not vis(b):
|
| 1242 |
+
continue
|
| 1243 |
+
if math.hypot(out[a][0] - out[b][0], out[a][1] - out[b][1]) > max_bone:
|
| 1244 |
+
if out[a][2] <= out[b][2]:
|
| 1245 |
+
out[a] = [0.0, 0.0, 0.0]
|
| 1246 |
+
else:
|
| 1247 |
+
out[b] = [0.0, 0.0, 0.0]
|
| 1248 |
+
return _flatten_keypoints_2d([(x, y, c) for x, y, c in out])
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
def _body_head_root_scale_from_pose(
|
| 1252 |
+
pose_arr: Optional[List[float]], *, conf_gate: float
|
| 1253 |
+
) -> Optional[Tuple[Tuple[float, float], float]]:
|
| 1254 |
+
if not isinstance(pose_arr, list) or len(pose_arr) % 3 != 0:
|
| 1255 |
+
return None
|
| 1256 |
+
kps = _reshape_keypoints_2d(pose_arr)
|
| 1257 |
+
|
| 1258 |
+
def vis(j):
|
| 1259 |
+
return (
|
| 1260 |
+
(float(kps[j][0]), float(kps[j][1]))
|
| 1261 |
+
if j < len(kps) and kps[j][2] >= conf_gate and not (kps[j][0] == 0 and kps[j][1] == 0)
|
| 1262 |
+
else None
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
pts = [p for p in (vis(j) for j in [0, 1, 14, 15, 16, 17]) if p is not None]
|
| 1266 |
+
if not pts:
|
| 1267 |
+
return None
|
| 1268 |
+
root = (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
|
| 1269 |
+
cands = [
|
| 1270 |
+
math.hypot(a[0] - b[0], a[1] - b[1])
|
| 1271 |
+
for a, b in ((vis(14), vis(15)), (vis(16), vis(17)), (vis(2), vis(5)))
|
| 1272 |
+
if a and b and math.hypot(a[0] - b[0], a[1] - b[1]) > 1e-3
|
| 1273 |
+
]
|
| 1274 |
+
return (root, float(sum(cands) / len(cands))) if cands else None
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
def _body_wrist_root_scale_from_pose(
|
| 1278 |
+
pose_arr: Optional[List[float]], *, side: str, conf_gate: float
|
| 1279 |
+
) -> Optional[Tuple[Tuple[float, float], float]]:
|
| 1280 |
+
if not isinstance(pose_arr, list) or len(pose_arr) % 3 != 0:
|
| 1281 |
+
return None
|
| 1282 |
+
kps = _reshape_keypoints_2d(pose_arr)
|
| 1283 |
+
w, e = (4, 3) if side == "right" else (7, 6)
|
| 1284 |
+
|
| 1285 |
+
def vis(j):
|
| 1286 |
+
return (
|
| 1287 |
+
(float(kps[j][0]), float(kps[j][1]))
|
| 1288 |
+
if j < len(kps) and kps[j][2] >= conf_gate and not (kps[j][0] == 0 and kps[j][1] == 0)
|
| 1289 |
+
else None
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
pw = vis(w)
|
| 1293 |
+
if not pw:
|
| 1294 |
+
return None
|
| 1295 |
+
pe = vis(e)
|
| 1296 |
+
s = math.hypot(pw[0] - pe[0], pw[1] - pe[1]) if pe and math.hypot(pw[0] - pe[0], pw[1] - pe[1]) > 1e-3 else None
|
| 1297 |
+
if s is None:
|
| 1298 |
+
p2, p5 = vis(2), vis(5)
|
| 1299 |
+
if p2 and p5 and math.hypot(p2[0] - p5[0], p2[1] - p5[1]) > 1e-3:
|
| 1300 |
+
s = math.hypot(p2[0] - p5[0], p2[1] - p5[1])
|
| 1301 |
+
return (pw, float(s)) if s else None
|
| 1302 |
+
|
| 1303 |
+
|
| 1304 |
+
def _smooth_dense_seq_anchored_to_body(
|
| 1305 |
+
dense_seq: List[Optional[List[float]]],
|
| 1306 |
+
body_pose_seq: List[Optional[List[float]]],
|
| 1307 |
+
*,
|
| 1308 |
+
kind: str,
|
| 1309 |
+
conf_gate_dense: float,
|
| 1310 |
+
conf_gate_body: float,
|
| 1311 |
+
median3: bool,
|
| 1312 |
+
zero_lag_alpha: float,
|
| 1313 |
+
) -> List[Optional[List[float]]]:
|
| 1314 |
+
if not dense_seq:
|
| 1315 |
+
return dense_seq
|
| 1316 |
+
Jd = next((len(a) // 3 for a in dense_seq if isinstance(a, list) and len(a) % 3 == 0 and len(a) > 0), None)
|
| 1317 |
+
if Jd is None:
|
| 1318 |
+
return dense_seq
|
| 1319 |
+
T = len(dense_seq)
|
| 1320 |
+
out = [None if a is None else list(a) for a in dense_seq]
|
| 1321 |
+
norm_seq = [None] * T
|
| 1322 |
+
|
| 1323 |
+
for t in range(T):
|
| 1324 |
+
arr, body = out[t], body_pose_seq[t] if t < len(body_pose_seq) else None
|
| 1325 |
+
if not isinstance(arr, list) or len(arr) != Jd * 3 or not isinstance(body, list):
|
| 1326 |
+
norm_seq[t] = arr
|
| 1327 |
+
continue
|
| 1328 |
+
rs = (
|
| 1329 |
+
_body_head_root_scale_from_pose(body, conf_gate=conf_gate_body)
|
| 1330 |
+
if kind == "face"
|
| 1331 |
+
else _body_wrist_root_scale_from_pose(
|
| 1332 |
+
body, side="left" if kind == "hand_left" else "right", conf_gate=conf_gate_body
|
| 1333 |
+
)
|
| 1334 |
+
)
|
| 1335 |
+
if not rs or rs[1] <= 1e-6:
|
| 1336 |
+
norm_seq[t] = arr
|
| 1337 |
+
continue
|
| 1338 |
+
(rx, ry), s = rs
|
| 1339 |
+
norm_seq[t] = [
|
| 1340 |
+
(x - rx) / s if i % 3 == 0 else (y - ry) / s if i % 3 == 1 else c
|
| 1341 |
+
for i, (x, y, c) in enumerate(zip(arr[0::3], arr[1::3], arr[2::3]))
|
| 1342 |
+
]
|
| 1343 |
+
|
| 1344 |
+
if median3:
|
| 1345 |
+
norm_seq = _median3_pose_seq(norm_seq, conf_gate=conf_gate_dense)
|
| 1346 |
+
norm_seq = _zero_lag_ema_pose_seq(norm_seq, alpha=zero_lag_alpha, conf_gate=conf_gate_dense)
|
| 1347 |
+
|
| 1348 |
+
for t in range(T):
|
| 1349 |
+
arrn, body = norm_seq[t], body_pose_seq[t] if t < len(body_pose_seq) else None
|
| 1350 |
+
if not isinstance(arrn, list) or len(arrn) != Jd * 3 or not isinstance(body, list):
|
| 1351 |
+
continue
|
| 1352 |
+
rs = (
|
| 1353 |
+
_body_head_root_scale_from_pose(body, conf_gate=conf_gate_body)
|
| 1354 |
+
if kind == "face"
|
| 1355 |
+
else _body_wrist_root_scale_from_pose(
|
| 1356 |
+
body, side="left" if kind == "hand_left" else "right", conf_gate=conf_gate_body
|
| 1357 |
+
)
|
| 1358 |
+
)
|
| 1359 |
+
if not rs or rs[1] <= 1e-6:
|
| 1360 |
+
continue
|
| 1361 |
+
(rx, ry), s = rs
|
| 1362 |
+
for j in range(Jd):
|
| 1363 |
+
if (
|
| 1364 |
+
out[t][3 * j + 2] >= conf_gate_dense
|
| 1365 |
+
and arrn[3 * j + 2] >= conf_gate_dense
|
| 1366 |
+
and not (out[t][3 * j] == 0 and out[t][3 * j + 1] == 0)
|
| 1367 |
+
):
|
| 1368 |
+
out[t][3 * j : 3 * j + 2] = [rx + arrn[3 * j] * s, ry + arrn[3 * j + 1] * s]
|
| 1369 |
+
return out
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def smooth_KPS_json_obj(
|
| 1373 |
+
data: Any,
|
| 1374 |
+
*,
|
| 1375 |
+
keep_face_untouched: bool = True,
|
| 1376 |
+
keep_hands_untouched: bool = True,
|
| 1377 |
+
filter_extra_people: Optional[bool] = None,
|
| 1378 |
+
) -> Any:
|
| 1379 |
+
if not isinstance(data, list):
|
| 1380 |
+
raise ValueError("Expected top-level JSON to be a list of frames.")
|
| 1381 |
+
filter_extra_people = bool(FILTER_EXTRA_PEOPLE) if filter_extra_people is None else filter_extra_people
|
| 1382 |
+
chosen_people: List[Optional[Dict[str, Any]]] = [None] * len(data)
|
| 1383 |
+
|
| 1384 |
+
if MAIN_PERSON_MODE == "longest_track":
|
| 1385 |
+
main_tr = _pick_main_track(_build_tracks_over_video(data))
|
| 1386 |
+
if main_tr:
|
| 1387 |
+
for t in range(len(data)):
|
| 1388 |
+
if t in main_tr.frames:
|
| 1389 |
+
chosen_people[t] = main_tr.frames[t]
|
| 1390 |
+
else:
|
| 1391 |
+
prev_center = None
|
| 1392 |
+
for i, frame in enumerate(data):
|
| 1393 |
+
if not isinstance(frame, dict) or not frame.get("people"):
|
| 1394 |
+
continue
|
| 1395 |
+
chosen_people[i] = _choose_single_person(frame.get("people", []), prev_center)
|
| 1396 |
+
if chosen_people[i]:
|
| 1397 |
+
c = _body_center_from_pose(chosen_people[i].get("pose_keypoints_2d"))
|
| 1398 |
+
if c:
|
| 1399 |
+
prev_center = c
|
| 1400 |
+
else:
|
| 1401 |
+
prev_center = None
|
| 1402 |
+
for i, frame in enumerate(data):
|
| 1403 |
+
if not isinstance(frame, dict) or not frame.get("people"):
|
| 1404 |
+
continue
|
| 1405 |
+
chosen_people[i] = _choose_single_person(frame.get("people", []), prev_center)
|
| 1406 |
+
if chosen_people[i]:
|
| 1407 |
+
c = _body_center_from_pose(chosen_people[i].get("pose_keypoints_2d"))
|
| 1408 |
+
if c:
|
| 1409 |
+
prev_center = c
|
| 1410 |
+
|
| 1411 |
+
pose_seq = [p.get("pose_keypoints_2d") if isinstance(p, dict) else None for p in chosen_people]
|
| 1412 |
+
|
| 1413 |
+
if SPATIAL_OUTLIER_FIX:
|
| 1414 |
+
pose_seq = [
|
| 1415 |
+
_suppress_spatial_outliers_in_pose_arr(arr, conf_gate=CONF_GATE_BODY) if arr else None for arr in pose_seq
|
| 1416 |
+
]
|
| 1417 |
+
|
| 1418 |
+
if GAP_FILL_ENABLED:
|
| 1419 |
+
pose_seq = _denoise_and_fill_gaps_pose_seq(
|
| 1420 |
+
pose_seq, conf_gate=CONF_GATE_BODY, min_run=MIN_RUN_FRAMES, max_gap=MAX_GAP_FRAMES
|
| 1421 |
+
)
|
| 1422 |
+
|
| 1423 |
+
if TORSO_SYNC_ENABLED:
|
| 1424 |
+
pose_seq = _sync_group_appearances(
|
| 1425 |
+
pose_seq, group=TORSO_JOINTS, conf_gate=CONF_GATE_BODY, lookahead=TORSO_LOOKAHEAD_FRAMES
|
| 1426 |
+
)
|
| 1427 |
+
|
| 1428 |
+
pose_seq = [
|
| 1429 |
+
_suppress_isolated_joints_in_pose_arr(arr, conf_gate=CONF_GATE_BODY, keep=TORSO_JOINTS) if arr else None
|
| 1430 |
+
for arr in pose_seq
|
| 1431 |
+
]
|
| 1432 |
+
|
| 1433 |
+
if MEDIAN3_ENABLED:
|
| 1434 |
+
pose_seq = _median3_pose_seq(pose_seq, conf_gate=CONF_GATE_BODY)
|
| 1435 |
+
if SUPER_SMOOTH_ENABLED:
|
| 1436 |
+
pose_seq = _zero_lag_ema_pose_seq(pose_seq, alpha=SUPER_SMOOTH_ALPHA, conf_gate=SUPER_SMOOTH_MIN_CONF)
|
| 1437 |
+
if ROOTSCALE_CARRY_ENABLED:
|
| 1438 |
+
pose_seq = _carry_pose_when_torso_missing(
|
| 1439 |
+
pose_seq,
|
| 1440 |
+
conf_gate=CARRY_CONF_GATE,
|
| 1441 |
+
max_carry=CARRY_MAX_FRAMES,
|
| 1442 |
+
anchor_joints=CARRY_ANCHOR_JOINTS,
|
| 1443 |
+
min_anchors=CARRY_MIN_ANCHORS,
|
| 1444 |
+
)
|
| 1445 |
+
pose_seq = _force_full_torso_pair(
|
| 1446 |
+
pose_seq,
|
| 1447 |
+
conf_gate=CARRY_CONF_GATE,
|
| 1448 |
+
anchor_joints=CARRY_ANCHOR_JOINTS,
|
| 1449 |
+
min_anchors=CARRY_MIN_ANCHORS,
|
| 1450 |
+
max_lookback=240,
|
| 1451 |
+
fill_legs_with_hip=True,
|
| 1452 |
+
always_fill_if_one_hip=True,
|
| 1453 |
+
)
|
| 1454 |
+
pose_seq = _denoise_and_fill_gaps_pose_seq(pose_seq, conf_gate=CONF_GATE_BODY, min_run=MIN_RUN_FRAMES, max_gap=0)
|
| 1455 |
+
|
| 1456 |
+
face_seq = [p.get("face_keypoints_2d") if isinstance(p, dict) else None for p in chosen_people]
|
| 1457 |
+
lh_seq = [p.get("hand_left_keypoints_2d") if isinstance(p, dict) else None for p in chosen_people]
|
| 1458 |
+
rh_seq = [p.get("hand_right_keypoints_2d") if isinstance(p, dict) else None for p in chosen_people]
|
| 1459 |
+
|
| 1460 |
+
if HANDS_SMOOTH_ENABLED and not keep_hands_untouched:
|
| 1461 |
+
lh_seq = [_suppress_spatial_outliers_in_hand_arr(a, conf_gate=CONF_GATE_HAND) if a else None for a in lh_seq]
|
| 1462 |
+
rh_seq = [_suppress_spatial_outliers_in_hand_arr(a, conf_gate=CONF_GATE_HAND) if a else None for a in rh_seq]
|
| 1463 |
+
lh_seq = _remove_short_presence_runs_kps_seq(
|
| 1464 |
+
lh_seq, conf_gate=CONF_GATE_HAND, min_points_present=HAND_MIN_POINTS_PRESENT, min_run=MIN_HAND_RUN_FRAMES
|
| 1465 |
+
)
|
| 1466 |
+
rh_seq = _remove_short_presence_runs_kps_seq(
|
| 1467 |
+
rh_seq, conf_gate=CONF_GATE_HAND, min_points_present=HAND_MIN_POINTS_PRESENT, min_run=MIN_HAND_RUN_FRAMES
|
| 1468 |
+
)
|
| 1469 |
+
lh_seq = _zero_sparse_frames_kps_seq(
|
| 1470 |
+
lh_seq, conf_gate=CONF_GATE_HAND, min_points_present=HAND_MIN_POINTS_PRESENT
|
| 1471 |
+
)
|
| 1472 |
+
rh_seq = _zero_sparse_frames_kps_seq(
|
| 1473 |
+
rh_seq, conf_gate=CONF_GATE_HAND, min_points_present=HAND_MIN_POINTS_PRESENT
|
| 1474 |
+
)
|
| 1475 |
+
if DENSE_GAP_FILL_ENABLED:
|
| 1476 |
+
lh_seq = _denoise_and_fill_gaps_pose_seq(
|
| 1477 |
+
lh_seq, conf_gate=CONF_GATE_HAND, min_run=DENSE_MIN_RUN_FRAMES, max_gap=DENSE_MAX_GAP_FRAMES
|
| 1478 |
+
)
|
| 1479 |
+
rh_seq = _denoise_and_fill_gaps_pose_seq(
|
| 1480 |
+
rh_seq, conf_gate=CONF_GATE_HAND, min_run=DENSE_MIN_RUN_FRAMES, max_gap=DENSE_MAX_GAP_FRAMES
|
| 1481 |
+
)
|
| 1482 |
+
lh_seq = _smooth_dense_seq_anchored_to_body(
|
| 1483 |
+
lh_seq,
|
| 1484 |
+
pose_seq,
|
| 1485 |
+
kind="hand_left",
|
| 1486 |
+
conf_gate_dense=CONF_GATE_HAND,
|
| 1487 |
+
conf_gate_body=CONF_GATE_BODY,
|
| 1488 |
+
median3=DENSE_MEDIAN3_ENABLED,
|
| 1489 |
+
zero_lag_alpha=DENSE_SUPER_SMOOTH_ALPHA,
|
| 1490 |
+
)
|
| 1491 |
+
rh_seq = _smooth_dense_seq_anchored_to_body(
|
| 1492 |
+
rh_seq,
|
| 1493 |
+
pose_seq,
|
| 1494 |
+
kind="hand_right",
|
| 1495 |
+
conf_gate_dense=CONF_GATE_HAND,
|
| 1496 |
+
conf_gate_body=CONF_GATE_BODY,
|
| 1497 |
+
median3=DENSE_MEDIAN3_ENABLED,
|
| 1498 |
+
zero_lag_alpha=DENSE_SUPER_SMOOTH_ALPHA,
|
| 1499 |
+
)
|
| 1500 |
+
|
| 1501 |
+
if FACE_SMOOTH_ENABLED and not keep_face_untouched:
|
| 1502 |
+
if DENSE_GAP_FILL_ENABLED:
|
| 1503 |
+
face_seq = _denoise_and_fill_gaps_pose_seq(
|
| 1504 |
+
face_seq, conf_gate=CONF_GATE_FACE, min_run=DENSE_MIN_RUN_FRAMES, max_gap=DENSE_MAX_GAP_FRAMES
|
| 1505 |
+
)
|
| 1506 |
+
face_seq = _smooth_dense_seq_anchored_to_body(
|
| 1507 |
+
face_seq,
|
| 1508 |
+
pose_seq,
|
| 1509 |
+
kind="face",
|
| 1510 |
+
conf_gate_dense=CONF_GATE_FACE,
|
| 1511 |
+
conf_gate_body=CONF_GATE_BODY,
|
| 1512 |
+
median3=DENSE_MEDIAN3_ENABLED,
|
| 1513 |
+
zero_lag_alpha=DENSE_SUPER_SMOOTH_ALPHA,
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
out_frames = []
|
| 1517 |
+
body_state: Optional[BodyState] = None
|
| 1518 |
+
|
| 1519 |
+
for i, frame in enumerate(data):
|
| 1520 |
+
if not isinstance(frame, dict):
|
| 1521 |
+
out_frames.append(frame)
|
| 1522 |
+
continue
|
| 1523 |
+
|
| 1524 |
+
frame_out = copy.deepcopy(frame)
|
| 1525 |
+
chosen = chosen_people[i]
|
| 1526 |
+
|
| 1527 |
+
if chosen is None:
|
| 1528 |
+
if filter_extra_people:
|
| 1529 |
+
frame_out["people"] = []
|
| 1530 |
+
out_frames.append(frame_out)
|
| 1531 |
+
body_state = None
|
| 1532 |
+
continue
|
| 1533 |
+
|
| 1534 |
+
p_out = copy.deepcopy(chosen)
|
| 1535 |
+
p_out["pose_keypoints_2d"] = pose_seq[i]
|
| 1536 |
+
|
| 1537 |
+
pose_arr = p_out.get("pose_keypoints_2d")
|
| 1538 |
+
joints = (len(pose_arr) // 3) if isinstance(pose_arr, list) else 0
|
| 1539 |
+
if body_state is None:
|
| 1540 |
+
body_state = BodyState(joints if joints > 0 else 18)
|
| 1541 |
+
|
| 1542 |
+
p_out["pose_keypoints_2d"] = _smooth_body_pose(p_out.get("pose_keypoints_2d"), body_state)
|
| 1543 |
+
|
| 1544 |
+
if FACE_SMOOTH_ENABLED and not keep_face_untouched:
|
| 1545 |
+
p_out["face_keypoints_2d"] = face_seq[i]
|
| 1546 |
+
else:
|
| 1547 |
+
p_out["face_keypoints_2d"] = chosen.get("face_keypoints_2d", p_out.get("face_keypoints_2d"))
|
| 1548 |
+
|
| 1549 |
+
if HANDS_SMOOTH_ENABLED and not keep_hands_untouched:
|
| 1550 |
+
p_out["hand_left_keypoints_2d"], p_out["hand_right_keypoints_2d"] = lh_seq[i], rh_seq[i]
|
| 1551 |
+
else:
|
| 1552 |
+
p_out["hand_left_keypoints_2d"] = chosen.get("hand_left_keypoints_2d", p_out.get("hand_left_keypoints_2d"))
|
| 1553 |
+
p_out["hand_right_keypoints_2d"] = chosen.get(
|
| 1554 |
+
"hand_right_keypoints_2d", p_out.get("hand_right_keypoints_2d")
|
| 1555 |
+
)
|
| 1556 |
+
|
| 1557 |
+
_pin_body_wrist_to_hand(
|
| 1558 |
+
p_out, side="left", conf_gate_body=CONF_GATE_BODY, conf_gate_hand=CONF_GATE_HAND, blend=1.0
|
| 1559 |
+
)
|
| 1560 |
+
_pin_body_wrist_to_hand(
|
| 1561 |
+
p_out, side="right", conf_gate_body=CONF_GATE_BODY, conf_gate_hand=CONF_GATE_HAND, blend=1.0
|
| 1562 |
+
)
|
| 1563 |
+
_fix_elbow_using_wrist(p_out, side="left", conf_gate=CONF_GATE_BODY)
|
| 1564 |
+
_fix_elbow_using_wrist(p_out, side="right", conf_gate=CONF_GATE_BODY)
|
| 1565 |
+
|
| 1566 |
+
if filter_extra_people:
|
| 1567 |
+
frame_out["people"] = [p_out]
|
| 1568 |
+
else:
|
| 1569 |
+
orig_people = frame.get("people", [])
|
| 1570 |
+
if not isinstance(orig_people, list):
|
| 1571 |
+
frame_out["people"] = [p_out]
|
| 1572 |
+
else:
|
| 1573 |
+
replaced, new_people = False, []
|
| 1574 |
+
for op in orig_people:
|
| 1575 |
+
if not replaced and (op is chosen):
|
| 1576 |
+
new_people.append(p_out)
|
| 1577 |
+
replaced = True
|
| 1578 |
+
else:
|
| 1579 |
+
new_people.append(copy.deepcopy(op))
|
| 1580 |
+
if not replaced:
|
| 1581 |
+
new_people = [p_out] + [copy.deepcopy(op) for op in orig_people]
|
| 1582 |
+
frame_out["people"] = new_people
|
| 1583 |
+
|
| 1584 |
+
out_frames.append(frame_out)
|
| 1585 |
+
|
| 1586 |
+
final_body, final_lh, final_rh, final_face = [], [], [], []
|
| 1587 |
+
for f in out_frames:
|
| 1588 |
+
if f.get("people") and len(f["people"]) > 0:
|
| 1589 |
+
p = f["people"][0]
|
| 1590 |
+
final_body.append(p.get("pose_keypoints_2d"))
|
| 1591 |
+
final_lh.append(p.get("hand_left_keypoints_2d"))
|
| 1592 |
+
final_rh.append(p.get("hand_right_keypoints_2d"))
|
| 1593 |
+
final_face.append(p.get("face_keypoints_2d"))
|
| 1594 |
+
else:
|
| 1595 |
+
final_body.append(None)
|
| 1596 |
+
final_lh.append(None)
|
| 1597 |
+
final_rh.append(None)
|
| 1598 |
+
final_face.append(None)
|
| 1599 |
+
|
| 1600 |
+
eff_min = max(2, MIN_RUN_FRAMES)
|
| 1601 |
+
|
| 1602 |
+
final_body = _denoise_and_fill_gaps_pose_seq(final_body, conf_gate=CONF_GATE_BODY, min_run=eff_min, max_gap=0)
|
| 1603 |
+
final_lh = _remove_short_presence_runs_kps_seq(
|
| 1604 |
+
final_lh, conf_gate=CONF_GATE_HAND, min_points_present=1, min_run=eff_min
|
| 1605 |
+
)
|
| 1606 |
+
final_rh = _remove_short_presence_runs_kps_seq(
|
| 1607 |
+
final_rh, conf_gate=CONF_GATE_HAND, min_points_present=1, min_run=eff_min
|
| 1608 |
+
)
|
| 1609 |
+
final_face = _remove_short_presence_runs_kps_seq(
|
| 1610 |
+
final_face, conf_gate=CONF_GATE_FACE, min_points_present=1, min_run=eff_min
|
| 1611 |
+
)
|
| 1612 |
+
|
| 1613 |
+
for i, f in enumerate(out_frames):
|
| 1614 |
+
if f.get("people") and len(f["people"]) > 0:
|
| 1615 |
+
f["people"][0]["pose_keypoints_2d"] = final_body[i]
|
| 1616 |
+
f["people"][0]["hand_left_keypoints_2d"] = final_lh[i]
|
| 1617 |
+
f["people"][0]["hand_right_keypoints_2d"] = final_rh[i]
|
| 1618 |
+
f["people"][0]["face_keypoints_2d"] = final_face[i]
|
| 1619 |
+
# ========================================================
|
| 1620 |
+
|
| 1621 |
+
return out_frames
|
| 1622 |
+
|
| 1623 |
+
|
| 1624 |
+
# ============================================================
|
| 1625 |
+
# === START: render_pose_video.py logic (ported to frame render)
|
| 1626 |
+
# ============================================================
|
| 1627 |
+
|
| 1628 |
+
OP_COLORS: List[Tuple[int, int, int]] = [
|
| 1629 |
+
(255, 0, 0),
|
| 1630 |
+
(255, 85, 0),
|
| 1631 |
+
(255, 170, 0),
|
| 1632 |
+
(255, 255, 0),
|
| 1633 |
+
(170, 255, 0),
|
| 1634 |
+
(85, 255, 0),
|
| 1635 |
+
(0, 255, 0),
|
| 1636 |
+
(0, 255, 85),
|
| 1637 |
+
(0, 255, 170),
|
| 1638 |
+
(0, 255, 255),
|
| 1639 |
+
(0, 170, 255),
|
| 1640 |
+
(0, 85, 255),
|
| 1641 |
+
(0, 0, 255),
|
| 1642 |
+
(85, 0, 255),
|
| 1643 |
+
(170, 0, 255),
|
| 1644 |
+
(255, 0, 255),
|
| 1645 |
+
(255, 0, 170),
|
| 1646 |
+
(255, 0, 85),
|
| 1647 |
+
]
|
| 1648 |
+
|
| 1649 |
+
BODY_EDGES: List[Tuple[int, int]] = [
|
| 1650 |
+
(1, 2),
|
| 1651 |
+
(1, 5),
|
| 1652 |
+
(2, 3),
|
| 1653 |
+
(3, 4),
|
| 1654 |
+
(5, 6),
|
| 1655 |
+
(6, 7),
|
| 1656 |
+
(1, 8),
|
| 1657 |
+
(8, 9),
|
| 1658 |
+
(9, 10),
|
| 1659 |
+
(1, 11),
|
| 1660 |
+
(11, 12),
|
| 1661 |
+
(12, 13),
|
| 1662 |
+
(1, 0),
|
| 1663 |
+
(0, 14),
|
| 1664 |
+
(14, 16),
|
| 1665 |
+
(0, 15),
|
| 1666 |
+
(15, 17),
|
| 1667 |
+
]
|
| 1668 |
+
|
| 1669 |
+
BODY_EDGE_COLORS = OP_COLORS[: len(BODY_EDGES)]
|
| 1670 |
+
BODY_JOINT_COLORS = OP_COLORS
|
| 1671 |
+
|
| 1672 |
+
HAND_EDGES: List[Tuple[int, int]] = [
|
| 1673 |
+
(0, 1),
|
| 1674 |
+
(1, 2),
|
| 1675 |
+
(2, 3),
|
| 1676 |
+
(3, 4),
|
| 1677 |
+
(0, 5),
|
| 1678 |
+
(5, 6),
|
| 1679 |
+
(6, 7),
|
| 1680 |
+
(7, 8),
|
| 1681 |
+
(0, 9),
|
| 1682 |
+
(9, 10),
|
| 1683 |
+
(10, 11),
|
| 1684 |
+
(11, 12),
|
| 1685 |
+
(0, 13),
|
| 1686 |
+
(13, 14),
|
| 1687 |
+
(14, 15),
|
| 1688 |
+
(15, 16),
|
| 1689 |
+
(0, 17),
|
| 1690 |
+
(17, 18),
|
| 1691 |
+
(18, 19),
|
| 1692 |
+
(19, 20),
|
| 1693 |
+
]
|
| 1694 |
+
|
| 1695 |
+
|
| 1696 |
+
def _valid_pt(x: float, y: float, c: float, conf_thresh: float) -> bool:
|
| 1697 |
+
return (c is not None) and (c >= conf_thresh) and not (x == 0 and y == 0)
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
def _hsv_to_bgr(h: float, s: float, v: float) -> Tuple[int, int, int]:
|
| 1701 |
+
H = int(np.clip(h, 0.0, 1.0) * 179.0)
|
| 1702 |
+
S = int(np.clip(s, 0.0, 1.0) * 255.0)
|
| 1703 |
+
V = int(np.clip(v, 0.0, 1.0) * 255.0)
|
| 1704 |
+
hsv = np.uint8([[[H, S, V]]])
|
| 1705 |
+
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)[0, 0]
|
| 1706 |
+
return int(bgr[0]), int(bgr[1]), int(bgr[2])
|
| 1707 |
+
|
| 1708 |
+
|
| 1709 |
+
def _looks_normalized(points: List[Tuple[float, float, float]], conf_thresh: float) -> bool:
|
| 1710 |
+
valid = [(x, y, c) for (x, y, c) in points if _valid_pt(x, y, c, conf_thresh)]
|
| 1711 |
+
if not valid:
|
| 1712 |
+
return False
|
| 1713 |
+
in01 = sum(1 for (x, y, _) in valid if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0)
|
| 1714 |
+
return (in01 / float(len(valid))) >= 0.7
|
| 1715 |
+
|
| 1716 |
+
|
| 1717 |
+
def _draw_body(
|
| 1718 |
+
canvas: np.ndarray, pose: List[Tuple[float, float, float]], conf_thresh: float, xinsr_stick_scaling: bool = False
|
| 1719 |
+
) -> None:
|
| 1720 |
+
CH, CW = canvas.shape[:2]
|
| 1721 |
+
stickwidth = 2
|
| 1722 |
+
valid = [(x, y, c) for (x, y, c) in pose if _valid_pt(x, y, c, conf_thresh)]
|
| 1723 |
+
norm = False
|
| 1724 |
+
if valid:
|
| 1725 |
+
in01 = sum(1 for (x, y, _) in valid if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0)
|
| 1726 |
+
norm = (in01 / float(len(valid))) >= 0.7
|
| 1727 |
+
|
| 1728 |
+
def to_px(x: float, y: float) -> Tuple[float, float]:
|
| 1729 |
+
if norm:
|
| 1730 |
+
return x * CW, y * CH
|
| 1731 |
+
return x, y
|
| 1732 |
+
|
| 1733 |
+
max_side = max(CW, CH)
|
| 1734 |
+
stick_scale = 1 if max_side < 500 else min(2 + (max_side // 1000), 7) if xinsr_stick_scaling else 1
|
| 1735 |
+
|
| 1736 |
+
for idx, (a, b) in enumerate(BODY_EDGES):
|
| 1737 |
+
if a >= len(pose) or b >= len(pose):
|
| 1738 |
+
continue
|
| 1739 |
+
ax, ay, ac = pose[a]
|
| 1740 |
+
bx, by, bc = pose[b]
|
| 1741 |
+
if not (_valid_pt(ax, ay, ac, conf_thresh) and _valid_pt(bx, by, bc, conf_thresh)):
|
| 1742 |
+
continue
|
| 1743 |
+
|
| 1744 |
+
ax, ay = to_px(ax, ay)
|
| 1745 |
+
bx, by = to_px(bx, by)
|
| 1746 |
+
base = BODY_EDGE_COLORS[idx] if idx < len(BODY_EDGE_COLORS) else (255, 255, 255)
|
| 1747 |
+
|
| 1748 |
+
X = np.array([ay, by], dtype=np.float32)
|
| 1749 |
+
Y = np.array([ax, bx], dtype=np.float32)
|
| 1750 |
+
|
| 1751 |
+
mX, mY = float(np.mean(X)), float(np.mean(Y))
|
| 1752 |
+
length = float(np.hypot(X[0] - X[1], Y[0] - Y[1]))
|
| 1753 |
+
if length < 1.0:
|
| 1754 |
+
continue
|
| 1755 |
+
|
| 1756 |
+
angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
|
| 1757 |
+
polygon = cv2.ellipse2Poly(
|
| 1758 |
+
(int(mY), int(mX)), (int(length / 2), int(stickwidth * stick_scale)), int(angle), 0, 360, 1
|
| 1759 |
+
)
|
| 1760 |
+
cv2.fillConvexPoly(canvas, polygon, (int(base[0] * 0.6), int(base[1] * 0.6), int(base[2] * 0.6)))
|
| 1761 |
+
|
| 1762 |
+
for j, (x, y, c) in enumerate(pose):
|
| 1763 |
+
if not _valid_pt(x, y, c, conf_thresh):
|
| 1764 |
+
continue
|
| 1765 |
+
x, y = to_px(x, y)
|
| 1766 |
+
col = BODY_JOINT_COLORS[j] if j < len(BODY_JOINT_COLORS) else (255, 255, 255)
|
| 1767 |
+
cv2.circle(canvas, (int(x), int(y)), 2, col, thickness=-1)
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
def _draw_hand(canvas: np.ndarray, hand: List[Tuple[float, float, float]], conf_thresh: float) -> None:
|
| 1771 |
+
if not hand or len(hand) < 21:
|
| 1772 |
+
return
|
| 1773 |
+
CH, CW = canvas.shape[:2]
|
| 1774 |
+
norm = _looks_normalized(hand, conf_thresh)
|
| 1775 |
+
|
| 1776 |
+
def to_px(x: float, y: float) -> Tuple[float, float]:
|
| 1777 |
+
return (x * CW, y * CH) if norm else (x, y)
|
| 1778 |
+
|
| 1779 |
+
n_edges = len(HAND_EDGES)
|
| 1780 |
+
for i, (a, b) in enumerate(HAND_EDGES):
|
| 1781 |
+
x1, y1, c1 = hand[a]
|
| 1782 |
+
x2, y2, c2 = hand[b]
|
| 1783 |
+
if _valid_pt(x1, y1, c1, conf_thresh) and _valid_pt(x2, y2, c2, conf_thresh):
|
| 1784 |
+
x1, y1 = to_px(x1, y1)
|
| 1785 |
+
x2, y2 = to_px(x2, y2)
|
| 1786 |
+
cv2.line(
|
| 1787 |
+
canvas,
|
| 1788 |
+
(int(x1), int(y1)),
|
| 1789 |
+
(int(x2), int(y2)),
|
| 1790 |
+
_hsv_to_bgr(i / float(n_edges), 1.0, 1.0),
|
| 1791 |
+
1,
|
| 1792 |
+
cv2.LINE_AA,
|
| 1793 |
+
)
|
| 1794 |
+
for x, y, c in hand:
|
| 1795 |
+
if _valid_pt(x, y, c, conf_thresh):
|
| 1796 |
+
x, y = to_px(x, y)
|
| 1797 |
+
cv2.circle(canvas, (int(x), int(y)), 1, (0, 0, 255), -1, cv2.LINE_AA)
|
| 1798 |
+
|
| 1799 |
+
|
| 1800 |
+
def _draw_face(canvas: np.ndarray, face: List[Tuple[float, float, float]], conf_thresh: float) -> None:
|
| 1801 |
+
if not face:
|
| 1802 |
+
return
|
| 1803 |
+
CH, CW = canvas.shape[:2]
|
| 1804 |
+
norm = _looks_normalized(face, conf_thresh)
|
| 1805 |
+
|
| 1806 |
+
def to_px(x: float, y: float) -> Tuple[float, float]:
|
| 1807 |
+
return (x * CW, y * CH) if norm else (x, y)
|
| 1808 |
+
|
| 1809 |
+
for x, y, c in face:
|
| 1810 |
+
if _valid_pt(x, y, c, conf_thresh):
|
| 1811 |
+
x, y = to_px(x, y)
|
| 1812 |
+
cv2.circle(canvas, (int(x), int(y)), 0, (255, 255, 255), -1, cv2.LINE_AA)
|
| 1813 |
+
|
| 1814 |
+
|
| 1815 |
+
def _draw_pose_frame_full(
|
| 1816 |
+
w: int,
|
| 1817 |
+
h: int,
|
| 1818 |
+
person: Dict[str, Any],
|
| 1819 |
+
conf_thresh_body: float = 0.10,
|
| 1820 |
+
conf_thresh_hands: float = 0.10,
|
| 1821 |
+
conf_thresh_face: float = 0.10,
|
| 1822 |
+
) -> np.ndarray:
|
| 1823 |
+
img = np.zeros((h, w, 3), dtype=np.uint8)
|
| 1824 |
+
pose = _reshape_keypoints_2d(person.get("pose_keypoints_2d") or [])
|
| 1825 |
+
face = _reshape_keypoints_2d(person.get("face_keypoints_2d") or [])
|
| 1826 |
+
hand_l = _reshape_keypoints_2d(person.get("hand_left_keypoints_2d") or [])
|
| 1827 |
+
hand_r = _reshape_keypoints_2d(person.get("hand_right_keypoints_2d") or [])
|
| 1828 |
+
|
| 1829 |
+
if pose:
|
| 1830 |
+
_draw_body(img, pose, conf_thresh_body)
|
| 1831 |
+
if hand_l:
|
| 1832 |
+
_draw_hand(img, hand_l, conf_thresh_hands)
|
| 1833 |
+
if hand_r:
|
| 1834 |
+
_draw_hand(img, hand_r, conf_thresh_hands)
|
| 1835 |
+
if face:
|
| 1836 |
+
_draw_face(img, face, conf_thresh_face)
|
| 1837 |
+
return img
|
nodes/preview_image_metadata.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import random
|
| 6 |
+
from typing import Any, Dict, List
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import folder_paths # ComfyUI
|
| 13 |
+
except Exception:
|
| 14 |
+
folder_paths = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _get_temp_dir() -> str:
|
| 18 |
+
if folder_paths is not None and hasattr(folder_paths, "get_temp_directory"):
|
| 19 |
+
return folder_paths.get_temp_directory()
|
| 20 |
+
return os.path.join(os.getcwd(), "temp")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _unique_basename(prefix: str = "preview") -> str:
|
| 24 |
+
return f"{prefix}_{int(time.time()*1000)}_{random.randint(0, 999999):06d}"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _tensor_to_pil(img: Any) -> Image.Image:
|
| 28 |
+
if hasattr(img, "detach"):
|
| 29 |
+
img = img.detach().cpu().numpy()
|
| 30 |
+
|
| 31 |
+
arr = np.asarray(img)
|
| 32 |
+
|
| 33 |
+
if arr.ndim != 3 or arr.shape[-1] not in (3, 4):
|
| 34 |
+
raise ValueError(f"Unsupported image shape for preview: {arr.shape}")
|
| 35 |
+
|
| 36 |
+
if np.issubdtype(arr.dtype, np.floating):
|
| 37 |
+
arr = np.clip(arr, 0.0, 1.0)
|
| 38 |
+
arr = (arr * 255.0).round().astype(np.uint8)
|
| 39 |
+
else:
|
| 40 |
+
arr = np.clip(arr, 0, 255).astype(np.uint8)
|
| 41 |
+
|
| 42 |
+
if arr.shape[-1] == 4:
|
| 43 |
+
pil = Image.fromarray(arr, mode="RGBA").convert("RGB")
|
| 44 |
+
else:
|
| 45 |
+
pil = Image.fromarray(arr, mode="RGB")
|
| 46 |
+
|
| 47 |
+
return pil
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class PreviewImageNoMetadata:
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def INPUT_TYPES(cls):
|
| 54 |
+
return {
|
| 55 |
+
"required": {
|
| 56 |
+
"image": ("IMAGE",),
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
RETURN_TYPES = ("IMAGE",)
|
| 61 |
+
FUNCTION = "preview"
|
| 62 |
+
OUTPUT_NODE = True
|
| 63 |
+
CATEGORY = "image"
|
| 64 |
+
|
| 65 |
+
def preview(self, image):
|
| 66 |
+
|
| 67 |
+
temp_dir = _get_temp_dir()
|
| 68 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 69 |
+
|
| 70 |
+
images_ui: List[Dict[str, str]] = []
|
| 71 |
+
|
| 72 |
+
batch = image
|
| 73 |
+
|
| 74 |
+
if hasattr(batch, "detach"):
|
| 75 |
+
b = int(batch.shape[0])
|
| 76 |
+
get_item = lambda i: batch[i]
|
| 77 |
+
else:
|
| 78 |
+
arr = np.asarray(batch)
|
| 79 |
+
b = int(arr.shape[0])
|
| 80 |
+
get_item = lambda i: arr[i]
|
| 81 |
+
|
| 82 |
+
base = _unique_basename("preview")
|
| 83 |
+
|
| 84 |
+
for i in range(b):
|
| 85 |
+
pil = _tensor_to_pil(get_item(i))
|
| 86 |
+
|
| 87 |
+
filename = f"{base}_{i:05d}.png"
|
| 88 |
+
out_path = os.path.join(temp_dir, filename)
|
| 89 |
+
|
| 90 |
+
# Всегда сохраняем БЕЗ metadata
|
| 91 |
+
pil.save(out_path, compress_level=4)
|
| 92 |
+
|
| 93 |
+
images_ui.append({"filename": filename, "subfolder": "", "type": "temp"})
|
| 94 |
+
|
| 95 |
+
return {"ui": {"images": images_ui}, "result": (image,)}
|
nodes/rename_files.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import uuid
|
| 4 |
+
import shutil
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def extract_first_number(s: str):
|
| 8 |
+
match = re.search(r"\d+", s)
|
| 9 |
+
return int(match.group()) if match else float("inf")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
sort_methods = [
|
| 13 |
+
"None",
|
| 14 |
+
"Alphabetical (ASC)",
|
| 15 |
+
"Alphabetical (DESC)",
|
| 16 |
+
"Numerical (ASC)",
|
| 17 |
+
"Numerical (DESC)",
|
| 18 |
+
"Datetime (ASC)",
|
| 19 |
+
"Datetime (DESC)",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def sort_by(items, base_path=".", method=None):
|
| 24 |
+
def fullpath(x):
|
| 25 |
+
return os.path.join(base_path, x)
|
| 26 |
+
|
| 27 |
+
def get_timestamp(path):
|
| 28 |
+
try:
|
| 29 |
+
return os.path.getmtime(path)
|
| 30 |
+
except FileNotFoundError:
|
| 31 |
+
return float("-inf")
|
| 32 |
+
|
| 33 |
+
if method == "Alphabetical (ASC)":
|
| 34 |
+
return sorted(items)
|
| 35 |
+
elif method == "Alphabetical (DESC)":
|
| 36 |
+
return sorted(items, reverse=True)
|
| 37 |
+
elif method == "Numerical (ASC)":
|
| 38 |
+
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]))
|
| 39 |
+
elif method == "Numerical (DESC)":
|
| 40 |
+
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]), reverse=True)
|
| 41 |
+
elif method == "Datetime (ASC)":
|
| 42 |
+
return sorted(items, key=lambda x: get_timestamp(fullpath(x)))
|
| 43 |
+
elif method == "Datetime (DESC)":
|
| 44 |
+
return sorted(items, key=lambda x: get_timestamp(fullpath(x)), reverse=True)
|
| 45 |
+
else:
|
| 46 |
+
return items
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _safe_list_files(directory: str):
|
| 50 |
+
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _format_name(index: int, digits: int, prefix: str, ext: str):
|
| 54 |
+
"""
|
| 55 |
+
ext ожидается как ".png"/".jpg"/".jpeg" (с точкой).
|
| 56 |
+
ВАЖНО: underscore после номера ВСЕГДА, потом расширение как есть.
|
| 57 |
+
Пример: prefix_0001_.png
|
| 58 |
+
"""
|
| 59 |
+
num = str(index).zfill(digits)
|
| 60 |
+
left = f"{prefix}_" if prefix else ""
|
| 61 |
+
return f"{left}{num}_{ext}"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _index_taken(directory: str, digits: int, prefix: str, index: int) -> bool:
|
| 65 |
+
"""
|
| 66 |
+
Проверяем, занят ли номер index ЛЮБЫМ расширением в папке.
|
| 67 |
+
Т.е. если есть prefix_0001_.png, то prefix_0001_.jpg уже нельзя.
|
| 68 |
+
"""
|
| 69 |
+
num = str(index).zfill(digits)
|
| 70 |
+
left = f"{prefix}_" if prefix else ""
|
| 71 |
+
start = f"{left}{num}_"
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
entries = os.listdir(directory)
|
| 75 |
+
except FileNotFoundError:
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
for f in entries:
|
| 79 |
+
p = os.path.join(directory, f)
|
| 80 |
+
if os.path.isfile(p) and f.startswith(start):
|
| 81 |
+
return True
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _find_next_free_index(directory: str, digits: int, prefix: str, start_from: int = 1) -> int:
|
| 86 |
+
idx = max(1, int(start_from))
|
| 87 |
+
while _index_taken(directory, digits, prefix, idx):
|
| 88 |
+
idx += 1
|
| 89 |
+
return idx
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class RenameFilesInDir:
|
| 93 |
+
OUTPUT_NODE = True
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
def INPUT_TYPES(cls):
|
| 97 |
+
return {
|
| 98 |
+
"required": {
|
| 99 |
+
"directory": ("STRING", {"default": ""}),
|
| 100 |
+
},
|
| 101 |
+
"optional": {
|
| 102 |
+
"output_directory": ("STRING", {"default": ""}),
|
| 103 |
+
"sort_method": (sort_methods,),
|
| 104 |
+
"start_index": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF, "step": 1}),
|
| 105 |
+
"files_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}),
|
| 106 |
+
"prefix": ("STRING", {"default": ""}),
|
| 107 |
+
"digits": ("INT", {"default": 4, "min": 1, "max": 16, "step": 1}),
|
| 108 |
+
},
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
RETURN_TYPES = ("INT",)
|
| 112 |
+
RETURN_NAMES = ("COUNT",)
|
| 113 |
+
FUNCTION = "run"
|
| 114 |
+
CATEGORY = "InspirePack/files"
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def IS_CHANGED(cls, **kwargs):
|
| 118 |
+
return float("NaN")
|
| 119 |
+
|
| 120 |
+
def run(
|
| 121 |
+
self,
|
| 122 |
+
directory: str,
|
| 123 |
+
output_directory: str = "",
|
| 124 |
+
sort_method=None,
|
| 125 |
+
start_index: int = 0,
|
| 126 |
+
files_load_cap: int = 0,
|
| 127 |
+
prefix: str = "",
|
| 128 |
+
digits: int = 4,
|
| 129 |
+
):
|
| 130 |
+
if not os.path.isdir(directory):
|
| 131 |
+
raise FileNotFoundError(f"Directory '{directory}' cannot be found.")
|
| 132 |
+
|
| 133 |
+
files = _safe_list_files(directory)
|
| 134 |
+
if not files:
|
| 135 |
+
return (0,)
|
| 136 |
+
|
| 137 |
+
files = sort_by(files, directory, sort_method)
|
| 138 |
+
files = files[start_index:]
|
| 139 |
+
|
| 140 |
+
if files_load_cap > 0:
|
| 141 |
+
files = files[:files_load_cap]
|
| 142 |
+
|
| 143 |
+
if not files:
|
| 144 |
+
return (0,)
|
| 145 |
+
|
| 146 |
+
inplace = (output_directory is None) or (str(output_directory).strip() == "")
|
| 147 |
+
|
| 148 |
+
if not inplace:
|
| 149 |
+
os.makedirs(output_directory, exist_ok=True)
|
| 150 |
+
|
| 151 |
+
count = 0
|
| 152 |
+
|
| 153 |
+
# ---------- COPY MODE ----------
|
| 154 |
+
if not inplace:
|
| 155 |
+
for fname in files:
|
| 156 |
+
src = os.path.join(directory, fname)
|
| 157 |
+
_, ext = os.path.splitext(fname) # ext = ".png" / ".jpg" / ...
|
| 158 |
+
|
| 159 |
+
next_idx = _find_next_free_index(output_directory, digits, prefix, start_from=1)
|
| 160 |
+
new_name = _format_name(next_idx, digits, prefix, ext)
|
| 161 |
+
|
| 162 |
+
dst = os.path.join(output_directory, new_name)
|
| 163 |
+
shutil.copy2(src, dst)
|
| 164 |
+
count += 1
|
| 165 |
+
|
| 166 |
+
return (count,)
|
| 167 |
+
|
| 168 |
+
# ---------- INPLACE RENAME ----------
|
| 169 |
+
temp_map = []
|
| 170 |
+
used_temp = set()
|
| 171 |
+
|
| 172 |
+
def _make_temp_name(old_name: str):
|
| 173 |
+
while True:
|
| 174 |
+
t = f"__tmp__{uuid.uuid4().hex}__{old_name}"
|
| 175 |
+
if t not in used_temp and not os.path.exists(os.path.join(directory, t)):
|
| 176 |
+
used_temp.add(t)
|
| 177 |
+
return t
|
| 178 |
+
|
| 179 |
+
# phase1 -> temp
|
| 180 |
+
for fname in files:
|
| 181 |
+
old_path = os.path.join(directory, fname)
|
| 182 |
+
tmp = _make_temp_name(fname)
|
| 183 |
+
tmp_path = os.path.join(directory, tmp)
|
| 184 |
+
|
| 185 |
+
os.rename(old_path, tmp_path)
|
| 186 |
+
temp_map.append((tmp, fname))
|
| 187 |
+
|
| 188 |
+
# phase2 -> final
|
| 189 |
+
for tmp, original_name in temp_map:
|
| 190 |
+
tmp_path = os.path.join(directory, tmp)
|
| 191 |
+
_, ext = os.path.splitext(original_name)
|
| 192 |
+
|
| 193 |
+
next_idx = _find_next_free_index(directory, digits, prefix, start_from=1)
|
| 194 |
+
new_name = _format_name(next_idx, digits, prefix, ext)
|
| 195 |
+
|
| 196 |
+
new_path = os.path.join(directory, new_name)
|
| 197 |
+
os.rename(tmp_path, new_path)
|
| 198 |
+
count += 1
|
| 199 |
+
|
| 200 |
+
return (count,)
|
nodes/save_load_pose.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import pickle
|
| 4 |
+
import glob
|
| 5 |
+
import folder_paths
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _ensure_output_dir():
|
| 9 |
+
out_dir = folder_paths.get_output_directory()
|
| 10 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 11 |
+
return out_dir
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# -------------------------
|
| 15 |
+
# UI: list PKL/PT under input/** (recursive)
|
| 16 |
+
# -------------------------
|
| 17 |
+
def _list_all_pkl_under_input():
|
| 18 |
+
inp = folder_paths.get_input_directory()
|
| 19 |
+
exts = (".pkl", ".pickle", ".pt")
|
| 20 |
+
|
| 21 |
+
files = []
|
| 22 |
+
for ext in exts:
|
| 23 |
+
pattern = os.path.join(inp, "**", f"*{ext}")
|
| 24 |
+
files.extend(glob.glob(pattern, recursive=True))
|
| 25 |
+
|
| 26 |
+
rel = []
|
| 27 |
+
for f in files:
|
| 28 |
+
if os.path.isfile(f):
|
| 29 |
+
r = os.path.relpath(f, inp).replace("\\", "/")
|
| 30 |
+
rel.append(r)
|
| 31 |
+
|
| 32 |
+
rel = sorted(set(rel))
|
| 33 |
+
return rel if rel else [""]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _abs_from_input(rel_path: str) -> str:
|
| 37 |
+
inp = folder_paths.get_input_directory()
|
| 38 |
+
return os.path.join(inp, rel_path).replace("\\", "/")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _make_unique_path(base_path: str) -> str:
|
| 42 |
+
"""
|
| 43 |
+
If file exists, append incremental suffix:
|
| 44 |
+
pose_data.pkl
|
| 45 |
+
pose_data_0001.pkl
|
| 46 |
+
pose_data_0002.pkl
|
| 47 |
+
"""
|
| 48 |
+
if not os.path.exists(base_path):
|
| 49 |
+
return base_path
|
| 50 |
+
|
| 51 |
+
directory = os.path.dirname(base_path)
|
| 52 |
+
name = os.path.basename(base_path)
|
| 53 |
+
base, ext = os.path.splitext(name)
|
| 54 |
+
|
| 55 |
+
idx = 1
|
| 56 |
+
while True:
|
| 57 |
+
new_name = f"{base}_{idx:04d}{ext}"
|
| 58 |
+
new_path = os.path.join(directory, new_name)
|
| 59 |
+
if not os.path.exists(new_path):
|
| 60 |
+
return new_path
|
| 61 |
+
idx += 1
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _default_filename(prefix: str, ext: str):
|
| 65 |
+
ts = time.strftime("%Y%m%d_%H%M%S")
|
| 66 |
+
return f"{prefix}_{ts}{ext}"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class TSSavePoseDataAsPickle:
|
| 70 |
+
OUTPUT_NODE = True
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def INPUT_TYPES(s):
|
| 74 |
+
return {
|
| 75 |
+
"required": {
|
| 76 |
+
"pose_data": ("POSEDATA",),
|
| 77 |
+
"filename": ("STRING", {"default": ""}),
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
RETURN_TYPES = ("STRING",)
|
| 82 |
+
RETURN_NAMES = ("saved_path",)
|
| 83 |
+
FUNCTION = "save"
|
| 84 |
+
CATEGORY = "save"
|
| 85 |
+
|
| 86 |
+
def save(self, pose_data, filename=""):
|
| 87 |
+
out_dir = _ensure_output_dir()
|
| 88 |
+
filename = (filename or "").strip()
|
| 89 |
+
if not filename:
|
| 90 |
+
filename = _default_filename("pose_data", ".pkl")
|
| 91 |
+
if not filename.lower().endswith((".pkl", ".pickle")):
|
| 92 |
+
filename += ".pkl"
|
| 93 |
+
|
| 94 |
+
abs_path = _make_unique_path(os.path.join(out_dir, filename))
|
| 95 |
+
|
| 96 |
+
with open(abs_path, "wb") as f:
|
| 97 |
+
pickle.dump(pose_data, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 98 |
+
|
| 99 |
+
return (abs_path,)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TSLoadPoseDataPickle:
|
| 103 |
+
@classmethod
|
| 104 |
+
def INPUT_TYPES(s):
|
| 105 |
+
return {
|
| 106 |
+
"required": {
|
| 107 |
+
# dropdown + Upload, recursive input/**
|
| 108 |
+
"file": (_list_all_pkl_under_input(),),
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
RETURN_TYPES = ("POSEDATA",)
|
| 113 |
+
RETURN_NAMES = ("pose_data",)
|
| 114 |
+
FUNCTION = "load"
|
| 115 |
+
CATEGORY = "load"
|
| 116 |
+
|
| 117 |
+
def load(self, file):
|
| 118 |
+
if not isinstance(file, str) or not file.strip():
|
| 119 |
+
raise ValueError("TS PoseData Pickle: Please select a .pkl/.pt file.")
|
| 120 |
+
|
| 121 |
+
abs_path = _abs_from_input(file)
|
| 122 |
+
if not os.path.isfile(abs_path):
|
| 123 |
+
raise ValueError(f"TS PoseData Pickle: File not found: {abs_path}")
|
| 124 |
+
|
| 125 |
+
with open(abs_path, "rb") as f:
|
| 126 |
+
pose_data = pickle.load(f)
|
| 127 |
+
|
| 128 |
+
return (pose_data,)
|
nodes/video_combine_metadata.py
ADDED
|
@@ -0,0 +1,1311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single-file extraction of the **Video Combine** node from ComfyUI-VideoHelperSuite.
|
| 2 |
+
|
| 3 |
+
- Node class: VideoCombine
|
| 4 |
+
- ComfyUI registration name: VHS_VideoCombine
|
| 5 |
+
|
| 6 |
+
This is intended to be dropped into your own custom node package as a single .py file.
|
| 7 |
+
|
| 8 |
+
Notes:
|
| 9 |
+
- This file includes the minimal helpers that VideoCombine depends on (ffmpeg discovery,
|
| 10 |
+
simple caching, format json parsing, ffmpeg/gifski subprocess pipelines, etc.).
|
| 11 |
+
- It assumes you're running inside ComfyUI, so core modules like `folder_paths`, `server`,
|
| 12 |
+
and `comfy.utils.ProgressBar` must be available.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import datetime
|
| 19 |
+
import functools
|
| 20 |
+
import itertools
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import os
|
| 24 |
+
import re
|
| 25 |
+
import shutil
|
| 26 |
+
import subprocess
|
| 27 |
+
import sys
|
| 28 |
+
import time
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from string import Template
|
| 31 |
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
from PIL import ExifTags, Image
|
| 36 |
+
from PIL.PngImagePlugin import PngInfo
|
| 37 |
+
|
| 38 |
+
import folder_paths
|
| 39 |
+
import server
|
| 40 |
+
from comfy.utils import ProgressBar
|
| 41 |
+
|
| 42 |
+
# -----------------------------------------------------------------------------
|
| 43 |
+
# Logging (minimal, compatible)
|
| 44 |
+
# -----------------------------------------------------------------------------
|
| 45 |
+
logger = logging.getLogger("VideoHelperSuite.VideoCombine")
|
| 46 |
+
if not logger.handlers:
|
| 47 |
+
handler = logging.StreamHandler(sys.stdout)
|
| 48 |
+
handler.setFormatter(logging.Formatter("[%(name)s] - %(levelname)s - %(message)s"))
|
| 49 |
+
logger.addHandler(handler)
|
| 50 |
+
logger.setLevel(logging.INFO)
|
| 51 |
+
logger.propagate = False
|
| 52 |
+
|
| 53 |
+
ENCODE_ARGS = ("utf-8", "backslashreplace")
|
| 54 |
+
|
| 55 |
+
# -----------------------------------------------------------------------------
|
| 56 |
+
# Small utility helpers copied/adapted from VideoHelperSuite
|
| 57 |
+
# -----------------------------------------------------------------------------
|
| 58 |
+
|
| 59 |
+
BIGMAX = 2**53 - 1
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class MultiInput(str):
|
| 63 |
+
"""ComfyUI trick: allows a single input to accept multiple types."""
|
| 64 |
+
|
| 65 |
+
def __new__(cls, string: str, allowed_types: Any = "*"):
|
| 66 |
+
res = super().__new__(cls, string)
|
| 67 |
+
res.allowed_types = allowed_types
|
| 68 |
+
return res
|
| 69 |
+
|
| 70 |
+
def __ne__(self, other: Any) -> bool:
|
| 71 |
+
if self.allowed_types == "*" or other == "*":
|
| 72 |
+
return False
|
| 73 |
+
return other not in self.allowed_types
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
imageOrLatent = MultiInput("IMAGE", ["IMAGE", "LATENT"])
|
| 77 |
+
floatOrInt = MultiInput("FLOAT", ["FLOAT", "INT"])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ContainsAll(dict):
|
| 81 |
+
"""ComfyUI hidden input helper."""
|
| 82 |
+
|
| 83 |
+
def __contains__(self, other: Any) -> bool: # noqa: D401
|
| 84 |
+
return True
|
| 85 |
+
|
| 86 |
+
def __getitem__(self, key: Any):
|
| 87 |
+
return super().get(key, (None, {}))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def cached(duration: int):
|
| 91 |
+
"""Time-based cache decorator (seconds)."""
|
| 92 |
+
|
| 93 |
+
def dec(f):
|
| 94 |
+
cached_ret = None
|
| 95 |
+
cache_time = 0.0
|
| 96 |
+
|
| 97 |
+
@functools.wraps(f)
|
| 98 |
+
def cached_func():
|
| 99 |
+
nonlocal cache_time, cached_ret
|
| 100 |
+
now = time.time()
|
| 101 |
+
if now > cache_time + duration or cached_ret is None:
|
| 102 |
+
cache_time = now
|
| 103 |
+
cached_ret = f()
|
| 104 |
+
return cached_ret
|
| 105 |
+
|
| 106 |
+
return cached_func
|
| 107 |
+
|
| 108 |
+
return dec
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def merge_filter_args(args: List[str], ftype: str = "-vf"):
|
| 112 |
+
"""Merge multiple -vf occurrences into one (simple, no filter_complex support)."""
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
start_index = args.index(ftype) + 1
|
| 116 |
+
index = start_index
|
| 117 |
+
while True:
|
| 118 |
+
index = args.index(ftype, index)
|
| 119 |
+
args[start_index] += "," + args[index + 1]
|
| 120 |
+
args.pop(index)
|
| 121 |
+
args.pop(index)
|
| 122 |
+
except ValueError:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# -----------------------------------------------------------------------------
|
| 127 |
+
# ffmpeg / gifski discovery (copied in spirit from VHS)
|
| 128 |
+
# -----------------------------------------------------------------------------
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _ffmpeg_suitability(path: str) -> int:
|
| 132 |
+
try:
|
| 133 |
+
version = subprocess.run([path, "-version"], check=True, capture_output=True).stdout.decode(*ENCODE_ARGS)
|
| 134 |
+
except Exception:
|
| 135 |
+
return 0
|
| 136 |
+
|
| 137 |
+
score = 0
|
| 138 |
+
simple_criterion = [("libvpx", 20), ("264", 10), ("265", 3), ("svtav1", 5), ("libopus", 1)]
|
| 139 |
+
for needle, pts in simple_criterion:
|
| 140 |
+
if needle in version:
|
| 141 |
+
score += pts
|
| 142 |
+
|
| 143 |
+
copyright_index = version.find("2000-2")
|
| 144 |
+
if copyright_index >= 0:
|
| 145 |
+
yr = version[copyright_index + 6 : copyright_index + 9]
|
| 146 |
+
if yr.isnumeric():
|
| 147 |
+
score += int(yr)
|
| 148 |
+
|
| 149 |
+
return score
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _pick_ffmpeg() -> Optional[str]:
|
| 153 |
+
if "VHS_FORCE_FFMPEG_PATH" in os.environ:
|
| 154 |
+
return os.environ.get("VHS_FORCE_FFMPEG_PATH")
|
| 155 |
+
|
| 156 |
+
ffmpeg_paths: List[str] = []
|
| 157 |
+
|
| 158 |
+
# Prefer imageio-ffmpeg if available.
|
| 159 |
+
try:
|
| 160 |
+
from imageio_ffmpeg import get_ffmpeg_exe # type: ignore
|
| 161 |
+
|
| 162 |
+
ffmpeg_paths.append(get_ffmpeg_exe())
|
| 163 |
+
except Exception:
|
| 164 |
+
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ:
|
| 165 |
+
raise
|
| 166 |
+
logger.warning("Failed to import imageio_ffmpeg")
|
| 167 |
+
|
| 168 |
+
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ and ffmpeg_paths:
|
| 169 |
+
return ffmpeg_paths[0]
|
| 170 |
+
|
| 171 |
+
system_ffmpeg = shutil.which("ffmpeg")
|
| 172 |
+
if system_ffmpeg:
|
| 173 |
+
ffmpeg_paths.append(system_ffmpeg)
|
| 174 |
+
|
| 175 |
+
if os.path.isfile("ffmpeg"):
|
| 176 |
+
ffmpeg_paths.append(os.path.abspath("ffmpeg"))
|
| 177 |
+
if os.path.isfile("ffmpeg.exe"):
|
| 178 |
+
ffmpeg_paths.append(os.path.abspath("ffmpeg.exe"))
|
| 179 |
+
|
| 180 |
+
if not ffmpeg_paths:
|
| 181 |
+
logger.error("No valid ffmpeg found.")
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
if len(ffmpeg_paths) == 1:
|
| 185 |
+
return ffmpeg_paths[0]
|
| 186 |
+
|
| 187 |
+
return max(ffmpeg_paths, key=_ffmpeg_suitability)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
ffmpeg_path: Optional[str] = _pick_ffmpeg()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
gifski_path: Optional[str] = os.environ.get("VHS_GIFSKI") or os.environ.get("JOV_GIFSKI")
|
| 194 |
+
if gifski_path is None:
|
| 195 |
+
gifski_path = shutil.which("gifski")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# -----------------------------------------------------------------------------
|
| 199 |
+
# Built-in video format definitions (embedded from VideoHelperSuite/video_formats)
|
| 200 |
+
# -----------------------------------------------------------------------------
|
| 201 |
+
|
| 202 |
+
BUILTIN_VIDEO_FORMATS: Dict[str, Dict[str, Any]] = {
|
| 203 |
+
"16bit-png": {"extension": "%03d.png", "input_color_depth": "16bit", "main_pass": ["-n", "-pix_fmt", "rgba64"]},
|
| 204 |
+
"8bit-png": {"extension": "%03d.png", "main_pass": ["-n"]},
|
| 205 |
+
"ProRes": {
|
| 206 |
+
"audio_pass": ["-c:a", "pcm_s16le"],
|
| 207 |
+
"extension": "mov",
|
| 208 |
+
"extra_widgets": [["profile", ["lt", "standard", "hq", "4444", "4444xq"], {"default": "hq"}]],
|
| 209 |
+
"fake_trc": "bt709",
|
| 210 |
+
"main_pass": [
|
| 211 |
+
"-n",
|
| 212 |
+
"-c:v",
|
| 213 |
+
"prores_ks",
|
| 214 |
+
"-profile:v",
|
| 215 |
+
[["$profile"]],
|
| 216 |
+
[
|
| 217 |
+
"profile",
|
| 218 |
+
{
|
| 219 |
+
"1": [[]],
|
| 220 |
+
"2": [[]],
|
| 221 |
+
"3": [[]],
|
| 222 |
+
"4": [
|
| 223 |
+
"has_alpha",
|
| 224 |
+
{"False": [["-pix_fmt", "yuv444p10le"]], "True": [["-pix_fmt", "yuva444p10le"]]},
|
| 225 |
+
],
|
| 226 |
+
"4444": [
|
| 227 |
+
"has_alpha",
|
| 228 |
+
{"False": [["-pix_fmt", "yuv444p10le"]], "True": [["-pix_fmt", "yuva444p10le"]]},
|
| 229 |
+
],
|
| 230 |
+
"4444xq": [
|
| 231 |
+
"has_alpha",
|
| 232 |
+
{"False": [["-pix_fmt", "yuv444p10le"]], "True": [["-pix_fmt", "yuva444p10le"]]},
|
| 233 |
+
],
|
| 234 |
+
"hq": [[]],
|
| 235 |
+
"lt": [[]],
|
| 236 |
+
"standard": [[]],
|
| 237 |
+
},
|
| 238 |
+
],
|
| 239 |
+
"-vf",
|
| 240 |
+
"scale=out_color_matrix=bt709",
|
| 241 |
+
"-colorspace",
|
| 242 |
+
"bt709",
|
| 243 |
+
"-color_primaries",
|
| 244 |
+
"bt709",
|
| 245 |
+
"-color_trc",
|
| 246 |
+
"bt709",
|
| 247 |
+
],
|
| 248 |
+
},
|
| 249 |
+
"av1-webm": {
|
| 250 |
+
"audio_pass": ["-c:a", "libopus"],
|
| 251 |
+
"environment": {"SVT_LOG": "1"},
|
| 252 |
+
"extension": "webm",
|
| 253 |
+
"fake_trc": "bt709",
|
| 254 |
+
"input_color_depth": ["input_color_depth", ["8bit", "16bit"]],
|
| 255 |
+
"main_pass": [
|
| 256 |
+
"-n",
|
| 257 |
+
"-c:v",
|
| 258 |
+
"libsvtav1",
|
| 259 |
+
"-pix_fmt",
|
| 260 |
+
["pix_fmt", ["yuv420p10le", "yuv420p"]],
|
| 261 |
+
"-crf",
|
| 262 |
+
["crf", "INT", {"default": 23, "max": 100, "min": 0, "step": 1}],
|
| 263 |
+
"-vf",
|
| 264 |
+
"scale=out_color_matrix=bt709",
|
| 265 |
+
"-color_range",
|
| 266 |
+
"tv",
|
| 267 |
+
"-colorspace",
|
| 268 |
+
"bt709",
|
| 269 |
+
"-color_primaries",
|
| 270 |
+
"bt709",
|
| 271 |
+
"-color_trc",
|
| 272 |
+
"bt709",
|
| 273 |
+
],
|
| 274 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 275 |
+
},
|
| 276 |
+
"ffmpeg-gif": {
|
| 277 |
+
"extension": "gif",
|
| 278 |
+
"main_pass": [
|
| 279 |
+
"-n",
|
| 280 |
+
"-filter_complex",
|
| 281 |
+
[
|
| 282 |
+
"dither",
|
| 283 |
+
[
|
| 284 |
+
"bayer",
|
| 285 |
+
"heckbert",
|
| 286 |
+
"floyd_steinberg",
|
| 287 |
+
"sierra2",
|
| 288 |
+
"sierra2_4a",
|
| 289 |
+
"sierra3",
|
| 290 |
+
"burkes",
|
| 291 |
+
"atkinson",
|
| 292 |
+
"none",
|
| 293 |
+
],
|
| 294 |
+
{"default": "sierra2_4a"},
|
| 295 |
+
"[0:v] split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff "
|
| 296 |
+
"[p]; [b][p] paletteuse=dither=$val",
|
| 297 |
+
],
|
| 298 |
+
],
|
| 299 |
+
},
|
| 300 |
+
"ffv1-mkv": {
|
| 301 |
+
"audio_pass": ["-c:a", "flac"],
|
| 302 |
+
"extension": "mkv",
|
| 303 |
+
"input_color_depth": "16bit",
|
| 304 |
+
"main_pass": [
|
| 305 |
+
"-n",
|
| 306 |
+
"-c:v",
|
| 307 |
+
"ffv1",
|
| 308 |
+
"-level",
|
| 309 |
+
["level", ["0", "1", "3"], {"default": "3"}],
|
| 310 |
+
"-coder",
|
| 311 |
+
["coder", ["0", "1", "2"], {"default": "1"}],
|
| 312 |
+
"-context",
|
| 313 |
+
["context", ["0", "1"], {"default": "1"}],
|
| 314 |
+
"-g",
|
| 315 |
+
["gop_size", "INT", {"default": 1, "max": 300, "min": 1, "step": 1}],
|
| 316 |
+
"-slices",
|
| 317 |
+
["slices", ["4", "6", "9", "12", "16", "20", "24", "30"], {"default": "16"}],
|
| 318 |
+
"-slicecrc",
|
| 319 |
+
["slicecrc", ["0", "1"], {"default": "1"}],
|
| 320 |
+
"-pix_fmt",
|
| 321 |
+
[
|
| 322 |
+
"pix_fmt",
|
| 323 |
+
[
|
| 324 |
+
"rgba64le",
|
| 325 |
+
"bgra",
|
| 326 |
+
"yuv420p",
|
| 327 |
+
"yuv422p",
|
| 328 |
+
"yuv444p",
|
| 329 |
+
"yuva420p",
|
| 330 |
+
"yuva422p",
|
| 331 |
+
"yuva444p",
|
| 332 |
+
"yuv420p10le",
|
| 333 |
+
"yuv422p10le",
|
| 334 |
+
"yuv444p10le",
|
| 335 |
+
"yuv420p12le",
|
| 336 |
+
"yuv422p12le",
|
| 337 |
+
"yuv444p12le",
|
| 338 |
+
"yuv420p14le",
|
| 339 |
+
"yuv422p14le",
|
| 340 |
+
"yuv444p14le",
|
| 341 |
+
"yuv420p16le",
|
| 342 |
+
"yuv422p16le",
|
| 343 |
+
"yuv444p16le",
|
| 344 |
+
"gray",
|
| 345 |
+
"gray10le",
|
| 346 |
+
"gray12le",
|
| 347 |
+
"gray16le",
|
| 348 |
+
],
|
| 349 |
+
{"default": "rgba64le"},
|
| 350 |
+
],
|
| 351 |
+
],
|
| 352 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 353 |
+
"trim_to_audio": ["trim_to_audio", "BOOLEAN", {"default": True}],
|
| 354 |
+
},
|
| 355 |
+
"gifski": {
|
| 356 |
+
"extension": "gif",
|
| 357 |
+
"gifski_pass": ["-Q", ["quality", "INT", {"default": 90, "max": 100, "min": 1, "step": 1}]],
|
| 358 |
+
"main_pass": ["-pix_fmt", "yuv444p", "-vf", "scale=out_color_matrix=bt709:out_range=pc", "-color_range", "pc"],
|
| 359 |
+
},
|
| 360 |
+
"h264-mp4": {
|
| 361 |
+
"audio_pass": ["-c:a", "aac"],
|
| 362 |
+
"extension": "mp4",
|
| 363 |
+
"fake_trc": "bt709",
|
| 364 |
+
"main_pass": [
|
| 365 |
+
"-n",
|
| 366 |
+
"-c:v",
|
| 367 |
+
"libx264",
|
| 368 |
+
"-pix_fmt",
|
| 369 |
+
["pix_fmt", ["yuv420p", "yuv420p10le"]],
|
| 370 |
+
"-crf",
|
| 371 |
+
["crf", "INT", {"default": 19, "max": 100, "min": 0, "step": 1}],
|
| 372 |
+
"-vf",
|
| 373 |
+
"scale=out_color_matrix=bt709",
|
| 374 |
+
"-color_range",
|
| 375 |
+
"tv",
|
| 376 |
+
"-colorspace",
|
| 377 |
+
"bt709",
|
| 378 |
+
"-color_primaries",
|
| 379 |
+
"bt709",
|
| 380 |
+
"-color_trc",
|
| 381 |
+
"bt709",
|
| 382 |
+
],
|
| 383 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 384 |
+
"trim_to_audio": ["trim_to_audio", "BOOLEAN", {"default": True}],
|
| 385 |
+
},
|
| 386 |
+
"h265-mp4": {
|
| 387 |
+
"audio_pass": ["-c:a", "aac"],
|
| 388 |
+
"extension": "mp4",
|
| 389 |
+
"fake_trc": "bt709",
|
| 390 |
+
"main_pass": [
|
| 391 |
+
"-n",
|
| 392 |
+
"-c:v",
|
| 393 |
+
"libx265",
|
| 394 |
+
"-vtag",
|
| 395 |
+
"hvc1",
|
| 396 |
+
"-pix_fmt",
|
| 397 |
+
["pix_fmt", ["yuv420p10le", "yuv420p"]],
|
| 398 |
+
"-crf",
|
| 399 |
+
["crf", "INT", {"default": 22, "max": 100, "min": 0, "step": 1}],
|
| 400 |
+
"-preset",
|
| 401 |
+
"medium",
|
| 402 |
+
"-x265-params",
|
| 403 |
+
"log-level=quiet",
|
| 404 |
+
"-vf",
|
| 405 |
+
"scale=out_color_matrix=bt709",
|
| 406 |
+
"-color_range",
|
| 407 |
+
"tv",
|
| 408 |
+
"-colorspace",
|
| 409 |
+
"bt709",
|
| 410 |
+
"-color_primaries",
|
| 411 |
+
"bt709",
|
| 412 |
+
"-color_trc",
|
| 413 |
+
"bt709",
|
| 414 |
+
],
|
| 415 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 416 |
+
},
|
| 417 |
+
"nvenc_av1-mp4": {
|
| 418 |
+
"audio_pass": ["-c:a", "aac"],
|
| 419 |
+
"bitrate": ["bitrate", "INT", {"default": 10, "max": 999, "min": 1, "step": 1}],
|
| 420 |
+
"extension": "mp4",
|
| 421 |
+
"fake_trc": "bt709",
|
| 422 |
+
"main_pass": [
|
| 423 |
+
"-n",
|
| 424 |
+
"-c:v",
|
| 425 |
+
"av1_nvenc",
|
| 426 |
+
"-pix_fmt",
|
| 427 |
+
["pix_fmt", ["yuv420p", "p010le"]],
|
| 428 |
+
"-vf",
|
| 429 |
+
"scale=out_color_matrix=bt709",
|
| 430 |
+
"-color_range",
|
| 431 |
+
"tv",
|
| 432 |
+
"-colorspace",
|
| 433 |
+
"bt709",
|
| 434 |
+
"-color_primaries",
|
| 435 |
+
"bt709",
|
| 436 |
+
"-color_trc",
|
| 437 |
+
"bt709",
|
| 438 |
+
],
|
| 439 |
+
"megabit": ["megabit", "BOOLEAN", {"default": True}],
|
| 440 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 441 |
+
},
|
| 442 |
+
"nvenc_h264-mp4": {
|
| 443 |
+
"audio_pass": ["-c:a", "aac"],
|
| 444 |
+
"bitrate": ["bitrate", "INT", {"default": 10, "max": 999, "min": 1, "step": 1}],
|
| 445 |
+
"extension": "mp4",
|
| 446 |
+
"fake_trc": "bt709",
|
| 447 |
+
"main_pass": [
|
| 448 |
+
"-n",
|
| 449 |
+
"-c:v",
|
| 450 |
+
"h264_nvenc",
|
| 451 |
+
"-pix_fmt",
|
| 452 |
+
["pix_fmt", ["yuv420p", "p010le"]],
|
| 453 |
+
"-vf",
|
| 454 |
+
"scale=out_color_matrix=bt709",
|
| 455 |
+
"-color_range",
|
| 456 |
+
"tv",
|
| 457 |
+
"-colorspace",
|
| 458 |
+
"bt709",
|
| 459 |
+
"-color_primaries",
|
| 460 |
+
"bt709",
|
| 461 |
+
"-color_trc",
|
| 462 |
+
"bt709",
|
| 463 |
+
],
|
| 464 |
+
"megabit": ["megabit", "BOOLEAN", {"default": True}],
|
| 465 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 466 |
+
},
|
| 467 |
+
"nvenc_hevc-mp4": {
|
| 468 |
+
"audio_pass": ["-c:a", "aac"],
|
| 469 |
+
"bitrate": ["bitrate", "INT", {"default": 10, "max": 999, "min": 1, "step": 1}],
|
| 470 |
+
"extension": "mp4",
|
| 471 |
+
"fake_trc": "bt709",
|
| 472 |
+
"main_pass": [
|
| 473 |
+
"-n",
|
| 474 |
+
"-c:v",
|
| 475 |
+
"hevc_nvenc",
|
| 476 |
+
"-vtag",
|
| 477 |
+
"hvc1",
|
| 478 |
+
"-pix_fmt",
|
| 479 |
+
["pix_fmt", ["yuv420p", "p010le"]],
|
| 480 |
+
"-vf",
|
| 481 |
+
"scale=out_color_matrix=bt709",
|
| 482 |
+
"-color_range",
|
| 483 |
+
"tv",
|
| 484 |
+
"-colorspace",
|
| 485 |
+
"bt709",
|
| 486 |
+
"-color_primaries",
|
| 487 |
+
"bt709",
|
| 488 |
+
"-color_trc",
|
| 489 |
+
"bt709",
|
| 490 |
+
],
|
| 491 |
+
"megabit": ["megabit", "BOOLEAN", {"default": True}],
|
| 492 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 493 |
+
},
|
| 494 |
+
"webm": {
|
| 495 |
+
"audio_pass": ["-c:a", "libvorbis"],
|
| 496 |
+
"extension": "webm",
|
| 497 |
+
"fake_trc": "bt709",
|
| 498 |
+
"main_pass": [
|
| 499 |
+
"-n",
|
| 500 |
+
"-pix_fmt",
|
| 501 |
+
["pix_fmt", ["yuv420p", "yuva420p"]],
|
| 502 |
+
"-crf",
|
| 503 |
+
["crf", "INT", {"default": 20, "max": 100, "min": 0, "step": 1}],
|
| 504 |
+
"-b:v",
|
| 505 |
+
"0",
|
| 506 |
+
"-vf",
|
| 507 |
+
"scale=out_color_matrix=bt709",
|
| 508 |
+
"-color_range",
|
| 509 |
+
"tv",
|
| 510 |
+
"-colorspace",
|
| 511 |
+
"bt709",
|
| 512 |
+
"-color_primaries",
|
| 513 |
+
"bt709",
|
| 514 |
+
"-color_trc",
|
| 515 |
+
"bt709",
|
| 516 |
+
],
|
| 517 |
+
"save_metadata": ["save_metadata", "BOOLEAN", {"default": True}],
|
| 518 |
+
"trim_to_audio": ["trim_to_audio", "BOOLEAN", {"default": True}],
|
| 519 |
+
},
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# -----------------------------------------------------------------------------
|
| 524 |
+
# Requeue support for BatchManager compatibility (as in VHS)
|
| 525 |
+
# -----------------------------------------------------------------------------
|
| 526 |
+
|
| 527 |
+
prompt_queue = server.PromptServer.instance.prompt_queue
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def requeue_workflow_unchecked():
|
| 531 |
+
"""Requeues the current workflow without checking for multiple requeues."""
|
| 532 |
+
|
| 533 |
+
currently_running = prompt_queue.currently_running
|
| 534 |
+
value = next(iter(currently_running.values()))
|
| 535 |
+
|
| 536 |
+
if len(value) == 6:
|
| 537 |
+
(_, prompt_id, prompt, extra_data, outputs_to_execute, sensitive) = value
|
| 538 |
+
else:
|
| 539 |
+
(_, prompt_id, prompt, extra_data, outputs_to_execute) = value
|
| 540 |
+
sensitive = {}
|
| 541 |
+
|
| 542 |
+
prompt = prompt.copy()
|
| 543 |
+
for uid in prompt:
|
| 544 |
+
if prompt[uid]["class_type"] == "VHS_BatchManager":
|
| 545 |
+
prompt[uid]["inputs"]["requeue"] = prompt[uid]["inputs"].get("requeue", 0) + 1
|
| 546 |
+
|
| 547 |
+
number = -server.PromptServer.instance.number
|
| 548 |
+
server.PromptServer.instance.number += 1
|
| 549 |
+
prompt_id = str(server.uuid.uuid4())
|
| 550 |
+
prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute, sensitive))
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
_requeue_guard = [None, 0, 0, {}]
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def requeue_workflow(requeue_required: Tuple[Any, bool] = (-1, True)):
|
| 557 |
+
"""Requeue once all managed outputs have finished this batch."""
|
| 558 |
+
|
| 559 |
+
assert len(prompt_queue.currently_running) == 1
|
| 560 |
+
global _requeue_guard
|
| 561 |
+
|
| 562 |
+
value = next(iter(prompt_queue.currently_running.values()))
|
| 563 |
+
if len(value) == 6:
|
| 564 |
+
(run_number, _, prompt, extra_data, outputs_to_execute, _) = value
|
| 565 |
+
else:
|
| 566 |
+
(run_number, _, prompt, extra_data, outputs_to_execute) = value
|
| 567 |
+
|
| 568 |
+
if _requeue_guard[0] != run_number:
|
| 569 |
+
managed_outputs = 0
|
| 570 |
+
for bm_uid in prompt:
|
| 571 |
+
if prompt[bm_uid]["class_type"] == "VHS_BatchManager":
|
| 572 |
+
for output_uid in prompt:
|
| 573 |
+
if prompt[output_uid]["class_type"] in ["VHS_VideoCombine"]:
|
| 574 |
+
for inp in prompt[output_uid]["inputs"].values():
|
| 575 |
+
if inp == [bm_uid, 0]:
|
| 576 |
+
managed_outputs += 1
|
| 577 |
+
_requeue_guard = [run_number, 0, managed_outputs, {}]
|
| 578 |
+
|
| 579 |
+
_requeue_guard[1] += 1
|
| 580 |
+
_requeue_guard[3][requeue_required[0]] = requeue_required[1]
|
| 581 |
+
|
| 582 |
+
if _requeue_guard[1] == _requeue_guard[2] and max(_requeue_guard[3].values() or [False]):
|
| 583 |
+
requeue_workflow_unchecked()
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
if "VHS_video_formats" not in folder_paths.folder_names_and_paths:
|
| 587 |
+
folder_paths.folder_names_and_paths["VHS_video_formats"] = ((), {".json"})
|
| 588 |
+
if len(folder_paths.folder_names_and_paths["VHS_video_formats"][1]) == 0:
|
| 589 |
+
folder_paths.folder_names_and_paths["VHS_video_formats"][1].add(".json")
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def flatten_list(l: List[Any]) -> List[Any]:
|
| 593 |
+
ret: List[Any] = []
|
| 594 |
+
for e in l:
|
| 595 |
+
if isinstance(e, list):
|
| 596 |
+
ret.extend(e)
|
| 597 |
+
else:
|
| 598 |
+
ret.append(e)
|
| 599 |
+
return ret
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def iterate_format(video_format: Dict[str, Any], for_widgets: bool = True):
|
| 603 |
+
"""Iterate over widget/argument definitions inside a format json."""
|
| 604 |
+
|
| 605 |
+
def indirector(cont: Any, index: Any):
|
| 606 |
+
if isinstance(cont[index], list) and (
|
| 607 |
+
not for_widgets or (len(cont[index]) > 1 and not isinstance(cont[index][1], dict))
|
| 608 |
+
):
|
| 609 |
+
inp = yield cont[index]
|
| 610 |
+
if inp is not None:
|
| 611 |
+
cont[index] = inp
|
| 612 |
+
yield
|
| 613 |
+
|
| 614 |
+
for k in video_format:
|
| 615 |
+
if k == "extra_widgets":
|
| 616 |
+
if for_widgets:
|
| 617 |
+
yield from video_format["extra_widgets"]
|
| 618 |
+
elif k.endswith("_pass"):
|
| 619 |
+
for i in range(len(video_format[k])):
|
| 620 |
+
yield from indirector(video_format[k], i)
|
| 621 |
+
if not for_widgets:
|
| 622 |
+
video_format[k] = flatten_list(video_format[k])
|
| 623 |
+
else:
|
| 624 |
+
yield from indirector(video_format, k)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
_external_formats_dir = os.environ.get("VHS_BASE_FORMATS_DIR")
|
| 628 |
+
if not _external_formats_dir:
|
| 629 |
+
_external_formats_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "video_formats")
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
@cached(5)
|
| 633 |
+
def get_video_formats():
|
| 634 |
+
format_files: Dict[str, Any] = {}
|
| 635 |
+
|
| 636 |
+
for format_name in folder_paths.get_filename_list("VHS_video_formats"):
|
| 637 |
+
format_files[format_name] = folder_paths.get_full_path("VHS_video_formats", format_name)
|
| 638 |
+
|
| 639 |
+
for k in BUILTIN_VIDEO_FORMATS.keys():
|
| 640 |
+
format_files.setdefault(k, ("__embedded__", k))
|
| 641 |
+
|
| 642 |
+
if _external_formats_dir and os.path.isdir(_external_formats_dir):
|
| 643 |
+
for item in os.scandir(_external_formats_dir):
|
| 644 |
+
if not item.is_file() or not item.name.endswith(".json"):
|
| 645 |
+
continue
|
| 646 |
+
format_files[item.name[:-5]] = item.path
|
| 647 |
+
|
| 648 |
+
formats: List[str] = []
|
| 649 |
+
format_widgets: Dict[str, List[Any]] = {}
|
| 650 |
+
|
| 651 |
+
for format_name, src in format_files.items():
|
| 652 |
+
if isinstance(src, tuple) and src[0] == "__embedded__":
|
| 653 |
+
video_format = copy.deepcopy(BUILTIN_VIDEO_FORMATS[src[1]])
|
| 654 |
+
else:
|
| 655 |
+
with open(src, "r", encoding="utf-8") as stream:
|
| 656 |
+
video_format = json.load(stream)
|
| 657 |
+
|
| 658 |
+
video_format.pop("save_metadata", None)
|
| 659 |
+
|
| 660 |
+
if "gifski_pass" in video_format and gifski_path is None:
|
| 661 |
+
continue
|
| 662 |
+
|
| 663 |
+
widgets = list(iterate_format(video_format))
|
| 664 |
+
formats.append("video/" + format_name)
|
| 665 |
+
if widgets:
|
| 666 |
+
format_widgets["video/" + format_name] = widgets
|
| 667 |
+
|
| 668 |
+
return formats, format_widgets
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def apply_format_widgets(format_name: str, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
| 672 |
+
"""Load a format definition and fill/resolve widget-driven parameters.
|
| 673 |
+
|
| 674 |
+
`format_name` here is the part after 'video/', i.e. the json name without extension.
|
| 675 |
+
"""
|
| 676 |
+
|
| 677 |
+
if format_name in BUILTIN_VIDEO_FORMATS:
|
| 678 |
+
video_format = copy.deepcopy(BUILTIN_VIDEO_FORMATS[format_name])
|
| 679 |
+
else:
|
| 680 |
+
external_path = None
|
| 681 |
+
if _external_formats_dir:
|
| 682 |
+
p = os.path.join(_external_formats_dir, format_name + ".json")
|
| 683 |
+
if os.path.exists(p):
|
| 684 |
+
external_path = p
|
| 685 |
+
|
| 686 |
+
if external_path is not None:
|
| 687 |
+
video_format_path = external_path
|
| 688 |
+
else:
|
| 689 |
+
video_format_path = folder_paths.get_full_path("VHS_video_formats", format_name)
|
| 690 |
+
|
| 691 |
+
with open(video_format_path, "r", encoding="utf-8") as stream:
|
| 692 |
+
video_format = json.load(stream)
|
| 693 |
+
|
| 694 |
+
video_format.pop("save_metadata", None)
|
| 695 |
+
|
| 696 |
+
for w in iterate_format(video_format):
|
| 697 |
+
if w[0] not in kwargs:
|
| 698 |
+
if len(w) > 2 and isinstance(w[2], dict) and "default" in w[2]:
|
| 699 |
+
default = w[2]["default"]
|
| 700 |
+
else:
|
| 701 |
+
if isinstance(w[1], list):
|
| 702 |
+
default = w[1][0]
|
| 703 |
+
else:
|
| 704 |
+
default = {"BOOLEAN": False, "INT": 0, "FLOAT": 0, "STRING": ""}[w[1]]
|
| 705 |
+
kwargs[w[0]] = default
|
| 706 |
+
logger.warning(f"Missing input for {w[0]} has been set to {default}")
|
| 707 |
+
|
| 708 |
+
wit = iterate_format(video_format, False)
|
| 709 |
+
for w in wit:
|
| 710 |
+
while isinstance(w, list):
|
| 711 |
+
if len(w) == 1:
|
| 712 |
+
w = [Template(x).substitute(**kwargs) for x in w[0]]
|
| 713 |
+
break
|
| 714 |
+
elif isinstance(w[1], dict):
|
| 715 |
+
w = w[1][str(kwargs[w[0]])]
|
| 716 |
+
elif len(w) > 3:
|
| 717 |
+
w = Template(w[3]).substitute(val=kwargs[w[0]])
|
| 718 |
+
else:
|
| 719 |
+
w = str(kwargs[w[0]])
|
| 720 |
+
wit.send(w)
|
| 721 |
+
|
| 722 |
+
video_format["save_metadata"] = "False"
|
| 723 |
+
|
| 724 |
+
return video_format
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
# -----------------------------------------------------------------------------
|
| 728 |
+
# Tensor -> bytes helpers
|
| 729 |
+
# -----------------------------------------------------------------------------
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def tensor_to_int(tensor: torch.Tensor, bits: int) -> np.ndarray:
|
| 733 |
+
arr = tensor.cpu().numpy() * (2**bits - 1) + 0.5
|
| 734 |
+
return np.clip(arr, 0, (2**bits - 1))
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def tensor_to_shorts(tensor: torch.Tensor) -> np.ndarray:
|
| 738 |
+
return tensor_to_int(tensor, 16).astype(np.uint16)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def tensor_to_bytes(tensor: torch.Tensor) -> np.ndarray:
|
| 742 |
+
return tensor_to_int(tensor, 8).astype(np.uint8)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# -----------------------------------------------------------------------------
|
| 746 |
+
# ffmpeg / gifski pipeline processes (generators)
|
| 747 |
+
# -----------------------------------------------------------------------------
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def ffmpeg_process(
|
| 751 |
+
args: List[str], video_format: Dict[str, Any], video_metadata: Dict[str, Any], file_path: str, env: Dict[str, str]
|
| 752 |
+
):
|
| 753 |
+
res = None
|
| 754 |
+
frame_data = yield
|
| 755 |
+
total_frames_output = 0
|
| 756 |
+
|
| 757 |
+
if video_format.get("save_metadata", "False") != "False":
|
| 758 |
+
os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
|
| 759 |
+
metadata_path = os.path.join(folder_paths.get_temp_directory(), "metadata.txt")
|
| 760 |
+
|
| 761 |
+
def escape_ffmpeg_metadata(key: str, value: Any) -> str:
|
| 762 |
+
value = str(value)
|
| 763 |
+
value = value.replace("\\", "\\\\")
|
| 764 |
+
value = value.replace(";", "\\;")
|
| 765 |
+
value = value.replace("#", "\\#")
|
| 766 |
+
value = value.replace("=", "\\=")
|
| 767 |
+
value = value.replace("\n", "\\\n")
|
| 768 |
+
return f"{key}={value}"
|
| 769 |
+
|
| 770 |
+
with open(metadata_path, "w", encoding="utf-8") as f:
|
| 771 |
+
f.write(";FFMETADATA1\n")
|
| 772 |
+
if "prompt" in video_metadata:
|
| 773 |
+
f.write(escape_ffmpeg_metadata("prompt", json.dumps(video_metadata["prompt"])) + "\n")
|
| 774 |
+
if "workflow" in video_metadata:
|
| 775 |
+
f.write(escape_ffmpeg_metadata("workflow", json.dumps(video_metadata["workflow"])) + "\n")
|
| 776 |
+
for k, v in video_metadata.items():
|
| 777 |
+
if k not in ["prompt", "workflow"]:
|
| 778 |
+
f.write(escape_ffmpeg_metadata(k, json.dumps(v)) + "\n")
|
| 779 |
+
|
| 780 |
+
m_args = (
|
| 781 |
+
args[:1]
|
| 782 |
+
+ ["-i", metadata_path]
|
| 783 |
+
+ args[1:]
|
| 784 |
+
+ ["-metadata", "creation_time=now", "-movflags", "use_metadata_tags"]
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
with subprocess.Popen(m_args + [file_path], stderr=subprocess.PIPE, stdin=subprocess.PIPE, env=env) as proc:
|
| 788 |
+
try:
|
| 789 |
+
while frame_data is not None:
|
| 790 |
+
proc.stdin.write(frame_data)
|
| 791 |
+
frame_data = yield
|
| 792 |
+
total_frames_output += 1
|
| 793 |
+
proc.stdin.flush()
|
| 794 |
+
proc.stdin.close()
|
| 795 |
+
res = proc.stderr.read()
|
| 796 |
+
except BrokenPipeError:
|
| 797 |
+
err = proc.stderr.read()
|
| 798 |
+
if os.path.exists(file_path):
|
| 799 |
+
raise Exception("An error occurred in the ffmpeg subprocess:\n" + err.decode(*ENCODE_ARGS))
|
| 800 |
+
print(err.decode(*ENCODE_ARGS), end="", file=sys.stderr)
|
| 801 |
+
logger.warning("An error occurred when saving with metadata")
|
| 802 |
+
|
| 803 |
+
if res != b"":
|
| 804 |
+
with subprocess.Popen(args + [file_path], stderr=subprocess.PIPE, stdin=subprocess.PIPE, env=env) as proc:
|
| 805 |
+
try:
|
| 806 |
+
while frame_data is not None:
|
| 807 |
+
proc.stdin.write(frame_data)
|
| 808 |
+
frame_data = yield
|
| 809 |
+
total_frames_output += 1
|
| 810 |
+
proc.stdin.flush()
|
| 811 |
+
proc.stdin.close()
|
| 812 |
+
res = proc.stderr.read()
|
| 813 |
+
except BrokenPipeError:
|
| 814 |
+
res = proc.stderr.read()
|
| 815 |
+
raise Exception("An error occurred in the ffmpeg subprocess:\n" + res.decode(*ENCODE_ARGS))
|
| 816 |
+
|
| 817 |
+
yield total_frames_output
|
| 818 |
+
if res and len(res) > 0:
|
| 819 |
+
print(res.decode(*ENCODE_ARGS), end="", file=sys.stderr)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def gifski_process(
|
| 823 |
+
args: List[str],
|
| 824 |
+
dimensions: Tuple[int, int],
|
| 825 |
+
frame_rate: float,
|
| 826 |
+
video_format: Dict[str, Any],
|
| 827 |
+
file_path: str,
|
| 828 |
+
env: Dict[str, str],
|
| 829 |
+
):
|
| 830 |
+
if gifski_path is None:
|
| 831 |
+
raise ProcessLookupError("gifski is required for this output format but was not found")
|
| 832 |
+
|
| 833 |
+
frame_data = yield
|
| 834 |
+
with subprocess.Popen(
|
| 835 |
+
args + video_format["main_pass"] + ["-f", "yuv4mpegpipe", "-"],
|
| 836 |
+
stderr=subprocess.PIPE,
|
| 837 |
+
stdin=subprocess.PIPE,
|
| 838 |
+
stdout=subprocess.PIPE,
|
| 839 |
+
env=env,
|
| 840 |
+
) as procff:
|
| 841 |
+
with subprocess.Popen(
|
| 842 |
+
[gifski_path]
|
| 843 |
+
+ video_format["gifski_pass"]
|
| 844 |
+
+ ["-W", f"{dimensions[0]}", "-H", f"{dimensions[1]}"]
|
| 845 |
+
+ ["-r", f"{frame_rate}"]
|
| 846 |
+
+ ["-q", "-o", file_path, "-"],
|
| 847 |
+
stderr=subprocess.PIPE,
|
| 848 |
+
stdin=procff.stdout,
|
| 849 |
+
stdout=subprocess.PIPE,
|
| 850 |
+
env=env,
|
| 851 |
+
) as procgs:
|
| 852 |
+
try:
|
| 853 |
+
while frame_data is not None:
|
| 854 |
+
procff.stdin.write(frame_data)
|
| 855 |
+
frame_data = yield
|
| 856 |
+
procff.stdin.flush()
|
| 857 |
+
procff.stdin.close()
|
| 858 |
+
resff = procff.stderr.read()
|
| 859 |
+
resgs = procgs.stderr.read()
|
| 860 |
+
outgs = procgs.stdout.read()
|
| 861 |
+
except BrokenPipeError:
|
| 862 |
+
procff.stdin.close()
|
| 863 |
+
resff = procff.stderr.read()
|
| 864 |
+
resgs = procgs.stderr.read()
|
| 865 |
+
raise Exception(
|
| 866 |
+
"An error occurred while creating gifski output\n"
|
| 867 |
+
"Make sure you are using gifski --version >=1.32.0\n"
|
| 868 |
+
+ "ffmpeg: "
|
| 869 |
+
+ resff.decode(*ENCODE_ARGS)
|
| 870 |
+
+ "\n"
|
| 871 |
+
+ "gifski: "
|
| 872 |
+
+ resgs.decode(*ENCODE_ARGS)
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
if resff and len(resff) > 0:
|
| 876 |
+
print(resff.decode(*ENCODE_ARGS), end="", file=sys.stderr)
|
| 877 |
+
if resgs and len(resgs) > 0:
|
| 878 |
+
print(resgs.decode(*ENCODE_ARGS), end="", file=sys.stderr)
|
| 879 |
+
if outgs and len(outgs) > 0:
|
| 880 |
+
print(outgs.decode(*ENCODE_ARGS))
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def to_pingpong(inp: Any):
|
| 884 |
+
if not hasattr(inp, "__getitem__"):
|
| 885 |
+
inp = list(inp)
|
| 886 |
+
yield from inp
|
| 887 |
+
for i in range(len(inp) - 2, 0, -1):
|
| 888 |
+
yield inp[i]
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
# -----------------------------------------------------------------------------
|
| 892 |
+
# VideoCombine node
|
| 893 |
+
# -----------------------------------------------------------------------------
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
class TSVideoCombineNoMetadata:
|
| 897 |
+
@classmethod
|
| 898 |
+
def INPUT_TYPES(cls):
|
| 899 |
+
ffmpeg_formats, format_widgets = get_video_formats()
|
| 900 |
+
format_widgets["image/webp"] = [["lossless", "BOOLEAN", {"default": True}]]
|
| 901 |
+
return {
|
| 902 |
+
"required": {
|
| 903 |
+
"images": (imageOrLatent,),
|
| 904 |
+
"frame_rate": (floatOrInt, {"default": 8, "min": 1, "step": 1}),
|
| 905 |
+
"loop_count": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
|
| 906 |
+
"filename_prefix": ("STRING", {"default": "AnimateDiff"}),
|
| 907 |
+
"format": (
|
| 908 |
+
["image/gif", "image/webp"] + ffmpeg_formats,
|
| 909 |
+
{"formats": format_widgets},
|
| 910 |
+
),
|
| 911 |
+
"pingpong": ("BOOLEAN", {"default": False}),
|
| 912 |
+
"save_output": ("BOOLEAN", {"default": True}),
|
| 913 |
+
},
|
| 914 |
+
"optional": {
|
| 915 |
+
"audio": ("AUDIO",),
|
| 916 |
+
"meta_batch": ("VHS_BatchManager",),
|
| 917 |
+
"vae": ("VAE",),
|
| 918 |
+
},
|
| 919 |
+
"hidden": ContainsAll(
|
| 920 |
+
{
|
| 921 |
+
"prompt": "PROMPT",
|
| 922 |
+
"extra_pnginfo": "EXTRA_PNGINFO",
|
| 923 |
+
"unique_id": "UNIQUE_ID",
|
| 924 |
+
}
|
| 925 |
+
),
|
| 926 |
+
}
|
| 927 |
+
|
| 928 |
+
RETURN_TYPES = ("VHS_FILENAMES",)
|
| 929 |
+
RETURN_NAMES = ("Filenames",)
|
| 930 |
+
OUTPUT_NODE = True
|
| 931 |
+
CATEGORY = "Video Combine"
|
| 932 |
+
FUNCTION = "combine_video"
|
| 933 |
+
|
| 934 |
+
def combine_video(
|
| 935 |
+
self,
|
| 936 |
+
frame_rate: int,
|
| 937 |
+
loop_count: int,
|
| 938 |
+
images=None,
|
| 939 |
+
latents=None,
|
| 940 |
+
filename_prefix: str = "AnimateDiff",
|
| 941 |
+
format: str = "image/gif",
|
| 942 |
+
pingpong: bool = False,
|
| 943 |
+
save_output: bool = True,
|
| 944 |
+
prompt=None,
|
| 945 |
+
extra_pnginfo=None,
|
| 946 |
+
audio=None,
|
| 947 |
+
unique_id=None,
|
| 948 |
+
manual_format_widgets=None,
|
| 949 |
+
meta_batch=None,
|
| 950 |
+
vae=None,
|
| 951 |
+
**kwargs,
|
| 952 |
+
):
|
| 953 |
+
if latents is not None:
|
| 954 |
+
images = latents
|
| 955 |
+
if images is None:
|
| 956 |
+
return ((save_output, []),)
|
| 957 |
+
|
| 958 |
+
if vae is not None:
|
| 959 |
+
if isinstance(images, dict):
|
| 960 |
+
images = images["samples"]
|
| 961 |
+
else:
|
| 962 |
+
vae = None
|
| 963 |
+
|
| 964 |
+
if isinstance(images, torch.Tensor) and images.size(0) == 0:
|
| 965 |
+
return ((save_output, []),)
|
| 966 |
+
|
| 967 |
+
num_frames = len(images)
|
| 968 |
+
pbar = ProgressBar(num_frames)
|
| 969 |
+
|
| 970 |
+
if vae is not None:
|
| 971 |
+
downscale_ratio = getattr(vae, "downscale_ratio", 8)
|
| 972 |
+
width = images.size(-1) * downscale_ratio
|
| 973 |
+
height = images.size(-2) * downscale_ratio
|
| 974 |
+
frames_per_batch = (1920 * 1080 * 16) // (width * height) or 1
|
| 975 |
+
|
| 976 |
+
def batched(it, n):
|
| 977 |
+
while batch := tuple(itertools.islice(it, n)):
|
| 978 |
+
yield batch
|
| 979 |
+
|
| 980 |
+
def batched_decode(latents_iter, vae_obj, fpb):
|
| 981 |
+
for batch in batched(iter(latents_iter), fpb):
|
| 982 |
+
latent_batch = torch.from_numpy(np.array(batch))
|
| 983 |
+
yield from vae_obj.decode(latent_batch)
|
| 984 |
+
|
| 985 |
+
images = batched_decode(images, vae, frames_per_batch)
|
| 986 |
+
first_image = next(images)
|
| 987 |
+
images = itertools.chain([first_image], images)
|
| 988 |
+
while len(first_image.shape) > 3:
|
| 989 |
+
first_image = first_image[0]
|
| 990 |
+
else:
|
| 991 |
+
first_image = images[0]
|
| 992 |
+
images = iter(images)
|
| 993 |
+
|
| 994 |
+
output_dir = folder_paths.get_output_directory() if save_output else folder_paths.get_temp_directory()
|
| 995 |
+
(full_output_folder, filename, _, subfolder, _) = folder_paths.get_save_image_path(filename_prefix, output_dir)
|
| 996 |
+
output_files: List[str] = []
|
| 997 |
+
|
| 998 |
+
metadata = PngInfo()
|
| 999 |
+
video_metadata: Dict[str, Any] = {}
|
| 1000 |
+
if prompt is not None:
|
| 1001 |
+
metadata.add_text("prompt", json.dumps(prompt))
|
| 1002 |
+
video_metadata["prompt"] = json.dumps(prompt)
|
| 1003 |
+
|
| 1004 |
+
if extra_pnginfo is not None:
|
| 1005 |
+
for x in extra_pnginfo:
|
| 1006 |
+
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
| 1007 |
+
video_metadata[x] = extra_pnginfo[x]
|
| 1008 |
+
extra_options = extra_pnginfo.get("workflow", {}).get("extra", {})
|
| 1009 |
+
else:
|
| 1010 |
+
extra_options = {}
|
| 1011 |
+
|
| 1012 |
+
metadata.add_text("CreationTime", datetime.datetime.now().isoformat(" ")[:19])
|
| 1013 |
+
|
| 1014 |
+
if meta_batch is not None and unique_id in getattr(meta_batch, "outputs", {}):
|
| 1015 |
+
(counter, output_process) = meta_batch.outputs[unique_id]
|
| 1016 |
+
else:
|
| 1017 |
+
max_counter = 0
|
| 1018 |
+
matcher = re.compile(f"{re.escape(filename)}_(\\d+)\\D*\\..+", re.IGNORECASE)
|
| 1019 |
+
for existing_file in os.listdir(full_output_folder):
|
| 1020 |
+
match = matcher.fullmatch(existing_file)
|
| 1021 |
+
if match:
|
| 1022 |
+
file_counter = int(match.group(1))
|
| 1023 |
+
max_counter = max(max_counter, file_counter)
|
| 1024 |
+
counter = max_counter + 1
|
| 1025 |
+
output_process = None
|
| 1026 |
+
|
| 1027 |
+
first_image_file = f"{filename}_{counter:05}.png"
|
| 1028 |
+
png_path = os.path.join(full_output_folder, first_image_file)
|
| 1029 |
+
if extra_options.get("VHS_MetadataImage", True) is not False:
|
| 1030 |
+
Image.fromarray(tensor_to_bytes(first_image)).save(png_path, pnginfo=metadata, compress_level=4)
|
| 1031 |
+
output_files.append(png_path)
|
| 1032 |
+
|
| 1033 |
+
format_type, format_ext = format.split("/")
|
| 1034 |
+
|
| 1035 |
+
if format_type == "image":
|
| 1036 |
+
if meta_batch is not None:
|
| 1037 |
+
raise Exception("Pillow('image/') formats are not compatible with batched output")
|
| 1038 |
+
|
| 1039 |
+
image_kwargs: Dict[str, Any] = {}
|
| 1040 |
+
if format_ext == "gif":
|
| 1041 |
+
image_kwargs["disposal"] = 2
|
| 1042 |
+
if format_ext == "webp":
|
| 1043 |
+
exif = Image.Exif()
|
| 1044 |
+
exif[ExifTags.IFD.Exif] = {36867: datetime.datetime.now().isoformat(" ")[:19]}
|
| 1045 |
+
image_kwargs["exif"] = exif
|
| 1046 |
+
image_kwargs["lossless"] = kwargs.get("lossless", True)
|
| 1047 |
+
|
| 1048 |
+
out_file = f"{filename}_{counter:05}.{format_ext}"
|
| 1049 |
+
out_path = os.path.join(full_output_folder, out_file)
|
| 1050 |
+
|
| 1051 |
+
if pingpong:
|
| 1052 |
+
images = to_pingpong(images)
|
| 1053 |
+
|
| 1054 |
+
def frames_gen(images_iter):
|
| 1055 |
+
for i in images_iter:
|
| 1056 |
+
pbar.update(1)
|
| 1057 |
+
yield Image.fromarray(tensor_to_bytes(i))
|
| 1058 |
+
|
| 1059 |
+
frames = frames_gen(images)
|
| 1060 |
+
next(frames).save(
|
| 1061 |
+
out_path,
|
| 1062 |
+
format=format_ext.upper(),
|
| 1063 |
+
save_all=True,
|
| 1064 |
+
append_images=frames,
|
| 1065 |
+
duration=round(1000 / frame_rate),
|
| 1066 |
+
loop=loop_count,
|
| 1067 |
+
compress_level=4,
|
| 1068 |
+
**image_kwargs,
|
| 1069 |
+
)
|
| 1070 |
+
output_files.append(out_path)
|
| 1071 |
+
file_for_preview = out_file
|
| 1072 |
+
|
| 1073 |
+
else:
|
| 1074 |
+
if ffmpeg_path is None:
|
| 1075 |
+
raise ProcessLookupError(
|
| 1076 |
+
"ffmpeg is required for video outputs and could not be found.\n"
|
| 1077 |
+
"In order to use video outputs, you must either:\n"
|
| 1078 |
+
"- Install imageio-ffmpeg with pip,\n"
|
| 1079 |
+
"- Place a ffmpeg executable in the ComfyUI working directory, or\n"
|
| 1080 |
+
"- Install ffmpeg and add it to the system path."
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if manual_format_widgets is not None:
|
| 1084 |
+
logger.warning(
|
| 1085 |
+
"Format args can now be passed directly. The manual_format_widgets argument is deprecated."
|
| 1086 |
+
)
|
| 1087 |
+
kwargs.update(manual_format_widgets)
|
| 1088 |
+
|
| 1089 |
+
has_alpha = first_image.shape[-1] == 4
|
| 1090 |
+
kwargs["has_alpha"] = has_alpha
|
| 1091 |
+
|
| 1092 |
+
video_format = apply_format_widgets(format_ext, kwargs)
|
| 1093 |
+
dim_alignment = video_format.get("dim_alignment", 2)
|
| 1094 |
+
|
| 1095 |
+
if (first_image.shape[1] % dim_alignment) or (first_image.shape[0] % dim_alignment):
|
| 1096 |
+
to_pad = (-first_image.shape[1] % dim_alignment, -first_image.shape[0] % dim_alignment)
|
| 1097 |
+
padding = (
|
| 1098 |
+
to_pad[0] // 2,
|
| 1099 |
+
to_pad[0] - to_pad[0] // 2,
|
| 1100 |
+
to_pad[1] // 2,
|
| 1101 |
+
to_pad[1] - to_pad[1] // 2,
|
| 1102 |
+
)
|
| 1103 |
+
padfunc = torch.nn.ReplicationPad2d(padding)
|
| 1104 |
+
|
| 1105 |
+
def pad(image):
|
| 1106 |
+
image = image.permute((2, 0, 1))
|
| 1107 |
+
padded = padfunc(image.to(dtype=torch.float32))
|
| 1108 |
+
return padded.permute((1, 2, 0))
|
| 1109 |
+
|
| 1110 |
+
images = map(pad, images)
|
| 1111 |
+
dimensions = (
|
| 1112 |
+
-first_image.shape[1] % dim_alignment + first_image.shape[1],
|
| 1113 |
+
-first_image.shape[0] % dim_alignment + first_image.shape[0],
|
| 1114 |
+
)
|
| 1115 |
+
logger.warning("Output images were not of valid resolution; padding was applied")
|
| 1116 |
+
else:
|
| 1117 |
+
dimensions = (first_image.shape[1], first_image.shape[0])
|
| 1118 |
+
|
| 1119 |
+
if pingpong:
|
| 1120 |
+
if meta_batch is not None:
|
| 1121 |
+
logger.error("pingpong is incompatible with batched output")
|
| 1122 |
+
images = to_pingpong(images)
|
| 1123 |
+
if num_frames > 2:
|
| 1124 |
+
num_frames = num_frames + (num_frames - 2)
|
| 1125 |
+
pbar.total = num_frames
|
| 1126 |
+
|
| 1127 |
+
loop_args = ["-vf", f"loop=loop={loop_count}:size={num_frames}"] if loop_count > 0 else []
|
| 1128 |
+
|
| 1129 |
+
if video_format.get("input_color_depth", "8bit") == "16bit":
|
| 1130 |
+
images = map(tensor_to_shorts, images)
|
| 1131 |
+
i_pix_fmt = "rgba64" if has_alpha else "rgb48"
|
| 1132 |
+
else:
|
| 1133 |
+
images = map(tensor_to_bytes, images)
|
| 1134 |
+
i_pix_fmt = "rgba" if has_alpha else "rgb24"
|
| 1135 |
+
|
| 1136 |
+
out_file = f"{filename}_{counter:05}.{video_format['extension']}"
|
| 1137 |
+
out_path = os.path.join(full_output_folder, out_file)
|
| 1138 |
+
|
| 1139 |
+
bitrate_arg: List[str] = []
|
| 1140 |
+
bitrate = video_format.get("bitrate")
|
| 1141 |
+
if bitrate is not None:
|
| 1142 |
+
if video_format.get("megabit") == "True":
|
| 1143 |
+
bitrate_arg = ["-b:v", str(bitrate) + "M"]
|
| 1144 |
+
else:
|
| 1145 |
+
bitrate_arg = ["-b:v", str(bitrate) + "K"]
|
| 1146 |
+
|
| 1147 |
+
args = [
|
| 1148 |
+
ffmpeg_path,
|
| 1149 |
+
"-v",
|
| 1150 |
+
"error",
|
| 1151 |
+
"-f",
|
| 1152 |
+
"rawvideo",
|
| 1153 |
+
"-pix_fmt",
|
| 1154 |
+
i_pix_fmt,
|
| 1155 |
+
"-color_range",
|
| 1156 |
+
"pc",
|
| 1157 |
+
"-colorspace",
|
| 1158 |
+
"rgb",
|
| 1159 |
+
"-color_primaries",
|
| 1160 |
+
"bt709",
|
| 1161 |
+
"-color_trc",
|
| 1162 |
+
video_format.get("fake_trc", "iec61966-2-1"),
|
| 1163 |
+
"-s",
|
| 1164 |
+
f"{dimensions[0]}x{dimensions[1]}",
|
| 1165 |
+
"-r",
|
| 1166 |
+
str(frame_rate),
|
| 1167 |
+
"-i",
|
| 1168 |
+
"-",
|
| 1169 |
+
] + loop_args
|
| 1170 |
+
|
| 1171 |
+
images = map(lambda x: x.tobytes(), images)
|
| 1172 |
+
|
| 1173 |
+
env = os.environ.copy()
|
| 1174 |
+
if "environment" in video_format:
|
| 1175 |
+
env.update(video_format["environment"])
|
| 1176 |
+
|
| 1177 |
+
if "pre_pass" in video_format:
|
| 1178 |
+
if meta_batch is not None:
|
| 1179 |
+
raise Exception("Formats requiring pre_pass are incompatible with Batch Manager")
|
| 1180 |
+
images = [b"".join(images)]
|
| 1181 |
+
os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
|
| 1182 |
+
in_args_len = args.index("-i") + 2
|
| 1183 |
+
pre_pass_args = args[:in_args_len] + video_format["pre_pass"]
|
| 1184 |
+
merge_filter_args(pre_pass_args)
|
| 1185 |
+
try:
|
| 1186 |
+
subprocess.run(pre_pass_args, input=images[0], env=env, capture_output=True, check=True)
|
| 1187 |
+
except subprocess.CalledProcessError as e:
|
| 1188 |
+
raise Exception("An error occurred in the ffmpeg prepass:\n" + e.stderr.decode(*ENCODE_ARGS))
|
| 1189 |
+
|
| 1190 |
+
if "inputs_main_pass" in video_format:
|
| 1191 |
+
in_args_len = args.index("-i") + 2
|
| 1192 |
+
args = args[:in_args_len] + video_format["inputs_main_pass"] + args[in_args_len:]
|
| 1193 |
+
|
| 1194 |
+
if output_process is None:
|
| 1195 |
+
if "gifski_pass" in video_format:
|
| 1196 |
+
format = "image/gif"
|
| 1197 |
+
output_process = gifski_process(args, dimensions, frame_rate, video_format, out_path, env)
|
| 1198 |
+
audio = None
|
| 1199 |
+
else:
|
| 1200 |
+
args += video_format["main_pass"] + bitrate_arg
|
| 1201 |
+
merge_filter_args(args)
|
| 1202 |
+
output_process = ffmpeg_process(args, video_format, video_metadata, out_path, env)
|
| 1203 |
+
|
| 1204 |
+
output_process.send(None)
|
| 1205 |
+
if meta_batch is not None:
|
| 1206 |
+
meta_batch.outputs[unique_id] = (counter, output_process)
|
| 1207 |
+
|
| 1208 |
+
for image_bytes in images:
|
| 1209 |
+
pbar.update(1)
|
| 1210 |
+
output_process.send(image_bytes)
|
| 1211 |
+
|
| 1212 |
+
if meta_batch is not None:
|
| 1213 |
+
requeue_workflow((meta_batch.unique_id, not meta_batch.has_closed_inputs))
|
| 1214 |
+
|
| 1215 |
+
if meta_batch is None or meta_batch.has_closed_inputs:
|
| 1216 |
+
try:
|
| 1217 |
+
total_frames_output = output_process.send(None)
|
| 1218 |
+
output_process.send(None)
|
| 1219 |
+
except StopIteration:
|
| 1220 |
+
total_frames_output = num_frames
|
| 1221 |
+
|
| 1222 |
+
if meta_batch is not None:
|
| 1223 |
+
meta_batch.outputs.pop(unique_id, None)
|
| 1224 |
+
if len(meta_batch.outputs) == 0:
|
| 1225 |
+
meta_batch.reset()
|
| 1226 |
+
else:
|
| 1227 |
+
return {"ui": {"unfinished_batch": [True]}, "result": ((save_output, []),)}
|
| 1228 |
+
|
| 1229 |
+
output_files.append(out_path)
|
| 1230 |
+
|
| 1231 |
+
a_waveform = None
|
| 1232 |
+
if audio is not None:
|
| 1233 |
+
try:
|
| 1234 |
+
a_waveform = audio["waveform"]
|
| 1235 |
+
except Exception:
|
| 1236 |
+
a_waveform = None
|
| 1237 |
+
|
| 1238 |
+
if a_waveform is not None:
|
| 1239 |
+
output_with_audio = f"{filename}_{counter:05}-audio.{video_format['extension']}"
|
| 1240 |
+
output_with_audio_path = os.path.join(full_output_folder, output_with_audio)
|
| 1241 |
+
|
| 1242 |
+
if "audio_pass" not in video_format:
|
| 1243 |
+
logger.warning("Selected video format does not have explicit audio support")
|
| 1244 |
+
video_format["audio_pass"] = ["-c:a", "libopus"]
|
| 1245 |
+
|
| 1246 |
+
channels = audio["waveform"].size(1)
|
| 1247 |
+
min_audio_dur = total_frames_output / frame_rate + 1
|
| 1248 |
+
apad = (
|
| 1249 |
+
[]
|
| 1250 |
+
if video_format.get("trim_to_audio", "True") != "False"
|
| 1251 |
+
else ["-af", f"apad=whole_dur={min_audio_dur}"]
|
| 1252 |
+
)
|
| 1253 |
+
|
| 1254 |
+
mux_args = (
|
| 1255 |
+
[
|
| 1256 |
+
ffmpeg_path,
|
| 1257 |
+
"-v",
|
| 1258 |
+
"error",
|
| 1259 |
+
"-n",
|
| 1260 |
+
"-i",
|
| 1261 |
+
out_path,
|
| 1262 |
+
"-ar",
|
| 1263 |
+
str(audio["sample_rate"]),
|
| 1264 |
+
"-ac",
|
| 1265 |
+
str(channels),
|
| 1266 |
+
"-f",
|
| 1267 |
+
"f32le",
|
| 1268 |
+
"-i",
|
| 1269 |
+
"-",
|
| 1270 |
+
"-c:v",
|
| 1271 |
+
"copy",
|
| 1272 |
+
]
|
| 1273 |
+
+ video_format["audio_pass"]
|
| 1274 |
+
+ apad
|
| 1275 |
+
+ ["-shortest", output_with_audio_path]
|
| 1276 |
+
)
|
| 1277 |
+
|
| 1278 |
+
audio_data = audio["waveform"].squeeze(0).transpose(0, 1).numpy().tobytes()
|
| 1279 |
+
merge_filter_args(mux_args, "-af")
|
| 1280 |
+
try:
|
| 1281 |
+
res = subprocess.run(mux_args, input=audio_data, env=env, capture_output=True, check=True)
|
| 1282 |
+
except subprocess.CalledProcessError as e:
|
| 1283 |
+
raise Exception("An error occurred in the ffmpeg subprocess:\n" + e.stderr.decode(*ENCODE_ARGS))
|
| 1284 |
+
|
| 1285 |
+
if res.stderr:
|
| 1286 |
+
print(res.stderr.decode(*ENCODE_ARGS), end="", file=sys.stderr)
|
| 1287 |
+
|
| 1288 |
+
output_files.append(output_with_audio_path)
|
| 1289 |
+
file_for_preview = output_with_audio
|
| 1290 |
+
else:
|
| 1291 |
+
file_for_preview = out_file
|
| 1292 |
+
|
| 1293 |
+
if extra_options.get("VHS_KeepIntermediate", True) is False:
|
| 1294 |
+
for intermediate in output_files[1:-1]:
|
| 1295 |
+
if os.path.exists(intermediate):
|
| 1296 |
+
os.remove(intermediate)
|
| 1297 |
+
|
| 1298 |
+
preview = {
|
| 1299 |
+
"filename": file_for_preview,
|
| 1300 |
+
"subfolder": subfolder,
|
| 1301 |
+
"type": "output" if save_output else "temp",
|
| 1302 |
+
"format": format,
|
| 1303 |
+
"frame_rate": frame_rate,
|
| 1304 |
+
"workflow": first_image_file,
|
| 1305 |
+
"fullpath": output_files[-1],
|
| 1306 |
+
}
|
| 1307 |
+
if num_frames == 1 and "png" in format and "%03d" in file_for_preview:
|
| 1308 |
+
preview["format"] = "image/png"
|
| 1309 |
+
preview["filename"] = file_for_preview.replace("%03d", "001")
|
| 1310 |
+
|
| 1311 |
+
return {"ui": {"gifs": [preview]}, "result": ((save_output, output_files),)}
|