|
30 | 30 |
|
31 | 31 | from advanced_omi_backend.config import get_diarization_settings |
32 | 32 | from advanced_omi_backend.constants import is_non_enrollable_speaker |
| 33 | +from advanced_omi_backend.controllers import data_audit_controller |
33 | 34 | from advanced_omi_backend.controllers.queue_controller import ( |
34 | 35 | JOB_RESULT_TTL, |
35 | 36 | default_queue, |
36 | 37 | ) |
| 38 | +from advanced_omi_backend.models.annotation import Annotation, AnnotationType |
37 | 39 | from advanced_omi_backend.models.conversation import Conversation |
38 | 40 | from advanced_omi_backend.speaker_recognition_client import SpeakerRecognitionClient |
39 | 41 | from advanced_omi_backend.users import User |
|
44 | 46 | from advanced_omi_backend.workers.speaker_discovery_jobs import ( |
45 | 47 | discover_speaker_candidates_job, |
46 | 48 | ) |
| 49 | +from advanced_omi_backend.workers.unknown_speaker_jobs import ( |
| 50 | + discover_unknown_speakers_job, |
| 51 | +) |
47 | 52 |
|
48 | 53 | logger = logging.getLogger(__name__) |
49 | 54 |
|
@@ -74,6 +79,196 @@ def _discovery_runs_collection(): |
74 | 79 | return Conversation.get_pymongo_collection().database["speaker_discovery_runs"] |
75 | 80 |
|
76 | 81 |
|
| 82 | +def _unknown_clusters_collection(): |
| 83 | + return Conversation.get_pymongo_collection().database["unknown_speaker_clusters"] |
| 84 | + |
| 85 | + |
| 86 | +def _unknown_runs_collection(): |
| 87 | + return Conversation.get_pymongo_collection().database["unknown_speaker_runs"] |
| 88 | + |
| 89 | + |
| 90 | +async def enqueue_unknown_discovery(user: User): |
| 91 | + """Start or reattach to corpus-wide unknown-identity clustering.""" |
| 92 | + user_id = str(user.user_id) |
| 93 | + existing = await _unknown_runs_collection().find_one({"requested_by": user_id}) |
| 94 | + status = _job_status(existing.get("job_id") if existing else None) |
| 95 | + if status in {"queued", "started", "deferred", "scheduled"}: |
| 96 | + return {"job_id": existing["job_id"], "status": status, "reused": True} |
| 97 | + job = default_queue.enqueue( |
| 98 | + discover_unknown_speakers_job, |
| 99 | + requested_by=user_id, |
| 100 | + job_timeout=14400, |
| 101 | + result_ttl=JOB_RESULT_TTL, |
| 102 | + description="Discover unknown speakers across corpus", |
| 103 | + ) |
| 104 | + await _unknown_runs_collection().update_one( |
| 105 | + {"requested_by": user_id}, |
| 106 | + {"$set": {"job_id": job.id, "queued_at": datetime.now(timezone.utc)}}, |
| 107 | + upsert=True, |
| 108 | + ) |
| 109 | + return {"job_id": job.id, "status": "queued", "reused": False} |
| 110 | + |
| 111 | + |
| 112 | +async def list_unknown_clusters(user: User, limit: int = 50): |
| 113 | + cursor = ( |
| 114 | + _unknown_clusters_collection() |
| 115 | + .find({"requested_by": str(user.user_id), "status": "pending"}, {"_id": 0}) |
| 116 | + .sort("segment_count", -1) |
| 117 | + .limit(limit) |
| 118 | + ) |
| 119 | + return {"clusters": await cursor.to_list(length=limit)} |
| 120 | + |
| 121 | + |
| 122 | +async def decide_unknown_cluster( |
| 123 | + user: User, |
| 124 | + cluster_id: str, |
| 125 | + run_fingerprint: str, |
| 126 | + action: str, |
| 127 | + speaker_name: Optional[str], |
| 128 | + accepted_identity_keys: list[str], |
| 129 | + enrollment_clips: list[dict], |
| 130 | +): |
| 131 | + """Relabel accepted members and enroll only explicitly selected clips.""" |
| 132 | + collection = _unknown_clusters_collection() |
| 133 | + cluster = await collection.find_one( |
| 134 | + { |
| 135 | + "requested_by": str(user.user_id), |
| 136 | + "cluster_id": cluster_id, |
| 137 | + "run_fingerprint": run_fingerprint, |
| 138 | + "status": "pending", |
| 139 | + } |
| 140 | + ) |
| 141 | + if not cluster: |
| 142 | + return JSONResponse(status_code=409, content={"error": "Cluster is stale"}) |
| 143 | + if action == "dismiss": |
| 144 | + await collection.update_one( |
| 145 | + {"_id": cluster["_id"]}, |
| 146 | + {"$set": {"status": "dismissed", "decided_at": datetime.now(timezone.utc)}}, |
| 147 | + ) |
| 148 | + return {"status": "dismissed"} |
| 149 | + if not speaker_name or is_non_enrollable_speaker(speaker_name): |
| 150 | + return JSONResponse( |
| 151 | + status_code=422, content={"error": "A real speaker name is required"} |
| 152 | + ) |
| 153 | + |
| 154 | + accepted = { |
| 155 | + member["identity_key"]: member |
| 156 | + for member in cluster["members"] |
| 157 | + if member["identity_key"] in set(accepted_identity_keys) |
| 158 | + } |
| 159 | + if not accepted: |
| 160 | + return JSONResponse( |
| 161 | + status_code=422, content={"error": "Select at least one identity"} |
| 162 | + ) |
| 163 | + if not enrollment_clips: |
| 164 | + return JSONResponse( |
| 165 | + status_code=422, content={"error": "Select at least one enrollment clip"} |
| 166 | + ) |
| 167 | + |
| 168 | + validated_segments = [] |
| 169 | + for member in accepted.values(): |
| 170 | + conversation = await Conversation.find_one( |
| 171 | + Conversation.conversation_id == member["conversation_id"] |
| 172 | + ) |
| 173 | + if not conversation or conversation.user_id != str(user.user_id): |
| 174 | + return JSONResponse( |
| 175 | + status_code=409, |
| 176 | + content={"error": "Conversation is no longer available"}, |
| 177 | + ) |
| 178 | + segments = _active_segments(conversation.model_dump()) |
| 179 | + for ref in member["segments"]: |
| 180 | + index = ref["segment_index"] |
| 181 | + if ( |
| 182 | + index >= len(segments) |
| 183 | + or abs(float(segments[index]["start"]) - ref["start"]) > 0.01 |
| 184 | + or not is_non_enrollable_speaker( |
| 185 | + segments[index].get("identified_as") |
| 186 | + or segments[index].get("speaker") |
| 187 | + ) |
| 188 | + or ( |
| 189 | + segments[index].get("identified_as") |
| 190 | + or segments[index].get("speaker") |
| 191 | + ) |
| 192 | + != member["local_label"] |
| 193 | + ): |
| 194 | + return JSONResponse( |
| 195 | + status_code=409, content={"error": "Transcript changed since scan"} |
| 196 | + ) |
| 197 | + validated_segments.append((member, ref, index, segments[index])) |
| 198 | + |
| 199 | + annotations = 0 |
| 200 | + for member, ref, index, segment in validated_segments: |
| 201 | + await Annotation( |
| 202 | + annotation_type=AnnotationType.DIARIZATION, |
| 203 | + user_id=str(user.user_id), |
| 204 | + conversation_id=member["conversation_id"], |
| 205 | + segment_index=index, |
| 206 | + original_speaker=segment.get("speaker") or "", |
| 207 | + corrected_speaker=speaker_name, |
| 208 | + segment_start_time=ref["start"], |
| 209 | + processed=False, |
| 210 | + ).insert() |
| 211 | + annotations += 1 |
| 212 | + |
| 213 | + client = SpeakerRecognitionClient() |
| 214 | + existing_speaker = await client.get_speaker_by_name( |
| 215 | + speaker_name, user_id=str(user.user_id) |
| 216 | + ) |
| 217 | + enrolled = appended = 0 |
| 218 | + for clip in enrollment_clips: |
| 219 | + member = accepted.get(clip.get("identity_key")) |
| 220 | + if not member: |
| 221 | + continue |
| 222 | + ref = next( |
| 223 | + ( |
| 224 | + segment |
| 225 | + for segment in member["segments"] |
| 226 | + if segment["segment_index"] == clip.get("segment_index") |
| 227 | + ), |
| 228 | + None, |
| 229 | + ) |
| 230 | + if not ref or ref["duration"] < MIN_CLIP_SECONDS: |
| 231 | + continue |
| 232 | + wav = await reconstruct_audio_segment( |
| 233 | + member["conversation_id"], ref["start"], ref["end"] |
| 234 | + ) |
| 235 | + if existing_speaker: |
| 236 | + result = await client.append_to_speaker( |
| 237 | + existing_speaker["id"], wav, user_id=str(user.user_id) |
| 238 | + ) |
| 239 | + if not result.get("error"): |
| 240 | + appended += 1 |
| 241 | + else: |
| 242 | + result = await client.enroll_new_speaker( |
| 243 | + speaker_name, wav, user_id=str(user.user_id) |
| 244 | + ) |
| 245 | + if not result.get("error"): |
| 246 | + enrolled += 1 |
| 247 | + existing_speaker = await client.get_speaker_by_name( |
| 248 | + speaker_name, user_id=str(user.user_id) |
| 249 | + ) |
| 250 | + |
| 251 | + await collection.update_one( |
| 252 | + {"_id": cluster["_id"]}, |
| 253 | + { |
| 254 | + "$set": { |
| 255 | + "status": "confirmed", |
| 256 | + "speaker_name": speaker_name, |
| 257 | + "accepted_identity_keys": list(accepted), |
| 258 | + "decided_at": datetime.now(timezone.utc), |
| 259 | + } |
| 260 | + }, |
| 261 | + ) |
| 262 | + apply_result = await data_audit_controller.apply_triage(user) |
| 263 | + return { |
| 264 | + "status": "confirmed", |
| 265 | + "annotations_created": annotations, |
| 266 | + "enrolled_new": enrolled, |
| 267 | + "appended": appended, |
| 268 | + "corrections_applied": getattr(apply_result, "body", apply_result), |
| 269 | + } |
| 270 | + |
| 271 | + |
77 | 272 | def _job_status(job_id: Optional[str]) -> Optional[str]: |
78 | 273 | if not job_id: |
79 | 274 | return None |
|
0 commit comments