feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
This commit is contained in:
@@ -171,7 +171,29 @@ def cluster_by_trace(
|
||||
return trace_embeddings, traces
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
def build_cooccurrence_constraints(frames_data: list) -> set:
|
||||
"""
|
||||
Build must-not-link constraints: traces appearing in same frame must be different persons.
|
||||
Returns set of (trace_id_a, trace_id_b) pairs.
|
||||
"""
|
||||
constraints = set()
|
||||
for frame in frames_data:
|
||||
trace_ids = set()
|
||||
for face in frame.get('faces', []):
|
||||
tid = face.get('trace_id')
|
||||
if tid is not None and tid >= 0:
|
||||
trace_ids.add(tid)
|
||||
# All traces in same frame must be different persons
|
||||
trace_list = list(trace_ids)
|
||||
for i in range(len(trace_list)):
|
||||
for j in range(i+1, len(trace_list)):
|
||||
constraints.add((min(trace_list[i], trace_list[j]),
|
||||
max(trace_list[i], trace_list[j])))
|
||||
return constraints
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15,
|
||||
cooccurrence_constraints: set = None, frames_data: list = None) -> tuple:
|
||||
"""
|
||||
Single-stage AgglomerativeClustering on trace means.
|
||||
No Stage 2 merge (the problematic logic has been removed).
|
||||
@@ -210,13 +232,67 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) ->
|
||||
trace_similarities = {}
|
||||
for i, trace_id in enumerate(trace_ids):
|
||||
trace_to_person[trace_id] = labels[i]
|
||||
# For agglomerative, similarity = 1 - distance to cluster (approximate)
|
||||
trace_similarities[trace_id] = 1.0 # placeholder; exact requires pairwise
|
||||
trace_similarities[trace_id] = 1.0
|
||||
|
||||
# Post-process: split clusters that violate co-occurrence constraints
|
||||
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
|
||||
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
|
||||
next_person_id = max(trace_to_person.values()) + 1
|
||||
|
||||
for tid_a, tid_b in cooccurrence_constraints:
|
||||
if trace_to_person.get(tid_a) == trace_to_person.get(tid_b):
|
||||
# Same cluster but shouldn't be - split the one with fewer faces
|
||||
count_a = trace_embeddings.get(tid_a, {}).get('face_count', 0)
|
||||
count_b = trace_embeddings.get(tid_b, {}).get('face_count', 0)
|
||||
if count_a <= count_b:
|
||||
trace_to_person[tid_a] = next_person_id
|
||||
print(f" Split trace {tid_a} from {tid_b} (faces: {count_a} vs {count_b})")
|
||||
else:
|
||||
trace_to_person[tid_b] = next_person_id
|
||||
print(f" Split trace {tid_b} from {tid_a} (faces: {count_a} vs {count_b})")
|
||||
next_person_id += 1
|
||||
|
||||
# Merge clusters that are actually the same person (high embedding similarity)
|
||||
print(f"[CLUSTER] Merging similar persons (threshold={threshold*0.3:.2f})...")
|
||||
merge_threshold = threshold * 0.3 # More conservative for merging
|
||||
person_embeddings = {}
|
||||
for tid, pid in trace_to_person.items():
|
||||
if tid in trace_embeddings:
|
||||
if pid not in person_embeddings:
|
||||
person_embeddings[pid] = []
|
||||
person_embeddings[pid].append(trace_embeddings[tid]['embedding'])
|
||||
|
||||
# Compute person mean embeddings
|
||||
person_means = {}
|
||||
for pid, embs in person_embeddings.items():
|
||||
person_means[pid] = np.mean(embs, axis=0)
|
||||
|
||||
# Find and merge similar persons
|
||||
pids = list(person_means.keys())
|
||||
for i in range(len(pids)):
|
||||
for j in range(i+1, len(pids)):
|
||||
pid_i, pid_j = pids[i], pids[j]
|
||||
emb_i = person_means[pid_i]
|
||||
emb_j = person_means[pid_j]
|
||||
sim = np.dot(emb_i, emb_j) / (np.linalg.norm(emb_i) * np.linalg.norm(emb_j))
|
||||
dist = 1 - sim
|
||||
if dist < merge_threshold:
|
||||
# Merge pid_j into pid_i
|
||||
for tid in trace_to_person:
|
||||
if trace_to_person[tid] == pid_j:
|
||||
trace_to_person[tid] = pid_i
|
||||
print(f" Merged Person_{pid_j} into Person_{pid_i} (dist={dist:.3f})")
|
||||
|
||||
# Reindex person IDs
|
||||
unique_pids = sorted(set(trace_to_person.values()))
|
||||
pid_map = {old: new for new, old in enumerate(unique_pids)}
|
||||
trace_to_person = {tid: pid_map[pid] for tid, pid in trace_to_person.items()}
|
||||
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15,
|
||||
cooccurrence_constraints: set = None) -> tuple:
|
||||
"""
|
||||
Seed-leader clustering with incremental mean centroids.
|
||||
Algorithm:
|
||||
@@ -302,6 +378,39 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tupl
|
||||
trace_to_person[tid] = person_label
|
||||
|
||||
print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons")
|
||||
|
||||
# Apply co-occurrence constraints: split traces that appear in same frame
|
||||
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
|
||||
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
|
||||
|
||||
# Build trace_id -> person mapping for fast lookup
|
||||
for tid_a, tid_b in cooccurrence_constraints:
|
||||
person_a = trace_to_person.get(tid_a)
|
||||
person_b = trace_to_person.get(tid_b)
|
||||
if person_a is not None and person_b is not None and person_a == person_b:
|
||||
# Same person but shouldn't be - split tid_b to new person
|
||||
new_person_label = len(persons)
|
||||
trace_to_person[tid_b] = new_person_label
|
||||
# Move trace from old person to new person
|
||||
old_person = persons[person_a]
|
||||
if tid_b in old_person["member_trace_ids"]:
|
||||
old_person["member_trace_ids"].remove(tid_b)
|
||||
# Create new person with just this trace
|
||||
if tid_b in trace_embeddings:
|
||||
persons.append({
|
||||
"centroid": trace_embeddings[tid_b]['embedding'].copy(),
|
||||
"member_trace_ids": [tid_b]
|
||||
})
|
||||
print(f" Split trace {tid_b} from Person_{person_a} (co-occurs with trace {tid_a})")
|
||||
|
||||
# Rebuild trace_to_person after splits
|
||||
trace_to_person = {}
|
||||
for person_label, person in enumerate(persons):
|
||||
for tid in person["member_trace_ids"]:
|
||||
trace_to_person[tid] = person_label
|
||||
|
||||
print(f"[CLUSTER] After constraints: {len(persons)} unique persons")
|
||||
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
@@ -466,13 +575,40 @@ def main():
|
||||
# Select clustering method
|
||||
threshold = args.threshold
|
||||
method = args.method
|
||||
|
||||
# Load face_traced.json to build co-occurrence constraints AND for later use
|
||||
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
|
||||
cooccurrence_constraints = set()
|
||||
traced_frames_dict = {} # Will be used later for person_id assignment
|
||||
if os.path.exists(traced_path):
|
||||
try:
|
||||
with open(traced_path) as f:
|
||||
traced_data = json.load(f)
|
||||
frames_raw = traced_data.get('frames', [])
|
||||
|
||||
# Build co-occurrence constraints
|
||||
cooccurrence_constraints = build_cooccurrence_constraints(frames_raw)
|
||||
print(f"[CONSTRAINT] Built {len(cooccurrence_constraints)} co-occurrence constraints from face_traced.json")
|
||||
|
||||
# Also build traced_frames_dict for later use
|
||||
if isinstance(frames_raw, list):
|
||||
for frame_obj in frames_raw:
|
||||
frame_num = frame_obj.get("frame")
|
||||
if frame_num is not None:
|
||||
traced_frames_dict[str(frame_num)] = frame_obj
|
||||
elif isinstance(frames_raw, dict):
|
||||
traced_frames_dict = frames_raw
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
if method == "leader":
|
||||
trace_to_person, trace_similarities = seed_leader_cluster(
|
||||
trace_embeddings, threshold=threshold
|
||||
)
|
||||
else:
|
||||
trace_to_person, trace_similarities = single_stage_clustering(
|
||||
trace_embeddings, threshold=threshold
|
||||
trace_embeddings, threshold=threshold,
|
||||
cooccurrence_constraints=cooccurrence_constraints
|
||||
)
|
||||
if not trace_to_person:
|
||||
print("Clustering produced no results.")
|
||||
@@ -484,35 +620,12 @@ def main():
|
||||
print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)")
|
||||
publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons")
|
||||
|
||||
# Load face_traced.json to get trace_id for each face
|
||||
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
|
||||
traced_frames = {}
|
||||
if os.path.exists(traced_path):
|
||||
try:
|
||||
with open(traced_path) as f:
|
||||
traced_data = json.load(f)
|
||||
frames_raw = traced_data.get("frames", {})
|
||||
# Handle both dict and list formats
|
||||
if isinstance(frames_raw, list):
|
||||
# Convert list to dict for backward compatibility
|
||||
for frame_obj in frames_raw:
|
||||
frame_num = frame_obj.get("frame")
|
||||
if frame_num is not None:
|
||||
traced_frames[str(frame_num)] = frame_obj
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)")
|
||||
elif isinstance(frames_raw, dict):
|
||||
traced_frames = frames_raw
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)")
|
||||
else:
|
||||
print(f" Warning: Unexpected frames format: {type(frames_raw)}")
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
# Use traced_frames_dict loaded earlier for person_id assignment
|
||||
matched_count = 0
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
frame_num = frame_obj.get("frame", frame_idx)
|
||||
# Get traced faces for this frame
|
||||
traced_frame = traced_frames.get(str(frame_num), {})
|
||||
traced_frame = traced_frames_dict.get(str(frame_num), {})
|
||||
traced_faces = traced_frame.get("faces", [])
|
||||
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
|
||||
Reference in New Issue
Block a user