Download pipeline02_gloss2pose.py from SignerX/StableSigner: direct link, hf CLI and curl.
- Browser
- Download file 92.9 kB
-
https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/pipeline02_gloss2pose.py
- Command line
-
hf download hf://datasets/SignerX/StableSigner/pipeline02_gloss2pose.py
-
curl -L -o pipeline02_gloss2pose.py https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/pipeline02_gloss2pose.py
92.9 kB
| #!/usr/bin/env python3 | |
| """ | |
| Sign Language Gloss Q&A System - Individual NPZ Version | |
| User inputs gloss, system generates corresponding pose video from individual NPZ files | |
| """ | |
| import torch | |
| from PIL import Image | |
| import numpy as np | |
| import json | |
| import os | |
| import sys | |
| import argparse | |
| from pathlib import Path | |
| import cv2 | |
| from tqdm import tqdm | |
| import re | |
| from datetime import datetime | |
| import shutil | |
| import subprocess | |
| from typing import Optional | |
| _DWposeDetector = None | |
| _DWPOSE_IMPORT_ERROR = None | |
| def _ensure_dwpose_imported(): | |
| """Lazy import DWposeDetector to avoid hard dependency unless needed.""" | |
| global _DWposeDetector, _DWPOSE_IMPORT_ERROR # noqa: PLW0603 | |
| if _DWposeDetector is not None or _DWPOSE_IMPORT_ERROR is not None: | |
| return | |
| try: | |
| from easy_dwpose import DWposeDetector # type: ignore | |
| _DWposeDetector = DWposeDetector | |
| except Exception as exc: # pylint: disable=broad-except | |
| _DWPOSE_IMPORT_ERROR = exc | |
| from easy_dwpose.draw.controlnext import draw_pose as draw_pose_controlnext, process_pose_data | |
| from easy_dwpose.draw.openpose import draw_pose as draw_pose_openpose | |
| from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic | |
| import copy | |
| # Fixed configuration (resolve relative to this file so plugins/symlinks work) | |
| BASE_DIR = Path(__file__).resolve().parent | |
| POSE_DICT_ROOT = BASE_DIR / "pose_dict" | |
| JSON_FILE = os.environ.get( | |
| "STABLE_SIGNER_GLOSS_JSON", | |
| str(POSE_DICT_ROOT / "WLASL_train.json"), | |
| ) # JSON mapping file | |
| NPZ_DIR = os.environ.get( | |
| "STABLE_SIGNER_NPZ_DIR", | |
| str(POSE_DICT_ROOT / "WLASL_train"), | |
| ) # Directory containing NPZ files | |
| OUTPUT_DIR = os.environ.get( | |
| "STABLE_SIGNER_OUTPUT_DIR", | |
| str(BASE_DIR / "generated_pose_video"), | |
| ) # Output video directory | |
| _FFMPEG_BINARY = None | |
| def _known_ffmpeg_search_roots() -> list[Path]: | |
| roots = [] | |
| env_hint = os.environ.get("STABLE_SIGNER_FFMPEG") | |
| if env_hint: | |
| roots.append(Path(env_hint).parent if Path(env_hint).is_file() else Path(env_hint)) | |
| env_dir_hint = os.environ.get("STABLE_SIGNER_FFMPEG_DIR") | |
| if env_dir_hint: | |
| roots.append(Path(env_dir_hint)) | |
| roots.extend( | |
| [ | |
| BASE_DIR / "tools", | |
| Path.home() / "miniforge3", | |
| Path.home() / "miniconda3", | |
| Path.home() / "anaconda3", | |
| Path("/research/cbim/vast/sf895/miniforge3"), | |
| ] | |
| ) | |
| # Remove duplicates while preserving order | |
| seen = set() | |
| unique_roots = [] | |
| for root in roots: | |
| if not root: | |
| continue | |
| try: | |
| key = str(root.resolve()) | |
| except Exception: | |
| key = str(root) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| unique_roots.append(root) | |
| return unique_roots | |
| def _probe_ffmpeg_in_known_locations() -> Optional[str]: | |
| patterns = [ | |
| "lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*", | |
| "envs/*/lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*", | |
| "site-packages/imageio_ffmpeg/binaries/ffmpeg*", | |
| "imageio_ffmpeg/binaries/ffmpeg*", | |
| "ffmpeg*", | |
| ] | |
| for root in _known_ffmpeg_search_roots(): | |
| if not root or not root.exists(): | |
| continue | |
| for pattern in patterns: | |
| for candidate in root.glob(pattern): | |
| if candidate.is_file() and os.access(candidate, os.X_OK): | |
| return str(candidate) | |
| return None | |
| def _get_ffmpeg_binary() -> str: | |
| """Locate an FFmpeg executable that actually works inside this environment.""" | |
| global _FFMPEG_BINARY # noqa: PLW0603 | |
| if _FFMPEG_BINARY: | |
| return _FFMPEG_BINARY | |
| try: | |
| from imageio_ffmpeg import get_ffmpeg_exe # type: ignore | |
| ffmpeg_path = get_ffmpeg_exe() | |
| if ffmpeg_path and Path(ffmpeg_path).exists(): | |
| _FFMPEG_BINARY = ffmpeg_path | |
| return ffmpeg_path | |
| except Exception: | |
| pass | |
| probed = _probe_ffmpeg_in_known_locations() | |
| if probed: | |
| _FFMPEG_BINARY = probed | |
| return probed | |
| fallback = shutil.which("ffmpeg") | |
| if fallback: | |
| _FFMPEG_BINARY = fallback | |
| return fallback | |
| # Last resort: just return string "ffmpeg" and let subprocess raise a clearer error. | |
| _FFMPEG_BINARY = "ffmpeg" | |
| return _FFMPEG_BINARY | |
| class SignLanguageQA: | |
| def __init__(self, max_candidates=10): | |
| self.gloss_data = None | |
| self.load_json_mapping() | |
| self.detector = None # Lazy load DWpose detector when needed | |
| self.max_candidates = max_candidates | |
| def load_json_mapping(self): | |
| """Load JSON mapping file""" | |
| try: | |
| json_path = Path(JSON_FILE) | |
| if not json_path.exists(): | |
| print(f"❌ JSON file does not exist: {JSON_FILE}") | |
| sys.exit(1) | |
| print(f"📚 Loading JSON mapping: {JSON_FILE}") | |
| with open(json_path, 'r', encoding='utf-8') as f: | |
| self.gloss_data = json.load(f) | |
| print(f"✅ JSON loaded successfully!") | |
| print(f" 📊 Total glosses: {len(self.gloss_data)}") | |
| # Create gloss to video_ids mapping | |
| self.gloss_to_videos = {} | |
| for item in self.gloss_data: | |
| gloss = item['gloss'].upper() | |
| if gloss not in self.gloss_to_videos: | |
| self.gloss_to_videos[gloss] = [] | |
| for instance in item['instances']: | |
| self.gloss_to_videos[gloss].append(instance['video_id']) | |
| except Exception as e: | |
| print(f"❌ JSON loading failed: {e}") | |
| sys.exit(1) | |
| def find_gloss_videos(self, gloss): | |
| """Find video_ids for a given gloss""" | |
| gloss_upper = gloss.upper() | |
| # Direct match | |
| if gloss_upper in self.gloss_to_videos: | |
| return self.gloss_to_videos[gloss_upper] | |
| # Fuzzy match | |
| matched_videos = [] | |
| for g, videos in self.gloss_to_videos.items(): | |
| if gloss_upper in g or g in gloss_upper: | |
| matched_videos.extend(videos) | |
| return list(set(matched_videos)) # Remove duplicates | |
| def load_video_npz(self, video_id): | |
| """Load NPZ file for a specific video""" | |
| npz_path = Path(NPZ_DIR) / f"{video_id}.npz" | |
| if not npz_path.exists(): | |
| print(f" ⚠️ NPZ file not found in Pose Dict: {npz_path}") | |
| return None | |
| try: | |
| npz_file = np.load(npz_path, allow_pickle=True) | |
| npz_dict = {key: npz_file[key] for key in npz_file.files} | |
| npz_file.close() | |
| return npz_dict | |
| except Exception as e: | |
| print(f" ⚠️ Failed to load NPZ: {e}") | |
| return None | |
| def check_frame_quality(self, frame_data): | |
| """Check if a frame has valid pose data based on confidence scores""" | |
| if not frame_data: | |
| return False | |
| # Check hand scores (most critical for sign language) | |
| if 'hands_scores' in frame_data: | |
| hands_scores = frame_data['hands_scores'] | |
| if hands_scores is not None and len(hands_scores) > 0: | |
| # Check if more than 80% of hand points have negative confidence | |
| valid_scores = hands_scores[hands_scores >= 0] | |
| if len(valid_scores) < len(hands_scores) * 0.2: | |
| return False | |
| # Check body scores | |
| if 'body_scores' in frame_data: | |
| body_scores = frame_data['body_scores'] | |
| if body_scores is not None and len(body_scores) > 0: | |
| valid_scores = body_scores[body_scores >= 0] | |
| if len(valid_scores) < len(body_scores) * 0.2: | |
| return False | |
| return True | |
| def check_video_quality(self, npz_data, check_frames=5, extended_check_frames=30): | |
| """Check video quality by examining start and end frames""" | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return False, "No frames found" | |
| # Check first and last N frames | |
| problematic_start = 0 | |
| problematic_end = 0 | |
| # Check start frames | |
| for i in range(1, min(check_frames + 1, total_frames + 1)): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if not self.check_frame_quality(frame_data): | |
| problematic_start += 1 | |
| # Check end frames | |
| for i in range(max(1, total_frames - check_frames + 1), total_frames + 1): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if not self.check_frame_quality(frame_data): | |
| problematic_end += 1 | |
| # If more than 3 frames are problematic, do extended check | |
| if problematic_start >= 3 or problematic_end >= 3: | |
| print(f" ⚠️ Initial check found {problematic_start} bad start frames, {problematic_end} bad end frames") | |
| # Extended check | |
| problematic_start_extended = 0 | |
| problematic_end_extended = 0 | |
| for i in range(1, min(extended_check_frames + 1, total_frames + 1)): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if not self.check_frame_quality(frame_data): | |
| problematic_start_extended += 1 | |
| for i in range(max(1, total_frames - extended_check_frames + 1), total_frames + 1): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if not self.check_frame_quality(frame_data): | |
| problematic_end_extended += 1 | |
| # If too many bad frames, reject video | |
| if problematic_start_extended > extended_check_frames * 0.5 or \ | |
| problematic_end_extended > extended_check_frames * 0.5: | |
| return False, f"Too many bad frames: {problematic_start_extended} start, {problematic_end_extended} end" | |
| return True, f"Quality check passed (bad frames: {problematic_start} start, {problematic_end} end)" | |
| def get_valid_frame_range(self, npz_data, margin=5): | |
| """Get the range of valid frames, excluding bad frames at start/end""" | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return 1, 0 | |
| # Find first valid frame | |
| start_frame = 1 | |
| for i in range(1, min(margin + 1, total_frames + 1)): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if self.check_frame_quality(frame_data): | |
| start_frame = i | |
| break | |
| else: | |
| start_frame = i + 1 | |
| # Find last valid frame | |
| end_frame = total_frames | |
| for i in range(total_frames, max(0, total_frames - margin), -1): | |
| frame_data = self.get_frame_data(npz_data, i) | |
| if self.check_frame_quality(frame_data): | |
| end_frame = i | |
| break | |
| else: | |
| end_frame = i - 1 | |
| return start_frame, end_frame | |
| def get_frame_data(self, npz_data, frame_num): | |
| """Extract frame data from NPZ""" | |
| frame_key = f"frame_{frame_num:08d}" | |
| frame_data = {} | |
| # Extract all components for this frame | |
| for suffix in ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']: | |
| key = f"{frame_key}_{suffix}" | |
| if key in npz_data: | |
| frame_data[suffix] = npz_data[key] | |
| return frame_data if frame_data else None | |
| def get_total_frames(self, npz_data): | |
| """Get total number of frames in NPZ file""" | |
| frame_keys = [k for k in npz_data.keys() if k.startswith('frame_') and k.endswith('_bodies')] | |
| return len(frame_keys) | |
| def create_pose_frame(self, frame_data, width=480, height=480, scale_x=1.0, scale_y=1.0, | |
| hide_torso_lines=False, y_offset=0, draw_style='controlnext', | |
| conf_threshold=0.6): | |
| """Create single frame pose image with progressive scaling and optional y offset | |
| Args: | |
| draw_style: 'controlnext' or 'openpose' | |
| """ | |
| try: | |
| # Apply progressive scaling if needed | |
| if scale_x != 1.0 or scale_y != 1.0: | |
| frame_data = self.apply_progressive_scaling(frame_data, scale_x, scale_y) | |
| # Apply y offset if provided | |
| if y_offset != 0: | |
| frame_data = self.apply_y_offset(frame_data, y_offset) | |
| if draw_style == 'openpose': | |
| filtered_frame = self.filter_pose_for_openpose(frame_data, conf_threshold=conf_threshold, update_subset=True) | |
| # Use OpenPose style (simpler, no processing needed) | |
| vis_img = draw_pose_openpose( | |
| pose=filtered_frame, | |
| height=height, | |
| width=width, | |
| include_face=True, | |
| include_hands=True, | |
| conf_threshold=conf_threshold | |
| ) | |
| return vis_img | |
| else: | |
| filtered_frame = self.filter_pose_for_openpose(frame_data, conf_threshold=conf_threshold, update_subset=False) | |
| # Use ControlNeXt style (default, with advanced features) | |
| processed_pred = process_pose_data(filtered_frame, height, width) | |
| vis_img = draw_pose_controlnext( | |
| pose=processed_pred, | |
| H=height, | |
| W=width, | |
| include_body=True, | |
| include_hand=True, | |
| include_face=True, | |
| hide_torso_lines=hide_torso_lines | |
| ) | |
| return vis_img.transpose(1, 2, 0) | |
| except Exception as e: | |
| import traceback | |
| print(f"⚠️ Failed to create pose frame: {e}") | |
| print("Traceback:") | |
| traceback.print_exc() | |
| return None | |
| def apply_progressive_scaling(self, frame_data, scale_x, scale_y): | |
| """Apply progressive scaling - minimal at top, maximal at bottom""" | |
| scaled_data = copy.deepcopy(frame_data) | |
| # Process bodies | |
| if 'bodies' in scaled_data and scaled_data['bodies'] is not None: | |
| bodies = scaled_data['bodies'].copy() | |
| # Debug: check shape | |
| # print(f"Bodies shape: {bodies.shape}") | |
| # Find the top point (minimum Y) to use as anchor | |
| y_values = bodies[:, 1] | |
| valid_mask = y_values > 0 | |
| valid_y = y_values[valid_mask] | |
| if len(valid_y) > 0: | |
| min_y = np.min(valid_y) | |
| max_y = np.max(valid_y) | |
| y_range = max_y - min_y if max_y > min_y else 1.0 | |
| # Apply progressive scaling | |
| for i in range(len(bodies)): | |
| if bodies[i, 1] > 0: # Valid point | |
| # Calculate progress from top to bottom (0 to 1) | |
| progress = (bodies[i, 1] - min_y) / y_range | |
| # Progressive Y scaling: 1.0 at top, scale_y at bottom | |
| y_scale = 1.0 + (scale_y - 1.0) * progress | |
| # Progressive X scaling: adjust to maintain proportions | |
| x_scale = 1.0 + (scale_x - 1.0) * progress | |
| # Apply scaling relative to the top anchor point | |
| # Y: scale from the top point | |
| bodies[i, 1] = min_y + (bodies[i, 1] - min_y) * y_scale | |
| # X: scale from center of the pose | |
| center_x = 0.5 # Assume normalized coordinates | |
| bodies[i, 0] = center_x + (bodies[i, 0] - center_x) * x_scale | |
| scaled_data['bodies'] = bodies | |
| # Apply same scaling to hands | |
| if 'hands' in scaled_data and scaled_data['hands'] is not None: | |
| hands = scaled_data['hands'].copy() | |
| # Debug: check hands shape | |
| # print(f"Hands shape: {hands.shape}") | |
| # Find reference points for hands | |
| if 'bodies' in frame_data and frame_data['bodies'] is not None and len(frame_data['bodies']) > 0: | |
| # Use the same min_y from bodies | |
| y_values = frame_data['bodies'][:, 1] | |
| valid_mask = y_values > 0 | |
| valid_y = y_values[valid_mask] | |
| if len(valid_y) > 0: | |
| min_y = np.min(valid_y) | |
| max_y = np.max(valid_y) | |
| y_range = max_y - min_y if max_y > min_y else 1.0 | |
| # Hands might be shape (2, 21, 2) or similar - iterate over hands | |
| if len(hands.shape) == 3: | |
| # Multiple hands | |
| for h in range(hands.shape[0]): | |
| for i in range(hands.shape[1]): | |
| y_val = float(hands[h, i, 1]) | |
| if y_val > 0: # Valid point | |
| progress = (y_val - min_y) / y_range | |
| progress = np.clip(progress, 0, 1) | |
| y_scale = 1.0 + (scale_y - 1.0) * progress | |
| x_scale = 1.0 + (scale_x - 1.0) * progress | |
| x_val = float(hands[h, i, 0]) | |
| hands[h, i, 1] = min_y + (y_val - min_y) * y_scale | |
| center_x = 0.5 | |
| hands[h, i, 0] = center_x + (x_val - center_x) * x_scale | |
| else: | |
| # Single array of points | |
| for i in range(len(hands)): | |
| y_val = float(hands[i, 1]) | |
| if y_val > 0: # Valid point | |
| progress = (y_val - min_y) / y_range | |
| progress = np.clip(progress, 0, 1) | |
| y_scale = 1.0 + (scale_y - 1.0) * progress | |
| x_scale = 1.0 + (scale_x - 1.0) * progress | |
| x_val = float(hands[i, 0]) | |
| hands[i, 1] = min_y + (y_val - min_y) * y_scale | |
| center_x = 0.5 | |
| hands[i, 0] = center_x + (x_val - center_x) * x_scale | |
| scaled_data['hands'] = hands | |
| # Apply same scaling to faces | |
| if 'faces' in scaled_data and scaled_data['faces'] is not None: | |
| faces = scaled_data['faces'].copy() | |
| # Debug: check faces shape | |
| # print(f"Faces shape: {faces.shape}") | |
| # Faces are usually at the top, so apply minimal scaling | |
| if 'bodies' in frame_data and frame_data['bodies'] is not None and len(frame_data['bodies']) > 0: | |
| y_values = frame_data['bodies'][:, 1] | |
| valid_mask = y_values > 0 | |
| valid_y = y_values[valid_mask] | |
| if len(valid_y) > 0: | |
| min_y = np.min(valid_y) | |
| max_y = np.max(valid_y) | |
| y_range = max_y - min_y if max_y > min_y else 1.0 | |
| # Faces might be shape (1, 68, 2) or similar - iterate properly | |
| if len(faces.shape) == 3: | |
| # Multiple faces | |
| for f in range(faces.shape[0]): | |
| for i in range(faces.shape[1]): | |
| y_val = float(faces[f, i, 1]) | |
| if y_val > 0: # Valid point | |
| progress = (y_val - min_y) / y_range | |
| progress = np.clip(progress, 0, 1) | |
| y_scale = 1.0 + (scale_y - 1.0) * progress | |
| x_scale = 1.0 + (scale_x - 1.0) * progress | |
| x_val = float(faces[f, i, 0]) | |
| faces[f, i, 1] = min_y + (y_val - min_y) * y_scale | |
| center_x = 0.5 | |
| faces[f, i, 0] = center_x + (x_val - center_x) * x_scale | |
| else: | |
| # Single array of points | |
| for i in range(len(faces)): | |
| y_val = float(faces[i, 1]) | |
| if y_val > 0: # Valid point | |
| progress = (y_val - min_y) / y_range | |
| progress = np.clip(progress, 0, 1) | |
| y_scale = 1.0 + (scale_y - 1.0) * progress | |
| x_scale = 1.0 + (scale_x - 1.0) * progress | |
| x_val = float(faces[i, 0]) | |
| faces[i, 1] = min_y + (y_val - min_y) * y_scale | |
| center_x = 0.5 | |
| faces[i, 0] = center_x + (x_val - center_x) * x_scale | |
| scaled_data['faces'] = faces | |
| return scaled_data | |
| def apply_y_offset(self, frame_data, y_offset): | |
| """Apply vertical offset to all pose points""" | |
| offset_data = copy.deepcopy(frame_data) | |
| # Apply offset to bodies | |
| if 'bodies' in offset_data and offset_data['bodies'] is not None: | |
| offset_data['bodies'][:, 1] += y_offset | |
| # Apply offset to hands | |
| if 'hands' in offset_data and offset_data['hands'] is not None: | |
| if len(offset_data['hands'].shape) == 3: | |
| offset_data['hands'][:, :, 1] += y_offset | |
| else: | |
| offset_data['hands'][:, 1] += y_offset | |
| # Apply offset to faces | |
| if 'faces' in offset_data and offset_data['faces'] is not None: | |
| if len(offset_data['faces'].shape) == 3: | |
| offset_data['faces'][:, :, 1] += y_offset | |
| else: | |
| offset_data['faces'][:, 1] += y_offset | |
| return offset_data | |
| def filter_pose_for_openpose(self, frame_data, conf_threshold=0.6, update_subset=True): | |
| """Filter low-confidence joints before rendering to avoid ghost limbs | |
| Args: | |
| conf_threshold: minimum confidence needed to keep a joint | |
| update_subset: when True, rewrite body_scores as OpenPose subset (-1 removes joints) | |
| """ | |
| filtered = copy.deepcopy(frame_data) | |
| # Bodies | |
| bodies = filtered.get('bodies', None) | |
| body_scores = filtered.get('body_scores', None) | |
| if bodies is not None: | |
| bodies = bodies.copy() | |
| min_valid = 1e-6 | |
| coord_mask = (bodies[:, 0] > min_valid) & (bodies[:, 1] > min_valid) | |
| conf_mask = None | |
| if body_scores is not None: | |
| scores = np.array(body_scores, copy=False) | |
| if scores.ndim == 2: | |
| score_vec = scores.reshape(-1) | |
| else: | |
| score_vec = scores | |
| score_vec = score_vec.astype(float) | |
| conf_mask = score_vec < conf_threshold | |
| if conf_mask.shape[0] < bodies.shape[0]: | |
| conf_mask = np.pad(conf_mask, (0, bodies.shape[0] - conf_mask.shape[0]), constant_values=False) | |
| elif conf_mask.shape[0] > bodies.shape[0]: | |
| conf_mask = conf_mask[:bodies.shape[0]] | |
| if conf_mask is None: | |
| valid_mask = coord_mask | |
| else: | |
| valid_mask = coord_mask & (~conf_mask) | |
| bodies[~valid_mask, :] = 0 | |
| filtered['bodies'] = bodies | |
| if update_subset: | |
| if body_scores is not None: | |
| subset = np.array(body_scores, copy=True) | |
| if subset.ndim == 1: | |
| subset = subset.reshape(1, -1) | |
| else: | |
| subset = np.arange(bodies.shape[0], dtype=float).reshape(1, -1) | |
| if subset.shape[1] < bodies.shape[0]: | |
| subset = np.pad(subset, ((0, 0), (0, bodies.shape[0] - subset.shape[1])), constant_values=-1) | |
| elif subset.shape[1] > bodies.shape[0]: | |
| subset = subset[:, :bodies.shape[0]] | |
| subset[:, ~valid_mask] = -1 | |
| filtered['body_scores'] = subset | |
| # Hands | |
| hands = filtered.get('hands', None) | |
| hand_scores = filtered.get('hands_scores', None) | |
| if hands is not None and hand_scores is not None: | |
| scores = np.array(hand_scores) | |
| hands = hands.copy() | |
| if hands.ndim == 3 and scores.ndim == 3: | |
| for h in range(hands.shape[0]): | |
| mask = (scores[h] < conf_threshold) | (scores[h] <= 0) | |
| hands[h][mask, :] = 0 | |
| elif hands.ndim == 3 and scores.ndim == 2: | |
| for h in range(hands.shape[0]): | |
| mask = (scores[h] < conf_threshold) | (scores[h] <= 0) | |
| hands[h][mask, :] = 0 | |
| elif hands.ndim == 2 and scores.ndim == 2: | |
| mask = (scores < conf_threshold) | (scores <= 0) | |
| hands[mask, :] = 0 | |
| elif hands.ndim == 2 and scores.ndim == 1: | |
| mask = (scores < conf_threshold) | (scores <= 0) | |
| hands[mask, :] = 0 | |
| filtered['hands'] = hands | |
| # Faces | |
| faces = filtered.get('faces', None) | |
| face_scores = filtered.get('faces_scores', None) | |
| if faces is not None and face_scores is not None: | |
| scores = np.array(face_scores) | |
| faces = faces.copy() | |
| if faces.ndim == 3 and scores.ndim == 3: | |
| for f in range(faces.shape[0]): | |
| mask = (scores[f] < conf_threshold) | (scores[f] <= 0) | |
| faces[f][mask, :] = 0 | |
| elif faces.ndim == 2 and scores.ndim == 2: | |
| mask = (scores < conf_threshold) | (scores <= 0) | |
| faces[mask, :] = 0 | |
| elif faces.ndim == 2 and scores.ndim == 1: | |
| mask = (scores < conf_threshold) | (scores <= 0) | |
| faces[mask, :] = 0 | |
| filtered['faces'] = faces | |
| return filtered | |
| def _is_valid_point(self, point): | |
| return point is not None and len(point) >= 2 and point[0] > 0 and point[1] > 0 | |
| def _face_points_and_mask(self, faces): | |
| if faces is None: | |
| return None, None, None | |
| if faces.ndim == 3: | |
| if faces.shape[0] == 0: | |
| return None, None, None | |
| points = faces[0] | |
| owner = 0 | |
| else: | |
| points = faces | |
| owner = None | |
| if points is None or len(points) == 0: | |
| return None, None, None | |
| mask = (points[:, 0] > 0) & (points[:, 1] > 0) | |
| if np.count_nonzero(mask) < 4: | |
| return None, None, None | |
| return points, mask, owner | |
| def _face_scale(self, points, mask): | |
| valid = points[mask, :2] | |
| if len(valid) < 4: | |
| return None | |
| min_xy = np.min(valid, axis=0) | |
| max_xy = np.max(valid, axis=0) | |
| scale = np.linalg.norm(max_xy - min_xy) | |
| return scale if scale > 1e-6 else None | |
| def _translate_nearest_hand_to_wrist_delta(self, frame_data, original_wrists, wrist_deltas): | |
| hands = frame_data.get('hands', None) | |
| if hands is None: | |
| return | |
| def choose_delta(root): | |
| candidates = [] | |
| for wrist_name, wrist in original_wrists.items(): | |
| if self._is_valid_point(wrist): | |
| candidates.append((np.linalg.norm(root[:2] - wrist[:2]), wrist_deltas[wrist_name])) | |
| if not candidates: | |
| return None | |
| return min(candidates, key=lambda item: item[0])[1] | |
| if hands.ndim == 3: | |
| for hand_idx in range(hands.shape[0]): | |
| root = hands[hand_idx, 0] | |
| if not self._is_valid_point(root): | |
| continue | |
| delta = choose_delta(root) | |
| if delta is not None: | |
| valid = (hands[hand_idx, :, 0] > 0) & (hands[hand_idx, :, 1] > 0) | |
| hands[hand_idx, valid, :2] += delta | |
| elif hands.ndim == 2 and len(hands) > 0: | |
| root = hands[0] | |
| if self._is_valid_point(root): | |
| delta = choose_delta(root) | |
| if delta is not None: | |
| valid = (hands[:, 0] > 0) & (hands[:, 1] > 0) | |
| hands[valid, :2] += delta | |
| hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0) | |
| hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0) | |
| frame_data['hands'] = hands | |
| def build_signer_template(self, npz_data, start_frame=1, end_frame=None): | |
| """Build a fixed signer template from a clip. | |
| The template stores median body keypoints, first-signer bone lengths, and | |
| face center/scale. It is intentionally conservative: torso/head/shoulders | |
| remain stable, while arms can later inherit directions from each word. | |
| """ | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return None | |
| if end_frame is None: | |
| end_frame = total_frames | |
| start_frame = max(1, start_frame) | |
| end_frame = min(total_frames, end_frame) | |
| body_samples = [] | |
| face_centers = [] | |
| face_scales = [] | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if not frame_data: | |
| continue | |
| bodies = frame_data.get('bodies', None) | |
| if bodies is not None and len(bodies) >= 18: | |
| body_samples.append(bodies[:, :2].copy()) | |
| faces = frame_data.get('faces', None) | |
| if faces is not None: | |
| points, mask, _owner = self._face_points_and_mask(faces) | |
| if points is not None: | |
| face_centers.append(np.mean(points[mask, :2], axis=0)) | |
| scale = self._face_scale(points, mask) | |
| if scale is not None: | |
| face_scales.append(scale) | |
| if not body_samples: | |
| return None | |
| stack = np.stack(body_samples, axis=0) | |
| valid = (stack[..., 0] > 0) & (stack[..., 1] > 0) | |
| template_body = np.zeros((18, 2), dtype=np.float32) | |
| for j in range(18): | |
| m = valid[:, j] | |
| if np.any(m): | |
| template_body[j] = np.median(stack[m, j, :2], axis=0) | |
| body_bones = [ | |
| (1, 0), (1, 2), (2, 3), (3, 4), | |
| (1, 5), (5, 6), (6, 7), | |
| (1, 8), (8, 9), (9, 10), | |
| (1, 11), (11, 12), (12, 13), | |
| (0, 14), (0, 15), (14, 16), (15, 17), | |
| ] | |
| lengths = {} | |
| for parent, child in body_bones: | |
| if self._is_valid_point(template_body[parent]) and self._is_valid_point(template_body[child]): | |
| length = float(np.linalg.norm(template_body[child] - template_body[parent])) | |
| if 0.002 < length < 0.8: | |
| lengths[(parent, child)] = length | |
| template = { | |
| 'body': template_body, | |
| 'lengths': lengths, | |
| 'face_center': np.median(face_centers, axis=0).astype(np.float32) if face_centers else None, | |
| 'face_scale': float(np.median(face_scales)) if face_scales else None, | |
| } | |
| print(" 🧍 First-signer template built") | |
| print(f" Body template joints: {np.count_nonzero((template_body[:, 0] > 0) & (template_body[:, 1] > 0))}/18") | |
| if template['face_center'] is not None: | |
| print(f" Face center: ({template['face_center'][0]:.3f}, {template['face_center'][1]:.3f})") | |
| return template | |
| def _retarget_arm_to_template(self, bodies, template_body, lengths, shoulder_idx, elbow_idx, wrist_idx): | |
| out = template_body.copy() | |
| shoulder = template_body[shoulder_idx] | |
| if not self._is_valid_point(shoulder): | |
| return out | |
| def direction(a, b, fallback): | |
| if self._is_valid_point(a) and self._is_valid_point(b): | |
| v = b[:2] - a[:2] | |
| n = np.linalg.norm(v) | |
| if n > 1e-6: | |
| return v / n | |
| if self._is_valid_point(fallback[0]) and self._is_valid_point(fallback[1]): | |
| v = fallback[1] - fallback[0] | |
| n = np.linalg.norm(v) | |
| if n > 1e-6: | |
| return v / n | |
| return np.array([0.0, 1.0], dtype=np.float32) | |
| upper_dir = direction(bodies[shoulder_idx], bodies[elbow_idx], (template_body[shoulder_idx], template_body[elbow_idx])) | |
| lower_dir = direction(bodies[elbow_idx], bodies[wrist_idx], (template_body[elbow_idx], template_body[wrist_idx])) | |
| upper_len = lengths.get((shoulder_idx, elbow_idx), np.linalg.norm(template_body[elbow_idx] - template_body[shoulder_idx])) | |
| lower_len = lengths.get((elbow_idx, wrist_idx), np.linalg.norm(template_body[wrist_idx] - template_body[elbow_idx])) | |
| out[elbow_idx] = shoulder + upper_dir * upper_len | |
| out[wrist_idx] = out[elbow_idx] + lower_dir * lower_len | |
| return out | |
| def retarget_pose_data_to_first_signer(self, npz_data, template, start_frame=1, end_frame=None, face_mode='retarget'): | |
| """Retarget a clip to the first signer's skeleton while preserving arm/hand motion. | |
| Torso/head/shoulders/hips use the first signer template. Elbow/wrist use | |
| the current clip's arm directions with first-signer bone lengths. Hands | |
| are translated by wrist deltas. Face local shape may come from the clip, | |
| but its center/scale is aligned to the first signer. | |
| """ | |
| if template is None or template.get('body') is None: | |
| return npz_data | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return npz_data | |
| if end_frame is None: | |
| end_frame = total_frames | |
| start_frame = max(1, start_frame) | |
| end_frame = min(total_frames, end_frame) | |
| template_body = template['body'] | |
| lengths = template.get('lengths', {}) | |
| face_center = template.get('face_center') | |
| face_scale = template.get('face_scale') | |
| print(" 🧍 Retargeting clip to first signer template") | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_key = f"frame_{frame_num:08d}" | |
| bodies_key = f"{frame_key}_bodies" | |
| if bodies_key not in npz_data or npz_data[bodies_key] is None: | |
| continue | |
| bodies = npz_data[bodies_key].copy() | |
| if len(bodies) < 18: | |
| continue | |
| original_wrists = { | |
| 'right': bodies[4, :2].copy() if len(bodies) > 4 else None, | |
| 'left': bodies[7, :2].copy() if len(bodies) > 7 else None, | |
| } | |
| new_body_xy = template_body.copy() | |
| right_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 2, 3, 4) | |
| left_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 5, 6, 7) | |
| new_body_xy[[3, 4]] = right_arm[[3, 4]] | |
| new_body_xy[[6, 7]] = left_arm[[6, 7]] | |
| new_bodies = bodies.copy() | |
| valid_template = (new_body_xy[:, 0] > 0) & (new_body_xy[:, 1] > 0) | |
| new_bodies[valid_template, :2] = new_body_xy[valid_template] | |
| new_bodies[:, 0] = np.clip(new_bodies[:, 0], 0.0, 1.0) | |
| new_bodies[:, 1] = np.clip(new_bodies[:, 1], 0.0, 1.0) | |
| npz_data[bodies_key] = new_bodies | |
| wrist_deltas = { | |
| 'right': new_bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(new_bodies) > 4 else np.zeros(2), | |
| 'left': new_bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(new_bodies) > 7 else np.zeros(2), | |
| } | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if frame_data: | |
| self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas) | |
| hands_key = f"{frame_key}_hands" | |
| if hands_key in npz_data and 'hands' in frame_data: | |
| npz_data[hands_key] = frame_data['hands'] | |
| faces_key = f"{frame_key}_faces" | |
| if face_mode != 'none' and face_center is not None and faces_key in npz_data and npz_data[faces_key] is not None: | |
| faces = npz_data[faces_key].copy() | |
| points, mask, owner = self._face_points_and_mask(faces) | |
| if points is not None: | |
| current_center = np.mean(points[mask, :2], axis=0) | |
| scaled_points = points.copy() | |
| if face_scale is not None: | |
| current_scale = self._face_scale(points, mask) | |
| if current_scale is not None and current_scale > 1e-6: | |
| scaled_points[mask, :2] = current_center + (points[mask, :2] - current_center) * (face_scale / current_scale) | |
| shifted_center = np.mean(scaled_points[mask, :2], axis=0) | |
| scaled_points[mask, :2] += face_center - shifted_center | |
| if owner is None: | |
| faces = scaled_points | |
| else: | |
| faces[owner] = scaled_points | |
| faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0) | |
| faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0) | |
| npz_data[faces_key] = faces | |
| return npz_data | |
| def stabilize_pose_data(self, npz_data, start_frame=1, end_frame=None, body_smoothing_alpha=0.75): | |
| """Stabilize a pose clip with fixed body bone lengths and fixed face scale.""" | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return npz_data | |
| if end_frame is None: | |
| end_frame = total_frames | |
| start_frame = max(1, start_frame) | |
| end_frame = min(total_frames, end_frame) | |
| if start_frame > end_frame: | |
| return npz_data | |
| body_bones = [ | |
| (1, 0), | |
| (1, 2), (2, 3), (3, 4), | |
| (1, 5), (5, 6), (6, 7), | |
| (1, 8), (8, 9), (9, 10), | |
| (1, 11), (11, 12), (12, 13), | |
| (0, 14), (0, 15), (14, 16), (15, 17), | |
| ] | |
| bone_lengths = {bone: [] for bone in body_bones} | |
| face_scales = [] | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if not frame_data or 'bodies' not in frame_data: | |
| continue | |
| bodies = frame_data['bodies'] | |
| if bodies is not None: | |
| for parent, child in body_bones: | |
| if parent < len(bodies) and child < len(bodies): | |
| if self._is_valid_point(bodies[parent]) and self._is_valid_point(bodies[child]): | |
| length = np.linalg.norm(bodies[child, :2] - bodies[parent, :2]) | |
| if 0.002 < length < 0.8: | |
| bone_lengths[(parent, child)].append(length) | |
| faces = frame_data.get('faces', None) | |
| if faces is not None: | |
| points, mask, _owner = self._face_points_and_mask(faces) | |
| if points is not None: | |
| scale = self._face_scale(points, mask) | |
| if scale is not None and 0.002 < scale < 0.8: | |
| face_scales.append(scale) | |
| median_lengths = { | |
| bone: float(np.median(lengths)) | |
| for bone, lengths in bone_lengths.items() | |
| if lengths | |
| } | |
| median_face_scale = float(np.median(face_scales)) if face_scales else None | |
| if not median_lengths and median_face_scale is None: | |
| print(" ⚠️ Skeleton stabilization skipped: insufficient valid body/face data") | |
| return npz_data | |
| print(" 🦴 Skeleton stabilization enabled") | |
| if median_lengths: | |
| print(f" Fixed body bones: {len(median_lengths)}") | |
| if median_face_scale is not None: | |
| print(f" Fixed face scale: {median_face_scale:.3f}") | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_key = f"frame_{frame_num:08d}" | |
| bodies_key = f"{frame_key}_bodies" | |
| if bodies_key in npz_data and npz_data[bodies_key] is not None: | |
| bodies = npz_data[bodies_key].copy() | |
| original_wrists = { | |
| 'right': bodies[4, :2].copy() if len(bodies) > 4 else None, | |
| 'left': bodies[7, :2].copy() if len(bodies) > 7 else None, | |
| } | |
| for parent, child in body_bones: | |
| target_len = median_lengths.get((parent, child)) | |
| if target_len is None or parent >= len(bodies) or child >= len(bodies): | |
| continue | |
| if not self._is_valid_point(bodies[parent]) or not self._is_valid_point(bodies[child]): | |
| continue | |
| direction = bodies[child, :2] - bodies[parent, :2] | |
| current_len = np.linalg.norm(direction) | |
| if current_len <= 1e-6: | |
| continue | |
| bodies[child, :2] = bodies[parent, :2] + direction / current_len * target_len | |
| bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0) | |
| bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0) | |
| npz_data[bodies_key] = bodies | |
| wrist_deltas = { | |
| 'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2), | |
| 'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2), | |
| } | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if frame_data: | |
| self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas) | |
| hands_key = f"{frame_key}_hands" | |
| if hands_key in npz_data and 'hands' in frame_data: | |
| npz_data[hands_key] = frame_data['hands'] | |
| faces_key = f"{frame_key}_faces" | |
| if median_face_scale is not None and faces_key in npz_data and npz_data[faces_key] is not None: | |
| faces = npz_data[faces_key].copy() | |
| points, mask, owner = self._face_points_and_mask(faces) | |
| if points is not None: | |
| current_scale = self._face_scale(points, mask) | |
| if current_scale is not None and current_scale > 1e-6: | |
| center = np.mean(points[mask, :2], axis=0) | |
| scaled_points = points.copy() | |
| scaled_points[mask, :2] = center + (points[mask, :2] - center) * (median_face_scale / current_scale) | |
| if owner is None: | |
| faces = scaled_points | |
| else: | |
| faces[owner] = scaled_points | |
| faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0) | |
| faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0) | |
| npz_data[faces_key] = faces | |
| previous_bodies = None | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_key = f"frame_{frame_num:08d}" | |
| bodies_key = f"{frame_key}_bodies" | |
| if bodies_key not in npz_data or npz_data[bodies_key] is None: | |
| continue | |
| bodies = npz_data[bodies_key].copy() | |
| if previous_bodies is not None and previous_bodies.shape == bodies.shape: | |
| original_wrists = { | |
| 'right': bodies[4, :2].copy() if len(bodies) > 4 else None, | |
| 'left': bodies[7, :2].copy() if len(bodies) > 7 else None, | |
| } | |
| valid = ( | |
| (bodies[:, 0] > 0) & (bodies[:, 1] > 0) & | |
| (previous_bodies[:, 0] > 0) & (previous_bodies[:, 1] > 0) | |
| ) | |
| bodies[valid, :2] = ( | |
| body_smoothing_alpha * bodies[valid, :2] + | |
| (1.0 - body_smoothing_alpha) * previous_bodies[valid, :2] | |
| ) | |
| bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0) | |
| bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0) | |
| npz_data[bodies_key] = bodies | |
| wrist_deltas = { | |
| 'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2), | |
| 'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2), | |
| } | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if frame_data: | |
| self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas) | |
| hands_key = f"{frame_key}_hands" | |
| if hands_key in npz_data and 'hands' in frame_data: | |
| npz_data[hands_key] = frame_data['hands'] | |
| previous_bodies = bodies.copy() | |
| return npz_data | |
| def normalize_pose_data(self, npz_data, reference_point='neck', scale_by='shoulders', | |
| target_shoulder_width=0.35, target_shoulder_y=0.45): | |
| """ | |
| Normalize pose data to a standard coordinate system | |
| This ensures different videos are in the same coordinate space | |
| Args: | |
| npz_data: NPZ data containing pose information | |
| reference_point: 'neck' or 'hips' - point to center on (default: 'neck') | |
| scale_by: 'shoulders' or 'height' - measure for scaling (default: 'shoulders') | |
| target_shoulder_width: Desired horizontal distance between shoulders after normalization | |
| target_shoulder_y: Desired Y coordinate for the shoulder line | |
| Returns: | |
| Normalized NPZ data (modifies in-place) | |
| """ | |
| total_frames = self.get_total_frames(npz_data) | |
| if total_frames == 0: | |
| return npz_data | |
| # Collect reference points, scale factors, and shoulder heights across all frames | |
| reference_positions = [] | |
| scale_factors = [] | |
| shoulder_y_positions = [] | |
| for frame_num in range(1, total_frames + 1): | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if not frame_data or 'bodies' not in frame_data: | |
| continue | |
| bodies = frame_data['bodies'] | |
| if bodies is None or len(bodies) == 0: | |
| continue | |
| # Calculate reference point | |
| if reference_point == 'neck': | |
| # Neck is typically index 1 in body keypoints | |
| if len(bodies) > 1 and bodies[1, 0] > 0 and bodies[1, 1] > 0: | |
| ref_pos = bodies[1, :2].copy() | |
| else: | |
| continue | |
| elif reference_point == 'hips': | |
| # Hip center: average of left hip (11) and right hip (12) | |
| if len(bodies) > 12: | |
| left_hip = bodies[11, :2] | |
| right_hip = bodies[12, :2] | |
| if left_hip[0] > 0 and right_hip[0] > 0: | |
| ref_pos = (left_hip + right_hip) / 2 | |
| else: | |
| continue | |
| else: | |
| continue | |
| else: | |
| continue | |
| reference_positions.append(ref_pos) | |
| # Calculate scale factor | |
| if scale_by == 'shoulders': | |
| # Shoulder width: distance between left shoulder (5) and right shoulder (2) | |
| if len(bodies) > 5: | |
| left_shoulder = bodies[5, :2] | |
| right_shoulder = bodies[2, :2] | |
| if left_shoulder[0] > 0 and right_shoulder[0] > 0: | |
| shoulder_width = np.linalg.norm(left_shoulder - right_shoulder) | |
| if shoulder_width > 0.01: # Avoid division by very small numbers | |
| scale_factors.append(shoulder_width) | |
| shoulder_mid_y = (left_shoulder[1] + right_shoulder[1]) / 2 | |
| shoulder_y_positions.append(shoulder_mid_y) | |
| elif scale_by == 'height': | |
| # Approximate height: distance from neck to hip center | |
| if len(bodies) > 12: | |
| neck = bodies[1, :2] | |
| left_hip = bodies[11, :2] | |
| right_hip = bodies[12, :2] | |
| if neck[1] > 0 and left_hip[0] > 0 and right_hip[0] > 0: | |
| hip_center = (left_hip + right_hip) / 2 | |
| height = np.linalg.norm(neck - hip_center) | |
| if height > 0.01: | |
| scale_factors.append(height) | |
| if not reference_positions or not scale_factors: | |
| print(" ⚠️ Normalization skipped: insufficient valid frames") | |
| return npz_data | |
| # Use median reference position and scale factor for robustness | |
| median_ref_pos = np.median(reference_positions, axis=0) | |
| median_scale = np.median(scale_factors) | |
| median_shoulder_y = np.median(shoulder_y_positions) if shoulder_y_positions else median_ref_pos[1] | |
| print(f" 📏 Normalization: ref={reference_point}, scale={scale_by}") | |
| print(f" Reference position: ({median_ref_pos[0]:.3f}, {median_ref_pos[1]:.3f})") | |
| print(f" Median shoulder y: {median_shoulder_y:.3f}") | |
| print(f" Median shoulder width: {median_scale:.3f} → target {target_shoulder_width:.3f}") | |
| # Determine uniform scaling factor so shoulders match the desired width | |
| width_scale = target_shoulder_width / median_scale if median_scale > 0 else 1.0 | |
| # Neck-centered offset already moves the neck to 0.5; compute extra offset so shoulders sit at desired y | |
| shoulder_delta_from_neck = median_shoulder_y - median_ref_pos[1] | |
| normalized_shoulder_y = 0.5 + shoulder_delta_from_neck * width_scale | |
| vertical_offset = target_shoulder_y - normalized_shoulder_y | |
| # Apply normalization to all frames | |
| for frame_num in range(1, total_frames + 1): | |
| frame_key = f"frame_{frame_num:08d}" | |
| # Normalize bodies | |
| bodies_key = f"{frame_key}_bodies" | |
| if bodies_key in npz_data: | |
| bodies = npz_data[bodies_key].copy() | |
| if bodies is not None and len(bodies) > 0: | |
| # Center on reference point | |
| for i in range(len(bodies)): | |
| if bodies[i, 0] > 0 and bodies[i, 1] > 0: | |
| bodies[i, :2] = (bodies[i, :2] - median_ref_pos) * width_scale + 0.5 | |
| bodies[i, 1] += vertical_offset | |
| # Clamp to drawing range | |
| bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0) | |
| bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0) | |
| npz_data[bodies_key] = bodies | |
| # Normalize hands | |
| hands_key = f"{frame_key}_hands" | |
| if hands_key in npz_data: | |
| hands = npz_data[hands_key].copy() | |
| if hands is not None: | |
| if len(hands.shape) == 3: | |
| # Multiple hands | |
| for h in range(hands.shape[0]): | |
| for i in range(hands.shape[1]): | |
| if hands[h, i, 0] > 0 and hands[h, i, 1] > 0: | |
| hands[h, i, :2] = (hands[h, i, :2] - median_ref_pos) * width_scale + 0.5 | |
| hands[h, i, 1] += vertical_offset | |
| else: | |
| # Single array | |
| for i in range(len(hands)): | |
| if hands[i, 0] > 0 and hands[i, 1] > 0: | |
| hands[i, :2] = (hands[i, :2] - median_ref_pos) * width_scale + 0.5 | |
| hands[i, 1] += vertical_offset | |
| hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0) | |
| hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0) | |
| npz_data[hands_key] = hands | |
| # Normalize faces | |
| faces_key = f"{frame_key}_faces" | |
| if faces_key in npz_data: | |
| faces = npz_data[faces_key].copy() | |
| if faces is not None: | |
| if len(faces.shape) == 3: | |
| # Multiple faces | |
| for f in range(faces.shape[0]): | |
| for i in range(faces.shape[1]): | |
| if faces[f, i, 0] > 0 and faces[f, i, 1] > 0: | |
| faces[f, i, :2] = (faces[f, i, :2] - median_ref_pos) * width_scale + 0.5 | |
| faces[f, i, 1] += vertical_offset | |
| else: | |
| # Single array | |
| for i in range(len(faces)): | |
| if faces[i, 0] > 0 and faces[i, 1] > 0: | |
| faces[i, :2] = (faces[i, :2] - median_ref_pos) * width_scale + 0.5 | |
| faces[i, 1] += vertical_offset | |
| faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0) | |
| faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0) | |
| npz_data[faces_key] = faces | |
| return npz_data | |
| def get_reference_head_top(self, ref_image_path, width, height): | |
| """Get the top of head position from reference image""" | |
| try: | |
| # Lazy load detector | |
| _ensure_dwpose_imported() | |
| if _DWposeDetector is None: | |
| if _DWPOSE_IMPORT_ERROR: | |
| print(f"⚠️ DWposeDetector unavailable: {_DWPOSE_IMPORT_ERROR}") | |
| else: | |
| print("⚠️ DWposeDetector module not available") | |
| return None | |
| if self.detector is None: | |
| device = "cuda:0" if torch.cuda.is_available() else "cpu" | |
| self.detector = _DWposeDetector(device=device) | |
| # Load and detect pose in reference image | |
| ref_image = Image.open(ref_image_path).convert("RGB") | |
| # Resize reference image to match target dimensions | |
| ref_image = ref_image.resize((width, height), Image.LANCZOS) | |
| # Detect pose | |
| pose_data = self.detector(ref_image, draw_pose=False) | |
| # Find head top from face points | |
| if 'faces' in pose_data and pose_data['faces'] is not None and len(pose_data['faces']) > 0: | |
| faces = pose_data['faces'] | |
| if len(faces.shape) == 3: | |
| # Multiple faces, use first one | |
| face_points = faces[0] | |
| else: | |
| face_points = faces | |
| # Get all valid Y coordinates | |
| y_coords = face_points[:, 1] | |
| valid_y = y_coords[y_coords > 0] | |
| if len(valid_y) > 0: | |
| # Head top is the minimum Y coordinate (top of the image) | |
| head_top_y = np.min(valid_y) | |
| return head_top_y | |
| # If no face found, try to use body points | |
| if 'bodies' in pose_data and pose_data['bodies'] is not None: | |
| bodies = pose_data['bodies'] | |
| # Look for head-related points (eyes, ears, nose) | |
| # Indices 0=nose, 14=right eye, 15=left eye, 16=right ear, 17=left ear | |
| head_indices = [0, 14, 15, 16, 17] | |
| head_y_coords = [] | |
| for idx in head_indices: | |
| if idx < len(bodies) and bodies[idx, 1] > 0: | |
| head_y_coords.append(bodies[idx, 1]) | |
| if head_y_coords: | |
| return min(head_y_coords) | |
| return None | |
| except Exception as e: | |
| print(f"⚠️ Failed to get reference head position: {e}") | |
| return None | |
| def calculate_neck_centrality_score(self, npz_data): | |
| """Calculate how centered the neck position is in the video | |
| Returns a score from 0 to 1, where 1 means perfectly centered | |
| Lower score means the person is more off-center | |
| """ | |
| neck_x_positions = [] | |
| # Sample frames throughout the video | |
| total_frames = self.get_total_frames(npz_data) | |
| sample_frames = [0, total_frames // 4, total_frames // 2, 3 * total_frames // 4, total_frames - 1] | |
| for frame_num in sample_frames: | |
| if frame_num >= total_frames: | |
| continue | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if frame_data and 'bodies' in frame_data: | |
| bodies = frame_data['bodies'] | |
| # Neck is typically index 1 in body keypoints | |
| if len(bodies) > 1 and bodies[1, 0] > 0: | |
| neck_x_positions.append(bodies[1, 0]) | |
| if not neck_x_positions: | |
| return 0.0 # No valid neck positions found | |
| # Calculate average neck X position | |
| avg_neck_x = np.mean(neck_x_positions) | |
| # Calculate distance from center (0.5) | |
| # Score is higher when closer to center | |
| distance_from_center = abs(avg_neck_x - 0.5) | |
| centrality_score = 1.0 - (distance_from_center * 2) # Scale to 0-1 | |
| return max(0.0, centrality_score) # Ensure non-negative | |
| def get_pose_head_top(self, frame_data): | |
| """Get the top of head position from pose frame data""" | |
| # Try faces first | |
| if 'faces' in frame_data and frame_data['faces'] is not None: | |
| faces = frame_data['faces'] | |
| if len(faces.shape) == 3: | |
| # Multiple faces, use first one | |
| face_points = faces[0] | |
| else: | |
| face_points = faces | |
| # Get all valid Y coordinates | |
| y_coords = face_points[:, 1] | |
| valid_y = y_coords[y_coords > 0] | |
| if len(valid_y) > 0: | |
| return np.min(valid_y) | |
| # Fall back to body points | |
| if 'bodies' in frame_data and frame_data['bodies'] is not None: | |
| bodies = frame_data['bodies'] | |
| # Look for head-related points | |
| head_indices = [0, 14, 15, 16, 17] # nose, eyes, ears | |
| head_y_coords = [] | |
| for idx in head_indices: | |
| if idx < len(bodies) and bodies[idx, 1] > 0: | |
| head_y_coords.append(bodies[idx, 1]) | |
| if head_y_coords: | |
| return min(head_y_coords) | |
| return None | |
| def generate_video_from_glosses(self, gloss_list, output_path, fps=25, width=480, height=480, | |
| smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0, | |
| scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None, | |
| draw_style='controlnext', normalize_pose=True, draw_conf_threshold=0.6, | |
| stabilize_skeleton=False, npz_interpolation_method='body-anchor', | |
| retarget_to_first_signer=True, retarget_face_mode='retarget', | |
| frame_callback=None): | |
| """Generate video from gloss list with optional progressive scaling and head alignment | |
| Args: | |
| draw_style: 'controlnext' (default) or 'openpose' - drawing style for pose visualization | |
| normalize_pose: Whether to normalize pose data to standard coordinate system (default: True) | |
| """ | |
| # Create output directory | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| # Get reference head position if provided | |
| ref_head_top = None | |
| y_offset = 0 | |
| if ref_image_path: | |
| ref_head_top = self.get_reference_head_top(ref_image_path, width, height) | |
| if ref_head_top is not None: | |
| print(f"📏 Reference head top position: {ref_head_top:.2f}") | |
| # Collect all frames from all glosses | |
| all_pose_frames = [] | |
| all_npz_data = [] # Store NPZ data for interpolation | |
| video_info = [] | |
| first_signer_template = None | |
| streamed_frame_count = 0 | |
| incremental_stream = frame_callback is not None and smoothing_method == 'none' | |
| def emit_stream_frame(frame, total_frames=None): | |
| nonlocal streamed_frame_count | |
| if frame_callback is None or frame is None: | |
| return | |
| try: | |
| frame_callback(streamed_frame_count, frame, total_frames or 0) | |
| streamed_frame_count += 1 | |
| except Exception as cb_err: | |
| print(f"⚠️ Frame callback failed at {streamed_frame_count}: {cb_err}") | |
| def build_interpolated_visual_frames(prev_info, curr_info): | |
| if npz_interpolation_frames <= 0: | |
| return [] | |
| npz1 = prev_info['npz_data'] | |
| npz2 = curr_info['npz_data'] | |
| end_frame1 = prev_info.get('end_frame', self.get_total_frames(npz1)) | |
| start_frame2 = curr_info.get('start_frame', 1) | |
| interpolated_npz_frames = interpolate_pose_npz( | |
| npz1, npz2, | |
| num_frames=npz_interpolation_frames, | |
| method=npz_interpolation_method, | |
| frame1_num=end_frame1, | |
| frame2_num=start_frame2 | |
| ) | |
| interpolated_frames = [] | |
| for interp_data in interpolated_npz_frames: | |
| frame_keys = [k for k in interp_data.keys() if k.endswith('_bodies')] | |
| if not frame_keys: | |
| continue | |
| frame_key = frame_keys[0] | |
| frame_num = int(frame_key.split('_')[1]) | |
| frame_data = {} | |
| for suffix in ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']: | |
| key = f"frame_{frame_num:08d}_{suffix}" | |
| if key in interp_data: | |
| frame_data[suffix] = interp_data[key] | |
| if not frame_data: | |
| continue | |
| pose_frame = self.create_pose_frame( | |
| frame_data, width, height, scale_x, scale_y, | |
| hide_torso_lines, y_offset, draw_style, | |
| conf_threshold=draw_conf_threshold | |
| ) | |
| if pose_frame is not None: | |
| interpolated_frames.append(pose_frame) | |
| return interpolated_frames | |
| for gloss in gloss_list: | |
| matched_videos = self.find_gloss_videos(gloss) | |
| total_matches = len(matched_videos) | |
| if not matched_videos: | |
| print(f"❌ '{gloss}' -> No matching Pose unit found") | |
| continue | |
| if self.max_candidates and total_matches > self.max_candidates: | |
| print(f" ℹ️ Limiting candidates to first {self.max_candidates} (out of {total_matches}) for efficiency") | |
| matched_videos = matched_videos[:self.max_candidates] | |
| print(f"🎯 '{gloss}' -> Found {total_matches} Unit in Pose Dict") | |
| print(f" 🔍 Evaluating {len(matched_videos)} candidate(s)") | |
| # Evaluate all videos and select the best one based on quality and centering | |
| candidate_videos = [] | |
| for idx, video_id in enumerate(matched_videos): | |
| npz_data = self.load_video_npz(video_id) | |
| if npz_data is not None: | |
| total_frames = self.get_total_frames(npz_data) | |
| # Check video quality | |
| is_good_quality, quality_msg = self.check_video_quality(npz_data) | |
| if not is_good_quality: | |
| continue | |
| # Get valid frame range | |
| start_frame, end_frame = self.get_valid_frame_range(npz_data) | |
| if start_frame > end_frame: | |
| continue | |
| # Calculate neck centrality score | |
| centrality_score = self.calculate_neck_centrality_score(npz_data) | |
| candidate_videos.append({ | |
| 'video_id': video_id, | |
| 'npz_data': npz_data, | |
| 'total_frames': total_frames, | |
| 'start_frame': start_frame, | |
| 'end_frame': end_frame, | |
| 'quality_msg': quality_msg, | |
| 'centrality_score': centrality_score | |
| }) | |
| if not candidate_videos: | |
| print(f" ❌ No good quality poses dict found for '{gloss}'") | |
| continue | |
| # Select video with best centrality score | |
| best_video = max(candidate_videos, key=lambda x: x['centrality_score']) | |
| video_id = best_video['video_id'] | |
| npz_data = best_video['npz_data'] | |
| total_frames = best_video['total_frames'] | |
| start_frame = best_video['start_frame'] | |
| end_frame = best_video['end_frame'] | |
| quality_msg = best_video['quality_msg'] | |
| centrality_score = best_video['centrality_score'] | |
| print(f" 📹 {video_id}: {total_frames} frames") | |
| print(f" ✅ {quality_msg}") | |
| print(f" 🎯 Centrality score: {centrality_score:.2f} (selected from {len(candidate_videos)} candidates)") | |
| print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})") | |
| # Apply normalization if enabled | |
| if normalize_pose: | |
| npz_data = self.normalize_pose_data(npz_data, reference_point='neck', scale_by='shoulders') | |
| if stabilize_skeleton: | |
| npz_data = self.stabilize_pose_data(npz_data, start_frame=start_frame, end_frame=end_frame) | |
| if retarget_to_first_signer: | |
| if first_signer_template is None: | |
| first_signer_template = self.build_signer_template(npz_data, start_frame=start_frame, end_frame=end_frame) | |
| npz_data = self.retarget_pose_data_to_first_signer( | |
| npz_data, first_signer_template, start_frame=start_frame, end_frame=end_frame, | |
| face_mode=retarget_face_mode | |
| ) | |
| # Store NPZ data for potential interpolation | |
| all_npz_data.append(npz_data) | |
| # Extract frames within valid range | |
| gloss_frames = [] | |
| for frame_num in range(start_frame, end_frame + 1): | |
| frame_data = self.get_frame_data(npz_data, frame_num) | |
| if frame_data and self.check_frame_quality(frame_data): | |
| # Calculate y offset for first frame if reference provided | |
| if ref_head_top is not None and y_offset == 0 and frame_num == start_frame: | |
| # Get head top from current pose | |
| current_head_top = self.get_pose_head_top(frame_data) | |
| if current_head_top is not None: | |
| y_offset = ref_head_top - current_head_top | |
| print(f"📐 Calculated Y offset: {y_offset:.2f}") | |
| pose_frame = self.create_pose_frame( | |
| frame_data, width, height, scale_x, scale_y, | |
| hide_torso_lines, y_offset, draw_style, | |
| conf_threshold=draw_conf_threshold | |
| ) | |
| if pose_frame is not None: | |
| gloss_frames.append(pose_frame) | |
| if gloss_frames: | |
| all_pose_frames.append(gloss_frames) | |
| video_info.append({ | |
| 'gloss': gloss, | |
| 'video_id': video_id, | |
| 'frame_count': len(gloss_frames), | |
| 'npz_data': npz_data, | |
| 'start_frame': start_frame, | |
| 'end_frame': end_frame | |
| }) | |
| print(f" ✅ Generated {len(gloss_frames)} pose frames") | |
| if incremental_stream: | |
| if len(video_info) > 1 and npz_interpolation_frames > 0: | |
| prev_info = video_info[-2] | |
| interp_frames = build_interpolated_visual_frames(prev_info, video_info[-1]) | |
| for pose_frame in interp_frames: | |
| emit_stream_frame(pose_frame) | |
| for pose_frame in gloss_frames: | |
| emit_stream_frame(pose_frame) | |
| if not all_pose_frames: | |
| print("❌ No frames generated") | |
| return False | |
| # Apply NPZ interpolation if requested | |
| if npz_interpolation_frames > 0 and len(all_pose_frames) > 1: | |
| print(f"🔄 Applying NPZ interpolation with {npz_interpolation_frames} frames ({npz_interpolation_method})...") | |
| interpolated_pose_frames = [] | |
| for i in range(len(all_pose_frames)): | |
| interpolated_pose_frames.extend(all_pose_frames[i]) | |
| if i < len(all_pose_frames) - 1: | |
| interp_frames = build_interpolated_visual_frames(video_info[i], video_info[i + 1]) | |
| interpolated_pose_frames.extend(interp_frames) | |
| print(f" ✅ Added {len(interp_frames)} interpolated frames between '{video_info[i]['gloss']}' and '{video_info[i+1]['gloss']}'") | |
| all_pose_frames = [interpolated_pose_frames] # Treat as single sequence | |
| # Apply smoothing if needed | |
| if smoothing_method != 'none' and len(all_pose_frames) > 1: | |
| final_frames = self.apply_smoothing(all_pose_frames, smoothing_frames, smoothing_method) | |
| else: | |
| # Concatenate all frames | |
| final_frames = [] | |
| for group in all_pose_frames: | |
| final_frames.extend(group) | |
| # For smoothed outputs, stream after final assembly because playback order changes. | |
| if frame_callback is not None and not incremental_stream: | |
| print("📡 Streaming preview frames...") | |
| total_preview_frames = len(final_frames) | |
| for stream_idx, stream_frame in enumerate(final_frames): | |
| try: | |
| frame_callback(stream_idx, stream_frame, total_preview_frames) | |
| streamed_frame_count += 1 | |
| except Exception as cb_err: | |
| print(f"⚠️ Frame callback failed at {stream_idx}: {cb_err}") | |
| break | |
| # Write video using FFmpeg directly for better compatibility | |
| print("💾 Writing video file...") | |
| # Try to use FFmpeg pipe for direct H.264 encoding | |
| use_ffmpeg_pipe = True | |
| try: | |
| import subprocess | |
| import threading | |
| ffmpeg_path = _get_ffmpeg_binary() | |
| print(f" ▶ Using FFmpeg binary: {ffmpeg_path}") | |
| # Create FFmpeg command for pipe input | |
| ffmpeg_cmd = [ | |
| ffmpeg_path, | |
| '-y', # Overwrite output file | |
| '-f', 'rawvideo', | |
| '-vcodec', 'rawvideo', | |
| '-s', f'{width}x{height}', | |
| '-pix_fmt', 'rgb24', | |
| '-r', str(fps), | |
| '-i', '-', # Read from pipe | |
| '-c:v', 'libx264', | |
| '-crf', '23', | |
| '-pix_fmt', 'yuv420p', | |
| '-movflags', '+faststart', | |
| str(output_path) | |
| ] | |
| # Start FFmpeg process with proper stderr handling | |
| process = subprocess.Popen( | |
| ffmpeg_cmd, | |
| stdin=subprocess.PIPE, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| bufsize=10**8 # Large buffer to prevent blocking | |
| ) | |
| # Collect stderr in background to prevent pipe blocking | |
| stderr_data = [] | |
| def read_stderr(): | |
| for line in process.stderr: | |
| stderr_data.append(line) | |
| stderr_thread = threading.Thread(target=read_stderr) | |
| stderr_thread.daemon = True | |
| stderr_thread.start() | |
| # Write frames to FFmpeg | |
| for pose_frame in tqdm(final_frames, desc="Writing frames"): | |
| try: | |
| # FFmpeg expects RGB format | |
| process.stdin.write(pose_frame.tobytes()) | |
| except BrokenPipeError: | |
| # FFmpeg died, check why | |
| process.wait() | |
| stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace') | |
| print(f"⚠️ FFmpeg died during write. Error output:") | |
| print(stderr_output[-500:] if len(stderr_output) > 500 else stderr_output) | |
| raise | |
| # Close pipe and wait for FFmpeg to finish | |
| process.stdin.close() | |
| process.wait(timeout=30) | |
| if process.returncode == 0: | |
| print(f"✅ Video generated successfully with H.264 codec!") | |
| else: | |
| stderr_output = b''.join(stderr_data).decode('utf-8', errors='replace') | |
| print(f"⚠️ FFmpeg failed with return code {process.returncode}") | |
| print(f" Last 500 chars of error: {stderr_output[-500:] if len(stderr_output) > 500 else stderr_output}") | |
| use_ffmpeg_pipe = False | |
| except Exception as e: | |
| print(f"⚠️ FFmpeg pipe method failed: {e}") | |
| use_ffmpeg_pipe = False | |
| # Fallback to OpenCV if FFmpeg pipe fails | |
| if not use_ffmpeg_pipe: | |
| print("⚠️ Falling back to OpenCV writer...") | |
| tmp_output_path = output_path.with_name(f"{output_path.stem}_mp4v_tmp{output_path.suffix}") | |
| fourcc = cv2.VideoWriter_fourcc(*'mp4v') | |
| video_writer = cv2.VideoWriter(str(tmp_output_path), fourcc, fps, (width, height)) | |
| if not video_writer.isOpened(): | |
| print("❌ Unable to create video file") | |
| return False | |
| for pose_frame in tqdm(final_frames, desc="Writing frames"): | |
| pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR) | |
| video_writer.write(pose_frame_bgr) | |
| video_writer.release() | |
| print("✅ Video generated successfully (raw MP4V). Re-encoding to H.264 for browser compatibility...") | |
| try: | |
| ffmpeg_bin = _get_ffmpeg_binary() | |
| print(f" ▶ Using FFmpeg binary: {ffmpeg_bin}") | |
| reencode_cmd = [ | |
| ffmpeg_bin, | |
| '-y', | |
| '-i', str(tmp_output_path), | |
| '-c:v', 'libx264', | |
| '-pix_fmt', 'yuv420p', | |
| '-movflags', '+faststart', | |
| str(output_path) | |
| ] | |
| result = subprocess.run( | |
| reencode_cmd, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| check=True | |
| ) | |
| tmp_output_path.unlink(missing_ok=True) | |
| print("✅ Re-encoded video with libx264 successfully!") | |
| if result.stderr: | |
| stderr_tail = result.stderr.decode('utf-8', errors='ignore')[-300:] | |
| if stderr_tail.strip(): | |
| print(stderr_tail) | |
| except Exception as re_err: | |
| print(f"⚠️ H.264 re-encode failed: {re_err}") | |
| print(" Keeping MP4V file; some browsers may not play it.") | |
| if tmp_output_path.exists(): | |
| shutil.move(str(tmp_output_path), str(output_path)) | |
| print(f" 📁 File: {output_path}") | |
| print(f" 📊 {len(final_frames)} frames, {fps}fps, {width}x{height}") | |
| if output_path.exists(): | |
| print(f" 💾 Size: {output_path.stat().st_size / 1024 / 1024:.2f} MB") | |
| # Show video details | |
| print(f"\n📈 Video details:") | |
| for info in video_info: | |
| print(f" {info['gloss']}: {info['video_id']} ({info['frame_count']} frames)") | |
| return True | |
| def apply_smoothing(self, frame_groups, smoothing_frames, method): | |
| """Apply smoothing between gloss groups""" | |
| print(f"🌊 Applying {method} smoothing ({smoothing_frames} frames)...") | |
| if method == 'fade': | |
| return self.apply_fade_smoothing(frame_groups, smoothing_frames) | |
| elif method == 'blend': | |
| return self.apply_blend_smoothing(frame_groups, smoothing_frames) | |
| elif method == 'pause': | |
| return self.apply_pause_smoothing(frame_groups, smoothing_frames) | |
| else: | |
| final_frames = [] | |
| for group in frame_groups: | |
| final_frames.extend(group) | |
| return final_frames | |
| def apply_fade_smoothing(self, frame_groups, fade_frames): | |
| """Apply fade in/out smoothing""" | |
| smoothed_frames = [] | |
| for i, group in enumerate(frame_groups): | |
| if i == 0: | |
| # First group: fade in | |
| for f in range(fade_frames): | |
| alpha = f / fade_frames | |
| black_frame = np.zeros_like(group[0]) | |
| faded_frame = (black_frame * (1 - alpha) + group[0] * alpha).astype(np.uint8) | |
| smoothed_frames.append(faded_frame) | |
| smoothed_frames.extend(group) | |
| if i < len(frame_groups) - 1: | |
| # Transition between groups | |
| next_group = frame_groups[i + 1] | |
| current_last = group[-1] | |
| next_first = next_group[0] | |
| for f in range(fade_frames): | |
| alpha = f / fade_frames | |
| blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8) | |
| smoothed_frames.append(blended_frame) | |
| return smoothed_frames | |
| def apply_blend_smoothing(self, frame_groups, blend_frames): | |
| """Apply blend smoothing""" | |
| smoothed_frames = [] | |
| for i, group in enumerate(frame_groups): | |
| smoothed_frames.extend(group) | |
| if i < len(frame_groups) - 1: | |
| next_group = frame_groups[i + 1] | |
| current_last = group[-1] | |
| next_first = next_group[0] | |
| for f in range(1, blend_frames + 1): | |
| alpha = f / (blend_frames + 1) | |
| blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8) | |
| smoothed_frames.append(blended_frame) | |
| return smoothed_frames | |
| def apply_pause_smoothing(self, frame_groups, pause_frames): | |
| """Apply pause smoothing""" | |
| smoothed_frames = [] | |
| for i, group in enumerate(frame_groups): | |
| smoothed_frames.extend(group) | |
| if i < len(frame_groups) - 1: | |
| last_frame = group[-1] | |
| for _ in range(pause_frames): | |
| smoothed_frames.append(last_frame.copy()) | |
| return smoothed_frames | |
| def show_available_glosses(self, limit=20): | |
| """Show available glosses""" | |
| glosses = list(self.gloss_to_videos.keys()) | |
| print(f"\n📋 Available Glosses ({len(glosses)}):") | |
| for i, gloss in enumerate(glosses[:limit]): | |
| videos = self.gloss_to_videos[gloss] | |
| print(f" {gloss} -> {len(videos)} videos") | |
| if len(glosses) > limit: | |
| print(f" ... and {len(glosses) - limit} more") | |
| def run_interactive(self): | |
| """Run interactive Q&A system""" | |
| print("\n" + "=" * 60) | |
| print("🤖 Sign Language Gloss Q&A System (Individual NPZ)") | |
| print("=" * 60) | |
| print("💬 Enter gloss to convert, separate multiple words with spaces") | |
| print("📋 Enter 'list' to view available glosses") | |
| print("🔧 Enter 'help' to view help") | |
| print("👋 Enter 'quit' to exit system") | |
| print("=" * 60) | |
| while True: | |
| try: | |
| user_input = input("\n🤖 Please enter gloss: ").strip() | |
| if not user_input: | |
| continue | |
| elif user_input.lower() == 'quit': | |
| print("👋 Thank you for using!") | |
| break | |
| elif user_input.lower() == 'list': | |
| self.show_available_glosses() | |
| continue | |
| elif user_input.lower() == 'help': | |
| self.show_help() | |
| continue | |
| # Parse input glosses | |
| gloss_list = user_input.upper().split() | |
| print(f"\n🎯 Query: {' + '.join(gloss_list)}") | |
| # Generate timestamp for filename | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| gloss_str = "_".join(gloss_list) | |
| # Ask for smoothing options if multiple glosses | |
| smoothing_method = 'none' | |
| smoothing_frames = 0 | |
| npz_interpolation_frames = 0 | |
| if len(gloss_list) > 1: | |
| print(f"\n🌊 Multiple glosses detected, choose smoothing method:") | |
| print(f" 1. none - No smoothing (direct concatenation)") | |
| print(f" 2. fade - Fade in/out transition") | |
| print(f" 3. blend - Frame blending transition") | |
| print(f" 4. pause - Add pause interval") | |
| print(f" 5. npz - NPZ interpolation (smoothest transition)") | |
| smooth_choice = input(f"Choose smoothing method [1-5, default 1]: ").strip() | |
| if smooth_choice == '2': | |
| smoothing_method = 'fade' | |
| smoothing_frames = int(input("Fade frames [default 5]: ").strip() or "5") | |
| elif smooth_choice == '3': | |
| smoothing_method = 'blend' | |
| smoothing_frames = int(input("Blend frames [default 3]: ").strip() or "3") | |
| elif smooth_choice == '4': | |
| smoothing_method = 'pause' | |
| smoothing_frames = int(input("Pause frames [default 10]: ").strip() or "10") | |
| elif smooth_choice == '5': | |
| npz_interpolation_frames = int(input("NPZ interpolation frames [default 10]: ").strip() or "10") | |
| print(f"📊 Using body-anchor NPZ interpolation for smooth transitions") | |
| # Generate output filename | |
| suffix = f"_{smoothing_method}" if smoothing_method != 'none' else "" | |
| if npz_interpolation_frames > 0: | |
| suffix = f"_npz{npz_interpolation_frames}" | |
| draw_style = 'controlnext' | |
| print(f"🎨 Using {draw_style} drawing style") | |
| style_suffix = f"_{draw_style}_style" | |
| output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}{style_suffix}.mp4" | |
| # Generate video | |
| success = self.generate_video_from_glosses( | |
| gloss_list, output_file, | |
| smoothing_frames=smoothing_frames, | |
| smoothing_method=smoothing_method, | |
| npz_interpolation_frames=npz_interpolation_frames, | |
| hide_torso_lines=False, | |
| draw_style=draw_style | |
| ) | |
| except KeyboardInterrupt: | |
| print("\n\n👋 System exited") | |
| break | |
| except Exception as e: | |
| print(f"❌ Error occurred: {e}") | |
| def show_help(self): | |
| """Show help information""" | |
| print("\n" + "=" * 50) | |
| print("📖 Help Information") | |
| print("=" * 50) | |
| print("🔹 Enter single gloss: HELLO") | |
| print("🔹 Enter multiple glosses: HELLO WORLD GOODBYE") | |
| print("🔹 View available content: list") | |
| print("🔹 System will match sign language videos from NPZ files") | |
| print(f"🔹 Generated videos are saved in {OUTPUT_DIR}/ directory") | |
| print("🔹 Smoothing options:") | |
| print(" - fade: Fade in/out transition") | |
| print(" - blend: Frame blending transition") | |
| print(" - pause: Add pause interval") | |
| print(" - npz: NPZ-level interpolation (smoothest, uses Catmull-Rom splines)") | |
| print("=" * 50) | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Sign Language Gloss Q&A System - Individual NPZ') | |
| parser.add_argument('--gloss', '-g', | |
| help='Directly input gloss to generate video, separated by spaces') | |
| parser.add_argument('--fps', type=int, default=25, | |
| help='Video frame rate (default: 25)') | |
| parser.add_argument('--width', type=int, default=480, | |
| help='Video width (default: 480)') | |
| parser.add_argument('--height', type=int, default=480, | |
| help='Video height (default: 480)') | |
| parser.add_argument('--smoothing', choices=['none', 'fade', 'blend', 'pause'], | |
| default='none', help='Smoothing method (default: none)') | |
| parser.add_argument('--smoothing-frames', type=int, default=5, | |
| help='Smoothing frames (default: 5)') | |
| parser.add_argument('--npz-interpolation', type=int, default=0, | |
| help='Number of NPZ interpolation frames between glosses (default: 0)') | |
| parser.add_argument('--npz-interpolation-method', | |
| choices=['body-anchor', 'catmull-rom', 'linear', 'cubic'], | |
| default='body-anchor', | |
| help='NPZ transition method. body-anchor keeps hand/face local shapes and only retargets them to interpolated wrists/neck. (default: body-anchor)') | |
| parser.add_argument('--scale-x', type=float, default=1.4, | |
| help='Progressive X-axis scaling factor (default: 1.4)') | |
| parser.add_argument('--scale-y', type=float, default=1.5, | |
| help='Progressive Y-axis scaling factor (default: 1.5)') | |
| parser.add_argument('--hide-torso-lines', type=str, choices=['true', 'false'], default='false', | |
| help='Hide torso lines from neck to hips (set to black). Choices: true/false (default: false)') | |
| parser.add_argument('--ref-image-path', type=str, default=None, | |
| help='Reference image path for head alignment') | |
| parser.add_argument('--draw-style', type=str, choices=['controlnext', 'openpose'], default='controlnext', | |
| help='Drawing style for pose visualization. controlnext: advanced features with confidence-based coloring. openpose: simpler classic style. (default: controlnext)') | |
| parser.add_argument('--draw-threshold', type=float, default=0.6, | |
| help='Confidence threshold for drawing joints (default: 0.6)') | |
| parser.add_argument('--normalize-pose', type=str, choices=['true', 'false'], default='true', | |
| help='Normalize pose data to standard coordinate system. This ensures different videos are in the same coordinate space, reducing inconsistency from different video sources. (default: true)') | |
| parser.add_argument('--max-candidates', type=int, default=10, | |
| help='Maximum number of NPZ candidates evaluated per gloss (default: 10, set 0 for unlimited)') | |
| parser.add_argument('--stabilize-skeleton', type=str, choices=['true', 'false'], default='false', | |
| help='Stabilize body bone lengths and face scale before rendering (default: false)') | |
| parser.add_argument('--retarget-to-first-signer', type=str, choices=['true', 'false'], default='true', | |
| help='Retarget every gloss clip to the first selected signer skeleton. Only arms/hands change across words. (default: true)') | |
| parser.add_argument('--retarget-face-mode', choices=['retarget', 'none'], default='retarget', | |
| help='Face handling when retargeting: retarget keeps local face shape but aligns center/scale to first signer; none leaves face unchanged. (default: retarget)') | |
| args = parser.parse_args() | |
| # Initialize QA system | |
| qa_system = SignLanguageQA(max_candidates=max(0, args.max_candidates)) | |
| # If gloss parameter provided, process directly | |
| if args.gloss: | |
| gloss_list = args.gloss.upper().split() | |
| print(f"🎯 Processing gloss: {' + '.join(gloss_list)}") | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| gloss_str = "_".join(gloss_list) | |
| suffix = f"_{args.smoothing}" if args.smoothing != 'none' else "" | |
| # Include video IDs in filename | |
| video_ids = [] | |
| for gloss in gloss_list: | |
| videos = qa_system.find_gloss_videos(gloss) | |
| if videos: | |
| video_ids.append(videos[0]) # Take first video | |
| video_id_str = "_".join(video_ids) if video_ids else "novideo" | |
| style_suffix = f"_{args.draw_style}_style" | |
| output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{video_id_str}_{timestamp}{suffix}{style_suffix}.mp4" | |
| if args.smoothing != 'none': | |
| print(f"🌊 Using {args.smoothing} smoothing ({args.smoothing_frames} frames)") | |
| if args.scale_x != 1.0 or args.scale_y != 1.0: | |
| print(f"📏 Using progressive scaling: X={args.scale_x}, Y={args.scale_y}") | |
| if args.draw_style != 'controlnext': | |
| print(f"🎨 Using {args.draw_style} drawing style") | |
| if args.normalize_pose == 'true': | |
| print(f"📏 Pose normalization enabled") | |
| else: | |
| print(f"⚠️ Pose normalization disabled") | |
| if args.stabilize_skeleton == 'true': | |
| print(f"🦴 Skeleton stabilization enabled") | |
| if args.npz_interpolation > 0: | |
| print(f"🔄 NPZ interpolation method: {args.npz_interpolation_method}") | |
| if args.retarget_to_first_signer == 'true': | |
| print(f"🧍 Retargeting all glosses to first signer skeleton (face={args.retarget_face_mode})") | |
| success = qa_system.generate_video_from_glosses( | |
| gloss_list, output_file, args.fps, args.width, args.height, | |
| args.smoothing_frames, args.smoothing, args.npz_interpolation, | |
| args.scale_x, args.scale_y, args.hide_torso_lines == 'true', | |
| args.ref_image_path, args.draw_style, args.normalize_pose == 'true', | |
| args.draw_threshold, args.stabilize_skeleton == 'true', | |
| args.npz_interpolation_method, | |
| args.retarget_to_first_signer == 'true', args.retarget_face_mode | |
| ) | |
| if not success: | |
| print("❌ Video generation failed") | |
| else: | |
| # Start interactive system | |
| qa_system.run_interactive() | |
| if __name__ == "__main__": | |
| main() | |