Instructions to use cszhilu1998/LiveWorld with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use cszhilu1998/LiveWorld with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("cszhilu1998/LiveWorld", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Download LiveWorld-Code/scripts/create_infer_sample/generate_eval_benchmark.py from cszhilu1998/LiveWorld: direct link, hf CLI and curl.
- Browser
- Download file 70.2 kB
-
https://huggingface.co/cszhilu1998/LiveWorld/resolve/main/LiveWorld-Code/scripts/create_infer_sample/generate_eval_benchmark.py
- Command line
-
hf download hf://cszhilu1998/LiveWorld/LiveWorld-Code/scripts/create_infer_sample/generate_eval_benchmark.py
-
curl -L -o generate_eval_benchmark.py https://huggingface.co/cszhilu1998/LiveWorld/resolve/main/LiveWorld-Code/scripts/create_infer_sample/generate_eval_benchmark.py
70.2 kB
#!/usr/bin/env python3
"""
Generate event-centric benchmark plans (final version: case1 + case2 only).
case1: Pure left/right horizontal translation (90% fg pixel exit, back-and-forth).
Originally named traj_f.
case2: Two-segment translation + in-place lookback yaw (right/left variants).
Core coordinate idea: define camera trajectory as *relative* poses in
first-frame local coordinates, then transform to world via
``c2w_first @ local_pose``.
Local convention (OpenCV camera):
X → right, Y → down, Z → forward (into the scene).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
import yaml
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import cv2
import numpy as np
CASE_CHOICES = ("case1", "case2")
EVENT_IDS = ("A", "B", "C", "D", "E", "F")
_QWEN_VL_CACHE: Dict[str, Tuple[object, object, str]] = {}
_DETECTION_MODEL_CACHE: Dict[Tuple[str, str, str, bool], Tuple[object, object]] = {}
# ---------------------------------------------------------------------------
# Combo definition registry
# ---------------------------------------------------------------------------
@dataclass
class ComboDef:
combo_id: str
case_type: str # "case1" or "case2"
num_events: int # 1, 2, or 3
num_rounds: int # 2-6
first_frame_has_event: bool
actions: List[Dict[str, str]] # per-round {"action": ..., "event": ...}
target_sequence: List[str] # per-round target location ID
motion_primitive: str # "case1" | "case2_right" | "case2_left"
is_core: bool = True # core = generated by default
event_ids: List[str] = field(default_factory=list) # which event IDs are used
frames_per_round: Optional[int] = None # override CLI --frames-per-round
fps: int = 16 # video fps (metadata only)
layout_scale: float = 1.0 # scale factor for layout radius
@dataclass
class LayoutConfig:
"""Spatial layout configuration for events and camera positions."""
name: str # "triangle", "square", "line", etc.
event_positions: Dict[str, List[float]] # event_id -> [x, y, z] local
centroid: np.ndarray # shape (3,), layout centroid
camera_orientation: str # "outward" | "inward" | "forward"
interpolation: str # "lerp_slerp"
path_noise_std: float # 0.0 = no noise
def _make_combo(combo_id, case_type, num_events, num_rounds, first_frame_has_event,
actions, targets, motion_primitive="default", is_core=True,
event_ids=None):
if event_ids is None:
event_ids = ["A", "B", "C"][:num_events]
return ComboDef(
combo_id=combo_id, case_type=case_type, num_events=num_events,
num_rounds=num_rounds, first_frame_has_event=first_frame_has_event,
actions=actions, target_sequence=targets,
motion_primitive=motion_primitive, is_core=is_core,
event_ids=event_ids,
)
COMBO_REGISTRY: Dict[str, ComboDef] = {}
# ============================================================================
# Case 1: 纯左右平移,去回去回 (原 traj_f, 2 combos)
# R0: 向右/左平移,到90%像素出屏幕
# R1: 平移回原点
# R2: 重复R0
# R3: 重复R1
# ============================================================================
COMBO_REGISTRY["case1_right"] = _make_combo(
"case1_right", "case1", 1, 4, True,
[{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"}],
["B", "A", "B", "A"],
motion_primitive="case1_right",
event_ids=["A"],
)
COMBO_REGISTRY["case1_left"] = _make_combo(
"case1_left", "case1", 1, 4, True,
[{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"}],
["B", "A", "B", "A"],
motion_primitive="case1_left",
event_ids=["A"],
)
# ============================================================================
# Case 2: 独立两段平移 + 两次转向 (2 combos, 4 rounds each)
# R0: A->B 平移,|AB|=T(T 按前景出屏阈值求得)
# R1: 在B原地转向前景中心
# R2: B->C 平移,|BC|=T(方向与AB一致)
# R3: 在C原地再转向前景中心
# ============================================================================
COMBO_REGISTRY["case2_right"] = _make_combo(
"case2_right", "case2", 1, 4, True,
[{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"}],
["B", "B", "C", "C"],
motion_primitive="case2_right",
event_ids=["A"],
)
COMBO_REGISTRY["case2_left"] = _make_combo(
"case2_left", "case2", 1, 4, True,
[{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "leave", "event": "A"}],
["B", "B", "C", "C"],
motion_primitive="case2_left",
event_ids=["A"],
)
def get_combos_for_case(case_type: str, all_variants: bool = False) -> List[ComboDef]:
"""Return all ComboDef entries for a given case_type."""
return [c for c in COMBO_REGISTRY.values()
if c.case_type == case_type and (all_variants or c.is_core)]
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class ObjectDetection:
entities: List[str]
bbox_xyxy: Tuple[int, int, int, int]
area_ratio: float
method: str
@dataclass
class SceneScale:
scene_center: List[float]
scene_extent_x: float
scene_extent_z: float
nav_radius: float
event_radius: float
motion_scale: float
geometry_used: bool
@dataclass
class SceneFeatures:
brightness_mean: float
edge_density: float
texture_std: float
clutter_score: float
environment_hint: str
# ---------------------------------------------------------------------------
# Scene meta
# ---------------------------------------------------------------------------
def _load_scene_meta(meta_path: str) -> Optional[Dict]:
"""Load scene meta.npz → dict with c2w (4×4) and points_world (N×3)."""
if not meta_path or not Path(meta_path).exists():
return None
data = np.load(meta_path)
if "c2w" not in data or "points_world" not in data:
return None
meta = {
"c2w": data["c2w"].astype(np.float32),
"points_world": data["points_world"].astype(np.float32),
"intrinsics": data["intrinsics"].astype(np.float32),
}
if "target_h" in data:
meta["target_h"] = int(data["target_h"])
if "target_w" in data:
meta["target_w"] = int(data["target_w"])
return meta
def _filter_fg_depth_outliers(
points_local: np.ndarray,
u_proj: np.ndarray,
v_proj: np.ndarray,
*,
keep_upper_q: float = 0.90,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Drop the farthest foreground depth tail to suppress long-tail artifacts."""
pts = np.asarray(points_local, dtype=np.float32)
u = np.asarray(u_proj, dtype=np.float32)
v = np.asarray(v_proj, dtype=np.float32)
if len(pts) == 0:
return pts, u, v
if pts.ndim != 2 or pts.shape[1] != 3:
raise ValueError(f"points_local must be Nx3, got shape={pts.shape}")
if len(u) != len(pts) or len(v) != len(pts):
raise ValueError("u_proj/v_proj must align with points_local length")
q_hi = float(np.clip(keep_upper_q, 0.5, 1.0))
z = pts[:, 2]
finite = np.isfinite(z)
if not np.any(finite):
raise ValueError("foreground points have no finite depth values")
z_finite = z[finite]
z_hi = float(np.quantile(z_finite, q_hi))
keep = finite & (z <= z_hi)
if int(np.count_nonzero(keep)) == 0:
raise ValueError("depth outlier filtering removed all foreground points")
return pts[keep], u[keep], v[keep]
def _estimate_event_points_local(
scene_meta: Optional[Dict],
fg_union_mask: np.ndarray,
) -> Optional[np.ndarray]:
"""Estimate foreground 3D points in first-frame local camera coordinates."""
if scene_meta is None:
return None
if fg_union_mask is None:
raise ValueError("fg_union_mask is required for mask-only foreground calibration")
pts_w = scene_meta.get("points_world")
c2w = scene_meta.get("c2w")
K = scene_meta.get("intrinsics")
if (
pts_w is None
or c2w is None
or K is None
or np.asarray(K).shape != (3, 3)
or len(pts_w) == 0
):
return None
pts_w = np.asarray(pts_w, dtype=np.float32)
w2c = np.linalg.inv(np.asarray(c2w, dtype=np.float32))
ones = np.ones((len(pts_w), 1), dtype=np.float32)
pts_local = (w2c @ np.hstack([pts_w, ones]).T).T[:, :3]
z = pts_local[:, 2]
valid = np.isfinite(z) & (z > 0.1)
if valid.sum() < 64:
return None
fx, fy = float(K[0, 0]), float(K[1, 1])
cx, cy = float(K[0, 2]), float(K[1, 2])
x = pts_local[:, 0]
y = pts_local[:, 1]
u = fx * x / np.maximum(z, 1e-6) + cx
v = fy * y / np.maximum(z, 1e-6) + cy
fg_mask = np.asarray(fg_union_mask)
if fg_mask.ndim != 2:
raise ValueError(f"fg_union_mask must be HxW, got shape={fg_mask.shape}")
fg_mask = (fg_mask > 0)
mask_h, mask_w = fg_mask.shape
if mask_h <= 0 or mask_w <= 0 or int(np.count_nonzero(fg_mask)) == 0:
raise ValueError("fg_union_mask is empty")
target_w = scene_meta.get("target_w")
target_h = scene_meta.get("target_h")
if target_w is None or target_h is None:
raise ValueError("scene_meta must contain target_w/target_h for mask alignment")
proj_w = max(1, int(target_w))
proj_h = max(1, int(target_h))
scale_u = float(mask_w) / float(proj_w)
scale_v = float(mask_h) / float(proj_h)
u_m = u * scale_u
v_m = v * scale_v
u_i = np.rint(u_m).astype(np.int32)
v_i = np.rint(v_m).astype(np.int32)
inside_image = (
valid
& np.isfinite(u_m)
& np.isfinite(v_m)
& (u_i >= 0)
& (u_i < int(mask_w))
& (v_i >= 0)
& (v_i < int(mask_h))
)
if inside_image.sum() < 32:
return None
fg_hit = np.zeros_like(inside_image, dtype=bool)
cand_idx = np.flatnonzero(inside_image)
if cand_idx.size > 0:
fg_hit[cand_idx] = fg_mask[v_i[cand_idx], u_i[cand_idx]]
if fg_hit.sum() < 32:
return None
pts = pts_local[fg_hit]
u_sel = u_m[fg_hit]
v_sel = v_m[fg_hit]
pts, u_sel, v_sel = _filter_fg_depth_outliers(pts, u_sel, v_sel)
if len(pts) < 32:
return None
boundary_idx = np.array(
[
int(np.argmin(u_sel)),
int(np.argmax(u_sel)),
int(np.argmin(v_sel)),
int(np.argmax(v_sel)),
],
dtype=np.int64,
)
boundary_idx = np.unique(boundary_idx)
if len(pts) > 2048:
keep_set = set(boundary_idx.tolist())
budget = 2048 - len(keep_set)
if budget > 0:
all_idx = np.arange(len(pts), dtype=np.int64)
if keep_set:
mask = np.ones(len(pts), dtype=bool)
mask[np.array(sorted(keep_set), dtype=np.int64)] = False
pool = all_idx[mask]
else:
pool = all_idx
if len(pool) <= budget:
sample_idx = pool
else:
sample_idx = pool[np.linspace(0, len(pool) - 1, budget, dtype=np.int64)]
keep_idx = np.unique(
np.concatenate(
[
np.array(sorted(keep_set), dtype=np.int64),
np.asarray(sample_idx, dtype=np.int64),
]
)
)
else:
keep_idx = boundary_idx[:2048]
pts = pts[keep_idx]
pts = pts.astype(np.float32, copy=False)
if not np.all(np.isfinite(pts)):
pts = pts[np.isfinite(pts).all(axis=1)]
if len(pts) == 0:
return None
return pts
# ---------------------------------------------------------------------------
# Image / scene feature helpers
# ---------------------------------------------------------------------------
def _load_image_rgb(image_path: str) -> np.ndarray:
img_bgr = cv2.imread(image_path, cv2.IMREAD_COLOR)
if img_bgr is None:
raise FileNotFoundError(f"Cannot load image: {image_path}")
return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
def _prepare_image_to_target(image_rgb: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
"""Resize/crop image to exact target size with same policy as scene builders."""
from liveworld.geometry_utils import resize_short_edge_and_center_crop
try:
return resize_short_edge_and_center_crop(image_rgb, target_h, target_w)
except ValueError:
pass
h, w = image_rgb.shape[:2]
scale = min(target_w / float(w), target_h / float(h))
new_w = max(1, int(round(w * scale)))
new_h = max(1, int(round(h * scale)))
resized = cv2.resize(image_rgb, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
canvas = np.zeros((target_h, target_w, 3), dtype=np.uint8)
y0 = (target_h - new_h) // 2
x0 = (target_w - new_w) // 2
canvas[y0 : y0 + new_h, x0 : x0 + new_w] = resized
return canvas
def _prepare_detection_image_for_scene(
image_path: str,
scene_meta: Optional[Dict],
) -> str:
"""Return detection image path aligned to scene_meta target geometry."""
if scene_meta is None:
return image_path
target_h = scene_meta.get("target_h")
target_w = scene_meta.get("target_w")
if target_h is None or target_w is None:
return image_path
target_h = int(target_h)
target_w = int(target_w)
if target_h <= 0 or target_w <= 0:
return image_path
raw_rgb = _load_image_rgb(image_path)
if raw_rgb.shape[0] == target_h and raw_rgb.shape[1] == target_w:
return image_path
aligned_rgb = _prepare_image_to_target(raw_rgb, target_h, target_w)
src = Path(image_path).resolve()
cache_dir = Path(".cache/event_bench/detect_aligned")
cache_dir.mkdir(parents=True, exist_ok=True)
key = f"{src}|{target_h}x{target_w}"
digest = hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
out_path = cache_dir / f"{src.stem}_{target_h}x{target_w}_{digest}.png"
if not out_path.exists():
cv2.imwrite(str(out_path), cv2.cvtColor(aligned_rgb, cv2.COLOR_RGB2BGR))
return str(out_path)
def extract_scene_features(image_rgb: np.ndarray) -> SceneFeatures:
gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
brightness_mean = float(np.mean(gray) / 255.0)
edges = cv2.Canny(gray, threshold1=80, threshold2=160)
edge_density = float(np.mean(edges > 0))
texture_std = float(np.std(cv2.Laplacian(gray, cv2.CV_32F)))
texture_norm = float(np.clip(texture_std / 40.0, 0.0, 1.0))
clutter_score = float(np.clip(0.6 * edge_density + 0.4 * texture_norm, 0.0, 1.0))
if clutter_score > 0.42:
environment_hint = "cluttered"
elif clutter_score > 0.22:
environment_hint = "moderate"
else:
environment_hint = "open"
return SceneFeatures(
brightness_mean=brightness_mean,
edge_density=edge_density,
texture_std=texture_std,
clutter_score=clutter_score,
environment_hint=environment_hint,
)
# ---------------------------------------------------------------------------
# Object detection
# ---------------------------------------------------------------------------
_DYNAMIC_FILTER_PROMPT = """\
Given this image and these detected objects: {entities}
Which of these can move ON THEIR OWN? (people, animals, birds, vehicles, robots, etc.)
STATIC (exclude): furniture, appliances, fixtures, radiators, doors, windows,
lamps, plants, decorations, buildings, structures, signs, sky, water, road, ground.
List ONLY the dynamic/movable ones. If none can move, output exactly: Nothing
Output format:
Nothing
OR numbered list:
1) person
2) dog"""
_STATIC_ENTITY_KEYWORDS = (
"sky",
"cloud",
"ground",
"floor",
"ceiling",
"wall",
"road",
"street",
"sidewalk",
"building",
"tree",
"grass",
"mountain",
"water",
"river",
"lake",
"ocean",
"sea",
"snow",
"forest",
"background",
"scenery",
"furniture",
"table",
"chair",
"sofa",
"couch",
"bench",
"door",
"window",
"ceiling",
)
def _is_static_entity_label(text: str) -> bool:
lowered = str(text).strip().lower()
if not lowered:
return True
if lowered in {"none", "nothing", "background"}:
return True
for kw in _STATIC_ENTITY_KEYWORDS:
if re.search(rf"\b{re.escape(kw)}\b", lowered):
return True
return False
def _bbox_from_mask(mask: np.ndarray) -> Tuple[int, int, int, int]:
ys, xs = np.where(mask > 0)
if len(xs) == 0:
return (0, 0, 0, 0)
return (int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max()))
def detect_event_object(
image_path: str,
qwen_model_path: str,
sam3_model_path: str,
scene_detect_prompt: str,
qwen_device: str = "cuda",
cpu_offload_qwen: bool = False,
cpu_offload_sam3: bool = False,
) -> Tuple[ObjectDetection, np.ndarray]:
"""Detect all foreground entities using Qwen+SAM."""
from scripts.create_train_data._entity_detector import Qwen3VLEntityExtractor
from scripts.create_train_data._sam3_segmenter import Sam3VideoSegmenter
qwen_device = str(qwen_device).strip().lower() if qwen_device else "cuda"
if cpu_offload_qwen:
qwen_device = "cpu"
if qwen_device not in {"cuda", "cpu"}:
qwen_device = "cuda"
if qwen_device == "cuda":
try:
import torch
if not torch.cuda.is_available():
qwen_device = "cpu"
except Exception:
qwen_device = "cpu"
cache_key = (qwen_model_path, sam3_model_path, qwen_device, bool(cpu_offload_sam3))
if cache_key not in _DETECTION_MODEL_CACHE:
qwen = Qwen3VLEntityExtractor(model_path=qwen_model_path, device=qwen_device)
sam3 = None if cpu_offload_sam3 else Sam3VideoSegmenter(checkpoint_path=sam3_model_path)
_DETECTION_MODEL_CACHE[cache_key] = (qwen, sam3)
else:
qwen, sam3 = _DETECTION_MODEL_CACHE[cache_key]
if cpu_offload_sam3 or sam3 is None:
sam3 = Sam3VideoSegmenter(checkpoint_path=sam3_model_path)
raw_entities, _ = qwen.extract(image_path, prompt=scene_detect_prompt)
entities = sorted(
{
str(e).strip()
for e in raw_entities
if str(e).strip() and not _is_static_entity_label(str(e))
}
)
if entities and hasattr(qwen, "generate_text"):
try:
from scripts.create_train_data._entity_detector import parse_entities as _parse_entities
filter_prompt = _DYNAMIC_FILTER_PROMPT.format(entities=", ".join(entities))
filter_raw = qwen.generate_text(image_path, filter_prompt)
filtered = [
str(e).strip()
for e in _parse_entities(filter_raw)
if str(e).strip() and not _is_static_entity_label(str(e))
]
if filtered:
entities = sorted({e for e in filtered})
except Exception as exc:
print(f" [warn] dynamic entity filtering failed, fallback to raw entities ({exc})")
image_rgb = _load_image_rgb(image_path)
h, w = image_rgb.shape[:2]
if not entities:
print(
f" [warn] Qwen detected no dynamic entities in {image_path}, "
"using center-crop fallback mask"
)
entities = ["foreground entity"]
union_mask = np.zeros((h, w), dtype=np.uint8)
cy, cx = h // 2, w // 2
rh, rw = h // 4, w // 4
union_mask[cy - rh : cy + rh, cx - rw : cx + rw] = 1
else:
union_mask = np.zeros((h, w), dtype=np.uint8)
for ent in entities:
seg = sam3.segment(
video_path=image_path,
prompts=[ent],
frame_index=0,
expected_frames=1,
)
if seg is None or seg.size == 0:
print(f" [warn] SAM3 returned empty mask for '{ent}', skipping")
continue
if seg.ndim == 3:
mask = seg[0]
elif seg.ndim == 2:
mask = seg
else:
mask = seg.reshape(seg.shape[-2], seg.shape[-1])
union_mask = np.maximum(union_mask, (mask > 0).astype(np.uint8))
x1, y1, x2, y2 = _bbox_from_mask(union_mask)
if x2 <= x1 or y2 <= y1:
print(
f" [warn] SAM3 union mask for entities {entities} has zero area, "
"using center-crop fallback mask"
)
union_mask = np.zeros((h, w), dtype=np.uint8)
cy, cx = h // 2, w // 2
rh, rw = h // 4, w // 4
union_mask[cy - rh : cy + rh, cx - rw : cx + rw] = 1
x1, y1, x2, y2 = _bbox_from_mask(union_mask)
area_ratio = ((x2 - x1 + 1) * (y2 - y1 + 1)) / float(h * w)
det = ObjectDetection(
entities=entities,
bbox_xyxy=(int(x1), int(y1), int(x2), int(y2)),
area_ratio=float(area_ratio),
method="qwen_sam",
)
if cpu_offload_sam3:
try:
import gc
import torch
del sam3
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception:
pass
return det, union_mask.astype(np.uint8)
# ---------------------------------------------------------------------------
# Motion scale estimation
# ---------------------------------------------------------------------------
def _estimate_motion_scale_from_area_ratio(area_ratio: float) -> float:
if area_ratio >= 0.18:
return 0.65
if area_ratio >= 0.10:
return 0.85
if area_ratio >= 0.05:
return 1.05
if area_ratio >= 0.02:
return 1.25
return 1.45
def _parse_motion_scale_from_text(text: str) -> Optional[float]:
if not text:
return None
start = text.find("{")
end = text.rfind("}")
if start >= 0 and end >= start:
try:
obj = json.loads(text[start : end + 1])
if "motion_scale" in obj:
val = float(obj["motion_scale"])
return float(np.clip(val, 0.5, 1.8))
except Exception:
pass
m = re.search(r"([-+]?\d*\.?\d+)", text)
if m is None:
return None
try:
val = float(m.group(1))
return float(np.clip(val, 0.5, 1.8))
except Exception:
return None
def _qwen_vl_motion_scale(
image_path: str,
qwen_model_path: str,
prompt: str,
) -> Optional[float]:
try:
import torch
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
except Exception:
return None
try:
device = "cuda" if torch.cuda.is_available() else "cpu"
cache_key = f"{qwen_model_path}@{device}"
if cache_key not in _QWEN_VL_CACHE:
load_kwargs = {
"device_map": {"": device},
}
if device == "cuda":
load_kwargs["dtype"] = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
load_kwargs["attn_implementation"] = "flash_attention_2"
else:
load_kwargs["dtype"] = torch.float32
model = Qwen3VLForConditionalGeneration.from_pretrained(qwen_model_path, **load_kwargs)
processor = AutoProcessor.from_pretrained(qwen_model_path)
_QWEN_VL_CACHE[cache_key] = (model, processor, device)
model, processor, device = _QWEN_VL_CACHE[cache_key]
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image_path},
{"type": "text", "text": prompt},
],
}
]
inputs = processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
)
inputs = inputs.to(device)
with torch.no_grad():
out_ids = model.generate(**inputs, max_new_tokens=96)
trimmed = [o[len(i) :] for i, o in zip(inputs.input_ids, out_ids)]
text = processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
return _parse_motion_scale_from_text(text)
except Exception:
return None
def _maybe_llm_adjust_motion_scale(
enable: bool,
image_path: str,
qwen_model_path: str,
area_ratio: float,
scene_features: SceneFeatures,
case_type: str,
) -> Optional[float]:
if not enable:
return None
prompt = (
"You are planning camera movement scale for a scene benchmark.\n"
f"Case: {case_type}\n"
f"Detected event object area ratio in first frame: {area_ratio:.4f}\n"
f"Scene environment hint: {scene_features.environment_hint}\n"
f"Scene clutter score [0,1]: {scene_features.clutter_score:.4f}\n"
f"Image brightness mean [0,1]: {scene_features.brightness_mean:.4f}\n"
"Return JSON only: {\"motion_scale\": number}.\n"
"Allowed range: 0.5 to 1.8. Larger means farther movement.\n"
"If object appears large/close or scene is cluttered, reduce movement scale.\n"
)
return _qwen_vl_motion_scale(
image_path=image_path,
qwen_model_path=qwen_model_path,
prompt=prompt,
)
def _estimate_nav_radius_screen_uniform(
*,
pts_local: np.ndarray,
intrinsics: np.ndarray,
target_w: Optional[int],
target_shift_ratio: float,
screen_depth_percentile: float,
) -> Optional[float]:
"""Estimate nav radius from desired screen-space displacement."""
if pts_local is None or len(pts_local) == 0:
return None
if intrinsics is None or np.asarray(intrinsics).shape != (3, 3):
return None
z = np.asarray(pts_local[:, 2], dtype=np.float32)
valid = np.isfinite(z) & (z > 0.25)
if valid.sum() < 128:
return None
z_ref = float(np.percentile(z[valid], float(np.clip(screen_depth_percentile, 5.0, 95.0))))
fx = float(abs(intrinsics[0, 0]))
if not np.isfinite(fx) or fx < 1e-6:
return None
if target_w is None or int(target_w) <= 0:
return None
ratio = float(np.clip(target_shift_ratio, 0.05, 0.45))
target_px = float(target_w) * ratio
d = target_px * z_ref / fx
nav_radius = d / 0.8
return float(np.clip(nav_radius, 0.4, 3.2))
def estimate_scene_scale(
det: ObjectDetection,
scene_features: SceneFeatures,
image_path: str,
geometry_path: str,
case_type: str,
llm_motion_scaling: bool,
qwen_model_path: str,
scene_meta: Optional[Dict] = None,
distance_mode: str = "screen_uniform",
target_shift_ratio: float = 0.18,
screen_depth_percentile: float = 45.0,
distance_blend_alpha: float = 0.7,
) -> SceneScale:
"""Estimate nav_radius / event_radius for trajectory planning (strict screen_uniform)."""
_ = geometry_path
_ = distance_blend_alpha
if distance_mode != "screen_uniform":
raise ValueError(
f"Unsupported distance_mode={distance_mode}. Only 'screen_uniform' is allowed."
)
if scene_meta is None:
raise ValueError("scene_meta is required for strict trajectory scale estimation.")
motion_scale = _estimate_motion_scale_from_area_ratio(det.area_ratio)
motion_scale = float(motion_scale * (1.1 - 0.35 * scene_features.clutter_score))
llm_scale = _maybe_llm_adjust_motion_scale(
enable=llm_motion_scaling,
image_path=image_path,
qwen_model_path=qwen_model_path,
area_ratio=det.area_ratio,
scene_features=scene_features,
case_type=case_type,
)
if llm_scale is not None:
motion_scale = 0.6 * motion_scale + 0.4 * llm_scale
c2w = scene_meta["c2w"] # (4,4)
w2c = np.linalg.inv(c2w)
pts_w = scene_meta["points_world"]
ones = np.ones((len(pts_w), 1), dtype=np.float32)
pts_local = (w2c @ np.hstack([pts_w, ones]).T).T[:, :3]
extent_x = float(np.percentile(pts_local[:, 0], 95) - np.percentile(pts_local[:, 0], 5))
extent_z = float(np.percentile(pts_local[:, 2], 95) - np.percentile(pts_local[:, 2], 5))
nav_radius = _estimate_nav_radius_screen_uniform(
pts_local=pts_local,
intrinsics=scene_meta.get("intrinsics"),
target_w=scene_meta.get("target_w"),
target_shift_ratio=target_shift_ratio,
screen_depth_percentile=screen_depth_percentile,
)
if nav_radius is None:
raise ValueError("Failed to estimate nav_radius in strict screen_uniform mode.")
event_radius = float(np.clip(2.0 * nav_radius, 0.8, 6.0))
return SceneScale(
scene_center=[0.0, 0.0, 0.0],
scene_extent_x=float(max(0.1, extent_x)),
scene_extent_z=float(max(0.1, extent_z)),
nav_radius=nav_radius,
event_radius=event_radius,
motion_scale=float(motion_scale),
geometry_used=True,
)
# ---------------------------------------------------------------------------
# Local-frame trajectory helpers
# ---------------------------------------------------------------------------
def _circle_points_local(
radius: float,
count: int,
y: float = 0.0,
z_offset: float = 0.0,
angle_offset_deg: float = 0.0,
) -> List[List[float]]:
"""Circle in the local XZ plane centred at origin."""
pts: List[List[float]] = []
for i in range(count):
ang = math.radians(angle_offset_deg + (360.0 * i / count))
x = radius * math.sin(ang)
z = z_offset + radius * math.cos(ang)
pts.append([float(x), float(y), float(z)])
return pts
def _normalize(v: np.ndarray) -> np.ndarray:
n = float(np.linalg.norm(v))
if n < 1e-8:
return v
return v / n
def _lookat_local(position: np.ndarray, look_at: np.ndarray) -> np.ndarray:
"""Build a 4×4 c2w (local) that looks from *position* towards *look_at*."""
forward = _normalize(look_at - position)
if float(np.linalg.norm(forward)) < 1e-8:
forward = np.array([0.0, 0.0, 1.0], dtype=np.float32)
world_up = np.array([0.0, -1.0, 0.0], dtype=np.float32)
right = np.cross(forward, world_up)
if float(np.linalg.norm(right)) < 1e-8:
world_up = np.array([1.0, 0.0, 0.0], dtype=np.float32)
right = np.cross(forward, world_up)
right = _normalize(right)
down = _normalize(np.cross(forward, right))
c2w = np.eye(4, dtype=np.float32)
c2w[:3, 0] = right
c2w[:3, 1] = down
c2w[:3, 2] = forward
c2w[:3, 3] = position
return c2w
def _local_to_world(local_c2w: np.ndarray, first_c2w: np.ndarray) -> np.ndarray:
"""Transform a local-frame c2w into world coordinates."""
return (first_c2w @ local_c2w).astype(np.float32)
# ---------------------------------------------------------------------------
# Event slot builder
# ---------------------------------------------------------------------------
def _build_event_slots(
combo: ComboDef,
event_points: Dict[str, List[float]],
entities: List[str],
) -> Dict[str, Dict]:
"""Build event slots based on combo definition."""
slots: Dict[str, Dict] = {}
spawn_rounds: Dict[str, int] = {}
for i, act in enumerate(combo.actions):
eid = act.get("event", "")
if act["action"] == "spawn" and eid:
spawn_rounds[eid] = i
if combo.first_frame_has_event and "A" in combo.event_ids:
spawn_rounds.setdefault("A", -1)
entities_text = ", ".join(entities) if entities else "foreground entity"
for eid in combo.event_ids:
if eid not in event_points:
continue
slots[eid] = {
"entities": list(entities),
"entity": entities_text,
"position": event_points[eid],
"spawn_round": spawn_rounds.get(eid, 0),
}
return slots
# ---------------------------------------------------------------------------
# Location / pose pool (all in LOCAL coords)
# ---------------------------------------------------------------------------
def _build_location_pool(
nav_radius: float,
event_slots: Dict[str, Dict],
) -> Dict[str, List[float]]:
"""Camera locations in local XZ plane."""
pool: Dict[str, List[float]] = {}
pool["S"] = [0.0, 0.0, 0.0]
pool["O"] = [0.0, 0.0, 0.9 * nav_radius]
return pool
def _build_location_pose_pool(
location_pool: Dict[str, List[float]],
event_slots: Dict[str, Dict],
) -> Dict[str, Dict]:
"""For each location, build a local c2w."""
pose_pool: Dict[str, Dict] = {}
forward_target = np.array([0.0, 0.0, 1.0], dtype=np.float32)
for loc, pos_list in location_pool.items():
pos = np.asarray(pos_list, dtype=np.float32)
if loc == "S":
c2w = np.eye(4, dtype=np.float32)
look = forward_target
elif loc in event_slots:
look = np.asarray(event_slots[loc]["position"], dtype=np.float32)
c2w = _lookat_local(pos, look)
else:
look = np.zeros(3, dtype=np.float32)
c2w = _lookat_local(pos, look)
pose_pool[loc] = {
"position": [float(x) for x in pos],
"look_at": [float(x) for x in look],
"c2w": c2w.astype(float).tolist(),
}
return pose_pool
# ---------------------------------------------------------------------------
# Trajectory calibration helpers
# ---------------------------------------------------------------------------
def _yaw_c2w_local(yaw_deg: float, position: Optional[np.ndarray] = None) -> np.ndarray:
"""Build a local c2w with given yaw angle around Y-down axis."""
rad = math.radians(yaw_deg)
c = math.cos(rad)
s = math.sin(rad)
R = np.array([
[ c, 0.0, s],
[0.0, 1.0, 0.0],
[-s, 0.0, c],
], dtype=np.float32)
c2w = np.eye(4, dtype=np.float32)
c2w[:3, :3] = R
if position is not None:
c2w[:3, 3] = position
return c2w
def _count_visible_fg_projection_points(
*,
points_local: np.ndarray,
intrinsics: np.ndarray,
image_width: int,
image_height: int,
position_local: np.ndarray,
yaw_deg: float,
) -> int:
"""Count visible foreground projections for one candidate local pose."""
pts = np.asarray(points_local, dtype=np.float32)
if pts.ndim != 2 or pts.shape[1] != 3 or len(pts) == 0:
return 0
c2w = _yaw_c2w_local(float(yaw_deg), position=np.asarray(position_local, dtype=np.float32))
R = c2w[:3, :3]
t = c2w[:3, 3]
p_cam = (R.T @ (pts - t).T).T
z = p_cam[:, 2]
valid_z = np.isfinite(z) & (z > 1e-6)
if not np.any(valid_z):
return 0
fx = float(intrinsics[0, 0])
fy = float(intrinsics[1, 1])
cx = float(intrinsics[0, 2])
cy = float(intrinsics[1, 2])
u = fx * p_cam[:, 0] / np.maximum(z, 1e-6) + cx
v = fy * p_cam[:, 1] / np.maximum(z, 1e-6) + cy
W = max(1, int(image_width))
H = max(1, int(image_height))
visible = (
valid_z
& np.isfinite(u)
& np.isfinite(v)
& (u >= 0.0)
& (u < float(W))
& (v >= 0.0)
& (v < float(H))
)
return int(np.count_nonzero(visible))
def _compute_exit_visible_threshold(
points_local: Optional[np.ndarray],
exit_visible_ratio: float,
) -> int:
"""Compute visible-count threshold for exit detection."""
if exit_visible_ratio <= 0:
return 0
if points_local is None:
return 0
total = int(len(points_local))
if total <= 0:
return 0
ratio = float(np.clip(exit_visible_ratio, 0.0, 1.0))
if ratio <= 0.0:
return 0
threshold = int(math.ceil(total * ratio))
return max(1, threshold)
def _find_first_no_projection_param(
eval_visible_count,
*,
hi: float,
n_steps: int = 320,
visible_count_threshold: int = 0,
) -> Optional[float]:
"""Dense-sample a trajectory and return first param where visible count is low."""
if hi <= 0:
return None
threshold = max(0, int(visible_count_threshold))
c0 = int(eval_visible_count(0.0))
if c0 <= threshold:
return 0.0
for i in range(1, n_steps + 1):
t = hi * float(i) / float(n_steps)
c = int(eval_visible_count(t))
if c <= threshold:
return float(t)
return None
def _solve_symmetric_exit_limits(
*,
points_local: np.ndarray,
intrinsics: np.ndarray,
image_width: int,
image_height: int,
nav_radius: float,
max_yaw: float = 85.0,
visible_count_threshold: int = 0,
) -> Dict[str, Optional[float]]:
"""Solve left/right exit limits by foreground no-projection criterion."""
W = max(1, int(image_width))
H = max(1, int(image_height))
pts = np.asarray(points_local, dtype=np.float32)
if pts.ndim != 2 or pts.shape[1] != 3 or len(pts) == 0:
return {
"d_left": None, "d_right": None, "d_max": None,
"yaw_left": None, "yaw_right": None, "yaw_max": None,
}
max_d = max(0.6, 2.8 * float(nav_radius))
d_right = _find_first_no_projection_param(
lambda d: _count_visible_fg_projection_points(
points_local=pts, intrinsics=intrinsics,
image_width=W, image_height=H,
position_local=np.array([float(d), 0.0, 0.0], dtype=np.float32),
yaw_deg=0.0,
),
hi=max_d, visible_count_threshold=visible_count_threshold,
)
d_left = _find_first_no_projection_param(
lambda d: _count_visible_fg_projection_points(
points_local=pts, intrinsics=intrinsics,
image_width=W, image_height=H,
position_local=np.array([-float(d), 0.0, 0.0], dtype=np.float32),
yaw_deg=0.0,
),
hi=max_d, visible_count_threshold=visible_count_threshold,
)
yaw_right = _find_first_no_projection_param(
lambda y: _count_visible_fg_projection_points(
points_local=pts, intrinsics=intrinsics,
image_width=W, image_height=H,
position_local=np.zeros(3, dtype=np.float32),
yaw_deg=float(y),
),
hi=float(max_yaw), visible_count_threshold=visible_count_threshold,
)
yaw_left = _find_first_no_projection_param(
lambda y: _count_visible_fg_projection_points(
points_local=pts, intrinsics=intrinsics,
image_width=W, image_height=H,
position_local=np.zeros(3, dtype=np.float32),
yaw_deg=-float(y),
),
hi=float(max_yaw), visible_count_threshold=visible_count_threshold,
)
d_candidates = [float(v) for v in (d_left, d_right) if v is not None and v > 1e-5]
yaw_candidates = [float(v) for v in (yaw_left, yaw_right) if v is not None and v > 1e-5]
d_max = max(d_candidates) if d_candidates else None
yaw_max_mag = max(yaw_candidates) if yaw_candidates else None
return {
"d_left": float(d_left) if d_left is not None else None,
"d_right": float(d_right) if d_right is not None else None,
"d_max": float(d_max) if d_max is not None else None,
"yaw_left": float(yaw_left) if yaw_left is not None else None,
"yaw_right": float(yaw_right) if yaw_right is not None else None,
"yaw_max": float(yaw_max_mag) if yaw_max_mag is not None else None,
}
# ---------------------------------------------------------------------------
# Round plan & interpolation
# ---------------------------------------------------------------------------
def _build_round_plan(
combo: ComboDef,
location_pool: Dict[str, List[float]],
location_pose_pool: Dict[str, Dict],
event_slots: Dict[str, Dict],
) -> Dict[str, Dict]:
"""Build round plan from combo definition."""
actions = combo.actions
targets = combo.target_sequence
if len(actions) != len(targets):
raise ValueError(
f"Combo {combo.combo_id}: actions ({len(actions)}) and "
f"targets ({len(targets)}) mismatch"
)
plan: Dict[str, Dict] = {}
for i in range(combo.num_rounds):
loc_to = targets[i]
loc_from = "S" if i == 0 else targets[i - 1]
event = actions[i].get("event", "")
action = actions[i]["action"]
if event and event in event_slots:
look_at = event_slots[event]["position"]
elif loc_to in event_slots:
look_at = event_slots[loc_to]["position"]
else:
look_at = [0.0, 0.0, 0.0]
plan[str(i)] = {
"action": action,
"event": event,
"location_from": loc_from,
"location_to": loc_to,
"camera_start": location_pool.get(loc_from, [0.0, 0.0, 0.0]),
"camera_end": location_pool.get(loc_to, [0.0, 0.0, 0.0]),
"pose_start_c2w": location_pose_pool.get(loc_from, {}).get(
"c2w", np.eye(4).tolist()
),
"pose_end_c2w": location_pose_pool.get(loc_to, {}).get(
"c2w", np.eye(4).tolist()
),
"look_at": look_at,
}
return plan
def _interp_rotation(R0: np.ndarray, R1: np.ndarray, t: float) -> np.ndarray:
R = (1.0 - t) * R0 + t * R1
u, _, vt = np.linalg.svd(R)
return (u @ vt).astype(np.float32)
def _interpolate_pose_sequence(
round_plan: Dict[str, Dict],
location_pose_pool: Dict[str, Dict],
frames_per_round: int,
first_c2w: np.ndarray,
motion_primitive: str = "default",
nav_radius: float = 1.0,
seed: int = 42,
calibration_points_local: Optional[np.ndarray] = None,
calibration_intrinsics: Optional[np.ndarray] = None,
calibration_image_width: Optional[int] = None,
calibration_image_height: Optional[int] = None,
exit_visible_ratio: float = 0.0,
) -> List[Dict]:
"""Interpolate per-frame poses and transform local → world.
Supports two motion primitives:
- case1_right / case1_left: Pure X translation (90% fg exit), back-and-forth
- case2_right / case2_left: Triangular A→B + yaw at B → B→C + yaw at C
"""
if frames_per_round < 2:
frames_per_round = 2
keys = sorted(round_plan.keys(), key=lambda x: int(x))
# --- Case 1: 纯左右平移,去回去回 (90%像素出屏幕) ---
if motion_primitive.startswith("case1_"):
if len(keys) != 4:
raise ValueError(f"case1 motion primitive expects 4 rounds, got {len(keys)}")
sign = -1.0 if motion_primitive == "case1_left" else 1.0
base_d = float(0.8 * nav_radius)
exit_d = base_d # fallback
calib_pts = calibration_points_local
calib_K = calibration_intrinsics
calib_W = calibration_image_width
calib_H = calibration_image_height
if (
calib_pts is not None and len(calib_pts) > 0
and calib_K is not None and np.asarray(calib_K).shape == (3, 3)
and calib_W is not None and calib_H is not None
):
W_cal = max(1, int(calib_W))
H_cal = max(1, int(calib_H))
visible_threshold = _compute_exit_visible_threshold(calib_pts, 0.1)
full_exit = _find_first_no_projection_param(
lambda a: _count_visible_fg_projection_points(
points_local=np.asarray(calib_pts, dtype=np.float32),
intrinsics=np.asarray(calib_K, dtype=np.float32),
image_width=W_cal,
image_height=H_cal,
position_local=np.array(
[sign * base_d * float(a), 0.0, 0.0], dtype=np.float32,
),
yaw_deg=0.0,
),
hi=4.0,
n_steps=640,
visible_count_threshold=visible_threshold,
)
if full_exit is not None and full_exit > 1e-5:
exit_d = base_d * float(full_exit)
trans_dist = exit_d
frames: List[Dict] = []
frame_idx = 0
for ri, rk in enumerate(keys):
r = round_plan[rk]
for si in range(frames_per_round):
t = float(si) / max(1, frames_per_round - 1)
if ri in (0, 2):
x = sign * trans_dist * t
elif ri in (1, 3):
x = sign * trans_dist * (1.0 - t)
else:
x = 0.0
pos = np.array([x, 0.0, 0.0], dtype=np.float32)
local = _yaw_c2w_local(0.0, position=pos)
world = _local_to_world(local, first_c2w)
frames.append({
"frame_idx": int(frame_idx),
"round_idx": int(rk),
"interp_t": float(t),
"location_from": r["location_from"],
"location_to": r["location_to"],
"action": r["action"],
"event": r["event"],
"c2w": world.astype(float).tolist(),
})
frame_idx += 1
return frames
# --- Case 2: Triangular layout A -> B -> (yaw at B) -> C -> (yaw at C)
if motion_primitive.startswith("case2_"):
base_d = float(0.8 * nav_radius)
base_Z = base_d / math.sqrt(3.0)
center_pt = np.array([0.0, 0.0, 1.0], dtype=np.float32)
if motion_primitive == "case2_right":
sign = 1.0
else:
sign = -1.0
pos_A = np.zeros(3, dtype=np.float32)
dir_AB = np.array([sign * base_d, 0.0, -base_Z], dtype=np.float32)
pos_B = dir_AB.copy()
dir_BC_unit = np.array([-sign, 0.0, 0.0], dtype=np.float32)
def _yaw_to_center(position_local: np.ndarray) -> float:
rel = center_pt - np.asarray(position_local, dtype=np.float32)
rel_z = float(rel[2])
if abs(rel_z) < 1e-4:
rel_z = 1e-4 if rel_z >= 0 else -1e-4
yaw = math.degrees(math.atan2(float(rel[0]), rel_z))
return float(np.clip(yaw, -85.0, 85.0))
yaw_B = _yaw_to_center(pos_B)
pos_C = np.array([0.0, 0.0, -base_Z], dtype=np.float32)
yaw_C = _yaw_to_center(pos_C)
calib_points = calibration_points_local
if (
calib_points is not None
and len(calib_points) > 0
and calibration_intrinsics is not None
and np.asarray(calibration_intrinsics).shape == (3, 3)
and calibration_image_width is not None
and calibration_image_height is not None
):
W_cal = max(1, int(calibration_image_width))
H_cal = max(1, int(calibration_image_height))
visible_threshold = _compute_exit_visible_threshold(
calib_points, exit_visible_ratio,
)
target_exit_amp = 0.75
_calib_pts = np.asarray(calib_points, dtype=np.float32)
_calib_K = np.asarray(calibration_intrinsics, dtype=np.float32)
# Step 1: Calibrate R0 (A -> B, yaw=0)
r0_exit_scale = _find_first_no_projection_param(
lambda a: _count_visible_fg_projection_points(
points_local=_calib_pts,
intrinsics=_calib_K,
image_width=W_cal,
image_height=H_cal,
position_local=(float(a) * dir_AB).astype(np.float32),
yaw_deg=0.0,
),
hi=2.0,
n_steps=640,
visible_count_threshold=visible_threshold,
)
if r0_exit_scale is not None and r0_exit_scale > 1e-5:
scale_AB = float(r0_exit_scale) / target_exit_amp
else:
scale_AB = 1.0
pos_B = (scale_AB * dir_AB).astype(np.float32)
# Step 2: Compute yaw_B
center_pt = np.median(_calib_pts, axis=0).astype(np.float32)
yaw_B = _yaw_to_center(pos_B)
# Step 3: Calibrate R2 (B -> C, yaw=yaw_B)
r2_exit_scale = _find_first_no_projection_param(
lambda a: _count_visible_fg_projection_points(
points_local=_calib_pts,
intrinsics=_calib_K,
image_width=W_cal,
image_height=H_cal,
position_local=(pos_B + float(a) * base_d * dir_BC_unit).astype(np.float32),
yaw_deg=yaw_B,
),
hi=2.0,
n_steps=640,
visible_count_threshold=visible_threshold,
)
if r2_exit_scale is not None and r2_exit_scale > 1e-5:
scale_BC = float(r2_exit_scale) / target_exit_amp
else:
scale_BC = scale_AB
dist_BC = base_d * scale_BC
pos_C = (pos_B + dist_BC * dir_BC_unit).astype(np.float32)
# Step 4: Compute yaw_C
yaw_C = _yaw_to_center(pos_C)
if len(keys) != 4:
raise ValueError(
f"case2 motion primitive expects 4 rounds, got {len(keys)}"
)
frames: List[Dict] = []
frame_idx = 0
for ri, rk in enumerate(keys):
r = round_plan[rk]
if ri == 0:
pos_start = pos_A
pos_end = pos_B
yaw_start = 0.0
yaw_end = 0.0
elif ri == 1:
pos_start = pos_B
pos_end = pos_B
yaw_start = 0.0
yaw_end = yaw_B
elif ri == 2:
pos_start = pos_B
pos_end = pos_C
yaw_start = yaw_B
yaw_end = yaw_B
else:
pos_start = pos_C
pos_end = pos_C
yaw_start = yaw_B
yaw_end = yaw_C
for si in range(frames_per_round):
t = float(si) / max(1, frames_per_round - 1)
pos = (1.0 - t) * pos_start + t * pos_end
yaw = (1.0 - t) * yaw_start + t * yaw_end
local = _yaw_c2w_local(yaw, position=pos)
world = _local_to_world(local, first_c2w)
frames.append({
"frame_idx": int(frame_idx),
"round_idx": int(rk),
"interp_t": float(t),
"location_from": r["location_from"],
"location_to": r["location_to"],
"action": r["action"],
"event": r["event"],
"c2w": world.astype(float).tolist(),
})
frame_idx += 1
return frames
# --- Default: waypoint lerp + slerp ---
frames: List[Dict] = []
frame_idx = 0
for rk in keys:
r = round_plan[rk]
c0 = np.asarray(
location_pose_pool[r["location_from"]]["c2w"], dtype=np.float32,
)
c1 = np.asarray(
location_pose_pool[r["location_to"]]["c2w"], dtype=np.float32,
)
for s in range(frames_per_round):
t = float(s) / float(frames_per_round)
p = (1.0 - t) * c0[:3, 3] + t * c1[:3, 3]
R = _interp_rotation(c0[:3, :3], c1[:3, :3], t)
local = np.eye(4, dtype=np.float32)
local[:3, :3] = R
local[:3, 3] = p
world = _local_to_world(local, first_c2w)
frames.append({
"frame_idx": int(frame_idx),
"round_idx": int(rk),
"interp_t": float(t),
"location_from": r["location_from"],
"location_to": r["location_to"],
"action": r["action"],
"event": r["event"],
"c2w": world.astype(float).tolist(),
})
frame_idx += 1
last = round_plan[keys[-1]]
c_end = np.asarray(
location_pose_pool[last["location_to"]]["c2w"], dtype=np.float32,
)
world_end = _local_to_world(c_end, first_c2w)
frames.append({
"frame_idx": int(frame_idx),
"round_idx": int(keys[-1]),
"interp_t": 1.0,
"location_from": last["location_to"],
"location_to": last["location_to"],
"action": "terminal",
"event": last["event"],
"c2w": world_end.astype(float).tolist(),
})
return frames
# ---------------------------------------------------------------------------
# Iter input (text prompts per round)
# ---------------------------------------------------------------------------
def _build_iter_input(
case_type: str,
round_plan: Dict[str, Dict],
event_slots: Dict[str, Dict],
) -> Dict[str, Dict[str, str]]:
out: Dict[str, Dict[str, str]] = {}
keys = sorted(round_plan.keys(), key=lambda x: int(x))
for k in keys:
r = round_plan[k]
action = r["action"]
event_id = r["event"]
scene_text = "A consistent indoor scene with smooth camera motion."
fg_text = ""
if event_id and event_id in event_slots:
entity = event_slots[event_id]["entity"]
if action == "spawn":
fg_text = f"{entity} starts an event naturally at its fixed location."
elif action == "revisit":
fg_text = f"{entity} continues naturally at the same location."
else:
fg_text = f"{entity} remains in its local area."
out[str(k)] = {"scene_text": scene_text, "fg_text": fg_text}
return out
# ---------------------------------------------------------------------------
# Main plan generator
# ---------------------------------------------------------------------------
def _save_geometry_npz(
plan: Dict,
meta_path: str,
out_dir: Path,
) -> Optional[Path]:
"""Save geometry.npz compatible with infer_spatia.py."""
if not meta_path or not Path(meta_path).exists():
return None
data = np.load(meta_path)
for key in ("depth_proc", "intrinsics_proc", "processed_size"):
if key not in data:
print(f" [geometry.npz] Skipped: '{key}' not in {meta_path}")
return None
depth_proc = data["depth_proc"]
intrinsics_proc = data["intrinsics_proc"]
processed_size = data["processed_size"]
target_h = int(data["target_h"])
target_w = int(data["target_w"])
traj = plan["trajectory_frames"]
total_frames = len(traj)
poses_c2w = np.array([f["c2w"] for f in traj], dtype=np.float32)
from liveworld.geometry_utils import scale_intrinsics
depth_target = cv2.resize(
depth_proc, (target_w, target_h), interpolation=cv2.INTER_NEAREST,
)
intrinsics_target = scale_intrinsics(
intrinsics_proc,
(int(processed_size[0]), int(processed_size[1])),
(target_h, target_w),
)
save_dict = {
"depths": np.stack([depth_proc] * total_frames),
"poses_c2w": poses_c2w,
"intrinsics": np.stack([intrinsics_proc] * total_frames),
"processed_size": processed_size,
"original_size": np.array([target_h, target_w]),
"depths_target": depth_target[None],
"intrinsics_target": intrinsics_target[None],
"target_size": np.array([target_h, target_w]),
}
geom_path = out_dir / "geometry.npz"
np.savez_compressed(geom_path, **save_dict)
return geom_path
def generate_plan_for_combo(
combo: ComboDef,
args: argparse.Namespace,
image_rgb: np.ndarray,
scene_features: SceneFeatures,
det: ObjectDetection,
det_union_mask: np.ndarray,
scene_meta: Optional[Dict],
first_c2w: np.ndarray,
scene_scale: SceneScale,
) -> Dict:
"""Generate a single plan for one combo variant."""
R = scene_scale.nav_radius * combo.layout_scale
Re = scene_scale.event_radius * combo.layout_scale
event_points = {eid: [0.0, 0.0, 0.0] for eid in combo.event_ids}
nav_points = _circle_points_local(R, count=6)
if det_union_mask is None:
raise ValueError("det_union_mask is required (mask-only foreground calibration)")
calibration_points_local = _estimate_event_points_local(scene_meta, det_union_mask)
calibration_center_local = (
np.median(calibration_points_local, axis=0).astype(np.float32)
if calibration_points_local is not None and len(calibration_points_local) > 0
else None
)
calibration_intrinsics = (
np.asarray(scene_meta.get("intrinsics"), dtype=np.float32)
if scene_meta is not None and scene_meta.get("intrinsics") is not None
else None
)
calibration_image_width = (
int(scene_meta.get("target_w"))
if scene_meta is not None and scene_meta.get("target_w") is not None
else None
)
calibration_image_height = (
int(scene_meta.get("target_h"))
if scene_meta is not None and scene_meta.get("target_h") is not None
else None
)
event_points_used = {
eid: event_points[eid]
for eid in combo.event_ids
if eid in event_points
}
event_slots = _build_event_slots(combo, event_points_used, det.entities)
location_pool = _build_location_pool(nav_radius=R, event_slots=event_slots)
# Add motion-primitive-specific locations
if combo.motion_primitive.startswith("case1_"):
d = float(1.6 * R)
sign = -1.0 if combo.motion_primitive == "case1_left" else 1.0
location_pool["A"] = [0.0, 0.0, 0.0]
location_pool["B"] = [float(sign * d), 0.0, 0.0]
elif combo.motion_primitive.startswith("case2_"):
d = 1.6 * R
Z = d / np.sqrt(3.0)
location_pool["A"] = [0.0, 0.0, 0.0]
if combo.motion_primitive == "case2_right":
location_pool["B"] = [float(d), 0.0, float(-Z)]
else:
location_pool["B"] = [float(-d), 0.0, float(-Z)]
location_pool["C"] = [0.0, 0.0, float(-Z)]
location_pose_pool = _build_location_pose_pool(
location_pool=location_pool, event_slots=event_slots,
)
round_plan = _build_round_plan(
combo=combo,
location_pool=location_pool,
location_pose_pool=location_pose_pool,
event_slots=event_slots,
)
fpr = combo.frames_per_round if combo.frames_per_round is not None else args.frames_per_round
trajectory_frames = _interpolate_pose_sequence(
round_plan=round_plan,
location_pose_pool=location_pose_pool,
frames_per_round=fpr,
first_c2w=first_c2w,
motion_primitive=combo.motion_primitive,
nav_radius=R,
seed=args.seed,
calibration_points_local=calibration_points_local,
calibration_intrinsics=calibration_intrinsics,
calibration_image_width=calibration_image_width,
calibration_image_height=calibration_image_height,
exit_visible_ratio=float(getattr(args, "exit_visible_ratio", 0.0)),
)
iter_input = _build_iter_input(combo.case_type, round_plan, event_slots)
# Convert event slot positions local → world
event_slots_world = {}
for eid, info in event_slots.items():
p_local = np.array(info["position"] + [1.0], dtype=np.float32)
p_world = (first_c2w @ p_local)[:3]
event_slots_world[eid] = {
**info,
"position": [float(p_world[0]), float(p_world[1]), float(p_world[2])],
"position_local": info["position"],
}
# Convert location pool local → world
location_pool_world = {}
for loc, pos in location_pool.items():
p_local = np.array(pos + [1.0], dtype=np.float32)
p_world = (first_c2w @ p_local)[:3]
location_pool_world[loc] = [
float(p_world[0]), float(p_world[1]), float(p_world[2]),
]
sample_id = (
args.sample_id
or f"{Path(args.image_path).stem}_{combo.combo_id}_seed{args.seed}"
)
exit_visible_ratio = float(getattr(args, "exit_visible_ratio", 0.0))
exit_visible_threshold = _compute_exit_visible_threshold(
calibration_points_local,
exit_visible_ratio,
)
if exit_visible_ratio <= 0.0:
exit_criterion = "visible_fg_projection_count == 0"
else:
exit_criterion = (
f"visible_fg_projection_count <= {exit_visible_threshold} "
f"(ratio <= {exit_visible_ratio:.4f})"
)
output = {
"sample_id": sample_id,
"image_path": args.image_path,
"scene_meta_path": getattr(args, "scene_meta_path", ""),
"geometry_path": getattr(args, "geometry_path", ""),
"combo_id": combo.combo_id,
"case_type": combo.case_type,
"motion_primitive": combo.motion_primitive,
"num_rounds": combo.num_rounds,
"num_events": combo.num_events,
"first_frame_has_event": combo.first_frame_has_event,
"first_c2w": first_c2w.astype(float).tolist(),
"object_detection": asdict(det),
"scene_features": asdict(scene_features),
"scene_scale": asdict(scene_scale),
"distance_normalization": {
"mode": str(args.distance_mode),
"target_shift_ratio": float(args.target_shift_ratio),
"screen_depth_percentile": float(args.screen_depth_percentile),
"distance_blend_alpha": float(args.distance_blend_alpha),
},
"view_calibration": {
"enabled": bool(calibration_points_local is not None and calibration_intrinsics is not None),
"event_center_local": (
[float(x) for x in calibration_center_local.tolist()]
if calibration_center_local is not None else None
),
"calibration_points_source": "foreground_event_points",
"calibration_points_count": (
int(len(calibration_points_local))
if calibration_points_local is not None
else 0
),
"exit_visible_ratio": float(exit_visible_ratio),
"exit_visible_count_threshold": int(exit_visible_threshold),
"all_foreground_points_exit_required": bool(exit_visible_ratio <= 0.0),
"projection_exit_criterion": exit_criterion,
"image_width": int(calibration_image_width) if calibration_image_width is not None else None,
"image_height": int(calibration_image_height) if calibration_image_height is not None else None,
},
"event_slots": event_slots_world,
"location_pool": location_pool_world,
"round_target_sequence": combo.target_sequence,
"nav_points": {f"N{i}": p for i, p in enumerate(nav_points)},
"round_plan": round_plan,
"frames_per_round": int(fpr),
"fps": int(combo.fps),
"total_frames": int(len(trajectory_frames)),
"trajectory_frames": trajectory_frames,
"iter_input": iter_input,
"camera_control": {
"yaw_rate_limit_deg_per_frame": float(args.yaw_rate_limit_deg_per_frame),
"pitch_limit_deg": [-15.0, 15.0],
"alpha_event": float(args.alpha_event),
"alpha_non_event": float(args.alpha_non_event),
},
"quality_gate": {
"min_in_frame_ratio": float(args.min_in_frame_ratio),
"min_event_separation_deg": float(args.min_event_separation_deg),
},
}
out_root = Path(args.output_dir) / sample_id
out_root.mkdir(parents=True, exist_ok=True)
with (out_root / "plan.json").open("w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=2)
meta_path = getattr(args, "scene_meta_path", "")
geom_path = _save_geometry_npz(output, meta_path, out_root)
if geom_path is not None:
print(f" [event_bench] geometry.npz saved: {geom_path}")
return output
def _load_scene_detect_prompt(system_config_path: str) -> str:
"""Load scene_detect_prompt from system_config.yaml."""
with open(system_config_path, "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f)
return cfg["event"]["detection"]["scene_detect_prompt"]
def generate_all_combos(args: argparse.Namespace) -> List[Dict]:
"""Generate plans for all combos of the specified case_type."""
scene_detect_prompt = _load_scene_detect_prompt(args.system_config_path)
image_rgb = _load_image_rgb(args.image_path)
scene_features = extract_scene_features(image_rgb)
scene_meta = _load_scene_meta(getattr(args, "scene_meta_path", ""))
detect_image_path = _prepare_detection_image_for_scene(args.image_path, scene_meta)
det, det_union_mask = detect_event_object(
image_path=detect_image_path,
qwen_model_path=args.qwen_model_path,
sam3_model_path=args.sam3_model_path,
scene_detect_prompt=scene_detect_prompt,
)
first_c2w = (
scene_meta["c2w"] if scene_meta is not None
else np.eye(4, dtype=np.float32)
)
scene_scale = estimate_scene_scale(
det=det,
scene_features=scene_features,
image_path=args.image_path,
geometry_path=getattr(args, "geometry_path", ""),
case_type=args.case_type,
llm_motion_scaling=args.llm_motion_scaling,
qwen_model_path=args.qwen_model_path,
scene_meta=scene_meta,
distance_mode=args.distance_mode,
target_shift_ratio=args.target_shift_ratio,
screen_depth_percentile=args.screen_depth_percentile,
distance_blend_alpha=args.distance_blend_alpha,
)
combos = get_combos_for_case(
args.case_type,
all_variants=getattr(args, "all_variants", False),
)
plans = []
for combo in combos:
plan = generate_plan_for_combo(
combo=combo,
args=args,
image_rgb=image_rgb,
scene_features=scene_features,
det=det,
det_union_mask=det_union_mask,
scene_meta=scene_meta,
first_c2w=first_c2w,
scene_scale=scene_scale,
)
plans.append(plan)
print(f" [event_bench] {combo.combo_id}: {plan['sample_id']}")
return plans
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def build_argparser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Generate event-centric eval benchmark plans (case1 + case2)",
)
parser.add_argument("--image-path", required=True, help="First-frame image path")
parser.add_argument(
"--scene-meta-path", default="",
help="Scene meta.npz from build_scene_pointcloud_da3.py or Stream3R",
)
parser.add_argument("--geometry-path", default="", help="Optional geometry.npz path")
parser.add_argument(
"--case-type", required=True, choices=CASE_CHOICES,
help="Benchmark case type (all combos for that case are generated)",
)
parser.add_argument(
"--all-variants", action="store_true",
help="Include optional (non-core) variants",
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--sample-id", default="", help="Custom sample id (overrides auto naming)")
parser.add_argument("--output-dir", default="outputs/event_bench")
parser.add_argument("--qwen-model-path", default="/home/zhangzhilu/anaconda3/pretrained_models/Qwen3-VL-8B-Instruct")
parser.add_argument("--sam3-model-path", default="/home/zhangzhilu/anaconda3/pretrained_models/sam3/sam3.pt")
parser.add_argument(
"--system-config-path",
default="configs/event_centric_infer/system_config.yaml",
help="Path to system_config.yaml (for scene_detect_prompt).",
)
parser.add_argument("--llm-motion-scaling", action="store_true",
help="Use QwenVL to adjust motion scale")
parser.add_argument(
"--distance-mode", default="screen_uniform",
choices=["screen_uniform"],
help="Trajectory distance scaling mode (only screen_uniform supported).",
)
parser.add_argument("--target-shift-ratio", type=float, default=0.18)
parser.add_argument("--screen-depth-percentile", type=float, default=45.0)
parser.add_argument("--distance-blend-alpha", type=float, default=0.7)
parser.add_argument(
"--exit-visible-ratio", type=float, default=0.0,
help="Treat foreground as out-of-frame when visible ratio <= this value (0 = strict).",
)
parser.add_argument("--frames-per-round", type=int, default=33)
parser.add_argument("--yaw-rate-limit-deg-per-frame", type=float, default=4.0)
parser.add_argument("--alpha-event", type=float, default=0.8)
parser.add_argument("--alpha-non-event", type=float, default=0.2)
parser.add_argument("--min-in-frame-ratio", type=float, default=0.8)
parser.add_argument("--min-event-separation-deg", type=float, default=60.0)
return parser
def main() -> None:
parser = build_argparser()
args = parser.parse_args()
combos = get_combos_for_case(
args.case_type,
all_variants=getattr(args, "all_variants", False),
)
print(
f"[event_bench] Generating {len(combos)} combo(s) for {args.case_type}: "
f"{[c.combo_id for c in combos]}"
)
plans = generate_all_combos(args)
print(f"[event_bench] Done. Generated {len(plans)} plan(s) under {args.output_dir}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Generate event-centric benchmark plans (final version: case1 + case2 only).
case1: Pure left/right horizontal translation (90% fg pixel exit, back-and-forth).
Originally named traj_f.
case2: Two-segment translation + in-place lookback yaw (right/left variants).
Core coordinate idea: define camera trajectory as *relative* poses in
first-frame local coordinates, then transform to world via
``c2w_first @ local_pose``.
Local convention (OpenCV camera):
X → right, Y → down, Z → forward (into the scene).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
import yaml
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import cv2
import numpy as np
CASE_CHOICES = ("case1", "case2")
EVENT_IDS = ("A", "B", "C", "D", "E", "F")
_QWEN_VL_CACHE: Dict[str, Tuple[object, object, str]] = {}
_DETECTION_MODEL_CACHE: Dict[Tuple[str, str, str, bool], Tuple[object, object]] = {}
# ---------------------------------------------------------------------------
# Combo definition registry
# ---------------------------------------------------------------------------
class ComboDef:
combo_id: str
case_type: str # "case1" or "case2"
num_events: int # 1, 2, or 3
num_rounds: int # 2-6
first_frame_has_event: bool
actions: List[Dict[str, str]] # per-round {"action": ..., "event": ...}
target_sequence: List[str] # per-round target location ID
motion_primitive: str # "case1" | "case2_right" | "case2_left"
is_core: bool = True # core = generated by default
event_ids: List[str] = field(default_factory=list) # which event IDs are used
frames_per_round: Optional[int] = None # override CLI --frames-per-round
fps: int = 16 # video fps (metadata only)
layout_scale: float = 1.0 # scale factor for layout radius
class LayoutConfig:
"""Spatial layout configuration for events and camera positions."""
name: str # "triangle", "square", "line", etc.
event_positions: Dict[str, List[float]] # event_id -> [x, y, z] local
centroid: np.ndarray # shape (3,), layout centroid
camera_orientation: str # "outward" | "inward" | "forward"
interpolation: str # "lerp_slerp"
path_noise_std: float # 0.0 = no noise
def _make_combo(combo_id, case_type, num_events, num_rounds, first_frame_has_event,
actions, targets, motion_primitive="default", is_core=True,
event_ids=None):
if event_ids is None:
event_ids = ["A", "B", "C"][:num_events]
return ComboDef(
combo_id=combo_id, case_type=case_type, num_events=num_events,
num_rounds=num_rounds, first_frame_has_event=first_frame_has_event,
actions=actions, target_sequence=targets,
motion_primitive=motion_primitive, is_core=is_core,
event_ids=event_ids,
)
COMBO_REGISTRY: Dict[str, ComboDef] = {}
# ============================================================================
# Case 1: 纯左右平移,去回去回 (原 traj_f, 2 combos)
# R0: 向右/左平移,到90%像素出屏幕
# R1: 平移回原点
# R2: 重复R0
# R3: 重复R1
# ============================================================================
COMBO_REGISTRY["case1_right"] = _make_combo(
"case1_right", "case1", 1, 4, True,
[{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"},
{"action": "leave", "event": "A"},
{"action": "revisit", "event": "A"}],