feat: face fix deployment + trace_* regeneration + executor stderr filter fix
- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64 - trace_* directories regenerated for KOBA (37 traces, start_frame 5307) - executor.rs: stderr filter now logs all non-empty stderr (was discarding) - VAD not skippable in ASRX (main_fixed.py Step 2 always runs) - Step 2.5 sentence boundary refinement added - Cluster agent async endpoints + similarity transparency - Keyword search: relationship text extraction, priority ordering - Face fix handoff doc for Studio team
This commit is contained in:
@@ -41,6 +41,7 @@ ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json")
|
||||
DB_URL = os.getenv("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry")
|
||||
|
||||
CLUSTER_THRESHOLD = 0.35
|
||||
CLUSTER_METHOD = "leader"
|
||||
|
||||
|
||||
def write_empty_output(status: str, file_uuid: str, output_path: str):
|
||||
@@ -159,29 +160,31 @@ def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_thre
|
||||
return trace_embeddings, traces
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict) -> dict:
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.35) -> tuple:
|
||||
"""
|
||||
Single-stage AgglomerativeClustering on trace means.
|
||||
No Stage 2 merge (the problematic logic has been removed).
|
||||
|
||||
Returns: (trace_to_person, trace_similarities)
|
||||
"""
|
||||
if not trace_embeddings:
|
||||
return {}
|
||||
return {}, {}
|
||||
|
||||
trace_ids = list(trace_embeddings.keys())
|
||||
n_traces = len(trace_ids)
|
||||
|
||||
if n_traces == 0:
|
||||
return {}
|
||||
return {}, {}
|
||||
|
||||
if n_traces == 1:
|
||||
return {trace_ids[0]: 0}
|
||||
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
|
||||
|
||||
embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids])
|
||||
|
||||
print(f"[CLUSTER] Clustering {n_traces} traces (threshold={CLUSTER_THRESHOLD})...")
|
||||
print(f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}...")
|
||||
clustering = AgglomerativeClustering(
|
||||
n_clusters=None,
|
||||
distance_threshold=CLUSTER_THRESHOLD,
|
||||
distance_threshold=threshold,
|
||||
metric="cosine",
|
||||
linkage="average"
|
||||
)
|
||||
@@ -191,10 +194,97 @@ def single_stage_clustering(trace_embeddings: dict) -> dict:
|
||||
print(f"[CLUSTER] Detected {len(unique_labels)} unique persons")
|
||||
|
||||
trace_to_person = {}
|
||||
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
|
||||
|
||||
return trace_to_person
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tuple:
|
||||
"""
|
||||
Seed-leader clustering with incremental mean centroids.
|
||||
Algorithm:
|
||||
1. Iterate traces in stable order (by trace_id).
|
||||
2. For each trace, compare its centroid to each existing person's mean centroid.
|
||||
3. If max cosine similarity >= (1 - threshold) → assign to that person, update mean.
|
||||
4. Else → create new person seeded by this trace.
|
||||
|
||||
threshold: cosine distance threshold (default 0.35 = similarity >= 0.65)
|
||||
|
||||
Returns: (trace_to_person: dict, trace_similarities: dict)
|
||||
trace_to_person: {trace_id: person_label}
|
||||
trace_similarities: {trace_id: similarity_to_centroid}
|
||||
"""
|
||||
if not trace_embeddings:
|
||||
return {}, {}
|
||||
|
||||
# Sort by trace_id for deterministic order
|
||||
trace_ids = sorted(trace_embeddings.keys())
|
||||
n_traces = len(trace_ids)
|
||||
|
||||
if n_traces == 0:
|
||||
return {}, {}
|
||||
|
||||
if n_traces == 1:
|
||||
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
|
||||
|
||||
sim_threshold = 1.0 - threshold # cosine similarity threshold
|
||||
persons = [] # list of {centroid: np.array, member_trace_ids: []}
|
||||
trace_similarities = {}
|
||||
|
||||
print(f"[CLUSTER] Seed-leader: {n_traces} traces, similarity_threshold={sim_threshold:.3f} (distance={threshold})...")
|
||||
|
||||
for trace_id in trace_ids:
|
||||
centroid = trace_embeddings[trace_id]["embedding"]
|
||||
|
||||
if not persons:
|
||||
# First trace → seed first person
|
||||
persons.append({
|
||||
"centroid": centroid.copy(),
|
||||
"member_trace_ids": [trace_id]
|
||||
})
|
||||
trace_similarities[trace_id] = 1.0 # first trace is the centroid
|
||||
continue
|
||||
|
||||
# Find best matching person by cosine similarity to current mean centroid
|
||||
best_sim = -1.0
|
||||
best_person_idx = -1
|
||||
for idx, person in enumerate(persons):
|
||||
p_centroid = person["centroid"]
|
||||
norm1 = np.linalg.norm(centroid)
|
||||
norm2 = np.linalg.norm(p_centroid)
|
||||
if norm1 > 0 and norm2 > 0:
|
||||
sim = np.dot(centroid, p_centroid) / (norm1 * norm2)
|
||||
if sim > best_sim:
|
||||
best_sim = sim
|
||||
best_person_idx = idx
|
||||
|
||||
if best_sim >= sim_threshold:
|
||||
# Assign to this person, update mean centroid (incremental)
|
||||
persons[best_person_idx]["member_trace_ids"].append(trace_id)
|
||||
trace_similarities[trace_id] = best_sim
|
||||
# Recompute mean from all member trace centroids
|
||||
member_embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in persons[best_person_idx]["member_trace_ids"]])
|
||||
persons[best_person_idx]["centroid"] = np.mean(member_embeddings, axis=0)
|
||||
else:
|
||||
# New person
|
||||
persons.append({
|
||||
"centroid": centroid.copy(),
|
||||
"member_trace_ids": [trace_id]
|
||||
})
|
||||
trace_similarities[trace_id] = 1.0 # seed trace is its own centroid
|
||||
|
||||
# Build trace_to_person mapping
|
||||
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] Seed-leader detected {len(persons)} unique persons")
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def auto_bind_speakers():
|
||||
@@ -285,6 +375,10 @@ def main():
|
||||
parser.add_argument("--uuid", help="Video UUID (optional, overrides env var)")
|
||||
parser.add_argument("--force", action="store_true", help="Overwrite existing output")
|
||||
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--method", choices=["agglomerative", "leader"], default="leader",
|
||||
help="Clustering method: agglomerative (sklearn) or seed-leader (default: leader)")
|
||||
parser.add_argument("--threshold", type=float, default=CLUSTER_THRESHOLD,
|
||||
help=f"Cosine distance threshold for clustering (default: {CLUSTER_THRESHOLD})")
|
||||
args = parser.parse_args()
|
||||
|
||||
OUTPUT_JSON_PATH = args.output_path
|
||||
@@ -329,9 +423,22 @@ def main():
|
||||
|
||||
publisher.progress("face_cluster", 10, 100, f"Loaded {len(points)} Qdrant points")
|
||||
|
||||
# Count unique traces before filtering
|
||||
unique_trace_ids = set()
|
||||
for p in points:
|
||||
tid = p.get("payload", {}).get("trace_id")
|
||||
if tid is not None and tid >= 0:
|
||||
unique_trace_ids.add(tid)
|
||||
|
||||
# Adaptive threshold: only filter noise when trace count is large
|
||||
# For small files (<=1000 traces), keep all traces for maximum recall
|
||||
# For large files (>1000 traces), filter out single-face noise
|
||||
min_faces = 4 if len(unique_trace_ids) > 1000 else 1
|
||||
print(f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces} (adaptive)")
|
||||
|
||||
trace_embeddings, traces = cluster_by_trace(
|
||||
points,
|
||||
min_faces_per_trace=1,
|
||||
min_faces_per_trace=min_faces,
|
||||
confidence_threshold=0.5
|
||||
)
|
||||
|
||||
@@ -343,7 +450,13 @@ def main():
|
||||
|
||||
publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces")
|
||||
|
||||
trace_to_person = single_stage_clustering(trace_embeddings)
|
||||
# Select clustering method
|
||||
threshold = args.threshold
|
||||
method = args.method
|
||||
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)
|
||||
if not trace_to_person:
|
||||
print("Clustering produced no results.")
|
||||
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
|
||||
@@ -354,40 +467,35 @@ 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")
|
||||
|
||||
qdrant_by_frame_trace = {}
|
||||
for point in points:
|
||||
payload = point.get("payload", {})
|
||||
frame = payload.get("frame")
|
||||
trace_id = payload.get("trace_id", -1)
|
||||
bbox = payload.get("bbox", {})
|
||||
if frame is not None and trace_id >= 0:
|
||||
cx = bbox.get("x", 0) + bbox.get("width", 0) // 2
|
||||
cy = bbox.get("y", 0) + bbox.get("height", 0) // 2
|
||||
key = (frame, cx, cy)
|
||||
qdrant_by_frame_trace[key] = trace_id
|
||||
# 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)
|
||||
traced_frames = traced_data.get("frames", {})
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames")
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
matched_count = 0
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
frame_num = frame_obj.get("frame", frame_idx)
|
||||
for face in frame_obj.get("faces", []):
|
||||
x = face.get("x", 0)
|
||||
y = face.get("y", 0)
|
||||
w = face.get("width", 0)
|
||||
h = face.get("height", 0)
|
||||
cx = x + w // 2
|
||||
cy = y + h // 2
|
||||
key = (frame_num, cx, cy)
|
||||
# Get traced faces for this frame
|
||||
traced_frame = traced_frames.get(str(frame_num), {})
|
||||
traced_faces = traced_frame.get("faces", [])
|
||||
|
||||
trace_id = qdrant_by_frame_trace.get(key)
|
||||
if trace_id is None:
|
||||
for (qf, qx, qy), tid in qdrant_by_frame_trace.items():
|
||||
if qf == frame_num and abs(qx - cx) < 50 and abs(qy - cy) < 50:
|
||||
trace_id = tid
|
||||
break
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
# Get trace_id from face_traced.json
|
||||
trace_id = None
|
||||
if face_idx < len(traced_faces):
|
||||
trace_id = traced_faces[face_idx].get("trace_id")
|
||||
|
||||
if trace_id is not None and trace_id in trace_to_person:
|
||||
person_label = trace_to_person[trace_id]
|
||||
face["person_id"] = f"Person_{person_label}"
|
||||
face["trace_id"] = trace_id
|
||||
matched_count += 1
|
||||
|
||||
print(f" Assigned person_id to {matched_count} faces")
|
||||
@@ -422,26 +530,52 @@ def main():
|
||||
}
|
||||
}
|
||||
|
||||
# Build per-person similarity stats from trace_similarities
|
||||
person_sims = defaultdict(list)
|
||||
sim_threshold_value = 1.0 - threshold # similarity threshold
|
||||
for tid, person_label in trace_to_person.items():
|
||||
sim = trace_similarities.get(tid, 0.0)
|
||||
person_sims[person_label].append(sim)
|
||||
|
||||
person_labels_sorted = sorted(person_face_count.keys(), key=lambda p: -person_face_count[p])
|
||||
clusters = []
|
||||
for person_id in person_labels_sorted:
|
||||
# Extract person number from "Person_N" to get the integer label
|
||||
person_label = None
|
||||
try:
|
||||
person_label = int(person_id.split("_")[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
sims = person_sims.get(person_label, []) if person_label is not None else []
|
||||
similarity_info = None
|
||||
if sims:
|
||||
similarity_info = {
|
||||
"min": round(float(min(sims)), 4),
|
||||
"avg": round(float(sum(sims) / len(sims)), 4),
|
||||
"threshold": round(sim_threshold_value, 4),
|
||||
}
|
||||
|
||||
cluster_entry = {
|
||||
"cluster_id": person_id,
|
||||
"face_count": person_face_count[person_id],
|
||||
"representative_face": person_best_face.get(person_id)
|
||||
"representative_face": person_best_face.get(person_id),
|
||||
}
|
||||
if similarity_info:
|
||||
cluster_entry["similarity"] = similarity_info
|
||||
clusters.append(cluster_entry)
|
||||
|
||||
output_frames = []
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
timestamp = frame_obj.get("timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0)
|
||||
output_faces = []
|
||||
for face in frame_obj.get("faces", []):
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
person_id = face.get("person_id")
|
||||
if person_id:
|
||||
output_faces.append({
|
||||
"face_id": f"face_{frame_idx}_{frame_idx}",
|
||||
"face_id": f"face_{frame_idx}_{face_idx}",
|
||||
"cluster_id": person_id,
|
||||
"trace_id": face.get("trace_id"),
|
||||
"confidence": face.get("confidence", 0.9),
|
||||
})
|
||||
if output_faces:
|
||||
|
||||
Reference in New Issue
Block a user