137 lines
4.5 KiB
Python
137 lines
4.5 KiB
Python
|
|
"""CPU SAM window regressions with a strict predictor double (no GPU imports)."""
|
||
|
|
|
||
|
|
import sys
|
||
|
|
from contextlib import nullcontext
|
||
|
|
from pathlib import Path
|
||
|
|
from types import SimpleNamespace
|
||
|
|
|
||
|
|
import numpy as np
|
||
|
|
import pytest
|
||
|
|
from PIL import Image
|
||
|
|
|
||
|
|
sys.path.insert(0, str(Path(__file__).parents[1]))
|
||
|
|
|
||
|
|
|
||
|
|
class Logits:
|
||
|
|
def __init__(self, values):
|
||
|
|
self.values = values
|
||
|
|
|
||
|
|
def __getitem__(self, key):
|
||
|
|
return Logits(self.values[key])
|
||
|
|
|
||
|
|
def float(self):
|
||
|
|
return self
|
||
|
|
|
||
|
|
def cpu(self):
|
||
|
|
return self
|
||
|
|
|
||
|
|
def numpy(self):
|
||
|
|
return self.values.copy()
|
||
|
|
|
||
|
|
|
||
|
|
class Predictor:
|
||
|
|
def __init__(self):
|
||
|
|
self.states = []
|
||
|
|
|
||
|
|
def init_state(self, path, **kwargs):
|
||
|
|
state = {
|
||
|
|
"start": int(Path(path).name.split("-")[1]),
|
||
|
|
"frames": len(list(Path(path).glob("*.jpg"))),
|
||
|
|
"prompts": [],
|
||
|
|
}
|
||
|
|
self.states.append(state)
|
||
|
|
return state
|
||
|
|
|
||
|
|
def add_new_mask(self, state, frame_idx, obj_id, mask):
|
||
|
|
state["prompts"].append(("mask", frame_idx, obj_id))
|
||
|
|
|
||
|
|
def add_new_points_or_box(self, state, frame_idx, obj_id, box):
|
||
|
|
state["prompts"].append(("box", frame_idx, obj_id))
|
||
|
|
|
||
|
|
def propagate_in_video(self, state):
|
||
|
|
if not state["prompts"]:
|
||
|
|
raise RuntimeError("No points are provided; please add points first")
|
||
|
|
ids = sorted({prompt[2] for prompt in state["prompts"]})
|
||
|
|
scores = np.full((len(ids), 1, 8, 16), -10, dtype="float32")
|
||
|
|
for position, identifier in enumerate(ids):
|
||
|
|
scores[position, 0, :, 8 * (identifier - 1) : 8 * identifier] = 10
|
||
|
|
for index in range(min(p[1] for p in state["prompts"]), state["frames"]):
|
||
|
|
yield index, ids, Logits(scores)
|
||
|
|
|
||
|
|
def reset_state(self, state):
|
||
|
|
state["reset"] = True
|
||
|
|
|
||
|
|
|
||
|
|
def run_windows(tmp_path, monkeypatch, tracks):
|
||
|
|
from llm_services.video_edit.preprocess import segment_people
|
||
|
|
|
||
|
|
monkeypatch.setitem(
|
||
|
|
sys.modules,
|
||
|
|
"torch",
|
||
|
|
SimpleNamespace(
|
||
|
|
inference_mode=nullcontext,
|
||
|
|
autocast=lambda *a, **k: nullcontext(),
|
||
|
|
bfloat16="bf16",
|
||
|
|
),
|
||
|
|
)
|
||
|
|
private = tmp_path / "private"
|
||
|
|
private.mkdir()
|
||
|
|
frames = private / "frames"
|
||
|
|
frames.mkdir()
|
||
|
|
for index in range(len(tracks)):
|
||
|
|
Image.new("RGB", (16, 8), (13, 27, 45)).save(frames / f"{index:06d}.png")
|
||
|
|
people = {}
|
||
|
|
for index, track in enumerate(tracks):
|
||
|
|
for person in track:
|
||
|
|
people.setdefault(person, {"first_frame": index})
|
||
|
|
for person in people:
|
||
|
|
(private / person / "mask").mkdir(parents=True)
|
||
|
|
original = (frames / "000000.png").read_bytes()
|
||
|
|
predictor = Predictor()
|
||
|
|
segment_people(predictor, frames, private, {"frames": len(tracks)}, tracks, people)
|
||
|
|
assert (frames / "000000.png").read_bytes() == original
|
||
|
|
assert not list(private.glob("sam-*"))
|
||
|
|
return predictor, private
|
||
|
|
|
||
|
|
|
||
|
|
ONE = {"person_0001": [0, 0, 8, 8]}
|
||
|
|
TWO = {**ONE, "person_0002": [8, 0, 16, 8]}
|
||
|
|
|
||
|
|
|
||
|
|
def test_empty_opening_window_skips_sam(tmp_path, monkeypatch):
|
||
|
|
predictor, private = run_windows(tmp_path, monkeypatch, [{}] * 77 + [ONE] * 3)
|
||
|
|
assert [s["start"] for s in predictor.states] == [77]
|
||
|
|
assert predictor.states[0]["prompts"] == [("box", 0, 1)]
|
||
|
|
assert not (private / "person_0001" / "mask" / "000000.png").exists()
|
||
|
|
assert (private / "person_0001" / "mask" / "000077.png").exists()
|
||
|
|
|
||
|
|
|
||
|
|
def test_empty_tail_and_middle_windows_do_not_reuse_old_masks(tmp_path, monkeypatch):
|
||
|
|
predictor, _ = run_windows(
|
||
|
|
tmp_path, monkeypatch, [ONE] * 77 + [{}] * 77 + [ONE] * 77 + [{}] * 77
|
||
|
|
)
|
||
|
|
assert [s["start"] for s in predictor.states] == [0, 154]
|
||
|
|
assert all(s["prompts"] == [("box", 0, 1)] for s in predictor.states)
|
||
|
|
|
||
|
|
|
||
|
|
def test_short_gap_at_boundary_restarts_with_current_box(tmp_path, monkeypatch):
|
||
|
|
predictor, _ = run_windows(tmp_path, monkeypatch, [ONE] * 75 + [{}] * 5 + [ONE] * 5)
|
||
|
|
assert predictor.states[1]["prompts"] == [("box", 3, 1)]
|
||
|
|
|
||
|
|
|
||
|
|
def test_adjacent_multi_actor_windows_keep_current_masks(tmp_path, monkeypatch):
|
||
|
|
predictor, private = run_windows(tmp_path, monkeypatch, [TWO] * 80)
|
||
|
|
assert predictor.states[1]["prompts"] == [("mask", 0, 1), ("mask", 0, 2)]
|
||
|
|
assert all(s.get("reset") for s in predictor.states)
|
||
|
|
assert np.asarray(Image.open(private / "person_0001" / "mask" / "000079.png"))[
|
||
|
|
:, :8
|
||
|
|
].all()
|
||
|
|
assert not np.asarray(Image.open(private / "person_0001" / "mask" / "000079.png"))[
|
||
|
|
:, 8:
|
||
|
|
].any()
|
||
|
|
|
||
|
|
|
||
|
|
def test_global_no_people_is_explicit_failure(tmp_path, monkeypatch):
|
||
|
|
with pytest.raises(ValueError, match="No people"):
|
||
|
|
run_windows(tmp_path, monkeypatch, [{}] * 80)
|