feat: restructure tools directory

新結構:
- tools/script/ (Python 處理器腳本)
- tools/cli/ (Swift/Rust CLI 工具)

遷移內容:
- Python 腳本: ASR, Face, Pose, Cut, OCR, VLM, Embedding, Identity
- Swift CLI: 24 個 Swift 處理器和測試文件
- Rust CLI: Face Cluster, Appearance, Pose

保留向後兼容:
- 舊路徑 scripts/ 仍然存在
- 環境變數可配置新路徑

文檔:
- tools/README.md
- docs_v1.0/DESIGN/Tools_Directory_Restructure.md
This commit is contained in:
Accusys
2026-09-27 12:04:23 +08:00
parent db74b11e21
commit af028ab8f4
54 changed files with 15459 additions and 0 deletions
+519
View File
@@ -0,0 +1,519 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Agent - Multi-Evidence Identity Inference
Core Logic:
1. Time Overlap Matching (Speaker vs Person frames)
2. Embedding Similarity Calculation
3. Multi-Evidence Fusion
4. LLM Inference for Ambiguous Cases
5. Identity Assignment
Usage:
python3 scripts/identity_agent.py --video-uuid <uuid> --analyze
python3 scripts/identity_agent.py --video-uuid <uuid> --suggest
"""
import sys
import json
import argparse
import os
import numpy as np
from typing import Dict, List, Optional, Tuple
from sklearn.metrics.pairwise import cosine_similarity
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
class IdentityAgent:
"""
Identity Agent for Multi-Evidence Identity Inference
Attributes:
video_uuid (str): Video UUID
output_dir (str): Output directory
fps (float): Video frame rate
auto_merge_threshold (float): Auto merge threshold (default: 0.8)
llm_threshold (float): LLM inference threshold (default: 0.5)
face_similarity_threshold (float): Face similarity threshold (default: 0.3)
use_llm (bool): Use LLM for ambiguous cases
model (str): LLM model name
"""
def __init__(
self,
video_uuid: str,
output_dir: str = None,
auto_merge_threshold: float = 0.8,
llm_threshold: float = 0.5,
face_similarity_threshold: float = 0.3,
use_llm: bool = True,
model: str = "gemma4",
):
self.video_uuid = video_uuid
self.output_dir = output_dir or os.getenv(
"MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev"
)
self.auto_merge_threshold = auto_merge_threshold
self.llm_threshold = llm_threshold
self.face_similarity_threshold = face_similarity_threshold
self.use_llm = use_llm
self.model = model
self.fps = 23.976 # Default FPS
self.face_data = None
self.asrx_data = None
self.persons = []
self.speakers = []
self.identities = []
self.publisher = RedisPublisher(video_uuid) if video_uuid else None
def load_data(self) -> bool:
"""Load face clustered and ASRX data from files"""
video_dir = os.path.join(self.output_dir, self.video_uuid)
face_clustered_path = os.path.join(
video_dir, f"{self.video_uuid}.face_clustered.json"
)
asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json")
probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json")
if not os.path.exists(face_clustered_path):
print(f"Error: Face clustered data not found: {face_clustered_path}")
return False
self.face_data = self._load_json(face_clustered_path)
self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None
if os.path.exists(probe_path):
probe_data = self._load_json(probe_path)
self.fps = probe_data.get("fps", 23.976)
self.persons = self._extract_persons()
self.speakers = self._extract_speakers()
print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers")
return True
def _load_json(self, path: str) -> Dict:
"""Load JSON file"""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _extract_persons(self) -> List[Dict]:
"""Extract persons from face clustered data"""
persons = []
if not self.face_data:
return persons
if "clusters" in self.face_data:
for cluster in self.face_data["clusters"]:
person_id = cluster.get("person_id", f"Person_{len(persons) + 1}")
frames = cluster.get("frames", [])
avg_embedding = cluster.get("avg_embedding", None)
persons.append({
"person_id": person_id,
"frames": frames,
"frame_count": len(frames),
"avg_embedding": avg_embedding,
"timestamps": [f / self.fps for f in frames],
})
return persons
def _extract_speakers(self) -> List[Dict]:
"""Extract speakers from ASRX data"""
speakers = []
if not self.asrx_data:
return speakers
if "segments" in self.asrx_data:
speaker_segments_map = {}
for segment in self.asrx_data["segments"]:
speaker_id = segment.get("speaker", "SPEAKER_01")
start = segment.get("start", 0.0)
end = segment.get("end", 0.0)
if speaker_id not in speaker_segments_map:
speaker_segments_map[speaker_id] = []
speaker_segments_map[speaker_id].append({"start": start, "end": end})
for speaker_id, segments in speaker_segments_map.items():
total_duration = sum(s["end"] - s["start"] for s in segments)
speakers.append({
"speaker_id": speaker_id,
"segments": segments,
"total_duration": total_duration,
})
return speakers
def calculate_speaker_person_overlap(
self, person: Dict, speaker: Dict
) -> Tuple[int, float]:
"""
Calculate overlap between Person and Speaker
Returns:
Tuple of (overlap_frames, overlap_ratio)
"""
overlap_frames = 0
for frame in person["frames"]:
frame_time = frame / self.fps
for segment in speaker["segments"]:
if segment["start"] <= frame_time <= segment["end"]:
overlap_frames += 1
break
overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0
return overlap_frames, overlap_ratio
def calculate_person_similarity(
self, person1: Dict, person2: Dict
) -> Optional[float]:
"""
Calculate cosine similarity between two Person embeddings
Returns:
Similarity score (0-1) or None if embeddings not available
"""
if not person1.get("avg_embedding") or not person2.get("avg_embedding"):
return None
emb1 = np.array(person1["avg_embedding"]).reshape(1, -1)
emb2 = np.array(person2["avg_embedding"]).reshape(1, -1)
similarity = cosine_similarity(emb1, emb2)[0][0]
return similarity
def fuse_evidence(
self,
face_similarity: Optional[float],
speaker_overlap: float,
time_overlap: float,
frame_ratio: float,
) -> float:
"""
Fuse multiple evidence sources into a single confidence score
Args:
face_similarity: Cosine similarity between face embeddings (0-1)
speaker_overlap: Speaker-Person overlap ratio (0-1)
time_overlap: Temporal overlap ratio (0-1)
frame_ratio: Person's frame count ratio in video (0-1)
Returns:
Fused confidence score (0-1)
"""
weights = {
"face": 0.4,
"speaker": 0.3,
"time": 0.2,
"frame": 0.1,
}
face_score = face_similarity if face_similarity is not None else 0.5
confidence = (
weights["face"] * face_score
+ weights["speaker"] * speaker_overlap
+ weights["time"] * time_overlap
+ weights["frame"] * frame_ratio
)
return confidence
def analyze(self) -> Dict:
"""
Analyze video identity
Returns:
Identity analysis result
"""
if not self.load_data():
return {"success": False, "error": "Failed to load data"}
if self.publisher:
self.publisher.info("identity", "IDENTITY_ANALYZE_START")
identities = []
for i, person in enumerate(self.persons):
identity_id = f"identity_{i + 1}"
speaker_overlaps = []
max_overlap = 0.0
max_speaker_id = None
for speaker in self.speakers:
overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap(
person, speaker
)
if overlap_ratio > 0.3:
speaker_overlaps.append({
"speaker_id": speaker["speaker_id"],
"overlap_frames": overlap_frames,
"overlap_ratio": overlap_ratio,
})
if overlap_ratio > max_overlap:
max_overlap = overlap_ratio
max_speaker_id = speaker["speaker_id"]
frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons)
confidence = self.fuse_evidence(
face_similarity=None,
speaker_overlap=max_overlap,
time_overlap=max_overlap,
frame_ratio=frame_ratio,
)
identity = {
"identity_id": identity_id,
"person_ids": [person["person_id"]],
"speaker_ids": [s["speaker_id"] for s in speaker_overlaps],
"confidence": confidence,
"evidence": {
"face_similarity": None,
"speaker_overlap": max_overlap,
"time_overlap": max_overlap,
"frame_ratio": frame_ratio,
},
"reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}",
}
identities.append(identity)
if self.publisher:
self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}")
return {
"success": True,
"video_uuid": self.video_uuid,
"identities": identities,
"processing_status": {
"status": "completed",
"persons_analyzed": len(self.persons),
"identities_created": len(identities),
"merges_suggested": 0,
},
}
def suggest_merges(self) -> Dict:
"""
Suggest Identity merges
Returns:
Merge suggestions
"""
analyze_result = self.analyze()
if not analyze_result.get("success"):
return analyze_result
identities = analyze_result["identities"]
merge_suggestions = []
for identity in identities:
if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1:
confidence = identity["confidence"]
if confidence > self.auto_merge_threshold:
action = "auto_apply"
elif confidence > self.llm_threshold:
action = "review_needed"
else:
continue
reasons = [
f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}",
f"Confidence: {confidence:.2f}",
]
merge_suggestions.append({
"target_person_id": identity["person_ids"][0],
"source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [],
"confidence": confidence,
"reasons": reasons,
"action": action,
})
return {
"success": True,
"video_uuid": self.video_uuid,
"merge_suggestions": merge_suggestions,
"naming_suggestions": [],
}
def call_llm(self, prompt: str) -> Dict:
"""
Call LLM for inference
Args:
prompt: LLM prompt
Returns:
LLM response
"""
import requests
ollama_url = "http://localhost:11434/api/generate"
body = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
try:
response = requests.post(ollama_url, json=body, timeout=30)
result = response.json()
llm_output = result.get("response", "")
try:
parsed = json.loads(llm_output)
return parsed
except json.JSONDecodeError:
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": llm_output,
}
except Exception as e:
print(f"LLM call failed: {e}")
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": f"LLM call failed: {e}",
}
def llm_identity_inference(self, evidence: Dict) -> Dict:
"""
Use LLM to infer identity for ambiguous cases
Args:
evidence: Multi-evidence data
Returns:
LLM inference result
"""
confidence = evidence.get("confidence", 0.5)
if confidence > self.auto_merge_threshold:
return {
"decision": "merge",
"confidence": confidence,
"reasoning": f"High confidence ({confidence:.2f}) - auto merge",
}
if confidence < self.llm_threshold:
return {
"decision": "keep_separate",
"confidence": confidence,
"reasoning": f"Low confidence ({confidence:.2f}) - keep separate",
}
if not self.use_llm:
return {
"decision": "review_needed",
"confidence": confidence,
"reasoning": "Medium confidence - manual review required",
}
prompt = f"""
You are an identity analyst for a video analysis system.
Given the following evidence:
- Face similarity: {evidence.get('face_similarity', 'N/A')}
- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f}
- Time overlap: {evidence.get('time_overlap', 0):.2f}
- Frame ratio: {evidence.get('frame_ratio', 0):.2f}
- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames)
- Shared speaker: {evidence.get('shared_speaker', 'None')}
Should this person be merged with other persons sharing the same speaker?
Provide:
1. Decision: "merge" or "keep_separate"
2. Confidence: 0.0-1.0
3. Reasoning: 1-2 sentences explaining your decision
Output in JSON format only:
{{
"decision": "merge" or "keep_separate",
"confidence": 0.85,
"reasoning": "..."
}}
"""
return self.call_llm(prompt)
def main():
parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference")
parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True)
parser.add_argument("--output-dir", "-o", help="Output directory", default=None)
parser.add_argument(
"--analyze", "-a", help="Analyze video identity", action="store_true"
)
parser.add_argument(
"--suggest", "-s", help="Suggest Identity merges", action="store_true"
)
parser.add_argument(
"--auto-merge-threshold",
"-t",
help="Auto merge threshold",
type=float,
default=0.8,
)
parser.add_argument(
"--llm-threshold",
"-l",
help="LLM inference threshold",
type=float,
default=0.5,
)
parser.add_argument(
"--use-llm", help="Use LLM for ambiguous cases", action="store_true"
)
parser.add_argument("--model", "-m", help="LLM model", default="gemma4")
args = parser.parse_args()
agent = IdentityAgent(
video_uuid=args.video_uuid,
output_dir=args.output_dir,
auto_merge_threshold=args.auto_merge_threshold,
llm_threshold=args.llm_threshold,
use_llm=args.use_llm,
model=args.model,
)
if args.analyze:
result = agent.analyze()
print(json.dumps(result, indent=2))
if args.suggest:
result = agent.suggest_merges()
print(json.dumps(result, indent=2))
if not args.analyze and not args.suggest:
print("Please specify --analyze or --suggest")
if __name__ == "__main__":
main()
@@ -0,0 +1,519 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Agent - Multi-Evidence Identity Inference
Core Logic:
1. Time Overlap Matching (Speaker vs Person frames)
2. Embedding Similarity Calculation
3. Multi-Evidence Fusion
4. LLM Inference for Ambiguous Cases
5. Identity Assignment
Usage:
python3 scripts/identity_agent.py --video-uuid <uuid> --analyze
python3 scripts/identity_agent.py --video-uuid <uuid> --suggest
"""
import sys
import json
import argparse
import os
import numpy as np
from typing import Dict, List, Optional, Tuple
from sklearn.metrics.pairwise import cosine_similarity
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
class IdentityAgent:
"""
Identity Agent for Multi-Evidence Identity Inference
Attributes:
video_uuid (str): Video UUID
output_dir (str): Output directory
fps (float): Video frame rate
auto_merge_threshold (float): Auto merge threshold (default: 0.8)
llm_threshold (float): LLM inference threshold (default: 0.5)
face_similarity_threshold (float): Face similarity threshold (default: 0.3)
use_llm (bool): Use LLM for ambiguous cases
model (str): LLM model name
"""
def __init__(
self,
video_uuid: str,
output_dir: str = None,
auto_merge_threshold: float = 0.8,
llm_threshold: float = 0.5,
face_similarity_threshold: float = 0.3,
use_llm: bool = True,
model: str = "gemma4",
):
self.video_uuid = video_uuid
self.output_dir = output_dir or os.getenv(
"MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev"
)
self.auto_merge_threshold = auto_merge_threshold
self.llm_threshold = llm_threshold
self.face_similarity_threshold = face_similarity_threshold
self.use_llm = use_llm
self.model = model
self.fps = 23.976 # Default FPS
self.face_data = None
self.asrx_data = None
self.persons = []
self.speakers = []
self.identities = []
self.publisher = RedisPublisher(video_uuid) if video_uuid else None
def load_data(self) -> bool:
"""Load face clustered and ASRX data from files"""
video_dir = os.path.join(self.output_dir, self.video_uuid)
face_clustered_path = os.path.join(
video_dir, f"{self.video_uuid}.face_clustered.json"
)
asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json")
probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json")
if not os.path.exists(face_clustered_path):
print(f"Error: Face clustered data not found: {face_clustered_path}")
return False
self.face_data = self._load_json(face_clustered_path)
self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None
if os.path.exists(probe_path):
probe_data = self._load_json(probe_path)
self.fps = probe_data.get("fps", 23.976)
self.persons = self._extract_persons()
self.speakers = self._extract_speakers()
print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers")
return True
def _load_json(self, path: str) -> Dict:
"""Load JSON file"""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _extract_persons(self) -> List[Dict]:
"""Extract persons from face clustered data"""
persons = []
if not self.face_data:
return persons
if "clusters" in self.face_data:
for cluster in self.face_data["clusters"]:
person_id = cluster.get("person_id", f"Person_{len(persons) + 1}")
frames = cluster.get("frames", [])
avg_embedding = cluster.get("avg_embedding", None)
persons.append({
"person_id": person_id,
"frames": frames,
"frame_count": len(frames),
"avg_embedding": avg_embedding,
"timestamps": [f / self.fps for f in frames],
})
return persons
def _extract_speakers(self) -> List[Dict]:
"""Extract speakers from ASRX data"""
speakers = []
if not self.asrx_data:
return speakers
if "segments" in self.asrx_data:
speaker_segments_map = {}
for segment in self.asrx_data["segments"]:
speaker_id = segment.get("speaker", "SPEAKER_01")
start = segment.get("start", 0.0)
end = segment.get("end", 0.0)
if speaker_id not in speaker_segments_map:
speaker_segments_map[speaker_id] = []
speaker_segments_map[speaker_id].append({"start": start, "end": end})
for speaker_id, segments in speaker_segments_map.items():
total_duration = sum(s["end"] - s["start"] for s in segments)
speakers.append({
"speaker_id": speaker_id,
"segments": segments,
"total_duration": total_duration,
})
return speakers
def calculate_speaker_person_overlap(
self, person: Dict, speaker: Dict
) -> Tuple[int, float]:
"""
Calculate overlap between Person and Speaker
Returns:
Tuple of (overlap_frames, overlap_ratio)
"""
overlap_frames = 0
for frame in person["frames"]:
frame_time = frame / self.fps
for segment in speaker["segments"]:
if segment["start"] <= frame_time <= segment["end"]:
overlap_frames += 1
break
overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0
return overlap_frames, overlap_ratio
def calculate_person_similarity(
self, person1: Dict, person2: Dict
) -> Optional[float]:
"""
Calculate cosine similarity between two Person embeddings
Returns:
Similarity score (0-1) or None if embeddings not available
"""
if not person1.get("avg_embedding") or not person2.get("avg_embedding"):
return None
emb1 = np.array(person1["avg_embedding"]).reshape(1, -1)
emb2 = np.array(person2["avg_embedding"]).reshape(1, -1)
similarity = cosine_similarity(emb1, emb2)[0][0]
return similarity
def fuse_evidence(
self,
face_similarity: Optional[float],
speaker_overlap: float,
time_overlap: float,
frame_ratio: float,
) -> float:
"""
Fuse multiple evidence sources into a single confidence score
Args:
face_similarity: Cosine similarity between face embeddings (0-1)
speaker_overlap: Speaker-Person overlap ratio (0-1)
time_overlap: Temporal overlap ratio (0-1)
frame_ratio: Person's frame count ratio in video (0-1)
Returns:
Fused confidence score (0-1)
"""
weights = {
"face": 0.4,
"speaker": 0.3,
"time": 0.2,
"frame": 0.1,
}
face_score = face_similarity if face_similarity is not None else 0.5
confidence = (
weights["face"] * face_score
+ weights["speaker"] * speaker_overlap
+ weights["time"] * time_overlap
+ weights["frame"] * frame_ratio
)
return confidence
def analyze(self) -> Dict:
"""
Analyze video identity
Returns:
Identity analysis result
"""
if not self.load_data():
return {"success": False, "error": "Failed to load data"}
if self.publisher:
self.publisher.info("identity", "IDENTITY_ANALYZE_START")
identities = []
for i, person in enumerate(self.persons):
identity_id = f"identity_{i + 1}"
speaker_overlaps = []
max_overlap = 0.0
max_speaker_id = None
for speaker in self.speakers:
overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap(
person, speaker
)
if overlap_ratio > 0.3:
speaker_overlaps.append({
"speaker_id": speaker["speaker_id"],
"overlap_frames": overlap_frames,
"overlap_ratio": overlap_ratio,
})
if overlap_ratio > max_overlap:
max_overlap = overlap_ratio
max_speaker_id = speaker["speaker_id"]
frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons)
confidence = self.fuse_evidence(
face_similarity=None,
speaker_overlap=max_overlap,
time_overlap=max_overlap,
frame_ratio=frame_ratio,
)
identity = {
"identity_id": identity_id,
"person_ids": [person["person_id"]],
"speaker_ids": [s["speaker_id"] for s in speaker_overlaps],
"confidence": confidence,
"evidence": {
"face_similarity": None,
"speaker_overlap": max_overlap,
"time_overlap": max_overlap,
"frame_ratio": frame_ratio,
},
"reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}",
}
identities.append(identity)
if self.publisher:
self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}")
return {
"success": True,
"video_uuid": self.video_uuid,
"identities": identities,
"processing_status": {
"status": "completed",
"persons_analyzed": len(self.persons),
"identities_created": len(identities),
"merges_suggested": 0,
},
}
def suggest_merges(self) -> Dict:
"""
Suggest Identity merges
Returns:
Merge suggestions
"""
analyze_result = self.analyze()
if not analyze_result.get("success"):
return analyze_result
identities = analyze_result["identities"]
merge_suggestions = []
for identity in identities:
if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1:
confidence = identity["confidence"]
if confidence > self.auto_merge_threshold:
action = "auto_apply"
elif confidence > self.llm_threshold:
action = "review_needed"
else:
continue
reasons = [
f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}",
f"Confidence: {confidence:.2f}",
]
merge_suggestions.append({
"target_person_id": identity["person_ids"][0],
"source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [],
"confidence": confidence,
"reasons": reasons,
"action": action,
})
return {
"success": True,
"video_uuid": self.video_uuid,
"merge_suggestions": merge_suggestions,
"naming_suggestions": [],
}
def call_llm(self, prompt: str) -> Dict:
"""
Call LLM for inference
Args:
prompt: LLM prompt
Returns:
LLM response
"""
import requests
ollama_url = "http://localhost:11434/api/generate"
body = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
try:
response = requests.post(ollama_url, json=body, timeout=30)
result = response.json()
llm_output = result.get("response", "")
try:
parsed = json.loads(llm_output)
return parsed
except json.JSONDecodeError:
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": llm_output,
}
except Exception as e:
print(f"LLM call failed: {e}")
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": f"LLM call failed: {e}",
}
def llm_identity_inference(self, evidence: Dict) -> Dict:
"""
Use LLM to infer identity for ambiguous cases
Args:
evidence: Multi-evidence data
Returns:
LLM inference result
"""
confidence = evidence.get("confidence", 0.5)
if confidence > self.auto_merge_threshold:
return {
"decision": "merge",
"confidence": confidence,
"reasoning": f"High confidence ({confidence:.2f}) - auto merge",
}
if confidence < self.llm_threshold:
return {
"decision": "keep_separate",
"confidence": confidence,
"reasoning": f"Low confidence ({confidence:.2f}) - keep separate",
}
if not self.use_llm:
return {
"decision": "review_needed",
"confidence": confidence,
"reasoning": "Medium confidence - manual review required",
}
prompt = f"""
You are an identity analyst for a video analysis system.
Given the following evidence:
- Face similarity: {evidence.get('face_similarity', 'N/A')}
- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f}
- Time overlap: {evidence.get('time_overlap', 0):.2f}
- Frame ratio: {evidence.get('frame_ratio', 0):.2f}
- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames)
- Shared speaker: {evidence.get('shared_speaker', 'None')}
Should this person be merged with other persons sharing the same speaker?
Provide:
1. Decision: "merge" or "keep_separate"
2. Confidence: 0.0-1.0
3. Reasoning: 1-2 sentences explaining your decision
Output in JSON format only:
{{
"decision": "merge" or "keep_separate",
"confidence": 0.85,
"reasoning": "..."
}}
"""
return self.call_llm(prompt)
def main():
parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference")
parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True)
parser.add_argument("--output-dir", "-o", help="Output directory", default=None)
parser.add_argument(
"--analyze", "-a", help="Analyze video identity", action="store_true"
)
parser.add_argument(
"--suggest", "-s", help="Suggest Identity merges", action="store_true"
)
parser.add_argument(
"--auto-merge-threshold",
"-t",
help="Auto merge threshold",
type=float,
default=0.8,
)
parser.add_argument(
"--llm-threshold",
"-l",
help="LLM inference threshold",
type=float,
default=0.5,
)
parser.add_argument(
"--use-llm", help="Use LLM for ambiguous cases", action="store_true"
)
parser.add_argument("--model", "-m", help="LLM model", default="gemma4")
args = parser.parse_args()
agent = IdentityAgent(
video_uuid=args.video_uuid,
output_dir=args.output_dir,
auto_merge_threshold=args.auto_merge_threshold,
llm_threshold=args.llm_threshold,
use_llm=args.use_llm,
model=args.model,
)
if args.analyze:
result = agent.analyze()
print(json.dumps(result, indent=2))
if args.suggest:
result = agent.suggest_merges()
print(json.dumps(result, indent=2))
if not args.analyze and not args.suggest:
print("Please specify --analyze or --suggest")
if __name__ == "__main__":
main()
+129
View File
@@ -0,0 +1,129 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Binding: cluster face traces → identity bindings.
Uses face embeddings from face_detections, clusters per trace, creates identities.
"""
import json, sys, time
import psycopg2
import numpy as np
from sklearn.cluster import AgglomerativeClustering
UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5"
DB = "dbname=momentry user=accusys"
DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering
print(f"=== Identity Binding for {UUID} ===")
conn = psycopg2.connect(DB)
cur = conn.cursor()
# Step 1: Get trace embeddings from face_detections
print("Loading face trace data...")
cur.execute("""
SELECT trace_id, embedding
FROM dev.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL
ORDER BY trace_id, id
""", (UUID,))
rows = cur.fetchall()
print(f"Face detections with embeddings: {len(rows)}")
# Group by trace_id and compute average embedding
trace_embs = {}
for trace_id, emb in rows:
if trace_id not in trace_embs:
trace_embs[trace_id] = []
trace_embs[trace_id].append(emb)
print(f"Unique traces: {len(trace_embs)}")
# Compute mean embeddings per trace
trace_ids = []
trace_vectors = []
for tid, embs in sorted(trace_embs.items()):
mean_emb = np.mean(embs, axis=0)
mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10)
trace_ids.append(tid)
trace_vectors.append(mean_emb)
X = np.array(trace_vectors)
print(f"Trace vectors shape: {X.shape}")
# Step 2: Cluster traces
print("Clustering traces...")
if len(X) > 1:
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=DISTANCE_THRESHOLD,
metric='cosine',
linkage='average'
)
labels = clustering.fit_predict(X)
else:
labels = [0]
n_clusters = len(set(labels))
print(f"Clusters/identities: {n_clusters}")
# Step 3: Get or create identity records
print("Creating identity records...")
# Get existing identities
cur.execute("SELECT id, uuid FROM dev.identities")
existing = {row[0]: row[1] for row in cur.fetchall()}
# Map cluster -> identity_id
cluster_to_identity = {}
for cluster_id in sorted(set(labels)):
# Create new identity
identity_uuid = None
cur.execute("""
INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid)
VALUES (%s, 'face', 'auto', 'active', NOW(), %s)
ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s)
RETURNING id
""", (f"stranger_{UUID}_{cluster_id}", UUID, UUID))
identity_id = cur.fetchone()[0]
cluster_to_identity[cluster_id] = identity_id
print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})")
# Step 4: Create identity bindings
print("Creating identity bindings...")
bindings = 0
for tid, label in zip(trace_ids, labels):
identity_id = cluster_to_identity[label]
# Get a representative face_id for this trace
cur.execute("""
SELECT face_id FROM dev.face_detections
WHERE file_uuid = %s AND trace_id = %s
LIMIT 1
""", (UUID, tid))
row = cur.fetchone()
if row:
face_id = row[0]
# Create binding
cur.execute("""
INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at)
VALUES (%s, 'trace', %s, 0.8, NOW())
ON CONFLICT DO NOTHING
""", (identity_id, str(tid)))
bindings += 1
# Also update face_detection with identity_id
cur.execute("""
UPDATE dev.face_detections SET identity_id = %s
WHERE file_uuid = %s AND trace_id = %s
""", (identity_id, UUID, tid))
conn.commit()
print(f"Created {bindings} identity bindings for {n_clusters} identities")
# Summary
print(f"\n=== Summary ===")
cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'")
print(f"Total auto-generated identities: {cur.fetchone()[0]}")
cur.execute("SELECT COUNT(*) FROM dev.identity_bindings")
print(f"Total identity bindings: {cur.fetchone()[0]}")
cur.close()
conn.close()
print("=== Done ===")
@@ -0,0 +1,129 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Binding: cluster face traces → identity bindings.
Uses face embeddings from face_detections, clusters per trace, creates identities.
"""
import json, sys, time
import psycopg2
import numpy as np
from sklearn.cluster import AgglomerativeClustering
UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5"
DB = "dbname=momentry user=accusys"
DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering
print(f"=== Identity Binding for {UUID} ===")
conn = psycopg2.connect(DB)
cur = conn.cursor()
# Step 1: Get trace embeddings from face_detections
print("Loading face trace data...")
cur.execute("""
SELECT trace_id, embedding
FROM dev.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL
ORDER BY trace_id, id
""", (UUID,))
rows = cur.fetchall()
print(f"Face detections with embeddings: {len(rows)}")
# Group by trace_id and compute average embedding
trace_embs = {}
for trace_id, emb in rows:
if trace_id not in trace_embs:
trace_embs[trace_id] = []
trace_embs[trace_id].append(emb)
print(f"Unique traces: {len(trace_embs)}")
# Compute mean embeddings per trace
trace_ids = []
trace_vectors = []
for tid, embs in sorted(trace_embs.items()):
mean_emb = np.mean(embs, axis=0)
mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10)
trace_ids.append(tid)
trace_vectors.append(mean_emb)
X = np.array(trace_vectors)
print(f"Trace vectors shape: {X.shape}")
# Step 2: Cluster traces
print("Clustering traces...")
if len(X) > 1:
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=DISTANCE_THRESHOLD,
metric='cosine',
linkage='average'
)
labels = clustering.fit_predict(X)
else:
labels = [0]
n_clusters = len(set(labels))
print(f"Clusters/identities: {n_clusters}")
# Step 3: Get or create identity records
print("Creating identity records...")
# Get existing identities
cur.execute("SELECT id, uuid FROM dev.identities")
existing = {row[0]: row[1] for row in cur.fetchall()}
# Map cluster -> identity_id
cluster_to_identity = {}
for cluster_id in sorted(set(labels)):
# Create new identity
identity_uuid = None
cur.execute("""
INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid)
VALUES (%s, 'face', 'auto', 'active', NOW(), %s)
ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s)
RETURNING id
""", (f"stranger_{UUID}_{cluster_id}", UUID, UUID))
identity_id = cur.fetchone()[0]
cluster_to_identity[cluster_id] = identity_id
print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})")
# Step 4: Create identity bindings
print("Creating identity bindings...")
bindings = 0
for tid, label in zip(trace_ids, labels):
identity_id = cluster_to_identity[label]
# Get a representative face_id for this trace
cur.execute("""
SELECT face_id FROM dev.face_detections
WHERE file_uuid = %s AND trace_id = %s
LIMIT 1
""", (UUID, tid))
row = cur.fetchone()
if row:
face_id = row[0]
# Create binding
cur.execute("""
INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at)
VALUES (%s, 'trace', %s, 0.8, NOW())
ON CONFLICT DO NOTHING
""", (identity_id, str(tid)))
bindings += 1
# Also update face_detection with identity_id
cur.execute("""
UPDATE dev.face_detections SET identity_id = %s
WHERE file_uuid = %s AND trace_id = %s
""", (identity_id, UUID, tid))
conn.commit()
print(f"Created {bindings} identity bindings for {n_clusters} identities")
# Summary
print(f"\n=== Summary ===")
cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'")
print(f"Total auto-generated identities: {cur.fetchone()[0]}")
cur.execute("SELECT COUNT(*) FROM dev.identity_bindings")
print(f"Total identity bindings: {cur.fetchone()[0]}")
cur.close()
conn.close()
print("=== Done ===")
+421
View File
@@ -0,0 +1,421 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Matcher - Multi-angle face matching against seeds
Flow:
1. Query Qdrant _faces for all traces in a file
2. Query Qdrant _seeds for all seeds (TMDb + manual + propagation)
3. Multi-angle matching: max(cosine(seed, rep)) across 3 representatives
4. Return suggestions with confidence scores
Thresholds:
- Round 1: 0.55 (TMDb seeds)
- Round 2: 0.55 (Propagation from confirmed traces)
- Round 3+: 0.50 (Propagation continues)
- Stranger clustering: 0.40
Usage:
python identity_matcher.py --file-uuid <uuid> --round 1
python identity_matcher.py --file-uuid <uuid> --round 2 --confirmed-traces 1,2,3
Output:
JSON with suggestions: {trace_id: {identity_id, identity_uuid, name, score, suggested_by}}
"""
import os
import sys
import json
import argparse
import numpy as np
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
from qdrant_faces import (
get_trace_representatives,
get_seeds,
search_seeds,
get_trace_centroid,
)
from tkg_helper import batch_mark_suggestions, batch_mark_strangers
TH_ROUND_1 = 0.55
TH_ROUND_2 = 0.55
TH_ROUND_3 = 0.50
TH_STRANGER = 0.40
def cosine_similarity(a: list, b: list) -> float:
"""Compute cosine similarity between two vectors"""
if len(a) != len(b) or len(a) == 0:
return 0.0
dot = sum(x * y for x, y in zip(a, b))
na = sum(x * x for x in a) ** 0.5
nb = sum(x * x for x in b) ** 0.5
if na == 0.0 or nb == 0.0:
return 0.0
return dot / (na * nb)
def multi_angle_match(seed_embedding: list, trace_reps: list) -> float:
"""Multi-angle matching: max(cosine(seed, rep))"""
if not trace_reps:
return 0.0
best_score = 0.0
for rep in trace_reps:
score = cosine_similarity(seed_embedding, rep["embedding"])
if score > best_score:
best_score = score
return best_score
def match_faces_round_1(file_uuid: str) -> dict:
"""Round 1: TMDb seeds → Traces (TH=0.55)
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'tmdb'}}
"""
traces = get_trace_representatives(file_uuid)
seeds = get_seeds(source="tmdb", file_uuid=file_uuid)
if not seeds:
print(f"[MATCH] No TMDb seeds available for {file_uuid}")
return {}
suggestions = {}
threshold = TH_ROUND_1
for trace_id, reps in traces.items():
best_match = None
best_score = 0.0
for seed in seeds:
seed_emb = seed.get("vector", [])
seed_payload = seed.get("payload", {})
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_payload.get("identity_id"),
"identity_uuid": seed_payload.get("identity_uuid"),
"name": seed_payload.get("name"),
"score": score,
"suggested_by": "tmdb",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round 1: {len(suggestions)}/{len(traces)} traces suggested (TH={threshold})")
return suggestions
def match_faces_round_2(
file_uuid: str,
confirmed_traces: list,
identity_map: dict,
) -> dict:
"""Round 2: Confirmed traces → Pending traces (TH=0.55)
Args:
file_uuid: Video file UUID
confirmed_traces: List of confirmed trace_ids
identity_map: {trace_id: {identity_id, identity_uuid, name}}
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}}
"""
traces = get_trace_representatives(file_uuid)
pending_traces = set(traces.keys()) - set(confirmed_traces)
if not pending_traces:
print("[MATCH] Round 2: No pending traces")
return {}
seed_pool = {}
for trace_id in confirmed_traces:
if trace_id not in traces:
continue
identity_info = identity_map.get(trace_id)
if not identity_info:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
identity_id = identity_info.get("identity_id")
if identity_id not in seed_pool:
seed_pool[identity_id] = {
"identity_id": identity_id,
"identity_uuid": identity_info.get("identity_uuid"),
"name": identity_info.get("name"),
"embeddings": [],
}
seed_pool[identity_id]["embeddings"].append(centroid)
if not seed_pool:
print("[MATCH] Round 2: No confirmed traces with embeddings")
return {}
suggestions = {}
threshold = TH_ROUND_2
for trace_id in pending_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
best_match = None
best_score = 0.0
for identity_id, seed_data in seed_pool.items():
for seed_emb in seed_data["embeddings"]:
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_data["identity_id"],
"identity_uuid": seed_data["identity_uuid"],
"name": seed_data["name"],
"score": score,
"suggested_by": "propagation",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round 2: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})")
return suggestions
def match_faces_round_3_plus(
file_uuid: str,
all_confirmed: dict,
prev_suggestions: dict,
round_num: int,
) -> dict:
"""Round 3+: Propagation continues (TH=0.50)
Args:
file_uuid: Video file UUID
all_confirmed: {trace_id: {identity_id, identity_uuid, name}} - all confirmed so far
prev_suggestions: {trace_id: {...}} - suggestions from previous round
round_num: Round number (3, 4, 5...)
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}}
"""
traces = get_trace_representatives(file_uuid)
confirmed_traces = set(all_confirmed.keys())
prev_suggested_traces = set(prev_suggestions.keys())
pending_traces = set(traces.keys()) - confirmed_traces - prev_suggested_traces
if not pending_traces:
print(f"[MATCH] Round {round_num}: No pending traces")
return {}
seed_pool = {}
for trace_id, identity_info in all_confirmed.items():
if trace_id not in traces:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
identity_id = identity_info.get("identity_id")
if identity_id not in seed_pool:
seed_pool[identity_id] = {
"identity_id": identity_id,
"identity_uuid": identity_info.get("identity_uuid"),
"name": identity_info.get("name"),
"embeddings": [],
}
seed_pool[identity_id]["embeddings"].append(centroid)
if not seed_pool:
print(f"[MATCH] Round {round_num}: No seeds available")
return {}
suggestions = {}
threshold = TH_ROUND_3
for trace_id in pending_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
best_match = None
best_score = 0.0
for identity_id, seed_data in seed_pool.items():
for seed_emb in seed_data["embeddings"]:
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_data["identity_id"],
"identity_uuid": seed_data["identity_uuid"],
"name": seed_data["name"],
"score": score,
"suggested_by": "propagation",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round {round_num}: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})")
return suggestions
def cluster_strangers(file_uuid: str, matched_traces: list) -> dict:
"""Stranger clustering: Greedy merge unmatched traces (TH=0.40)
Args:
file_uuid: Video file UUID
matched_traces: List of trace_ids that have identity suggestions
Returns:
{stranger_cluster_id: [trace_ids]}
"""
traces = get_trace_representatives(file_uuid)
unmatched_traces = set(traces.keys()) - set(matched_traces)
if not unmatched_traces:
print("[STRANGER] All traces matched")
return {}
clusters = []
threshold = TH_STRANGER
for trace_id in unmatched_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
best_cluster_idx = None
best_score = 0.0
for idx, cluster in enumerate(clusters):
cluster_centroid = compute_cluster_centroid(cluster, traces)
score = cosine_similarity(centroid, cluster_centroid)
if score >= threshold and score > best_score:
best_score = score
best_cluster_idx = idx
if best_cluster_idx is not None:
clusters[best_cluster_idx].append(trace_id)
else:
clusters.append([trace_id])
stranger_clusters = {}
for idx, trace_ids in enumerate(clusters):
stranger_clusters[idx + 1] = trace_ids
print(f"[STRANGER] {len(stranger_clusters)} clusters from {len(unmatched_traces)} unmatched traces (TH={threshold})")
return stranger_clusters
def compute_cluster_centroid(cluster: list, traces: dict) -> list:
"""Compute centroid embedding for a cluster of traces"""
all_embeddings = []
for trace_id in cluster:
reps = traces.get(trace_id, [])
for rep in reps:
all_embeddings.append(rep["embedding"])
if not all_embeddings:
return [0.0] * 512
centroid = [0.0] * 512
for emb in all_embeddings:
for i, v in enumerate(emb):
centroid[i] += v
for i in range(512):
centroid[i] /= len(all_embeddings)
return centroid
def main():
parser = argparse.ArgumentParser(description="Identity Matcher")
parser.add_argument("--file-uuid", required=True, help="Video file UUID")
parser.add_argument("--round", type=int, default=1, help="Round number (1, 2, 3+)")
parser.add_argument("--confirmed-traces", help="Comma-separated confirmed trace_ids (for Round 2+)")
parser.add_argument("--identity-map", help="JSON file with {trace_id: {identity_id, uuid, name}} (for Round 2+)")
parser.add_argument("--output", help="Output JSON file path")
parser.add_argument("--stranger", action="store_true", help="Also run stranger clustering")
parser.add_argument("--mark-tkg", action="store_true", help="Mark TKG face_track nodes with suggestions")
args = parser.parse_args()
if args.round == 1:
suggestions = match_faces_round_1(args.file_uuid)
elif args.round == 2:
confirmed = []
identity_map = {}
if args.confirmed_traces:
confirmed = [int(x) for x in args.confirmed_traces.split(",")]
if args.identity_map:
with open(args.identity_map) as f:
identity_map = json.load(f)
suggestions = match_faces_round_2(args.file_uuid, confirmed, identity_map)
else:
all_confirmed = {}
prev_suggestions = {}
if args.identity_map:
with open(args.identity_map) as f:
all_confirmed = json.load(f)
suggestions = match_faces_round_3_plus(
args.file_uuid, all_confirmed, prev_suggestions, args.round
)
result = {
"file_uuid": args.file_uuid,
"round": args.round,
"suggestions": suggestions,
"total_traces": len(get_trace_representatives(args.file_uuid)),
"matched": len(suggestions),
}
if args.stranger:
matched_traces = list(suggestions.keys())
stranger_clusters = cluster_strangers(args.file_uuid, matched_traces)
result["stranger_clusters"] = stranger_clusters
# Mark TKG nodes if requested
if args.mark_tkg:
tkg_updated = batch_mark_suggestions(args.file_uuid, suggestions)
result["tkg_nodes_updated"] = tkg_updated
if args.stranger and stranger_clusters:
tkg_strangers = batch_mark_strangers(args.file_uuid, stranger_clusters)
result["tkg_strangers_updated"] = tkg_strangers
output_json = json.dumps(result, indent=2, ensure_ascii=False)
if args.output:
with open(args.output, "w") as f:
f.write(output_json)
print(f"[MATCH] Output saved to {args.output}")
else:
print(output_json)
if __name__ == "__main__":
main()