gigastt-core 2.12.0

Core inference engine for gigastt — GigaAM v3 ONNX Runtime, model management, quantization
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
//! Output formatters for transcription results.
//!
//! Supports plain text, JSON, SRT, WebVTT, and Markdown export from the
//! [`TranscribeResult`] structure returned by the inference engine.

use crate::error::GigasttError;
use crate::inference::{TranscribeResult, WordInfo};
use serde::Serialize;
use std::str::FromStr;

/// Supported export formats for transcription results.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ExportFormat {
    /// JSON with word-level metadata (default).
    #[default]
    Json,
    /// Plain text transcript only.
    Txt,
    /// SubRip subtitles.
    Srt,
    /// WebVTT subtitles.
    Vtt,
    /// Markdown with YAML frontmatter and optional speaker/timing sections.
    Md,
}

impl FromStr for ExportFormat {
    type Err = GigasttError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "json" => Ok(Self::Json),
            "txt" | "text" => Ok(Self::Txt),
            "srt" => Ok(Self::Srt),
            "vtt" => Ok(Self::Vtt),
            "md" | "markdown" => Ok(Self::Md),
            _ => Err(GigasttError::InvalidInput {
                message: format!("unsupported export format: {s}"),
            }),
        }
    }
}

impl std::fmt::Display for ExportFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Json => write!(f, "json"),
            Self::Txt => write!(f, "txt"),
            Self::Srt => write!(f, "srt"),
            Self::Vtt => write!(f, "vtt"),
            Self::Md => write!(f, "md"),
        }
    }
}

impl ExportFormat {
    /// MIME type to serve for this format over HTTP.
    pub fn content_type(&self) -> &'static str {
        match self {
            Self::Json => "application/json; charset=utf-8",
            Self::Txt => "text/plain; charset=utf-8",
            Self::Srt => "application/x-subrip; charset=utf-8",
            Self::Vtt => "text/vtt; charset=utf-8",
            Self::Md => "text/markdown; charset=utf-8",
        }
    }

    /// Default file extension (without leading dot).
    pub fn extension(&self) -> &'static str {
        match self {
            Self::Json => "json",
            Self::Txt => "txt",
            Self::Srt => "srt",
            Self::Vtt => "vtt",
            Self::Md => "md",
        }
    }

    /// Render a [`TranscribeResult`] into this format.
    pub fn render(&self, result: &TranscribeResult, opts: &RenderOpts) -> String {
        match self {
            Self::Json => to_json(result),
            Self::Txt => to_txt(result),
            Self::Srt => to_srt(
                &result.words,
                opts.max_chars_per_line,
                opts.max_words_per_line,
            ),
            Self::Vtt => to_vtt(
                &result.words,
                opts.max_chars_per_line,
                opts.max_words_per_line,
            ),
            Self::Md => to_md(result, opts.include_word_timestamps),
        }
    }
}

/// Options controlling subtitle line breaking and Markdown detail level.
#[derive(Clone, Copy, Debug)]
pub struct RenderOpts {
    /// Maximum characters per subtitle/caption line. `0` means unlimited.
    pub max_chars_per_line: usize,
    /// Maximum words per subtitle/caption line. `0` means unlimited.
    pub max_words_per_line: usize,
    /// Include per-word timestamps in Markdown output.
    pub include_word_timestamps: bool,
}

impl Default for RenderOpts {
    fn default() -> Self {
        Self {
            max_chars_per_line: 80,
            max_words_per_line: 14,
            include_word_timestamps: false,
        }
    }
}

/// Serialize the full result as JSON, mirroring the current REST contract.
///
/// The REST API exposes `duration` rather than the internal `duration_s` field
/// name, so this formatter maps the field explicitly.
pub fn to_json(result: &TranscribeResult) -> String {
    serde_json::json!({
        "text": result.text,
        "words": result.words,
        "duration": result.duration_s,
    })
    .to_string()
}

/// Plain text transcript only.
pub fn to_txt(result: &TranscribeResult) -> String {
    result.text.clone()
}

