forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipeline.py
More file actions
2537 lines (2313 loc) · 106 KB
/
Copy pathpipeline.py
File metadata and controls
2537 lines (2313 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Sync local-files pipeline: decode → VAD → fair-use → STT → conversation merge.
Extracted from routers/sync.py so the router stays thin and utils never imports routers.
"""
# pyright: reportPrivateUsage=false, reportUnusedFunction=false, reportUnusedVariable=false, reportUnusedImport=false, reportUnnecessaryComparison=false, reportAssignmentType=false, reportIndexIssue=false, reportArgumentType=false
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import io
import logging
import os
import shutil
import threading
import time
import wave
from collections import deque
from datetime import datetime, timezone
from typing import Callable, Dict, Iterable, List, Optional, Tuple
import httpx
import numpy as np
from fastapi import HTTPException, UploadFile
from pydub import AudioSegment
from database import conversations as conversations_db
from database import users as users_db
from database.conversations import get_closest_conversation_to_timestamps, update_conversation_segments
from database.firestore_read_metrics import FirestoreReadSite
from database.sync_jobs import (
RUN_LOCK_HEARTBEAT_SECONDS,
RUN_LOCK_RENEWAL_SAFETY_SECONDS,
RUN_LOCK_TTL_SECONDS,
FencedSyncJobMutation,
add_processed_segment,
add_processed_segment_if_run_owner,
delete_sync_job_run_lock_epoch,
fenced_finalize_sync_job,
fenced_finalize_sync_job_from_durable_ledger,
fenced_mark_job_failed,
fenced_mark_job_processing,
fenced_update_sync_job,
finalize_sync_job,
get_sync_job_run_lock_epoch,
get_sync_job,
get_processed_segments,
mark_job_failed,
mark_job_processing,
release_job_run_lock,
renew_job_run_lock,
try_mark_once,
update_sync_job,
)
from database.sync_ledger import (
add_processed_sync_segment_id,
bind_sync_content_run_token,
checkpoint_sync_content_partial_result,
get_processed_sync_segment_ids,
get_sync_content_partial_result,
is_valid_completed_sync_content_result,
mark_sync_content_completed,
release_sync_content_claim_after_job_retired,
release_sync_content_claim,
)
from models.conversation import Conversation, CreateConversation
from models.conversation_enums import ConversationSource
from models.geolocation import Geolocation
from models.transcript_segment import TranscriptSegment
from utils.analytics import record_usage
from utils.byok import get_byok_keys, set_byok_keys, set_byok_uid
from utils.conversations.factory import deserialize_conversation
from utils.conversations.location import async_resolve_geolocation
from utils.conversations.process_conversation import process_conversation
from utils.executors import (
db_executor,
postprocess_executor,
run_blocking,
start_background_task,
storage_executor,
submit_with_context,
sync_executor,
)
from utils.fair_use import (
FAIR_USE_ENABLED,
FAIR_USE_RESTRICT_DAILY_DG_MS,
check_soft_caps,
get_enforcement_stage,
get_rolling_speech_ms,
is_dg_budget_exhausted,
record_dg_usage_ms,
record_speech_ms,
trigger_classifier_if_needed,
)
from utils.http_client import _get_semaphore
from utils.cloud_tasks import is_audio_merge_dispatch_enabled
from utils.other.storage import (
compute_audio_files_fingerprint,
delete_syncing_temporal_file,
download_syncing_temporal_file,
enqueue_conversation_artifact_build,
get_syncing_file_temporal_signed_url,
precache_conversation_audio,
schedule_syncing_temporal_file_deletion,
upload_audio_chunk,
upload_syncing_temporal_file,
)
from utils.observability.fallback import record_fallback
from utils.observability.transcription import record_sync_transcription_outcome
from utils.speaker_assignment import process_speaker_assigned_segments
from utils.speaker_identification import detect_speaker_from_text
from utils.stt.pre_recorded import get_prerecorded_service, postprocess_words, prerecorded
from utils.stt.outcomes import (
TranscriptionFailure,
TranscriptionOutcome,
bounded_provider,
failure_from_exception,
)
from utils.stt.speaker_embedding import compare_embeddings, extract_embedding_from_bytes
from utils.stt.speaker_match import select_speaker_match
from utils.stt.vad import vad_is_empty
from utils.sync.files import decode_files_to_wav, get_timestamp_from_path, get_wav_duration
from utils.sync.backfill import release_backfill_slot, reserve_backfill_speech
from utils.sync.content_id import compute_sync_segment_id
from utils.sync.lanes import SyncLane
from utils.sync.telemetry import bounded_exception_type as _bounded_exception_type
from utils.sync.telemetry import bounded_sync_lane as _bounded_sync_lane
from utils.sync.telemetry import bounded_sync_model as _bounded_sync_model
from utils.sync.merge_audio import store_partial_merge_survivor_audio
from utils.sync.merge_dedupe import dedupe_segments_for_merge
from utils.metrics import OMI_SYNC_BACKFILL_DAILY_USED_MS, OMI_SYNC_LANE_SPEECH_MS_TOTAL
logger = logging.getLogger(__name__)
MAX_VAD_SEGMENT_SECONDS = int(os.getenv('SYNC_MAX_VAD_SEGMENT_SECONDS', '300'))
# Valid terminal segment results — a transcript, or audio with no speech. All else is a failure.
_NON_ERROR_SEGMENT_OUTCOMES = frozenset({TranscriptionOutcome.SUCCESS, TranscriptionOutcome.EXPECTED_SILENCE})
_PARTIAL_RESULT_FENCED_CONVERSATION_IDS = 'fenced_conversation_ids'
_RESPONSE_FENCED_CONVERSATION_IDS = '_fenced_conversation_ids'
_SYNC_FAILURE_REASON_CODES = {
'backfill_capacity',
'backfill_paced',
'stt_empty_unexpected',
'stt_invalid_input',
'stt_provider_configuration_error',
'stt_timeout',
'stt_upstream_error',
'sync_backfill_dispatch_unavailable',
'sync_backfill_paced',
'sync_conversation_persistence_fenced',
'sync_dispatch_staging_failed',
'sync_decode_failed',
'sync_invalid_audio',
'sync_staged_audio_expired',
'sync_transcription_budget_exhausted',
'sync_vad_failed',
'sync_worker_stale',
}
async def _resolve_fair_use_soft_cap_plan(uid: str):
"""Return the stored plan, falling back to the default soft-cap tier on read failure."""
try:
fair_use_sub = await run_blocking(db_executor, users_db.get_existing_user_subscription, uid)
return fair_use_sub.plan if fair_use_sub else None
except Exception as e:
logger.warning(
'event=sync_fair_use outcome=subscription_plan_fallback exception_type=%s',
_bounded_exception_type(e),
)
record_fallback(
component='other',
from_mode='subscription_plan',
to_mode='default_cap',
reason='policy',
outcome='degraded',
log=logger,
)
return None
def _bounded_sync_failure_reason(reason: str | None) -> str:
return reason if reason in _SYNC_FAILURE_REASON_CODES else 'other'
def _record_sync_segment_outcome(
outcome: TranscriptionOutcome,
*,
provider: str,
model: str,
lane: str,
retryable: bool,
job_id: str | None = None,
segment_key: str | None = None,
) -> None:
"""Emit one fixed-shape event without audio, transcript, or user identity."""
if isinstance(job_id, str) and isinstance(segment_key, str):
metric_tag = f'segment_outcome:{hashlib.sha256(segment_key.encode()).hexdigest()[:24]}'
try:
if not try_mark_once(job_id, metric_tag):
return
except Exception:
# Observability cannot prevent a durable segment checkpoint from
# completing. A later retry may duplicate this metric, but not the
# customer-visible transcription result.
logger.warning('event=sync_transcription_metric outcome=dedupe_failed kind=segment')
log = logger.info if outcome in _NON_ERROR_SEGMENT_OUTCOMES else logger.error
log(
'event=sync_transcription_segment outcome=%s provider=%s model=%s lane=%s retryable=%s',
outcome.value,
bounded_provider(provider),
_bounded_sync_model(model),
_bounded_sync_lane(lane),
str(retryable).lower(),
)
try:
record_sync_transcription_outcome(
kind='segment',
provider=provider,
model=model,
lane=lane,
outcome=outcome,
)
except Exception:
logger.warning('event=sync_transcription_metric outcome=emit_failed kind=segment')
def _record_sync_segment_failure(
failure: TranscriptionFailure,
*,
model: str,
lane: str,
lock: threading.Lock,
errors: list,
record_metric: bool = True,
job_id: str | None = None,
segment_key: str | None = None,
) -> None:
if record_metric:
_record_sync_segment_outcome(
failure.outcome,
provider=failure.provider,
model=model,
lane=lane,
retryable=failure.retryable,
job_id=job_id,
segment_key=segment_key,
)
with lock:
errors.append(failure.error_code)
def _record_empty_segment_as_silence(
*,
provider: str,
model: str,
lane: str,
deferred_outcome: dict | None,
) -> None:
"""Record a speech-free segment as a valid empty result, not a failure.
Records the outcome exactly as the success path does but appends nothing to
the job's error list, so a job whose every segment is speech-free finalizes
completed rather than failed and the client stops re-uploading it.
"""
_set_deferred_segment_outcome(
deferred_outcome,
outcome=TranscriptionOutcome.EXPECTED_SILENCE,
provider=provider,
model=model,
retryable=False,
)
if deferred_outcome is None:
_record_sync_segment_outcome(
TranscriptionOutcome.EXPECTED_SILENCE,
provider=provider,
model=model,
lane=lane,
retryable=False,
)
def _set_deferred_segment_outcome(
deferred_outcome: dict | None,
*,
outcome: TranscriptionOutcome,
provider: str,
model: str,
retryable: bool,
) -> None:
"""Keep v2 outcome data local until its durable checkpoint commits."""
if deferred_outcome is not None:
deferred_outcome.update(
outcome=outcome,
provider=provider,
model=model,
retryable=retryable,
)
def _deferred_segment_labels(
deferred_outcome: dict,
*,
fallback_outcome: TranscriptionOutcome,
fallback_provider: str,
fallback_model: str,
fallback_retryable: bool,
) -> tuple[TranscriptionOutcome, str, str, bool]:
"""Read locally deferred values without widening telemetry labels."""
outcome = deferred_outcome.get('outcome')
provider = deferred_outcome.get('provider')
model = deferred_outcome.get('model')
retryable = deferred_outcome.get('retryable')
return (
outcome if isinstance(outcome, TranscriptionOutcome) else fallback_outcome,
provider if isinstance(provider, str) else fallback_provider,
model if isinstance(model, str) else fallback_model,
retryable if isinstance(retryable, bool) else fallback_retryable,
)
_SYNC_ERROR_CODE_OUTCOMES = {
'stt_provider_configuration_error': TranscriptionOutcome.CONFIG_ERROR,
'stt_timeout': TranscriptionOutcome.TIMEOUT,
'stt_upstream_error': TranscriptionOutcome.UPSTREAM_ERROR,
'stt_empty_unexpected': TranscriptionOutcome.EMPTY_UNEXPECTED,
'stt_invalid_input': TranscriptionOutcome.INVALID_INPUT,
}
def _job_transcription_outcome(segment_errors: list[str]) -> TranscriptionOutcome:
if not segment_errors:
return TranscriptionOutcome.SUCCESS
present = set(segment_errors)
for error_code, outcome in _SYNC_ERROR_CODE_OUTCOMES.items():
if error_code in present:
return outcome
return TranscriptionOutcome.UPSTREAM_ERROR
def _record_sync_job_outcome(
outcome: TranscriptionOutcome,
*,
provider: str,
model: str,
lane: str,
job_id: str | None = None,
) -> None:
if isinstance(job_id, str):
try:
if not try_mark_once(job_id, 'terminal_outcome_metric'):
return
except Exception:
logger.warning('event=sync_transcription_metric outcome=dedupe_failed kind=job')
try:
record_sync_transcription_outcome(
kind='job',
provider=provider,
model=model,
lane=lane,
outcome=outcome,
)
except Exception:
logger.warning('event=sync_transcription_metric outcome=emit_failed kind=job')
async def _record_sync_job_outcome_async(
outcome: TranscriptionOutcome,
*,
provider: str,
model: str,
lane: str,
job_id: str | None = None,
) -> None:
"""Keep Redis-backed job metric dedupe off the pipeline coordinator loop."""
try:
await run_blocking(
db_executor,
_record_sync_job_outcome,
outcome,
provider=provider,
model=model,
lane=lane,
job_id=job_id,
)
except Exception:
# Telemetry must not turn a durably finalized transcription into a
# failed/retryable job when the DB executor is unavailable.
logger.warning('event=sync_transcription_metric outcome=offload_failed kind=job')
async def _record_sync_segment_failure_async(
failure: TranscriptionFailure,
*,
model: str,
lane: str,
lock: threading.Lock,
errors: list,
job_id: str | None = None,
segment_key: str | None = None,
) -> None:
"""Record a coordinator-observed segment failure without blocking the loop."""
try:
await run_blocking(
db_executor,
_record_sync_segment_outcome,
failure.outcome,
provider=failure.provider,
model=model,
lane=lane,
retryable=failure.retryable,
job_id=job_id,
segment_key=segment_key,
)
except Exception:
# Preserve the retryable failure even when best-effort metric delivery
# cannot obtain a DB executor slot.
logger.warning('event=sync_transcription_metric outcome=offload_failed kind=segment')
with lock:
errors.append(failure.error_code)
class SyncJobRunLeaseLost(RuntimeError):
"""A worker tried to write after its run token stopped owning the job."""
class SyncConversationPersistenceFenced(RuntimeError):
"""Conversation lifecycle rejected this worker's stale processing result."""
def _require_current_conversation_persistence(persisted: bool) -> None:
"""Turn a lifecycle fence into the worker's terminal supersession signal."""
if not persisted:
raise SyncConversationPersistenceFenced('sync conversation persistence fenced')
def _raise_sync_terminal_result(result: object) -> None:
"""Preserve lifecycle fences across ``asyncio.gather`` exception fan-in."""
if isinstance(result, SyncConversationPersistenceFenced):
raise result
def _require_run_owner(mutation: FencedSyncJobMutation, *, job_id: str) -> Dict | None:
"""Turn a non-applied Redis CAS result into the worker's stop signal."""
if mutation.applied:
return mutation.job
raise SyncJobRunLeaseLost(f'sync job run lease lost: job={job_id} outcome={mutation.outcome.value}')
def _update_sync_job_for_run(job_id: str, run_lock_token: str | None, updates: Dict) -> Dict | None:
if run_lock_token is None:
# During the mixed-revision compatibility phase, the raw-CAS helper
# returns None when another worker already reached a terminal state.
# Treat that exactly like a lost fenced lease: a late worker must stop
# before it can release retry material or publish more side effects.
updated = update_sync_job(job_id, updates)
if updated is None:
raise SyncJobRunLeaseLost(f'sync job legacy state is no longer mutable: job={job_id}')
return updated
return _require_run_owner(
fenced_update_sync_job(
job_id,
run_lock_token,
updates,
allowed_current_statuses={'processing'},
),
job_id=job_id,
)
def _mark_job_processing_for_run(job_id: str, run_lock_token: str | None) -> Dict | None:
if run_lock_token is None:
updated = mark_job_processing(job_id)
if updated is None:
raise SyncJobRunLeaseLost(f'sync job legacy state is no longer mutable: job={job_id}')
return updated
return _require_run_owner(fenced_mark_job_processing(job_id, run_lock_token), job_id=job_id)
def _finalize_sync_job_for_run(job_id: str, run_lock_token: str | None, result: Dict) -> Dict | None:
if run_lock_token is None:
finalized = finalize_sync_job(job_id, result)
if finalized is None:
raise SyncJobRunLeaseLost(f'sync job legacy state is no longer mutable: job={job_id}')
return finalized
return _require_run_owner(fenced_finalize_sync_job(job_id, run_lock_token, result), job_id=job_id)
def _mark_job_failed_for_run(
job_id: str,
run_lock_token: str | None,
error: str,
*,
reason_code: str | None = None,
retry_after: int | None = None,
) -> Dict | None:
if run_lock_token is None:
failed = mark_job_failed(job_id, error, reason_code=reason_code, retry_after=retry_after)
if failed is None:
raise SyncJobRunLeaseLost(f'sync job legacy state is no longer mutable: job={job_id}')
return failed
return _require_run_owner(
fenced_mark_job_failed(
job_id,
run_lock_token,
error,
reason_code=reason_code,
retry_after=retry_after,
),
job_id=job_id,
)
def _add_processed_segment_for_run(job_id: str, run_lock_token: str | None, segment_path: str) -> None:
if run_lock_token is None:
add_processed_segment(job_id, segment_path)
return
_require_run_owner(add_processed_segment_if_run_owner(job_id, run_lock_token, segment_path), job_id=job_id)
def bind_or_converge_sync_ledger_completion(
*,
job_id: str,
uid: str,
content_id: str | None,
run_lock_token: str | None,
) -> Dict | None:
"""Bind a live lease to the durable ledger or converge a proven completion.
This synchronous DB-boundary helper is shared by Cloud Tasks, inline work,
and stale polling. A higher epoch displaces an old owner before any decode,
provider, ledger mutation, or stale failure can occur. A valid completion
that landed just before lease replacement becomes the current Redis result
through the caller's *current* fenced token rather than being overwritten
as a failure.
"""
if not content_id or run_lock_token is None:
return None
binding = bind_sync_content_run_token(
uid,
content_id,
job_id,
run_lock_token,
get_sync_job_run_lock_epoch(run_lock_token),
)
if binding.bound:
return None
if not binding.completed or not is_valid_completed_sync_content_result(binding.result):
raise SyncJobRunLeaseLost(f'sync content ledger owner lost: job={job_id}')
finalized = _require_run_owner(
fenced_finalize_sync_job_from_durable_ledger(job_id, run_lock_token, binding.result), job_id=job_id
)
delete_sync_job_run_lock_epoch(job_id)
return finalized
async def finalize_sync_job_superseded(
*,
job_id: str,
run_lock_token: str | None,
lane: str,
provider: str,
model: str,
) -> None:
"""Acknowledge a stale conversation processor without inviting a WAL retry.
A lifecycle fence means another generation owns the conversation, not that
audio decoding or the Cloud Task failed. The released clients only
acknowledge ``completed`` sync jobs, so publish a zero-segment completed
result with an explicit bounded ``superseded`` outcome rather than a
retryable failure status.
"""
finalized = await run_blocking(
db_executor,
_finalize_sync_job_for_run,
job_id,
run_lock_token,
{
'failed_segments': 0,
'total_segments': 0,
'errors': [],
'outcome': 'superseded',
'provider': provider,
'model': model,
'lane': lane,
},
)
if finalized is None:
raise SyncJobRunLeaseLost(f'sync job state is no longer mutable: job={job_id} outcome=superseded')
async def _finalize_sync_job_failure(
*,
job_id: str,
uid: str,
content_id: str | None,
error_code: str,
outcome: TranscriptionOutcome,
provider: str,
model: str,
lane: str,
reason_code: str | None = None,
retry_after: int | None = None,
run_lock_token: str | None = None,
) -> None:
"""Offload the atomic failure publication boundary to the DB executor."""
finalized = await run_blocking(
db_executor,
finalize_sync_job_failure_now,
job_id=job_id,
uid=uid,
content_id=content_id,
error_code=error_code,
outcome=outcome,
provider=provider,
model=model,
lane=lane,
reason_code=reason_code,
retry_after=retry_after,
run_lock_token=run_lock_token,
)
if finalized is None:
# The epoch-fenced path lost its lease; the compatibility path saw an
# already-terminal raw-CAS state. Both mean this worker no longer owns
# the authority to release retry material or publish a second result.
raise SyncJobRunLeaseLost(f'sync job state is no longer mutable: job={job_id} outcome=terminal_failure')
def finalize_sync_job_failure_now(
*,
job_id: str,
uid: str,
content_id: str | None,
error_code: str,
outcome: TranscriptionOutcome,
provider: str,
model: str,
lane: str,
reason_code: str | None = None,
retry_after: int | None = None,
run_lock_token: str | None = None,
) -> Optional[Dict]:
"""Publish one truthful failure and then make its retry claim available.
This synchronous boundary is shared by async workers and the polling stale
reaper. A run-token owner fences the Redis terminal transition first; only
that winning owner may release the durable retry claim afterward.
"""
if run_lock_token is None:
finalized = mark_job_failed(
job_id,
error_code,
reason_code=reason_code or error_code,
retry_after=retry_after,
)
else:
try:
finalized = _mark_job_failed_for_run(
job_id,
run_lock_token,
error_code,
reason_code=reason_code or error_code,
retry_after=retry_after,
)
except SyncJobRunLeaseLost:
return None
if finalized is None:
return None
if content_id:
if run_lock_token is None:
# The pre-cutover protocol has no epoch binding. Keep all ledger
# operations tokenless while legacy revisions may still exist.
release_sync_content_claim(uid, content_id, job_id)
else:
# The fenced Redis terminal transition already succeeded. A lease
# can expire between that CAS and Firestore release, so use the
# deliberately retired-job transaction rather than treating this
# as a live write.
release_sync_content_claim_after_job_retired(uid, content_id, job_id)
if run_lock_token is not None:
delete_sync_job_run_lock_epoch(job_id)
logger.error(
'event=sync_transcription_job outcome=%s status=failed provider=%s model=%s lane=%s reason_code=%s',
outcome.value,
bounded_provider(provider),
_bounded_sync_model(model),
_bounded_sync_lane(lane),
_bounded_sync_failure_reason(reason_code or error_code),
)
_record_sync_job_outcome(outcome, provider=provider, model=model, lane=lane, job_id=job_id)
return finalized
def _merge_and_cap_vad_segments(voice_segments: list) -> list:
merged = []
for segment in voice_segments:
if (
merged
and (segment['start'] - merged[-1]['end']) < 120
and (segment['end'] - merged[-1]['start']) <= MAX_VAD_SEGMENT_SECONDS
):
merged[-1]['end'] = segment['end']
else:
merged.append(dict(segment))
segments = []
for segment in merged:
if segment['end'] - segment['start'] <= MAX_VAD_SEGMENT_SECONDS:
segments.append(segment)
else:
chunk_start = segment['start']
while chunk_start < segment['end']:
chunk_end = min(chunk_start + MAX_VAD_SEGMENT_SECONDS, segment['end'])
segments.append({'start': chunk_start, 'end': chunk_end})
chunk_start = chunk_end
return segments
def retrieve_vad_segments(path: str, segmented_paths: set, errors: list = None):
try:
start_timestamp = get_timestamp_from_path(path)
voice_segments = vad_is_empty(path, return_segments=True, cache=True)
except Exception as e:
error_code = 'sync_vad_failed'
logger.error(
'event=sync_vad outcome=upstream_error exception_type=%s',
_bounded_exception_type(e),
)
if errors is not None:
errors.append(error_code)
raise # Re-raise to ensure thread failure is visible
segments = _merge_and_cap_vad_segments(voice_segments)
logger.info('event=sync_vad outcome=success segment_count=%d', len(segments))
aseg = AudioSegment.from_wav(path)
path_dir = '/'.join(path.split('/')[:-1])
try:
for i, segment in enumerate(segments):
if (segment['end'] - segment['start']) < 1:
continue
segment_timestamp = start_timestamp + segment['start']
segment_path = f'{path_dir}/{segment_timestamp}.wav'
segment_aseg = aseg[segment['start'] * 1000 : segment['end'] * 1000]
segment_aseg.export(segment_path, format='wav')
segmented_paths.add(segment_path)
# Explicitly delete segment to free memory immediately
del segment_aseg
finally:
# Explicitly delete main audio to free memory
del aseg
def _run_conversation_created_webhook(uid: str, conversation: Conversation) -> None:
"""Load the webhook surface only in the post-processing worker that uses it."""
from utils.webhooks import conversation_created_webhook
asyncio.run(conversation_created_webhook(uid, conversation))
def _reprocess_conversation_after_update(uid: str, conversation_id: str, language: str):
"""
Reprocess a conversation after new segments have been added.
This checks if the conversation should still be discarded and regenerates
the summary/structured data if it now has sufficient content.
"""
# Fetch the updated conversation with all segments
conversation_data = conversations_db.get_conversation(uid, conversation_id)
if not conversation_data:
logger.warning(f'Conversation {conversation_id} not found for reprocessing')
return
# Convert to Conversation object
conversation = deserialize_conversation(conversation_data)
was_discarded = conversation.discarded
processed_conversation = process_conversation(
uid=uid,
language_code=language or 'en',
conversation=conversation,
force_process=True,
is_reprocess=True,
bypass_jit_first_open=True,
persistence_observer=_require_current_conversation_persistence,
)
# Limitless uploads commonly begin as a short discarded fragment and only
# become a real conversation after later WAL segments are merged. The
# initial discarded pass is not a useful creation event, while the generic
# reprocess path deliberately suppresses webhooks. Emit exactly at the
# discarded -> visible transition so pendant conversations reach developer
# integrations without duplicating events on ordinary later reprocessing.
if conversation.source == ConversationSource.limitless and was_discarded and not processed_conversation.discarded:
submit_with_context(postprocess_executor, _run_conversation_created_webhook, uid, processed_conversation)
logger.info(f'Successfully reprocessed conversation {conversation_id}')
USER_SELF_PERSON_ID = 'user'
SPEAKER_ID_MIN_AUDIO = 1.0 # Minimum seconds of audio per speaker for embedding extraction
def build_person_embeddings_cache(uid: str) -> Dict[str, dict]:
"""Build a cache of person embeddings for speaker identification.
Loads the user's own speaker embedding and all people with stored embeddings.
Returns dict mapping person_id -> {embedding: np.ndarray, name: str}.
"""
cache: Dict[str, dict] = {}
# Load user's own speaker embedding
embedding_list = users_db.get_user_speaker_embedding(uid)
if embedding_list:
user_embedding = np.array(embedding_list, dtype=np.float32).reshape(1, -1)
cache[USER_SELF_PERSON_ID] = {'embedding': user_embedding, 'name': 'User'}
# Load all people with speaker embeddings
people = users_db.get_people(uid)
for person in people or []:
emb = person.get('speaker_embedding')
# Only load embedding if person has speech samples — contacts without
# samples may have stale embeddings from a pre-v3 model (#6238)
if emb and person.get('speech_samples'):
cache[person['id']] = {
'embedding': np.array(emb, dtype=np.float32).reshape(1, -1),
'name': person['name'],
}
return cache
def _download_audio_bytes(url: str) -> Optional[bytes]:
"""Download audio from a signed URL. Returns WAV bytes or None on failure."""
try:
resp = httpx.get(url, timeout=60.0)
resp.raise_for_status()
return resp.content
except Exception as e:
logger.warning(f'Speaker ID: failed to download audio: {e}')
return None
def _extract_speaker_clip_wav(audio_bytes: bytes, start_sec: float, end_sec: float) -> Optional[bytes]:
"""Extract a clip from WAV audio bytes between start_sec and end_sec.
Returns WAV bytes for the clip, or None if extraction fails or clip is too short.
"""
try:
with wave.open(io.BytesIO(audio_bytes), 'rb') as wf:
framerate = wf.getframerate()
n_channels = wf.getnchannels()
sampwidth = wf.getsampwidth()
n_frames = wf.getnframes()
total_duration = n_frames / framerate
# Clamp to audio bounds
start_sec = max(0.0, start_sec)
end_sec = min(total_duration, end_sec)
if end_sec - start_sec < SPEAKER_ID_MIN_AUDIO:
return None
# Cap extraction at 10 seconds
if end_sec - start_sec > 10.0:
center = (start_sec + end_sec) / 2
start_sec = center - 5.0
end_sec = center + 5.0
start_sec = max(0.0, start_sec)
end_sec = min(total_duration, end_sec)
start_frame = int(start_sec * framerate)
end_frame = int(end_sec * framerate)
wf.setpos(start_frame)
frames = wf.readframes(end_frame - start_frame)
# Write clip as WAV
clip_buf = io.BytesIO()
with wave.open(clip_buf, 'wb') as out_wf:
out_wf.setnchannels(n_channels)
out_wf.setsampwidth(sampwidth)
out_wf.setframerate(framerate)
out_wf.writeframes(frames)
return clip_buf.getvalue()
except Exception as e:
logger.warning(f'Speaker ID: failed to extract clip: {e}')
return None
def identify_speakers_for_segments(
transcript_segments: List['TranscriptSegment'],
audio_bytes: Optional[bytes],
person_embeddings_cache: Dict[str, dict],
uid: str,
) -> None:
"""Identify speakers in transcript segments using voice embeddings and text detection.
Modifies segments in-place by assigning person_id and is_user fields.
Steps:
1. Voice embedding matching (requires audio_bytes and non-empty cache):
For each unique speaker_id, find the longest segment (>=1s), extract audio clip,
get embedding, match against person_embeddings_cache.
2. Text-based detection ("I am X") runs independently for all unmatched speakers.
3. Apply assignments via process_speaker_assigned_segments.
"""
speaker_to_person_map: Dict[int, Tuple[str, str]] = {}
segment_person_assignment_map: Dict[str, str] = {}
# Group segments by speaker_id, find best (longest) segment per speaker for embedding
speaker_segments: Dict[int, List[TranscriptSegment]] = {}
for seg in transcript_segments:
sid = seg.speaker_id if seg.speaker_id is not None else 0
speaker_segments.setdefault(sid, []).append(seg)
# Voice embedding matching (only when audio and cached embeddings are available)
# Track matched person_ids so each person is only assigned to one speaker
# (diarization tells us speakers are distinct — no person can be two speakers).
matched_person_ids: set = set()
if audio_bytes and person_embeddings_cache:
# Sort speakers by best single segment duration (longest first) — this is the clip
# actually used for embedding, so it determines match quality.
# Note: matched_person_ids assumes diarization is correct (one person = one speaker).
# If diarization fragments one person across speaker IDs, only the best match wins.
sorted_speakers = sorted(
speaker_segments.items(),
key=lambda kv: max(s.end - s.start for s in kv[1]),
reverse=True,
)
for speaker_id, segments in sorted_speakers:
best_seg = max(segments, key=lambda s: s.end - s.start)
seg_duration = best_seg.end - best_seg.start
if seg_duration < SPEAKER_ID_MIN_AUDIO:
continue
clip_wav = _extract_speaker_clip_wav(audio_bytes, best_seg.start, best_seg.end)
if not clip_wav:
continue
try:
query_embedding = extract_embedding_from_bytes(clip_wav, "sync_speaker.wav")
except (ValueError, Exception) as e:
logger.info(f'Speaker ID: embedding extraction failed for speaker {speaker_id}: {e} uid={uid}')
continue
# Keep assigned candidates in the ambiguity comparison. Removing the
# owner after a first match must not make a similar household voice
# look unambiguous; apply one-person/one-speaker dedup only afterward.
distances = {
person_id: compare_embeddings(query_embedding, data['embedding'])
for person_id, data in person_embeddings_cache.items()
}
decision = select_speaker_match(distances)
accepted = decision.person_id is not None and decision.person_id not in matched_person_ids
logger.info(
'speaker_id_decision surface=sync uid=%s speaker=%s clip_seconds=%.1f '
'best=%s best_distance=%.3f runner_up_distance=%.3f accepted=%s',
uid,
speaker_id,
seg_duration,
decision.best_id,
decision.best_distance,
decision.runner_up_distance,
accepted,
)
if accepted and decision.person_id is not None:
person_id = decision.person_id
speaker_to_person_map[speaker_id] = (person_id, person_embeddings_cache[person_id]['name'])
segment_person_assignment_map[best_seg.id] = person_id
matched_person_ids.add(person_id)
# Text-based detection runs independently for all unmatched speakers.
# For speaker_id > 0 (diarized): update both speaker_to_person_map and per-segment map.
# For speaker_id <= 0 (undiarized): only assign per-segment (avoid mapping all speaker_id=0
# segments to one person when diarization is inactive).
for speaker_id, segments in speaker_segments.items():
if speaker_id in speaker_to_person_map:
continue
for seg in segments:
detected_name = detect_speaker_from_text(seg.text)
if detected_name:
person = users_db.get_person_by_name(uid, detected_name)
if person:
# Per-segment assignment always applies
segment_person_assignment_map[seg.id] = person['id']
# Update speaker map only when diarization is active
if speaker_id > 0:
speaker_to_person_map[speaker_id] = (person['id'], person['name'])
logger.info(
f'Speaker ID (sync): text detection speaker {speaker_id} -> '
f'{person["id"]} via "{detected_name}" uid={uid}'
)