fix: face clustering speaker mapping + representative face_id

- auto_bind_speakers: remove dead DB writes to nonexistent talents table,
  output speaker_person_mapping metadata into face_cluster.json instead
- fix representative_face.face_id to use face_idx (was frame_idx twice,
  causing duplicate face_ids for multi-face frames)
- fix asrx segment field names (start_time/end_time) and pass correct
  asrx path (ASRX_JSON_PATH was stale after UUID reassignment)
This commit is contained in:
Accusys
2026-08-12 05:04:48 +08:00
parent 59ca6cdf83
commit 258f8c4e96
+131 -106
View File
@@ -27,7 +27,6 @@ import json
import numpy as np
import os
import sys
import psycopg2
from collections import defaultdict
from sklearn.cluster import AgglomerativeClustering
@@ -38,7 +37,6 @@ UUID = os.getenv("UUID", "quick_preview")
OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output")
OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json")
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"
@@ -49,7 +47,7 @@ def write_empty_output(status: str, file_uuid: str, output_path: str):
"status": status,
"file_uuid": file_uuid,
"clusters": [],
"frames": []
"frames": [],
}
with open(output_path, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
@@ -61,6 +59,7 @@ def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
publisher.progress("face_cluster", 0, 100, "Loading embeddings from Qdrant")
try:
import requests
qdrant_url = os.environ.get("QDRANT_URL", "http://localhost:6333")
qdrant_api_key = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
headers = {}
@@ -74,11 +73,7 @@ def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
"limit": 10000,
"with_payload": True,
"with_vector": True,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": uuid}}
]
}
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
}
if offset:
body["offset"] = offset
@@ -87,7 +82,7 @@ def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
f"{qdrant_url}/collections/_faces/points/scroll",
json=body,
headers=headers,
timeout=60
timeout=60,
)
if resp.status_code != 200:
print(f"Qdrant scroll error: {resp.status_code}")
@@ -108,7 +103,9 @@ def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
return []
def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_threshold: float = 0.5) -> tuple:
def cluster_by_trace(
points: list, min_faces_per_trace: int = 1, confidence_threshold: float = 0.5
) -> tuple:
"""
Cluster faces by trace_id:
1. Filter low-confidence faces
@@ -116,10 +113,13 @@ def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_thre
3. Compute weighted average embedding per trace
"""
high_conf_points = [
p for p in points
p
for p in points
if p.get("payload", {}).get("confidence", 0) >= confidence_threshold
]
print(f"[FILTER] {len(high_conf_points)}/{len(points)} faces pass confidence >= {confidence_threshold}")
print(
f"[FILTER] {len(high_conf_points)}/{len(points)} faces pass confidence >= {confidence_threshold}"
)
traces = defaultdict(list)
for point in high_conf_points:
@@ -153,7 +153,7 @@ def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_thre
"face_count": len(trace_points),
"avg_confidence": float(np.mean(weights)),
"frames": [p.get("payload", {}).get("frame") for p in trace_points],
"points": trace_points
"points": trace_points,
}
print(f"[TRACE] {len(trace_embeddings)} traces with >= {min_faces_per_trace} faces")
@@ -164,7 +164,7 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.35) ->
"""
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:
@@ -181,12 +181,14 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.35) ->
embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids])
print(f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}...")
print(
f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}..."
)
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=threshold,
metric="cosine",
linkage="average"
linkage="average",
)
labels = clustering.fit_predict(embeddings)
@@ -211,9 +213,9 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tupl
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}
@@ -235,17 +237,18 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tupl
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})...")
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]
})
persons.append(
{"centroid": centroid.copy(), "member_trace_ids": [trace_id]}
)
trace_similarities[trace_id] = 1.0 # first trace is the centroid
continue
@@ -267,14 +270,18 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tupl
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"]])
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]
})
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
@@ -287,20 +294,28 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tupl
return trace_to_person, trace_similarities
def auto_bind_speakers():
if not os.path.exists(OUTPUT_JSON_PATH) or not os.path.exists(ASRX_JSON_PATH):
def auto_bind_speakers(output_frames: list, asrx_path: str = ASRX_JSON_PATH) -> dict:
"""
Compute speaker -> Person_N mapping by vote.
Each ASRX segment is matched against face timestamps; the most frequent
person within the segment's time span gets one vote for that speaker.
Returns {"SPEAKER_0": "Person_37", ...}. Pure computation, no DB writes.
"""
if not os.path.exists(asrx_path):
print("Missing data for speaker binding.")
return
return {}
with open(OUTPUT_JSON_PATH) as f:
face_clustered = json.load(f)
with open(ASRX_JSON_PATH) as f:
asrx_data = json.load(f)
try:
with open(asrx_path) as f:
asrx_data = json.load(f)
except Exception as e:
print(f" Failed to load ASRX: {e}")
return {}
print("Auto-binding Speakers to Persons...")
face_spans = []
for frame_obj in face_clustered.get("frames", []):
for frame_obj in output_frames:
ts = frame_obj.get("timestamp")
for face in frame_obj.get("faces", []):
person_id = face.get("cluster_id")
@@ -310,12 +325,14 @@ def auto_bind_speakers():
speaker_person_counts = {}
for seg in asrx_data.get("segments", []):
start = seg.get("start")
end = seg.get("end")
start = seg.get("start_time", seg.get("start"))
end = seg.get("end_time", seg.get("end"))
speaker = seg.get("speaker_id")
if not speaker or start is None or end is None:
continue
candidates = [f for f in face_spans if f.get("ts") is not None and start <= f["ts"] <= end]
candidates = [
f for f in face_spans if f.get("ts") is not None and start <= f["ts"] <= end
]
if candidates:
person_counts = {}
for c in candidates:
@@ -328,42 +345,15 @@ def auto_bind_speakers():
speaker_person_counts[speaker].get(best_person, 0) + 1
)
try:
conn = psycopg2.connect(DB_URL)
cur = conn.cursor()
for speaker, persons in speaker_person_counts.items():
if not persons:
continue
best_person = max(persons, key=persons.get)
print(f" {speaker} is likely {best_person} ({persons[best_person]} votes)")
mapping = {}
for speaker, persons in speaker_person_counts.items():
if not persons:
continue
best_person = max(persons, key=persons.get)
mapping[speaker] = best_person
print(f" {speaker} is likely {best_person} ({persons[best_person]} votes)")
cur.execute("SELECT id FROM talents WHERE real_name = %s", (best_person,))
row = cur.fetchone()
if row:
talent_id = row[0]
else:
cur.execute(
"INSERT INTO talents (real_name) VALUES (%s) RETURNING id",
(best_person,),
)
talent_id = cur.fetchone()[0]
print(f" Created Talent #{talent_id} ({best_person})")
cur.execute(
"""
INSERT INTO identity_bindings (talent_id, binding_type, binding_value, source, confidence)
VALUES (%s, 'speaker', %s, 'auto_cluster', 0.8)
ON CONFLICT (binding_type, binding_value) DO UPDATE SET talent_id = EXCLUDED.talent_id
""",
(talent_id, speaker),
)
print(f" Bound {speaker} -> {best_person}")
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f" DB Error: {e}")
return mapping
def main():
@@ -373,12 +363,22 @@ def main():
parser.add_argument("video_path", help="Path to video file")
parser.add_argument("output_path", help="Path to output JSON file")
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(
"--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})")
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
@@ -434,12 +434,12 @@ def main():
# 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)")
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=min_faces,
confidence_threshold=0.5
points, min_faces_per_trace=min_faces, confidence_threshold=0.5
)
if not trace_embeddings:
@@ -454,9 +454,13 @@ def main():
threshold = args.threshold
method = args.method
if method == "leader":
trace_to_person, trace_similarities = seed_leader_cluster(trace_embeddings, threshold=threshold)
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_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)
@@ -511,23 +515,26 @@ def main():
person_face_count = defaultdict(int)
person_best_face = {}
for frame_idx, frame_obj in enumerate(frames_list):
for face in frame_obj.get("faces", []):
for face_idx, face in enumerate(frame_obj.get("faces", [])):
person_id = face.get("person_id")
if not person_id:
continue
person_face_count[person_id] += 1
confidence = face.get("confidence", 0.9)
if person_id not in person_best_face or confidence > person_best_face[person_id]["confidence"]:
if (
person_id not in person_best_face
or confidence > person_best_face[person_id]["confidence"]
):
person_best_face[person_id] = {
"face_id": f"face_{frame_idx}_{frame_idx}",
"face_id": f"face_{frame_idx}_{face_idx}",
"confidence": confidence,
"frame": frame_obj.get("frame", frame_idx),
"bbox": {
"x": face.get("x"),
"y": face.get("y"),
"width": face.get("width"),
"height": face.get("height")
}
"height": face.get("height"),
},
}
# Build per-person similarity stats from trace_similarities
@@ -537,7 +544,9 @@ def main():
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])
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
@@ -567,23 +576,29 @@ def main():
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)
timestamp = frame_obj.get(
"timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0
)
output_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}_{face_idx}",
"cluster_id": person_id,
"trace_id": face.get("trace_id"),
"confidence": face.get("confidence", 0.9),
})
output_faces.append(
{
"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:
output_frames.append({
"frame": frame_obj.get("frame", frame_idx),
"timestamp": timestamp,
"faces": output_faces,
})
output_frames.append(
{
"frame": frame_obj.get("frame", frame_idx),
"timestamp": timestamp,
"faces": output_faces,
}
)
output_data = {
"status": "has_faces",
@@ -591,15 +606,25 @@ def main():
"clusters": clusters,
"frames": output_frames,
}
speaker_mapping = auto_bind_speakers(
output_frames, os.path.join(output_dir, f"{uuid}.asrx.json")
)
if speaker_mapping:
output_data["speaker_person_mapping"] = speaker_mapping
with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"Saved clustered data to {OUTPUT_JSON_PATH}")
publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters")
auto_bind_speakers()
publisher.complete("face_cluster", f"{len(clusters)} clusters")
if speaker_mapping:
publisher.info(
"face_cluster",
f"Speaker mapping: {len(speaker_mapping)} speakers",
)
if __name__ == "__main__":
main()
main()