/// SubRip (SRT) subtitles from word-level timings.
///
/// Words are grouped into lines respecting `max_chars_per_line` and
/// `max_words_per_line`. Speaker labels are rendered as `[SPEAKER_N] text`.
pub fn to_srt(words: &[WordInfo], max_chars_per_line: usize, max_words_per_line: usize) -> String {
    let cues = build_cues(words, max_chars_per_line, max_words_per_line);
    let mut out = String::new();
    for (i, cue) in cues.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&(i + 1).to_string());
        out.push('\n');
        out.push_str(&format_srt_time(cue.start));
        out.push_str(" --> ");
        out.push_str(&format_srt_time(cue.end));
        out.push('\n');
        out.push_str(&cue.text);
        out.push('\n');
    }
    out
}

/// WebVTT subtitles from word-level timings.
pub fn to_vtt(words: &[WordInfo], max_chars_per_line: usize, max_words_per_line: usize) -> String {
    let cues = build_cues(words, max_chars_per_line, max_words_per_line);
    let mut out = String::from("WEBVTT\n\n");
    for cue in &cues {
        out.push_str(&format_vtt_time(cue.start));
        out.push_str(" --> ");
        out.push_str(&format_vtt_time(cue.end));
        out.push('\n');
        out.push_str(&cue.text);
        out.push('\n');
        out.push('\n');
    }
    out
}

/// Markdown export with YAML frontmatter and an optional word-level appendix.
pub fn to_md(result: &TranscribeResult, include_word_timestamps: bool) -> String {
    let speaker_count = result
        .words
        .iter()
        .filter_map(|w| w.speaker)
        .max()
        .map(|m| m + 1)
        .unwrap_or(0);

    let mut out = String::new();
    out.push_str("---\n");
    out.push_str(&format!("duration: {}\n", result.duration_s));
    out.push_str("language: ru\n");
    out.push_str(&format!("speakers: {speaker_count}\n"));
    out.push_str("---\n\n");

    out.push_str("# Transcript\n\n");
    out.push_str(&result.text);
    out.push_str("\n\n");

    if include_word_timestamps && !result.words.is_empty() {
        out.push_str("# Word timings\n\n");
        out.push_str("| Word | Start | End | Confidence | Speaker |\n");
        out.push_str("|------|-------|-----|------------|---------|\n");
        for w in &result.words {
            let speaker = w
                .speaker
                .map(|s| format!("SPEAKER_{s}"))
                .unwrap_or_else(|| "-".to_string());
            out.push_str(&format!(
                "| {} | {:.3}s | {:.3}s | {:.3} | {speaker} |\n",
                w.word.replace('|', "\\|"),
                w.start,
                w.end,
                w.confidence
            ));
        }
    }

    out
}

/// Internal cue used for SRT/VTT line grouping.
///
/// Carries the words that fall within the cue's span so higher-level exports
/// (segment JSON, segment-grouped Markdown) can reuse the exact same grouping
/// boundaries as SRT/VTT instead of re-deriving them.
#[derive(Clone, Debug)]
struct Cue {
    start: f64,
    end: f64,
    text: String,
    words: Vec<WordInfo>,
}

/// A grouped transcript segment: a span of words with an aggregate start/end,
/// text, and optional speaker label. Used both for the natural-boundary
/// segments returned by `?segments=true` and for the cue-based segments behind
/// `format=md&segments=true`, SRT, and VTT.
#[derive(Clone, Debug, Serialize)]
pub struct Segment {
    /// Segment start time in seconds (start of its first word).
    pub start: f64,
    /// Segment end time in seconds (end of its last word).
    pub end: f64,
    /// Rendered segment text (speaker label prefix included only for cue-based
    /// caption exports; natural segments keep the label in `speaker`).
    pub text: String,
    /// The words that fall within this segment's span.
    pub words: Vec<WordInfo>,
    /// Speaker label when the segment came from diarization or channel split.
    /// Omitted from JSON for plain mono transcription to keep responses small.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speaker: Option<u32>,
}

/// Pause gap that triggers a new natural segment (seconds). Chosen to split
/// typical conversational pauses without fragmenting normal word spacing.
const SEGMENT_PAUSE_THRESHOLD_S: f64 = 0.9;

/// Maximum duration of a natural segment (seconds). Utterances longer than
/// this are split even when no pause, punctuation, or speaker change occurred.
const MAX_SEGMENT_DURATION_S: f64 = 30.0;

/// Sentence-ending punctuation that forces a segment boundary after the word
/// that carries it.
const SEGMENT_SENTENCE_END_PUNCTUATION: &[char] = &['.', '!', '?'];

