1use std::{
4 collections::{BTreeSet, HashMap, HashSet},
5 sync::Arc,
6};
7
8use anyhow::{Context, ensure};
9use chrono::{DateTime, Utc};
10use kcode_speaker_extract::ExtractionOutcome;
11use kcode_speaker_system::{Cohort, IdentifyEvidence, SpeechClassifier, TrainOutcome};
12pub use kcode_speaker_system::{FeatureRow, ObservationKey};
13use serde::{Deserialize, Serialize};
14use uuid::Uuid;
15
16pub const CLASSIFIER_PROVIDER: &str = "google";
18pub const CLASSIFIER_MODEL: &str = "gemini-3.1-pro-preview";
20pub const CLASSIFIER_PROMPT_VERSION: &str = "gemini-speaker-24-freeform/1";
22pub const CLASSIFIER_SCHEMA_VERSION: &str = "gemini-speaker-24-normalized/1";
24
25const READ_ONLY_IDENTIFY_THRESHOLD: f64 = 1e308;
26
27#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
29#[serde(deny_unknown_fields)]
30pub struct ParsedUtterance {
31 pub speaker: String,
33 pub language: String,
35 pub original_text: String,
37 pub english_translation: String,
39 pub corrected_natural_text: Option<String>,
41 pub coaching: Vec<String>,
43 pub annotations: Vec<String>,
45}
46
47#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
49#[serde(deny_unknown_fields)]
50pub struct ParsedSpeaker {
51 pub local_label: String,
53 pub primary_language: Option<String>,
55 pub feature_row: Option<FeatureRow>,
57}
58
59#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
61#[serde(deny_unknown_fields)]
62pub struct ParsedChunk {
63 pub utterances: Vec<ParsedUtterance>,
65 pub notes: Vec<String>,
67 pub clip_valid: bool,
69 pub clip_validity_reason: Option<String>,
71 pub speakers: Vec<ParsedSpeaker>,
73}
74
75#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
77pub struct CandidateMapping {
78 pub full_name: String,
80 pub cost: f64,
82 pub confidence: f64,
84 pub runner_up_full_name: Option<String>,
86 pub runner_up_cost: Option<f64>,
88 pub background_population_cost: f64,
90}
91
92#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
94pub struct CorrectionObservation {
95 pub local_label: String,
97 pub speaker_ordinal: u32,
99 pub observation_key: ObservationKey,
101 pub candidate: Option<CandidateMapping>,
103 pub identified_full_name: Option<String>,
105 pub confirmed_full_name: Option<String>,
107}
108
109#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
111pub struct CorrectionChunk {
112 pub chunk_index: usize,
114 pub chunk_count: usize,
116 pub audio_start_ms: u64,
118 pub audio_end_ms: u64,
120 pub raw_gemini_response: String,
122 pub parsed: ParsedChunk,
124 pub observations: Vec<CorrectionObservation>,
126 pub clean: bool,
128}
129
130#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
132#[serde(rename_all = "snake_case")]
133pub enum ConfirmationState {
134 Unconfirmed,
136 AutomaticallyTrained,
138 Confirmed,
140}
141
142#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
144pub struct CorrectionPacket {
145 pub recording_id: Uuid,
147 pub user_id: String,
149 pub sha256: String,
151 pub original_filename: String,
153 pub size_bytes: u64,
155 pub recorded_at: DateTime<Utc>,
157 pub clean: bool,
159 pub chunk_count: usize,
161 pub chunks: Vec<CorrectionChunk>,
163 pub confirmation_state: ConfirmationState,
165}
166
167#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
169pub struct ObservationConfirmation {
170 pub observation_key: ObservationKey,
172 pub confirmed_full_name: String,
174}
175
176#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
178pub struct RecordingConfirmation {
179 pub recording_id: Uuid,
181 pub observations: Vec<ObservationConfirmation>,
183}
184
185#[derive(Clone)]
186pub(crate) struct ClassificationContext {
187 pub(crate) recording_id: Uuid,
188 pub(crate) user_id: String,
189 pub(crate) sha256: String,
190 pub(crate) original_filename: String,
191 pub(crate) size_bytes: u64,
192 pub(crate) recorded_at: DateTime<Utc>,
193 pub(crate) classifier: Arc<SpeechClassifier>,
194}
195
196#[derive(Deserialize)]
197#[serde(deny_unknown_fields)]
198struct TranscriptChunk {
199 utterances: Vec<ParsedUtterance>,
200 notes: Vec<String>,
201 speakers: Vec<TranscriptSpeaker>,
202}
203
204#[derive(Deserialize)]
205#[serde(deny_unknown_fields)]
206struct TranscriptSpeaker {
207 local_label: String,
208 speaker_ordinal: u16,
209}
210
211pub(crate) fn parse_and_validate_chunk(
212 response: &str,
213 extraction: &ExtractionOutcome,
214 chunk_duration_seconds: f64,
215) -> anyhow::Result<ParsedChunk> {
216 ensure!(
217 !response.trim().is_empty(),
218 "GPT parser returned an empty response"
219 );
220 let transcript: TranscriptChunk = serde_json::from_str(response)
221 .context("GPT parser response is not one valid transcript JSON object")?;
222
223 let (profile_count, clip_valid, clip_validity_reason) = match extraction {
224 ExtractionOutcome::Scored(scored) if scored.additional_speakers.is_empty() => {
225 (scored.speakers.len(), true, None)
226 }
227 ExtractionOutcome::Scored(scored) => (
228 scored.speakers.len() + scored.additional_speakers.len(),
229 false,
230 Some("One or more speakers lacked a complete feature profile.".to_owned()),
231 ),
232 ExtractionOutcome::Unscorable {
233 reason,
234 additional_speakers,
235 } => (additional_speakers.len(), false, Some(reason.clone())),
236 };
237 ensure!(
238 transcript.speakers.len() == profile_count,
239 "transcript and normalized speaker counts differ"
240 );
241
242 let mut speakers = transcript.speakers;
243 speakers.sort_by_key(|speaker| speaker.speaker_ordinal);
244 ensure!(
245 speakers
246 .iter()
247 .enumerate()
248 .all(|(index, speaker)| usize::from(speaker.speaker_ordinal) == index),
249 "transcript speaker ordinals must be contiguous from zero"
250 );
251 let speakers = speakers
252 .into_iter()
253 .map(|speaker| {
254 let profile = match extraction {
255 ExtractionOutcome::Scored(scored) => scored
256 .speakers
257 .iter()
258 .find(|profile| profile.speaker_ordinal == speaker.speaker_ordinal),
259 ExtractionOutcome::Unscorable { .. } => None,
260 };
261 ParsedSpeaker {
262 local_label: speaker.local_label,
263 primary_language: profile.map(|value| value.primary_language.as_ref().to_owned()),
264 feature_row: profile.map(|value| value.features),
265 }
266 })
267 .collect();
268 let mut parsed = ParsedChunk {
269 utterances: transcript.utterances,
270 notes: transcript.notes,
271 clip_valid,
272 clip_validity_reason,
273 speakers,
274 };
275 validate_parsed_chunk(&mut parsed, chunk_duration_seconds)?;
276 Ok(parsed)
277}
278
279pub(crate) fn validate_parsed_chunk(
280 parsed: &mut ParsedChunk,
281 chunk_duration_seconds: f64,
282) -> anyhow::Result<()> {
283 ensure!(
284 chunk_duration_seconds.is_finite() && chunk_duration_seconds > 0.0,
285 "chunk duration must be finite and positive"
286 );
287 ensure!(
288 parsed.notes.iter().all(|note| !note.trim().is_empty()),
289 "chunk notes must not contain empty entries"
290 );
291 match (parsed.clip_valid, parsed.clip_validity_reason.as_deref()) {
292 (true, None) => {}
293 (false, Some(reason)) if !reason.trim().is_empty() => {}
294 (true, Some(_)) => anyhow::bail!("a valid clip must not carry an invalidity reason"),
295 (false, _) => anyhow::bail!("an invalid clip requires a brief reason"),
296 }
297
298 let mut labels = HashSet::new();
299 for speaker in &parsed.speakers {
300 ensure!(
301 !speaker.local_label.trim().is_empty(),
302 "speaker labels must not be empty"
303 );
304 ensure!(
305 labels.insert(speaker.local_label.clone()),
306 "duplicate speaker label {:?}",
307 speaker.local_label
308 );
309 ensure!(
310 speaker.primary_language.is_some() == speaker.feature_row.is_some(),
311 "speaker language and feature row must be present together"
312 );
313 if let Some(language) = speaker.primary_language.as_deref() {
314 validate_iso_639_3(language)
315 .with_context(|| format!("speaker {} primary language", speaker.local_label))?;
316 }
317 }
318
319 let mut referenced = HashSet::new();
320 for (index, utterance) in parsed.utterances.iter().enumerate() {
321 ensure!(
322 labels.contains(&utterance.speaker),
323 "utterance {index} references unknown speaker {:?}",
324 utterance.speaker
325 );
326 referenced.insert(utterance.speaker.clone());
327 validate_iso_639_3(&utterance.language)
328 .with_context(|| format!("utterance {index} language"))?;
329 ensure!(
330 !utterance.original_text.trim().is_empty(),
331 "utterance {index} original text must not be empty"
332 );
333 if utterance.language == "eng" {
334 ensure!(
335 utterance.english_translation.is_empty(),
336 "English utterance {index} must use an empty translation"
337 );
338 } else {
339 ensure!(
340 !utterance.english_translation.trim().is_empty(),
341 "non-English utterance {index} requires a complete English translation"
342 );
343 }
344 if let Some(corrected) = utterance.corrected_natural_text.as_deref() {
345 ensure!(
346 !corrected.trim().is_empty(),
347 "utterance {index} corrected text must not be empty"
348 );
349 }
350 ensure!(
351 utterance
352 .coaching
353 .iter()
354 .chain(&utterance.annotations)
355 .all(|entry| !entry.trim().is_empty()),
356 "utterance {index} notes must not contain empty entries"
357 );
358 }
359
360 ensure!(
361 parsed
362 .speakers
363 .iter()
364 .all(|speaker| referenced.contains(&speaker.local_label)),
365 "every speaker row must be referenced by at least one utterance"
366 );
367 if parsed.clip_valid {
368 ensure!(
369 !parsed.speakers.is_empty()
370 && parsed
371 .speakers
372 .iter()
373 .all(|speaker| speaker.feature_row.is_some()),
374 "a valid clip must contain complete speaker rows"
375 );
376 }
377 Ok(())
378}
379
380pub(crate) fn classify_speakers(
381 context: &ClassificationContext,
382 chunk_index: usize,
383 parsed: &ParsedChunk,
384) -> anyhow::Result<(Vec<CorrectionObservation>, bool)> {
385 let mut observations = Vec::with_capacity(parsed.speakers.len());
386 for (ordinal, speaker) in parsed.speakers.iter().enumerate() {
387 let (primary_language, feature_row) = match (
388 speaker.primary_language.as_deref(),
389 speaker.feature_row.as_ref(),
390 ) {
391 (Some(language), Some(row)) => (language, row),
392 (None, None) => continue,
393 _ => anyhow::bail!("speaker profile is only partially present"),
394 };
395 let speaker_ordinal = u32::try_from(ordinal)
396 .context("chunk has more speakers than the key schema supports")?;
397 let cohort = cohort(primary_language);
398 let probe_key = ObservationKey {
399 object_id: probe_object_id(context.recording_id, chunk_index),
400 piece_index: speaker_ordinal,
401 };
402 let outcome = context
403 .classifier
404 .identify(
405 probe_key.clone(),
406 cohort,
407 *feature_row,
408 READ_ONLY_IDENTIFY_THRESHOLD,
409 )
410 .with_context(|| {
411 format!(
412 "read-only identity scoring failed for chunk {chunk_index} speaker {}",
413 speaker.local_label
414 )
415 })?;
416 if outcome.speaker_id.is_some() {
417 context
418 .classifier
419 .delete(probe_key)
420 .context("removing an unexpectedly accepted read-only probe")?;
421 }
422 let candidate = outcome.evidence.as_ref().map(candidate_mapping);
423 let identified_full_name = candidate.as_ref().map(|value| value.full_name.clone());
424 observations.push(CorrectionObservation {
425 local_label: speaker.local_label.clone(),
426 speaker_ordinal,
427 observation_key: ObservationKey {
428 object_id: training_object_id(context.recording_id, chunk_index),
429 piece_index: speaker_ordinal,
430 },
431 candidate,
432 identified_full_name,
433 confirmed_full_name: None,
434 });
435 }
436 let clean = chunk_is_clean(parsed.clip_valid, &observations);
437 Ok((observations, clean))
438}
439
440pub(crate) fn unclassified_observations(
441 recording_id: Uuid,
442 chunk_index: usize,
443 parsed: &ParsedChunk,
444) -> anyhow::Result<Vec<CorrectionObservation>> {
445 parsed
446 .speakers
447 .iter()
448 .enumerate()
449 .filter(|(_, speaker)| speaker.feature_row.is_some())
450 .map(|(ordinal, speaker)| {
451 let speaker_ordinal = u32::try_from(ordinal)
452 .context("chunk has more speakers than the key schema supports")?;
453 Ok(CorrectionObservation {
454 local_label: speaker.local_label.clone(),
455 speaker_ordinal,
456 observation_key: ObservationKey {
457 object_id: training_object_id(recording_id, chunk_index),
458 piece_index: speaker_ordinal,
459 },
460 candidate: None,
461 identified_full_name: None,
462 confirmed_full_name: None,
463 })
464 })
465 .collect()
466}
467
468pub(crate) fn chunk_is_clean(clip_valid: bool, observations: &[CorrectionObservation]) -> bool {
469 if !clip_valid || observations.is_empty() {
470 return false;
471 }
472 let mut names = HashSet::new();
473 observations.iter().all(|observation| {
474 observation.candidate.as_ref().is_some_and(|candidate| {
475 candidate.confidence > 0.0
476 && candidate.cost < candidate.background_population_cost
477 && candidate
478 .runner_up_cost
479 .is_some_and(|cost| cost > candidate.background_population_cost)
480 && names.insert(candidate.full_name.as_str())
481 })
482 })
483}
484
485pub(crate) fn build_packet(
486 context: &ClassificationContext,
487 chunks: Vec<CorrectionChunk>,
488) -> anyhow::Result<CorrectionPacket> {
489 ensure!(!chunks.is_empty(), "correction packet has no chunks");
490 let chunk_count = chunks.len();
491 ensure!(
492 chunks.iter().enumerate().all(|(index, chunk)| {
493 chunk.chunk_index == index
494 && chunk.chunk_count == chunk_count
495 && chunk.audio_end_ms > chunk.audio_start_ms
496 && chunk.observations.len()
497 == chunk
498 .parsed
499 .speakers
500 .iter()
501 .filter(|speaker| speaker.feature_row.is_some())
502 .count()
503 }),
504 "correction packet chunks are not one complete chronological plan"
505 );
506 let clean = chunks.iter().all(|chunk| chunk.clean);
507 Ok(CorrectionPacket {
508 recording_id: context.recording_id,
509 user_id: context.user_id.clone(),
510 sha256: context.sha256.clone(),
511 original_filename: context.original_filename.clone(),
512 size_bytes: context.size_bytes,
513 recorded_at: context.recorded_at,
514 clean,
515 chunk_count,
516 chunks,
517 confirmation_state: ConfirmationState::Unconfirmed,
518 })
519}
520
521pub(crate) fn train_clean_packet(
522 classifier: &SpeechClassifier,
523 packet: &mut CorrectionPacket,
524) -> anyhow::Result<()> {
525 if !packet.clean {
526 ensure!(
527 packet.confirmation_state == ConfirmationState::Unconfirmed,
528 "unclean packet unexpectedly claims retained training"
529 );
530 return Ok(());
531 }
532
533 let mut added = Vec::new();
534 for chunk in &packet.chunks {
535 for observation in &chunk.observations {
536 let speaker = speaker_for_observation(chunk, observation)?;
537 let (primary_language, feature_row) = classifier_row(speaker)?;
538 let full_name = observation
539 .identified_full_name
540 .as_deref()
541 .context("clean observation omitted its identified full name")?;
542 match classifier.train(
543 observation.observation_key.clone(),
544 cohort(primary_language),
545 feature_row,
546 full_name.to_owned(),
547 ) {
548 Ok(TrainOutcome::Added) => added.push(observation.observation_key.clone()),
549 Ok(TrainOutcome::Unchanged | TrainOutcome::Corrected) => {}
550 Err(error) => {
551 let rollback_errors = rollback_added(classifier, &added);
552 if rollback_errors.is_empty() {
553 anyhow::bail!("automatic identity training failed: {error}");
554 }
555 anyhow::bail!(
556 "automatic identity training failed: {error}; rollback also failed: {}",
557 rollback_errors.join("; ")
558 );
559 }
560 }
561 }
562 }
563 packet.confirmation_state = ConfirmationState::AutomaticallyTrained;
564 Ok(())
565}
566
567pub(crate) fn validate_confirmation_coverage(
568 packet: &CorrectionPacket,
569 confirmation: &RecordingConfirmation,
570) -> Result<(), String> {
571 if confirmation.recording_id != packet.recording_id {
572 return Err("Confirmation recording ID does not match the packet.".into());
573 }
574
575 let known = packet
576 .chunks
577 .iter()
578 .flat_map(|chunk| &chunk.observations)
579 .map(|observation| key_tuple(&observation.observation_key))
580 .collect::<BTreeSet<_>>();
581 if known.is_empty() {
582 return Err("The correction packet contains no speaker observations.".into());
583 }
584
585 let mut supplied = BTreeSet::new();
586 for observation in &confirmation.observations {
587 if observation.confirmed_full_name.trim().is_empty()
588 || observation.confirmed_full_name.chars().count() > 512
589 {
590 return Err("Confirmed full names must contain between 1 and 512 characters.".into());
591 }
592 if !supplied.insert(key_tuple(&observation.observation_key)) {
593 return Err("Confirmation contains a duplicate observation key.".into());
594 }
595 }
596 if supplied != known {
597 return Err(
598 "Confirmation must cover every known observation exactly once, with no extras.".into(),
599 );
600 }
601 Ok(())
602}
603
604pub(crate) fn apply_confirmations(
605 classifier: &SpeechClassifier,
606 packet: &mut CorrectionPacket,
607 confirmation: &RecordingConfirmation,
608) -> anyhow::Result<()> {
609 validate_confirmation_coverage(packet, confirmation).map_err(anyhow::Error::msg)?;
610 let assignments = confirmation
611 .observations
612 .iter()
613 .map(|entry| {
614 (
615 key_tuple(&entry.observation_key),
616 entry.confirmed_full_name.trim().to_owned(),
617 )
618 })
619 .collect::<HashMap<_, _>>();
620
621 #[derive(Clone)]
622 struct Target {
623 chunk_position: usize,
624 observation_position: usize,
625 key: ObservationKey,
626 cohort: Cohort,
627 row: FeatureRow,
628 new_name: String,
629 old_name: Option<String>,
630 }
631
632 let mut targets = Vec::new();
633 for (chunk_position, chunk) in packet.chunks.iter().enumerate() {
634 for (observation_position, observation) in chunk.observations.iter().enumerate() {
635 let speaker = speaker_for_observation(chunk, observation)?;
636 let (primary_language, feature_row) = classifier_row(speaker)?;
637 targets.push(Target {
638 chunk_position,
639 observation_position,
640 key: observation.observation_key.clone(),
641 cohort: cohort(primary_language),
642 row: feature_row,
643 new_name: assignments
644 .get(&key_tuple(&observation.observation_key))
645 .context("validated confirmation assignment disappeared")?
646 .clone(),
647 old_name: retained_name(packet.confirmation_state, observation),
648 });
649 }
650 }
651
652 let mut applied = Vec::<(Target, TrainOutcome)>::new();
653 for target in targets {
654 match classifier.train(
655 target.key.clone(),
656 target.cohort.clone(),
657 target.row,
658 target.new_name.clone(),
659 ) {
660 Ok(outcome) => applied.push((target, outcome)),
661 Err(error) => {
662 let mut rollback_errors = Vec::new();
663 for (previous, outcome) in applied.iter().rev() {
664 let rollback = if let Some(old_name) = &previous.old_name {
665 classifier
666 .train(
667 previous.key.clone(),
668 previous.cohort.clone(),
669 previous.row,
670 old_name.clone(),
671 )
672 .map(|_| ())
673 } else if *outcome == TrainOutcome::Added {
674 classifier.delete(previous.key.clone()).map(|_| ())
675 } else {
676 Ok(())
677 };
678 if let Err(rollback_error) = rollback {
679 rollback_errors.push(rollback_error.to_string());
680 }
681 }
682 if rollback_errors.is_empty() {
683 anyhow::bail!("applying identity confirmations failed: {error}");
684 }
685 anyhow::bail!(
686 "applying identity confirmations failed: {error}; rollback also failed: {}",
687 rollback_errors.join("; ")
688 );
689 }
690 }
691 }
692
693 for (target, _) in applied {
694 packet.chunks[target.chunk_position].observations[target.observation_position]
695 .confirmed_full_name = Some(target.new_name);
696 }
697 packet.confirmation_state = ConfirmationState::Confirmed;
698 Ok(())
699}
700
701pub(crate) fn restore_packet_training(
702 classifier: &SpeechClassifier,
703 packet: &CorrectionPacket,
704) -> Vec<String> {
705 let mut errors = Vec::new();
706 for chunk in packet.chunks.iter().rev() {
707 for observation in chunk.observations.iter().rev() {
708 let result = match retained_name(packet.confirmation_state, observation) {
709 Some(name) => speaker_for_observation(chunk, observation).and_then(|speaker| {
710 let (primary_language, feature_row) = classifier_row(speaker)?;
711 classifier
712 .train(
713 observation.observation_key.clone(),
714 cohort(primary_language),
715 feature_row,
716 name,
717 )
718 .map(|_| ())
719 .map_err(anyhow::Error::from)
720 }),
721 None => classifier
722 .delete(observation.observation_key.clone())
723 .map(|_| ())
724 .map_err(anyhow::Error::from),
725 };
726 if let Err(error) = result {
727 errors.push(error.to_string());
728 }
729 }
730 }
731 errors
732}
733
734pub(crate) fn training_object_id(recording_id: Uuid, chunk_index: usize) -> String {
735 format!("kcode-audio-ingress/recording/{recording_id}/chunk/{chunk_index}")
736}
737
738fn probe_object_id(recording_id: Uuid, chunk_index: usize) -> String {
739 format!("kcode-audio-ingress/probe/{recording_id}/chunk/{chunk_index}")
740}
741
742fn cohort(primary_language: &str) -> Cohort {
743 Cohort {
744 provider: CLASSIFIER_PROVIDER.into(),
745 model: CLASSIFIER_MODEL.into(),
746 prompt_version: CLASSIFIER_PROMPT_VERSION.into(),
747 schema_version: CLASSIFIER_SCHEMA_VERSION.into(),
748 primary_language: primary_language.into(),
749 }
750}
751
752fn candidate_mapping(evidence: &IdentifyEvidence) -> CandidateMapping {
753 CandidateMapping {
754 full_name: evidence.best.speaker_id.clone(),
755 cost: evidence.best.cost,
756 confidence: evidence.confidence_score,
757 runner_up_full_name: evidence
758 .runner_up
759 .as_ref()
760 .map(|candidate| candidate.speaker_id.clone()),
761 runner_up_cost: evidence.runner_up.as_ref().map(|candidate| candidate.cost),
762 background_population_cost: evidence.background_population_cost,
763 }
764}
765
766fn speaker_for_observation<'a>(
767 chunk: &'a CorrectionChunk,
768 observation: &CorrectionObservation,
769) -> anyhow::Result<&'a ParsedSpeaker> {
770 let speaker = chunk
771 .parsed
772 .speakers
773 .get(observation.speaker_ordinal as usize)
774 .context("observation ordinal is outside the parsed speaker rows")?;
775 ensure!(
776 speaker.local_label == observation.local_label,
777 "observation label does not match its parsed speaker row"
778 );
779 Ok(speaker)
780}
781
782fn classifier_row(speaker: &ParsedSpeaker) -> anyhow::Result<(&str, FeatureRow)> {
783 Ok((
784 speaker
785 .primary_language
786 .as_deref()
787 .context("speaker observation omitted its primary language")?,
788 speaker
789 .feature_row
790 .context("speaker observation omitted its feature row")?,
791 ))
792}
793
794fn retained_name(state: ConfirmationState, observation: &CorrectionObservation) -> Option<String> {
795 match state {
796 ConfirmationState::Unconfirmed => None,
797 ConfirmationState::AutomaticallyTrained => observation.identified_full_name.clone(),
798 ConfirmationState::Confirmed => observation.confirmed_full_name.clone(),
799 }
800}
801
802fn rollback_added(classifier: &SpeechClassifier, keys: &[ObservationKey]) -> Vec<String> {
803 let mut errors = Vec::new();
804 for key in keys.iter().rev() {
805 if let Err(error) = classifier.delete(key.clone()) {
806 errors.push(error.to_string());
807 }
808 }
809 errors
810}
811
812fn key_tuple(key: &ObservationKey) -> (String, u32) {
813 (key.object_id.clone(), key.piece_index)
814}
815
816fn validate_iso_639_3(value: &str) -> anyhow::Result<()> {
817 ensure!(
818 value.len() == 3 && value.bytes().all(|byte| byte.is_ascii_lowercase()),
819 "must be a lowercase ISO 639-3 code"
820 );
821 ensure!(
822 !matches!(value, "mis" | "mul" | "und" | "zxx"),
823 "must identify one primary spoken language"
824 );
825 Ok(())
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831 use kcode_speaker_extract::{AdditionalSpeaker, CompleteSpeaker, ScoredClip};
832 use kcode_speaker_system::DeleteOutcome;
833 use serde_json::{Value, json};
834 use std::{
835 fs,
836 path::{Path, PathBuf},
837 sync::atomic::{AtomicU64, Ordering},
838 };
839
840 static NEXT_PATH: AtomicU64 = AtomicU64::new(0);
841
842 fn database_path(label: &str) -> PathBuf {
843 std::env::temp_dir().join(format!(
844 "kcode-audio-ingress-identity-{}-{label}-{}.sqlite3",
845 std::process::id(),
846 NEXT_PATH.fetch_add(1, Ordering::Relaxed)
847 ))
848 }
849
850 fn remove_database(path: &Path) {
851 for suffix in ["", "-wal", "-shm"] {
852 let mut value = path.as_os_str().to_os_string();
853 value.push(suffix);
854 let _ = fs::remove_file(PathBuf::from(value));
855 }
856 }
857
858 fn row() -> FeatureRow {
859 FeatureRow::new(std::array::from_fn(|index| {
860 u8::try_from(index * 3 + 10).unwrap()
861 }))
862 .unwrap()
863 }
864
865 fn extraction() -> ExtractionOutcome {
866 ExtractionOutcome::Scored(ScoredClip {
867 speakers: vec![CompleteSpeaker {
868 speaker_ordinal: 0,
869 primary_language: kcode_speaker_extract::Key::parse("eng").unwrap(),
870 closest_dialect: "General American English".into(),
871 usable_speech_ms: 1_000,
872 features: row(),
873 }],
874 additional_speakers: Vec::new(),
875 })
876 }
877
878 fn parsed() -> ParsedChunk {
879 ParsedChunk {
880 utterances: vec![ParsedUtterance {
881 speaker: "Speaker A".into(),
882 language: "eng".into(),
883 original_text: "Hello.".into(),
884 english_translation: String::new(),
885 corrected_natural_text: None,
886 coaching: Vec::new(),
887 annotations: Vec::new(),
888 }],
889 notes: vec!["Clear recording.".into()],
890 clip_valid: true,
891 clip_validity_reason: None,
892 speakers: vec![ParsedSpeaker {
893 local_label: "Speaker A".into(),
894 primary_language: Some("eng".into()),
895 feature_row: Some(row()),
896 }],
897 }
898 }
899
900 fn observation(name: &str, confidence: f64, ordinal: u32) -> CorrectionObservation {
901 CorrectionObservation {
902 local_label: format!("Speaker {}", char::from(b'A' + ordinal as u8)),
903 speaker_ordinal: ordinal,
904 observation_key: ObservationKey {
905 object_id: "recording".into(),
906 piece_index: ordinal,
907 },
908 candidate: Some(CandidateMapping {
909 full_name: name.into(),
910 cost: 1.0,
911 confidence,
912 runner_up_full_name: Some("Runner Up".into()),
913 runner_up_cost: Some(4.0),
914 background_population_cost: 3.0,
915 }),
916 identified_full_name: Some(name.into()),
917 confirmed_full_name: None,
918 }
919 }
920
921 fn packet(clean: bool) -> CorrectionPacket {
922 CorrectionPacket {
923 recording_id: Uuid::nil(),
924 user_id: "user".into(),
925 sha256: "0".repeat(64),
926 original_filename: "audio.wav".into(),
927 size_bytes: 44,
928 recorded_at: DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
929 .unwrap()
930 .with_timezone(&Utc),
931 clean,
932 chunk_count: 1,
933 chunks: vec![CorrectionChunk {
934 chunk_index: 0,
935 chunk_count: 1,
936 audio_start_ms: 0,
937 audio_end_ms: 1_000,
938 raw_gemini_response: "raw".into(),
939 parsed: parsed(),
940 observations: vec![observation("David Example", 2.0, 0)],
941 clean,
942 }],
943 confirmation_state: ConfirmationState::Unconfirmed,
944 }
945 }
946
947 #[test]
948 fn parser_merges_frozen_features_and_requires_matching_speakers() {
949 let valid = json!({
950 "utterances": [{
951 "speaker":"Speaker A",
952 "language":"eng",
953 "original_text":"Hello.",
954 "english_translation":"",
955 "corrected_natural_text":null,
956 "coaching":[],
957 "annotations":[]
958 }],
959 "notes":["Clear recording."],
960 "speakers":[{"local_label":"Speaker A", "speaker_ordinal":0}]
961 });
962 let restored = parse_and_validate_chunk(&valid.to_string(), &extraction(), 2.0).unwrap();
963 assert_eq!(restored, parsed());
964
965 let mut unknown = valid.clone();
966 unknown["utterances"][0]["speaker"] = Value::String("Speaker Z".into());
967 assert!(parse_and_validate_chunk(&unknown.to_string(), &extraction(), 2.0).is_err());
968
969 let mut wrong_ordinal = valid.clone();
970 wrong_ordinal["speakers"][0]["speaker_ordinal"] = json!(1);
971 assert!(parse_and_validate_chunk(&wrong_ordinal.to_string(), &extraction(), 2.0).is_err());
972
973 let incomplete = ExtractionOutcome::Scored(ScoredClip {
974 speakers: Vec::new(),
975 additional_speakers: vec![AdditionalSpeaker {
976 speaker_ordinal: 0,
977 description: "Too little speech.".into(),
978 }],
979 });
980 let restored = parse_and_validate_chunk(&valid.to_string(), &incomplete, 2.0).unwrap();
981 assert!(
982 !restored.clip_valid
983 && restored.speakers[0].primary_language.is_none()
984 && restored.speakers[0].feature_row.is_none()
985 );
986 }
987
988 #[test]
989 fn deterministic_keys_are_unique_for_multi_speaker_chunks() {
990 let recording = Uuid::new_v4();
991 let first = training_object_id(recording, 0);
992 let second = training_object_id(recording, 1);
993 assert_ne!(first, second);
994 let keys = [
995 ObservationKey {
996 object_id: first.clone(),
997 piece_index: 0,
998 },
999 ObservationKey {
1000 object_id: first,
1001 piece_index: 1,
1002 },
1003 ObservationKey {
1004 object_id: second,
1005 piece_index: 0,
1006 },
1007 ];
1008 assert_eq!(
1009 keys.iter().map(key_tuple).collect::<BTreeSet<_>>().len(),
1010 keys.len()
1011 );
1012 }
1013
1014 #[test]
1015 fn clean_gate_requires_background_bracketing_and_unique_candidates() {
1016 let bracketed = observation("David Example", 1.0, 0);
1017 assert!(chunk_is_clean(true, std::slice::from_ref(&bracketed)));
1018 assert!(!chunk_is_clean(true, &[]));
1019
1020 let mut missing_candidate = bracketed.clone();
1021 missing_candidate.candidate = None;
1022 assert!(!chunk_is_clean(true, &[missing_candidate]));
1023
1024 let zero_confidence = observation("David Example", 0.0, 0);
1025 assert!(!chunk_is_clean(true, &[zero_confidence]));
1026 let negative_confidence = observation("David Example", -1.0, 0);
1027 assert!(!chunk_is_clean(true, &[negative_confidence]));
1028
1029 let mut best_equal = bracketed.clone();
1030 best_equal.candidate.as_mut().unwrap().cost = 3.0;
1031 assert!(!chunk_is_clean(true, &[best_equal]));
1032 let mut best_greater = bracketed.clone();
1033 best_greater.candidate.as_mut().unwrap().cost = 4.0;
1034 assert!(!chunk_is_clean(true, &[best_greater]));
1035
1036 let mut runner_up_absent = bracketed.clone();
1037 let candidate = runner_up_absent.candidate.as_mut().unwrap();
1038 candidate.runner_up_full_name = None;
1039 candidate.runner_up_cost = None;
1040 assert!(!chunk_is_clean(true, &[runner_up_absent]));
1041
1042 let mut runner_up_equal = bracketed.clone();
1043 runner_up_equal.candidate.as_mut().unwrap().runner_up_cost = Some(3.0);
1044 assert!(!chunk_is_clean(true, &[runner_up_equal]));
1045 let mut runner_up_below = bracketed.clone();
1046 runner_up_below.candidate.as_mut().unwrap().runner_up_cost = Some(2.0);
1047 assert!(!chunk_is_clean(true, &[runner_up_below]));
1048
1049 assert!(!chunk_is_clean(
1050 true,
1051 &[bracketed.clone(), observation("David Example", 2.0, 1),]
1052 ));
1053 assert!(!chunk_is_clean(false, &[bracketed]));
1054 }
1055
1056 #[test]
1057 fn recording_training_gate_trains_only_clean_packets() {
1058 let path = database_path("training-gate");
1059 let classifier = SpeechClassifier::open(&path).unwrap();
1060 let mut unclean = packet(false);
1061 train_clean_packet(&classifier, &mut unclean).unwrap();
1062 assert_eq!(
1063 classifier
1064 .delete(unclean.chunks[0].observations[0].observation_key.clone())
1065 .unwrap(),
1066 DeleteOutcome::NotFound
1067 );
1068
1069 let mut clean = packet(true);
1070 train_clean_packet(&classifier, &mut clean).unwrap();
1071 assert_eq!(
1072 clean.confirmation_state,
1073 ConfirmationState::AutomaticallyTrained
1074 );
1075 assert_eq!(
1076 classifier
1077 .delete(clean.chunks[0].observations[0].observation_key.clone())
1078 .unwrap(),
1079 DeleteOutcome::Deleted
1080 );
1081 drop(classifier);
1082 remove_database(&path);
1083 }
1084
1085 #[test]
1086 fn confirmation_requires_exact_coverage() {
1087 let packet = packet(false);
1088 let key = packet.chunks[0].observations[0].observation_key.clone();
1089 let exact = RecordingConfirmation {
1090 recording_id: packet.recording_id,
1091 observations: vec![ObservationConfirmation {
1092 observation_key: key.clone(),
1093 confirmed_full_name: "David Example".into(),
1094 }],
1095 };
1096 assert!(validate_confirmation_coverage(&packet, &exact).is_ok());
1097
1098 let duplicate = RecordingConfirmation {
1099 recording_id: packet.recording_id,
1100 observations: vec![
1101 ObservationConfirmation {
1102 observation_key: key.clone(),
1103 confirmed_full_name: "David Example".into(),
1104 },
1105 ObservationConfirmation {
1106 observation_key: key,
1107 confirmed_full_name: "David Example".into(),
1108 },
1109 ],
1110 };
1111 assert!(validate_confirmation_coverage(&packet, &duplicate).is_err());
1112
1113 let empty = RecordingConfirmation {
1114 recording_id: packet.recording_id,
1115 observations: Vec::new(),
1116 };
1117 assert!(validate_confirmation_coverage(&packet, &empty).is_err());
1118 }
1119}