/// Return the common speaker label for a group of words, if all words share
/// the same non-`None` speaker. Used to populate `Segment::speaker` only when
/// diarization or channel split produced labels.
fn segment_speaker(words: &[WordInfo]) -> Option<u32> {
    let first = words.first()?.speaker?;
    if words.iter().all(|w| w.speaker == Some(first)) {
        Some(first)
    } else {
        None
    }
}

/// Group words into caption cues with speaker-aware line breaking.
fn build_cues(words: &[WordInfo], max_chars: usize, max_words: usize) -> Vec<Cue> {
    if words.is_empty() {
        return Vec::new();
    }

    let mut cues = Vec::new();
    let mut current = Cue {
        start: words[0].start,
        end: words[0].end,
        text: String::new(),
        words: Vec::new(),
    };
    let mut current_speaker: Option<u32> = None;
    let mut word_count = 0;

    let flush = |cue: &mut Cue, cues: &mut Vec<Cue>| {
        if !cue.text.is_empty() {
            // Trim trailing space left by append_word.
            cue.text = cue.text.trim_end().to_string();
            cues.push(cue.clone());
            cue.text.clear();
            cue.words.clear();
        }
    };

    for word in words {
        let speaker_changed = word.speaker != current_speaker;
        if speaker_changed {
            flush(&mut current, &mut cues);
            current.start = word.start;
            current_speaker = word.speaker;
            word_count = 0;
            if let Some(speaker) = word.speaker {
                current.text.push_str(&format!("[SPEAKER_{speaker}] "));
            }
        }

        let would_chars = if current.text.is_empty() {
            word.word.len()
        } else {
            current.text.len() + 1 + word.word.len()
        };
        let would_words = word_count + 1;

        let break_line = !current.text.is_empty()
            && ((max_chars > 0 && would_chars > max_chars)
                || (max_words > 0 && would_words > max_words));

        if break_line {
            flush(&mut current, &mut cues);
            current.start = word.start;
            current.end = word.end;
            word_count = 0;
            if let Some(speaker) = word.speaker {
                current.text.push_str(&format!("[SPEAKER_{speaker}] "));
            }
        }

        if !current.text.is_empty() && !current.text.ends_with(' ') {
            current.text.push(' ');
        }
        current.text.push_str(&word.word);
        current.end = word.end;
        current.words.push(word.clone());
        word_count += 1;
    }

    flush(&mut current, &mut cues);
    cues
}

/// Group a word list into cue-sized segments, reusing the SRT/VTT cue
/// boundaries so every export format agrees on segment spans.
///
/// Each returned [`Segment`] carries the words that fall within its span, so a
/// consumer can render segment-level UI (e.g. `### [mm:ss]` sections) without
/// re-deriving offsets from the flat per-word list.
pub fn to_segments(words: &[WordInfo], max_chars: usize, max_words: usize) -> Vec<Segment> {
    build_cues(words, max_chars, max_words)
        .into_iter()
        .map(|cue| Segment {
            start: cue.start,
            end: cue.end,
            text: cue.text,
            words: cue.words.clone(),
            speaker: segment_speaker(&cue.words),
        })
        .collect()
}

/// Group a word list into natural transcript segments using pause, sentence-end
/// punctuation, speaker change, and a maximum duration boundary.
///
/// This is the segmenter behind `POST /v1/transcribe?segments=true`. It is kept
/// separate from the SRT/VTT cue builder so subtitle line-breaking can remain
/// driven by `max_chars_per_line` / `max_words_per_line` while the JSON segment
/// array uses conversation-level boundaries.
pub fn to_transcript_segments(words: &[WordInfo]) -> Vec<Segment> {
    build_segments(words)
}

fn build_segments(words: &[WordInfo]) -> Vec<Segment> {
    if words.is_empty() {
        return Vec::new();
    }

    let mut segments = Vec::new();
    let mut current = Segment {
        start: words[0].start,
        end: words[0].end,
        text: words[0].word.clone(),
        words: vec![words[0].clone()],
        speaker: words[0].speaker,
    };

    for i in 1..words.len() {
        let word = &words[i];
        let prev = &words[i - 1];

        let pause = word.start - prev.end;
        let speaker_changed = word.speaker != prev.speaker;
        let prev_ended_sentence = prev
            .word
            .trim_end()
            .ends_with(SEGMENT_SENTENCE_END_PUNCTUATION);
        let would_exceed_duration = word.end - current.start > MAX_SEGMENT_DURATION_S;

        if pause > SEGMENT_PAUSE_THRESHOLD_S
            || speaker_changed
            || prev_ended_sentence
            || would_exceed_duration
        {
            current.speaker = segment_speaker(&current.words);
            segments.push(current);
            current = Segment {
                start: word.start,
                end: word.end,
                text: word.word.clone(),
                words: vec![word.clone()],
                speaker: word.speaker,
            };
        } else {
            current.text.push(' ');
            current.text.push_str(&word.word);
            current.end = word.end;
            current.words.push(word.clone());
        }
    }

    current.speaker = segment_speaker(&current.words);
    segments.push(current);
    segments
}

/// Segment-grouped Markdown: `### [mm:ss]` (or `[hh:mm:ss]` past one hour)
/// section headers per cue-sized segment, followed by that segment's text.
///
/// Shares its boundaries with SRT/VTT and `?segments=true` (all via
/// `build_cues`). Motivated by downstream consumers that otherwise fabricate
/// `### mm:ss` offsets because only flat per-word timings were exposed.
pub fn to_md_segments(result: &TranscribeResult, max_chars: usize, max_words: usize) -> String {
    let segments = to_segments(&result.words, max_chars, max_words);

    let speaker_count = result
        .words
        .iter()
        .filter_map(|w| w.speaker)
        .max()
        .map(|m| m + 1)
        .unwrap_or(0);

    let mut out = String::new();
    out.push_str("---\n");
    out.push_str(&format!("duration: {}\n", result.duration_s));
    out.push_str("language: ru\n");
    out.push_str(&format!("speakers: {speaker_count}\n"));
    out.push_str("---\n\n");

    for segment in &segments {
        out.push_str(&format!(
            "### [{}]\n\n",
            format_timestamp_hms(segment.start)
        ));
        out.push_str(&segment.text);
        out.push_str("\n\n");
    }

    out
}

/// Format a timestamp as `mm:ss`, widening to `hh:mm:ss` once it reaches one
/// hour. Used for the `### [mm:ss]` segment-Markdown headers.
fn format_timestamp_hms(seconds: f64) -> String {
    let total_s = seconds.max(0.0).round() as u64;
    let s = total_s % 60;
    let total_m = total_s / 60;
    let m = total_m % 60;
    let h = total_m / 60;
    if h > 0 {
        format!("{h:02}:{m:02}:{s:02}")
    } else {
        format!("{m:02}:{s:02}")
    }
}

fn format_srt_time(seconds: f64) -> String {
    let total_ms = (seconds.max(0.0) * 1000.0).round() as u64;
    let ms = total_ms % 1000;
    let total_s = total_ms / 1000;
    let s = total_s % 60;
    let total_m = total_s / 60;
    let m = total_m % 60;
    let h = total_m / 60;
    format!("{h:02}:{m:02}:{s:02},{ms:03}")
}

fn format_vtt_time(seconds: f64) -> String {
    let total_ms = (seconds.max(0.0) * 1000.0).round() as u64;
    let ms = total_ms % 1000;
    let total_s = total_ms / 1000;
    let s = total_s % 60;
    let total_m = total_s / 60;
    let m = total_m % 60;
    let h = total_m / 60;
    format!("{h:02}:{m:02}:{s:02}.{ms:03}")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_words() -> Vec<WordInfo> {
        vec![
            WordInfo {
                word: "привет".to_string(),
                start: 0.0,
                end: 0.5,
                confidence: 0.98,
                speaker: Some(0),
            },
            WordInfo {
                word: "как".to_string(),
                start: 0.6,
                end: 0.9,
                confidence: 0.95,
                speaker: Some(0),
            },
            WordInfo {
                word: "дела".to_string(),
                start: 1.0,
                end: 1.4,
                confidence: 0.97,
                speaker: Some(1),
            },
        ]
    }

    fn sample_result() -> TranscribeResult {
        TranscribeResult {
            text: "привет как дела".to_string(),
            words: sample_words(),
            duration_s: 1.4,
        }
    }

    #[test]
    fn test_to_txt() {
        let result = sample_result();
        assert_eq!(to_txt(&result), "привет как дела");
    }

    #[test]
    fn test_to_json() {
        let result = sample_result();
        let json = to_json(&result);
        assert!(json.contains("привет как дела"));
        assert!(json.contains("\"duration\":1.4"));
    }

    #[test]
    fn test_to_srt() {
        let words = sample_words();
        let srt = to_srt(&words, 80, 14);
        assert!(srt.contains("00:00:00,000 -->"));
        assert!(srt.contains("[SPEAKER_0] привет как"));
        assert!(srt.contains("[SPEAKER_1] дела"));
        assert!(srt.starts_with("1\n"));
    }

    #[test]
    fn test_to_vtt() {
        let words = sample_words();
        let vtt = to_vtt(&words, 80, 14);
        assert!(vtt.starts_with("WEBVTT\n\n"));
        assert!(vtt.contains("00:00:00.000 -->"));
        assert!(vtt.contains("[SPEAKER_1] дела"));
    }

    #[test]
    fn test_to_md() {
        let result = sample_result();
        let md = to_md(&result, true);
        assert!(md.contains("duration: 1.4"));
        assert!(md.contains("speakers: 2"));
        assert!(md.contains("привет как дела"));
        assert!(md.contains("| Word | Start | End |"));
    }

    #[test]
    fn test_format_srt_time() {
        assert_eq!(format_srt_time(0.0), "00:00:00,000");
        assert_eq!(format_srt_time(61.123), "00:01:01,123");
        assert_eq!(format_srt_time(3661.5), "01:01:01,500");
    }

    #[test]
    fn test_format_vtt_time() {
        assert_eq!(format_vtt_time(0.0), "00:00:00.000");
        assert_eq!(format_vtt_time(61.123), "00:01:01.123");
    }

    #[test]
    fn test_export_format_from_str() {
        assert_eq!(ExportFormat::from_str("srt").unwrap(), ExportFormat::Srt);
        assert_eq!(ExportFormat::from_str("SRT").unwrap(), ExportFormat::Srt);
        assert_eq!(
            ExportFormat::from_str("markdown").unwrap(),
            ExportFormat::Md
        );
        assert!(ExportFormat::from_str("docx").is_err());
    }

    #[test]
    fn test_empty_words() {
        let words: Vec<WordInfo> = Vec::new();
        assert!(to_srt(&words, 80, 14).is_empty());
        assert!(to_vtt(&words, 80, 14) == "WEBVTT\n\n");
    }

    #[test]
    fn test_export_format_display_all_variants() {
        assert_eq!(ExportFormat::Json.to_string(), "json");
        assert_eq!(ExportFormat::Txt.to_string(), "txt");
        assert_eq!(ExportFormat::Srt.to_string(), "srt");
        assert_eq!(ExportFormat::Vtt.to_string(), "vtt");
        assert_eq!(ExportFormat::Md.to_string(), "md");
    }

    #[test]
    fn test_export_format_content_type_all_variants() {
        assert_eq!(
            ExportFormat::Json.content_type(),
            "application/json; charset=utf-8"
        );
        assert_eq!(
            ExportFormat::Txt.content_type(),
            "text/plain; charset=utf-8"
        );
        assert_eq!(
            ExportFormat::Srt.content_type(),
            "application/x-subrip; charset=utf-8"
        );
        assert_eq!(ExportFormat::Vtt.content_type(), "text/vtt; charset=utf-8");
        assert_eq!(
            ExportFormat::Md.content_type(),
            "text/markdown; charset=utf-8"
        );
    }

    #[test]
    fn test_export_format_extension_all_variants() {
        assert_eq!(ExportFormat::Json.extension(), "json");
        assert_eq!(ExportFormat::Txt.extension(), "txt");
        assert_eq!(ExportFormat::Srt.extension(), "srt");
        assert_eq!(ExportFormat::Vtt.extension(), "vtt");
        assert_eq!(ExportFormat::Md.extension(), "md");
    }

    #[test]
    fn test_render_dispatches_each_format() {
        let result = sample_result();
        let opts = RenderOpts::default();

        let json = ExportFormat::Json.render(&result, &opts);
        assert_eq!(json, to_json(&result));

        let txt = ExportFormat::Txt.render(&result, &opts);
        assert_eq!(txt, "привет как дела");

        let srt = ExportFormat::Srt.render(&result, &opts);
        assert!(srt.starts_with("1\n"));

        let vtt = ExportFormat::Vtt.render(&result, &opts);
        assert!(vtt.starts_with("WEBVTT\n\n"));

        let md = ExportFormat::Md.render(&result, &opts);
        assert!(md.starts_with("---\n"));
        // Default opts disable word timestamps, so no table is emitted.
        assert!(!md.contains("| Word | Start | End |"));
    }

    #[test]
    fn test_render_md_with_word_timestamps_opt_in() {
        let result = sample_result();
        let opts = RenderOpts {
            include_word_timestamps: true,
            ..RenderOpts::default()
        };
        let md = ExportFormat::Md.render(&result, &opts);
        assert!(md.contains("# Word timings"));
        assert!(md.contains("| Word | Start | End |"));
    }

    #[test]
    fn test_render_opts_default_values() {
        let opts = RenderOpts::default();
        assert_eq!(opts.max_chars_per_line, 80);
        assert_eq!(opts.max_words_per_line, 14);
        assert!(!opts.include_word_timestamps);
    }

    #[test]
    fn test_from_str_all_aliases() {
        assert_eq!(ExportFormat::from_str("json").unwrap(), ExportFormat::Json);
        assert_eq!(ExportFormat::from_str("txt").unwrap(), ExportFormat::Txt);
        assert_eq!(ExportFormat::from_str("text").unwrap(), ExportFormat::Txt);
        assert_eq!(ExportFormat::from_str("vtt").unwrap(), ExportFormat::Vtt);
        assert_eq!(ExportFormat::from_str("md").unwrap(), ExportFormat::Md);
    }

    #[test]
    fn test_to_md_no_speakers_zero_count() {
        let result = TranscribeResult {
            text: "no speaker words".to_string(),
            words: vec![WordInfo {
                word: "no".to_string(),
                start: 0.0,
                end: 0.3,
                confidence: 0.9,
                speaker: None,
            }],
            duration_s: 0.3,
        };
        let md = to_md(&result, true);
        assert!(md.contains("speakers: 0"));
        // Speaker column renders "-" when no speaker is assigned.
        assert!(md.contains("| - |"));
    }

    #[test]
    fn test_to_md_word_timestamps_skipped_when_empty() {
        let result = TranscribeResult {
            text: String::new(),
            words: Vec::new(),
            duration_s: 0.0,
        };
        let md = to_md(&result, true);
        // Empty word list means the appendix table is omitted entirely.
        assert!(!md.contains("# Word timings"));
        assert!(md.contains("speakers: 0"));
    }

    #[test]
    fn test_to_md_escapes_pipe_in_word() {
        let result = TranscribeResult {
            text: "a|b".to_string(),
            words: vec![WordInfo {
                word: "a|b".to_string(),
                start: 0.0,
                end: 0.5,
                confidence: 0.91,
                speaker: Some(2),
            }],
            duration_s: 0.5,
        };
        let md = to_md(&result, true);
        // Pipe in the word must be escaped to avoid breaking the table column.
        assert!(md.contains("a\\|b"));
        assert!(md.contains("SPEAKER_2"));
        assert!(md.contains("speakers: 3"));
    }

    #[test]
    fn test_srt_speaker_change_breaks_cue_with_label() {
        // Two speakers force a cue break; each cue carries its speaker label.
        let words = sample_words();
        let cues = build_cues(&words, 80, 14);
        assert_eq!(cues.len(), 2);
        assert!(cues[0].text.starts_with("[SPEAKER_0]"));
        assert!(cues[1].text.starts_with("[SPEAKER_1]"));
        assert!(cues[1].text.contains("дела"));
    }

    #[test]
    fn test_line_breaking() {
        let words: Vec<WordInfo> = (0..20)
            .map(|i| WordInfo {
                word: format!("word{i}"),
                start: i as f64,
                end: i as f64 + 0.4,
                confidence: 0.9,
                speaker: None,
            })
            .collect();
        let srt = to_srt(&words, 40, 5);
        let cue_count = srt.trim().split("\n\n").count();
        // 20 words / 5 per line = 4 cues, but exact count depends on chars.
        assert!(cue_count >= 2);
    }

    #[test]
    fn test_to_segments_shares_cue_boundaries() {
        // Two speakers force a cue break, so segments mirror the SRT cues:
        // one per speaker, with matching spans and per-segment word membership.
        let words = sample_words();
        let segments = to_segments(&words, 80, 14);
        assert_eq!(segments.len(), 2);

        assert_eq!(segments[0].start, 0.0);
        assert_eq!(segments[0].end, 0.9);
        assert!(segments[0].text.starts_with("[SPEAKER_0] привет"));
        assert_eq!(segments[0].words.len(), 2);
        assert_eq!(segments[0].words[0].word, "привет");
        assert_eq!(segments[0].words[1].word, "как");

        assert_eq!(segments[1].start, 1.0);
        assert_eq!(segments[1].end, 1.4);
        assert!(segments[1].text.contains("дела"));
        assert_eq!(segments[1].words.len(), 1);
        assert_eq!(segments[1].words[0].word, "дела");
    }

    #[test]
    fn test_to_segments_word_cap_splits() {
        // A tight per-line cap groups the 20 words into multiple segments whose
        // spans and word membership line up with the flat list order.
        let words: Vec<WordInfo> = (0..20)
            .map(|i| WordInfo {
                word: format!("word{i}"),
                start: i as f64,
                end: i as f64 + 0.4,
                confidence: 0.9,
                speaker: None,
            })
            .collect();
        let segments = to_segments(&words, 0, 5);
        assert_eq!(segments.len(), 4);
        // Every word is accounted for exactly once, in order.
        let total: usize = segments.iter().map(|s| s.words.len()).sum();
        assert_eq!(total, 20);
        assert_eq!(segments[0].words[0].word, "word0");
        assert_eq!(segments[0].start, 0.0);
        assert_eq!(segments[0].end, 4.4);
        assert_eq!(segments[3].words.last().unwrap().word, "word19");
    }

    #[test]
    fn test_to_segments_empty() {
        let words: Vec<WordInfo> = Vec::new();
        assert!(to_segments(&words, 80, 14).is_empty());
    }

    #[test]
    fn test_to_segments_serializes_with_words() {
        let words = sample_words();
        let segments = to_segments(&words, 80, 14);
        let json = serde_json::to_value(&segments).unwrap();
        assert_eq!(json[0]["start"], 0.0);
        assert_eq!(json[0]["end"], 0.9);
        assert_eq!(json[0]["words"][0]["word"], "привет");
        // Speaker is carried through (skip_serializing_if only drops None).
        assert_eq!(json[0]["words"][0]["speaker"], 0);
    }

    #[test]
    fn test_to_md_segments_emits_headers() {
        let result = sample_result();
        let md = to_md_segments(&result, 80, 14);
        // Frontmatter is preserved; the flat "# Transcript" blob is replaced by
        // per-segment "### [mm:ss]" headers.
        assert!(md.starts_with("---\n"));
        assert!(md.contains("duration: 1.4"));
        assert!(md.contains("speakers: 2"));
        assert!(md.contains("### [00:00]\n"));
        assert!(md.contains("### [00:01]\n"));
        assert!(md.contains("[SPEAKER_0] привет как"));
        assert!(md.contains("дела"));
        assert!(!md.contains("# Transcript"));
    }

    #[test]
    fn test_to_md_segments_empty_words() {
        let result = TranscribeResult {
            text: String::new(),
            words: Vec::new(),
            duration_s: 0.0,
        };
        let md = to_md_segments(&result, 80, 14);
        // No words means no section headers, but the frontmatter still renders.
        assert!(md.starts_with("---\n"));
        assert!(md.contains("speakers: 0"));
        assert!(!md.contains("### ["));
    }

    #[test]
    fn test_format_timestamp_hms() {
        // Under a minute, exactly a minute-plus, and past an hour widen as needed.
        assert_eq!(format_timestamp_hms(0.0), "00:00");
        assert_eq!(format_timestamp_hms(65.0), "01:05");
        assert_eq!(format_timestamp_hms(3661.0), "01:01:01");
        // Rounds to the nearest second; negatives clamp to zero.
        assert_eq!(format_timestamp_hms(59.6), "01:00");
        assert_eq!(format_timestamp_hms(-5.0), "00:00");
    }

    #[test]
    fn test_md_segments_and_srt_agree_on_boundaries() {
        // The whole point of routing both through build_cues: the segment count
        // matches the SRT cue count for the same caps.
        let words: Vec<WordInfo> = (0..20)
            .map(|i| WordInfo {
                word: format!("word{i}"),
                start: i as f64,
                end: i as f64 + 0.4,
                confidence: 0.9,
                speaker: None,
            })
            .collect();
        let segments = to_segments(&words, 0, 5);
        let srt = to_srt(&words, 0, 5);
        let srt_cues = srt.matches("-->").count();
        assert_eq!(segments.len(), srt_cues);
    }

    // -----------------------------------------------------------------------
    // Natural-boundary transcript segmenter (`to_transcript_segments`)
    // -----------------------------------------------------------------------

    #[test]
    fn test_to_transcript_segments_empty() {
        let words: Vec<WordInfo> = Vec::new();
        let segments = to_transcript_segments(&words);
        assert!(segments.is_empty());
    }

    #[test]
    fn test_to_transcript_segments_single_word() {
        let words = vec![WordInfo::new("привет", 0.0, 0.5, 0.98, None)];
        let segments = to_transcript_segments(&words);
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].start, 0.0);
        assert_eq!(segments[0].end, 0.5);
        assert_eq!(segments[0].text, "привет");
        assert_eq!(segments[0].words.len(), 1);
        assert_eq!(segments[0].speaker, None);
    }

    #[test]
    fn test_to_transcript_segments_split_on_pause() {
        // 1.1 s gap between the two words crosses the 0.9 s pause threshold.
        let words = vec![
            WordInfo::new("привет", 0.0, 0.5, 0.98, None),
            WordInfo::new("мир", 1.6, 2.0, 0.97, None),
        ];
        let segments = to_transcript_segments(&words);
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].text, "привет");
        assert_eq!(segments[1].text, "мир");
    }

    #[test]
    fn test_to_transcript_segments_split_on_punctuation() {
        // "привет." ends a sentence, so the next word starts a new segment.
        let words = vec![
            WordInfo::new("привет.", 0.0, 0.5, 0.98, None),
            WordInfo::new("мир", 0.6, 1.0, 0.97, None),
            WordInfo::new("как", 1.1, 1.5, 0.96, None),
        ];
        let segments = to_transcript_segments(&words);
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].text, "привет.");
        assert_eq!(segments[1].text, "мир как");
    }

    #[test]
    fn test_to_transcript_segments_split_on_speaker_change() {
        let words = vec![
            WordInfo::new("привет", 0.0, 0.5, 0.98, Some(0)),
            WordInfo::new("мир", 0.6, 1.0, 0.97, Some(1)),
        ];
        let segments = to_transcript_segments(&words);
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].speaker, Some(0));
        assert_eq!(segments[1].speaker, Some(1));
    }

    #[test]
    fn test_to_transcript_segments_split_on_max_duration() {
        // Generate 35 words with gaps just under the pause threshold so the
        // only reason to split is the 30 s duration cap.
        let words: Vec<WordInfo> = (0..35)
            .map(|i| {
                let start = i as f64 * 0.89;
                WordInfo::new(format!("word{i}"), start, start + 0.1, 0.95, None)
            })
            .collect();
        let segments = to_transcript_segments(&words);
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].start, 0.0);
        // The first segment ends where the 30 s cap is crossed.
        assert!(segments[0].end <= 30.0, "first segment exceeds cap");
        assert_eq!(
            segments[1].start,
            segments[0].words.last().unwrap().end + 0.79
        );
        // Every word is accounted for exactly once.
        let total: usize = segments.iter().map(|s| s.words.len()).sum();
        assert_eq!(total, 35);
    }

    #[test]
    fn test_to_transcript_segments_speaker_omitted_when_none() {
        let words = vec![
            WordInfo::new("привет", 0.0, 0.5, 0.98, None),
            WordInfo::new("мир", 0.6, 1.0, 0.97, None),
        ];
        let segments = to_transcript_segments(&words);
        let json = serde_json::to_value(&segments).unwrap();
        assert!(json[0].get("speaker").is_none());
    }

    #[test]
    fn test_to_transcript_segments_speaker_present_when_diarized() {
        let words = vec![
            WordInfo::new("привет", 0.0, 0.5, 0.98, Some(0)),
            WordInfo::new("мир", 0.6, 1.0, 0.97, Some(0)),
        ];
        let segments = to_transcript_segments(&words);
        let json = serde_json::to_value(&segments).unwrap();
        assert_eq!(json[0]["speaker"], 0);
    }
}