parla-clean 0.1.0

Deterministic post-processing for Brazilian Portuguese speech transcription: filler removal, vocabulary variant correction, ASR deduplication
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
//! Passadas do pipeline de limpeza (ADR-0010).
//!
//! Cada passada é uma função pura sobre o [`TokenStream`] (a última,
//! normalização, é sobre o texto renderizado). A ordem é fixa e
//! documentada no orquestrador (`mod.rs`):
//!
//! 1. `fix_variants` — variantes de grafia do vocabulário, ANTES de tudo
//!    ("o sematlman" vira "O Sam Altman" e não "O sematlman");
//! 2. `remove_fillers` — muletas com guardas de contexto;
//! 3. `dedupe_repetitions` — repetições do ASR;
//! 4. `normalize` — espaços, pontuação, capitalização, ponto final.

use std::collections::HashSet;

use super::rules::{fold, fold_flat, FillerRule, FUNCTION_WORDS, KNOWN_VARIANTS, DEFAULT_FILLERS, Position};
use super::tokens::{Token, TokenKind, TokenStream};
use super::CleanConfig;

/// Contadores por passada — base da calibração A/B prevista no ADR-0009
/// (fase 2) e da telemetria local opcional.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PassStats {
    /// Muletas removidas (tokens de palavra).
    pub fillers_removed: usize,
    /// Ocorrências de variante corrigidas.
    pub variants_fixed: usize,
    /// Tokens duplicados removidos.
    pub repetitions_removed: usize,
}

// ---------------------------------------------------------------------------
// Passada 1 — variantes do vocabulário (sobre o texto, flat matching)
// ---------------------------------------------------------------------------

/// Corrige variantes de grafia dos termos do vocabulário: o termo em caixa
/// errada ("sam altman" → "Sam Altman", "github" → "GitHub") e as variantes
/// fonéticas conhecidas ("sematlman" → "Sam Altman", "cloud code" →
/// "Claude Code"). Casamento por caracteres exatos ignorando caixa e
/// espaços, com fronteiras de palavra — "Cloud" NUNCA vira "Claude" e
/// "sematlmanx" não é tocado.
///
/// Roda sobre o TEXTO (não sobre tokens) de propósito: o casamento é
/// "flat" (ignora espaços em qualquer posição — "sem atlman" também é
/// variante), o que não é expressável como sequência de tokens de palavra.
/// Custo: prefilter O(n) por alvo; o texto é re-tokenizado UMA vez depois.
pub(crate) fn fix_variants(text: &str, vocab: &[String]) -> (String, usize) {
    if text.is_empty() || vocab.is_empty() {
        return (text.to_string(), 0);
    }
    // termos maiores primeiro: evita "Git" casar dentro de "GitHub"
    let mut terms: Vec<&String> = vocab.iter().filter(|v| v.chars().count() >= 3).collect();
    terms.sort_by_key(|v| std::cmp::Reverse(v.chars().count()));

    // (alvo flat-fold, substituição) — deduplicado por alvo
    let mut replacements: Vec<(String, String)> = Vec::new();
    let mut seen_targets: HashSet<String> = HashSet::new();
    for term in terms {
        let target = fold_flat(term);
        if target.is_empty() || !seen_targets.insert(target.clone()) {
            continue;
        }
        for (canonical, variants) in KNOWN_VARIANTS {
            // bug 3 corrigido: fold completo, nunca eq_ignore_ascii_case
            if fold_flat(canonical) == target {
                for v in *variants {
                    if seen_targets.insert(fold_flat(v)) {
                        replacements.push((fold_flat(v), canonical.to_string()));
                    }
                }
            }
        }
        // o próprio termo em caixa/espaçamento errado ("git hub" → "GitHub")
        replacements.push((target, term.to_string()));
    }

    let mut out = text.to_string();
    let mut fixed = 0usize;
    for (target, replacement) in replacements {
        let (t, n) = replace_word_matches_counted(&out, &target, &replacement);
        out = t;
        fixed += n;
    }
    (out, fixed)
}

/// Substitui `target` por `replacement` quando casa ignorando caixa e
/// espaços, com fronteiras de palavra (o char antes/depois não é
/// alfanumérico). Função pura e testada — usada aqui e por consumidores
/// externos via API pública.
pub fn replace_word_matches(text: &str, target: &str, replacement: &str) -> String {
    replace_word_matches_counted(text, target, replacement).0
}

fn replace_word_matches_counted(text: &str, target: &str, replacement: &str) -> (String, usize) {
    let needle: Vec<char> = fold_flat(target).chars().collect();
    if needle.is_empty() {
        return (text.to_string(), 0);
    }
    // prefilter O(n): sem a agulha no texto achatado, não há o que casar —
    // o caso típico (vocab pequeno, frase curta) fica ~O(n) sem dep nenhuma
    let flat = fold_flat(text);
    if !flat.contains(&needle.iter().collect::<String>()) {
        return (text.to_string(), 0);
    }
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0usize;
    let mut count = 0usize;
    while i < chars.len() {
        let mut k = 0usize;
        let mut j = i;
        while j < chars.len() && k < needle.len() {
            if chars[j].is_whitespace() {
                j += 1;
                continue;
            }
            // bug 2 corrigido: o folding de UM char pode gerar VÁRIOS chars
            // (İ → "i̇"); comparamos o folding inteiro, não só o primeiro
            let f: Vec<char> = chars[j].to_lowercase().collect();
            if f.is_empty() {
                j += 1;
                continue;
            }
            if f.len() <= needle.len() - k && f.as_slice() == &needle[k..k + f.len()] {
                j += 1;
                k += f.len();
            } else {
                break;
            }
        }
        let matched = k == needle.len();
        let before_ok = !matched || i == 0 || !chars[i - 1].is_alphanumeric();
        let after_ok = !matched || j >= chars.len() || !chars[j].is_alphanumeric();
        if matched && before_ok && after_ok {
            out.push_str(replacement);
            i = j;
            count += 1;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    (out, count)
}

// ---------------------------------------------------------------------------
// Passada 2 — muletas (sobre tokens)
// ---------------------------------------------------------------------------

/// Remove muletas em posição inequívoca. Devolve o stream filtrado, se uma
/// muleta final foi removida (a frase "ganhou fim" e pode receber ponto
/// final) e quantas muletas saíram.
///
/// Regras vêm de [`DEFAULT_FILLERS`] + `user_fillers` da config (regra
/// genérica: só posição isolada — o padrão conservador).
/// Mecânica da deleção (bugs 1 e 4 corrigidos):
/// - a palavra + vírgulas coladas (", né?" vira nada, sem " ,");
/// - pontuação terminal: pertence à FRASE quando a regra tem
///   `keep_terminal` ("disso né?" → "Disso?"); para tag declarativa
///   ("sabe?") a pontuação é da tag e a frase ganha ponto;
/// - spans ordenados e FUNDIDOS (adjacentes/sobrepostos), sem vírgula
///   órfã entre "tipo, assim,".
pub(crate) fn remove_fillers(
    stream: &TokenStream,
    config: &CleanConfig,
) -> (TokenStream, bool, usize) {
    let toks = &stream.tokens;
    let mut matched_rule: Vec<Option<FillerRule>> = vec![None; toks.len()];

    for (i, tok) in toks.iter().enumerate() {
        if tok.kind != TokenKind::Word {
            continue;
        }
        let word = fold(&tok.text);
        // muleta do usuário (config) ou regra padrão — regra genérica de
        // usuário: SÓ posição isolada, sem guardas (o conservador máximo)
        let rule = if config.user_fillers.iter().any(|f| f.to_lowercase() == word) {
            Some(USER_FILLER_RULE)
        } else {
            DEFAULT_FILLERS.iter().copied().find(|r| r.word == word)
        };
        let Some(rule) = rule else { continue };

        let prev = stream.prev_significant(i);
        let next = stream.next_significant(i);
        let prev_word = prev
            .filter(|t| t.kind == TokenKind::Word)
            .map(|t| fold(&t.text));
        let next_word = next
            .filter(|t| t.kind == TokenKind::Word)
            .map(|t| fold(&t.text));
        let is_content = |t: &TokenKind| matches!(t, TokenKind::Word | TokenKind::Number | TokenKind::Url | TokenKind::Email);
        let boundary_before = prev.is_none_or(|t| !is_content(&t.kind));
        let boundary_after = next.is_none_or(|t| !is_content(&t.kind));

        let position_ok = rule.positions.iter().any(|p| match p {
            Position::Start => boundary_before,
            Position::End => boundary_after,
            Position::Isolated => boundary_before && boundary_after,
        });
        let compound_ok = rule
            .compound_prev
            .iter()
            .any(|w| prev_word.as_deref() == Some(*w))
            || (rule
                .compound_next
                .iter()
                .any(|w| next_word.as_deref() == Some(*w))
                && (!rule.compound_requires_boundary_before || boundary_before));
        let requires_ok = rule.requires_prev.is_empty()
            || rule.requires_prev.iter().any(|w| prev_word.as_deref() == Some(*w));
        let guards_ok = !rule.not_if_prev.iter().any(|w| prev_word.as_deref() == Some(*w))
            && !rule.not_if_next.iter().any(|w| next_word.as_deref() == Some(*w));
        let comma_ok = !rule.requires_after_comma
            || matches!(
                next,
                Some(t) if t.kind == TokenKind::Punct && t.text == ","
            );

        if (position_ok || compound_ok) && requires_ok && guards_ok && comma_ok {
            matched_rule[i] = Some(rule);
        }
    }

    // índices de span sobre o stream: (início, fim) de tokens a REMOVER.
    // A extensão por vírgula/pontuação é resolvida aqui, nos tokens.
    let last_word_idx = toks
        .iter()
        .rposition(|t| matches!(t.kind, TokenKind::Word | TokenKind::Number));
    let mut spans: Vec<(usize, usize)> = Vec::new();
    let mut trailing_filler = false;
    for (i, rule) in matched_rule.iter().enumerate() {
        let Some(rule) = rule else { continue };
        let mut s = i;
        let mut e = i + 1;
        // vírgula colada à esquerda: "disso, né?" → "disso?"
        if let Some(p) = stream.prev_significant(i) {
            if p.kind == TokenKind::Punct && p.text == "," {
                s = toks.iter().position(|t| t.start == p.start).unwrap_or(i);
            }
        }
        // vírgula colada à direita: "tipo, o Sam" → "o Sam".
        // SÓ engole se não houver palavra colada SEM espaço depois dela:
        // "assim,sabe,t." → "assim,t." (não "assimt." — remover a vírgula
        // colaria duas palavras, regressão real achada pelo teste de
        // propriedade I1; o normalize devolve o espaço "assim, t.")
        if let Some(n) = stream.next_significant(i) {
            if n.kind == TokenKind::Punct && n.text == "," {
                let n_idx = toks.iter().position(|t| t.start == n.start).unwrap_or(i);
                let after = stream.next_significant(n_idx);
                let glued = matches!(
                    after,
                    Some(t)
                        if matches!(
                            t.kind,
                            TokenKind::Word
                                | TokenKind::Number
                                | TokenKind::Url
                                | TokenKind::Email
                        ) && t.start == n.end
                );
                if !glued {
                    e = n_idx + 1;
                }
            }
        }
        // muleta final: pontuação terminal ou fim do texto
        if Some(i) == last_word_idx {
            match stream.next_significant(i) {
                Some(n) if n.kind == TokenKind::Punct && matches!(n.text.as_str(), "." | "!" | "?") => {
                    // keep_terminal: o '?' é da FRASE — o token fica no stream;
                    // senão a tag declarativa engole a pontuação
                    if !rule.keep_terminal {
                        e = toks.iter().position(|t| t.start == n.start).unwrap_or(e) + 1;
                    }
                    trailing_filler = true;
                }
                None => trailing_filler = true,
                _ => {}
            }
        }
        spans.push((s, e));
    }
    let fillers_removed = spans.len();
    if spans.is_empty() {
        return (stream.clone(), false, 0);
    }

    // merge explícito (bug 4): spans ordenados e fundidos — dois spans
    // adjacentes/sobrepostos ("tipo, assim,") viram um só
    spans.sort_unstable();
    let mut merged: Vec<(usize, usize)> = Vec::with_capacity(spans.len());
    for (s, e) in spans {
        match merged.last_mut() {
            Some(last) if s <= last.1 => last.1 = last.1.max(e),
            _ => merged.push((s, e)),
        }
    }

    let kept: Vec<Token> = toks
        .iter()
        .enumerate()
        .filter(|(idx, _)| !merged.iter().any(|(s, e)| idx >= s && idx < e))
        .map(|(_, t)| t.clone())
        .collect();
    (TokenStream { tokens: kept }, trailing_filler, fillers_removed)
}

/// Regra genérica para muletas do usuário (`user_fillers`): só posição
/// isolada, sem guardas — o padrão mais conservador possível. O `word` é
/// um marcador que nunca casa por nome: a seleção é feita pela checagem
/// explícita em `remove_fillers`.
const USER_FILLER_RULE: FillerRule = FillerRule {
    word: "«usuário»",
    positions: &[Position::Isolated],
    not_if_prev: &[],
    not_if_next: &[],
    compound_prev: &[],
    compound_next: &[],
    compound_requires_boundary_before: false,
    requires_prev: &[],
    requires_after_comma: false,
    keep_terminal: false,
};

// ---------------------------------------------------------------------------
// Passada 3 — repetições do ASR (sobre tokens)
// ---------------------------------------------------------------------------

/// Deduplica repetições consecutivas do ASR mantendo a PRIMEIRA ocorrência
/// (caixa original): 2x em palavra funcional ("eu eu acho") ou em número
/// ("14h30 14h30" — nova na v2: o tokenizer rico enxerga o número), e 3x+
/// em qualquer palavra (loop típico: "OpenAI, OpenAI, OpenAI" → "OpenAI").
/// Repetição separada por pontuação ("não, não, não quero") NUNCA é tocada
/// (pode ser ênfase) e "muito muito bom" (conteúdo, 2x) também não.
pub(crate) fn dedupe_repetitions(stream: &TokenStream) -> (TokenStream, usize) {
    let toks = &stream.tokens;
    let mut remove = vec![false; toks.len()];
    let mut i = 0usize;
    while i < toks.len() {
        let t = &toks[i];
        if !matches!(t.kind, TokenKind::Word | TokenKind::Number) {
            i += 1;
            continue;
        }
        let mut j = i;
        let mut run = 1usize;
        loop {
            // o próximo token de CONTEÚDO pode ter Whitespace no meio
            let mut k = j + 1;
            while k < toks.len() && toks[k].kind == TokenKind::Whitespace {
                k += 1;
            }
            if k >= toks.len()
                || toks[k].kind != t.kind
                || toks[k].text.to_lowercase() != t.text.to_lowercase()
            {
                break;
            }
            j = k;
            run += 1;
        }
        let is_function = FUNCTION_WORDS.contains(&t.text.to_lowercase().as_str());
        let is_number = t.kind == TokenKind::Number;
        if (run >= 2 && (is_function || is_number)) || run >= 3 {
            // remove só os tokens de CONTEÚDO duplicados — os espaços do
            // meio ficam (o normalize colapsa depois): remover o espaço
            // colaria vizinhos ("ÓQ6 6pi" → "ÓQ6pi", regressão real)
            for k in (i + 1)..=j {
                if matches!(toks[k].kind, TokenKind::Word | TokenKind::Number) {
                    remove[k] = true;
                }
            }
        }
        i = j + 1;
    }
    // stats contam só tokens de CONTEÚDO (o whitespace do meio é removido
    // junto, mas não é "repetição")
    let removed = (0..toks.len())
        .filter(|k| remove[*k] && matches!(toks[*k].kind, TokenKind::Word | TokenKind::Number))
        .count();
    if removed == 0 {
        return (stream.clone(), 0);
    }
    let kept: Vec<Token> = toks
        .iter()
        .enumerate()
        .filter(|(k, _)| !remove[*k])
        .map(|(_, t)| t.clone())
        .collect();
    (TokenStream { tokens: kept }, removed)
}

// ---------------------------------------------------------------------------
// Passada 4 — normalização (token-aware)
// ---------------------------------------------------------------------------

/// Normaliza espaços, pontuação e capitalização; adiciona ponto final
/// apenas quando uma muleta final foi removida e a frase não tem pontuação
/// terminal ("disso né" → "Disso."; "disso né?" → "Disso?").
///
/// Token-aware (novo na v2): tokens `Url`/`Email` são ATÔMICOS — nenhum
/// espaço interno, nenhuma capitalização, nenhuma pontuação tocada
/// ("https://tipo.com" sai intacto; na v1 o colapso abria um espaço após
/// o ':' e capitalizava o "com"). Números também não disparam início de
/// frase no '.' interno de "1.000,50".
pub(crate) fn normalize(stream: &TokenStream, add_final_period: bool) -> String {
    let toks = &stream.tokens;
    let mut out = String::with_capacity(64);
    let mut pending_space = false;
    let mut at_sentence_start = true;
    for tok in toks {
        if matches!(tok.kind, TokenKind::Url | TokenKind::Email) {
            if pending_space {
                out.push(' ');
                pending_space = false;
            }
            out.push_str(&tok.text);
            at_sentence_start = false;
            continue;
        }
        for c in tok.text.chars() {
            if c.is_whitespace() {
                if !out.is_empty() {
                    pending_space = true;
                }
                continue;
            }
            let drop_space = matches!(c, ',' | '.' | ';' | ':' | '!' | '?' | ')' | ']' | '}');
            if pending_space && !drop_space {
                out.push(' ');
            }
            pending_space = false;
            if at_sentence_start && c.is_alphabetic() {
                // maiúscula no início de frase (texto em CAIXA ALTA e nomes
                // já capitalizados passam: só sobe se está minúsculo)
                for ch in c.to_uppercase() {
                    out.push(ch);
                }
                at_sentence_start = false;
            } else {
                // vírgulas coladas antes de .?! (resíduo de muleta removida)
                // são removidas NA MESMA passada — ",,!" → "!" numa limpeza
                // só (o replace encadeado da v1 deixava ",!" para a próxima
                // passada e quebrava a idempotência — regressão real)
                if matches!(c, '.' | '!' | '?') {
                    while out.ends_with(',') {
                        out.pop();
                    }
                }
                out.push(c);
                if matches!(c, '.' | '!' | '?') {
                    at_sentence_start = true;
                } else if !c.is_whitespace() {
                    at_sentence_start = false;
                }
            }
            if matches!(c, ',' | ';' | ':' | '!' | '?') {
                pending_space = true;
            }
        }
    }
    let mut s = out.trim().to_string();
    // vírgulas residuais no início (resíduo de muleta cujo span não pôde
    // engolir a vírgula colada — ver remove_fillers): "assim,sabe,t." →
    // ", t." → "t."
    while s.starts_with(',') {
        s.remove(0);
    }
    s = s.trim().to_string();
    // a frase "recomeçou" depois do strip — capitaliza o primeiro char
    if let Some(first) = s.chars().next() {
        if first.is_alphabetic() {
            let upper: String = first.to_uppercase().collect();
            s = upper + &s[first.len_utf8()..];
        }
    }
    // ponto final só quando a frase ganhou fim pela remoção de muleta
    // ("disso né" → "Disso."); fragmento sem muleta fica como ditado
    if add_final_period && !s.ends_with(['.', '!', '?']) {
        s.push('.');
    }
    s
}

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

    fn clean(text: &str) -> String {
        clean_with(text, &[], &CleanConfig::default())
    }

    fn clean_with(text: &str, vocab: &[String], config: &CleanConfig) -> String {
        clean_text_with(text, vocab, config).text
    }

    // -----------------------------------------------------------------
    // Bug 1 — pontuação terminal por regra
    // -----------------------------------------------------------------

    #[test]
    fn trailing_ne_keeps_question_mark() {
        // "né?" é pergunta real: o '?' pertence à frase (bug 1 corrigido)
        assert_eq!(clean("a gente precisa disso né?"), "A gente precisa disso?");
    }

    #[test]
    fn trailing_ne_keeps_exclamation() {
        assert_eq!(clean("que dia incrível né!"), "Que dia incrível!");
    }

    #[test]
    fn trailing_ne_without_punct_adds_period() {
        assert_eq!(clean("a gente precisa disso, né"), "A gente precisa disso.");
    }

    #[test]
    fn ne_nao_keeps_question_mark() {
        assert_eq!(clean("isso vai dar certo, né não?"), "Isso vai dar certo?");
    }

    #[test]
    fn declarative_tags_stay_declarative() {
        // tag de concordância: a frase é declarativa, o '?' era da tag
        assert_eq!(clean("o projeto está bom, sabe?"), "O projeto está bom.");
        assert_eq!(clean("vamos mudar tudo, entendeu?"), "Vamos mudar tudo.");
        assert_eq!(clean("é assim mesmo, viu"), "É assim mesmo.");
        assert_eq!(clean("vai dar certo, tá?"), "Vai dar certo.");
    }

    #[test]
    fn mid_sentence_question_not_lost() {
        assert_eq!(clean("você vem amanhã, né?"), "Você vem amanhã?");
    }

    // -----------------------------------------------------------------
    // Muletas — positivos (paridade com a v1)
    // -----------------------------------------------------------------

    #[test]
    fn removes_leading_tipo() {
        assert_eq!(clean("tipo, o Sam Altman usa o Claude Code"), "O Sam Altman usa o Claude Code");
    }

    #[test]
    fn removes_tipo_assim_phrase() {
        assert_eq!(
            clean("tipo assim, eu acho que a gente deveria melhorar isso né"),
            "Eu acho que a gente deveria melhorar isso."
        );
    }

    #[test]
    fn removes_tipo_assim_mid_sentence_without_boundary() {
        // "é tipo assim" — o "tipo" cai pelo compound, sem fronteira antes
        assert_eq!(clean("é tipo assim, vamos começar"), "É vamos começar");
    }

    #[test]
    fn removes_mid_sentence_tipo_between_commas() {
        assert_eq!(clean("eu acho que, tipo, a gente vai"), "Eu acho que a gente vai");
    }

    #[test]
    fn removes_leading_assim() {
        assert_eq!(clean("assim, vamos começar pelo básico"), "Vamos começar pelo básico");
    }

    #[test]
    fn removes_leading_ne() {
        assert_eq!(clean("né, vamos lá"), "Vamos lá");
    }

    #[test]
    fn removes_isolated_entao() {
        assert_eq!(clean("Então, vamos começar"), "Vamos começar");
        assert_eq!(clean("vamos, então, começar"), "Vamos começar");
    }

    #[test]
    fn removes_isolated_ta() {
        assert_eq!(clean("vai dar certo, tá?"), "Vai dar certo.");
        assert_eq!(clean("tá, vamos lá"), "Vamos lá");
    }

    #[test]
    fn removes_leading_olha() {
        assert_eq!(clean("olha, isso aqui é importante"), "Isso aqui é importante");
    }

    #[test]
    fn cleans_english_word_mix_without_touching_terms() {
        assert_eq!(
            clean("tipo, eu falo GitHub e ele escreve GitHub, né?"),
            "Eu falo GitHub e ele escreve GitHub?"
        );
    }

    #[test]
    fn keeps_numbers_and_dates_untouched() {
        assert_eq!(
            clean("a reunião é dia 15, tipo, às 14h30 né"),
            "A reunião é dia 15 às 14h30."
        );
    }

    // -----------------------------------------------------------------
    // Bug 4 — fillers adjacentes múltiplos
    // -----------------------------------------------------------------

    #[test]
    fn removes_adjacent_fillers_with_commas() {
        assert_eq!(clean("tipo, assim, vamos agora"), "Vamos agora");
    }

    #[test]
    fn removes_adjacent_fillers_without_commas() {
        assert_eq!(clean("tipo assim vamos agora"), "Vamos agora");
    }

    #[test]
    fn removes_compound_chain_with_trailing_punct() {
        assert_eq!(clean("é tipo assim, né?"), "É?");
    }

    // -----------------------------------------------------------------
    // Muletas — guardas (negativos: NÃO podem mudar) — paridade com a v1
    // -----------------------------------------------------------------

    #[test]
    fn keeps_nominal_tipo_de_que() {
        assert_eq!(clean("que tipo de pessoa é essa"), "Que tipo de pessoa é essa");
        assert_eq!(clean("um tipo de coisa que eu gosto"), "Um tipo de coisa que eu gosto");
        assert_eq!(clean("é o tipo de assunto que eu evito"), "É o tipo de assunto que eu evito");
    }

    #[test]
    fn keeps_functional_assim() {
        assert_eq!(clean("assim como o João disse"), "Assim como o João disse");
        assert_eq!(clean("mesmo assim eu vou"), "Mesmo assim eu vou");
        assert_eq!(clean("faz assim que é melhor"), "Faz assim que é melhor");
        assert_eq!(clean("é assim que funciona"), "É assim que funciona");
    }

    #[test]
    fn keeps_conjunction_entao() {
        assert_eq!(clean("estudei, então passei"), "Estudei, então passei");
    }

    #[test]
    fn keeps_verb_sabe_in_middle_and_end() {
        assert_eq!(clean("você sabe o que eu quero dizer"), "Você sabe o que eu quero dizer");
        assert_eq!(clean("ele sabe?"), "Ele sabe?");
        assert_eq!(clean("isso é ótimo sabe?"), "Isso é ótimo sabe?");
    }

    #[test]
    fn keeps_ta_bom_and_verb_ta() {
        assert_eq!(clean("tá bom, vamos nessa"), "Tá bom, vamos nessa");
        assert_eq!(clean("ela tá cansada"), "Ela tá cansada");
        assert_eq!(clean("ele tá."), "Ele tá.");
    }

    #[test]
    fn keeps_imperative_olha() {
        assert_eq!(clean("olha isso aqui"), "Olha isso aqui");
    }

    #[test]
    fn keeps_mid_sentence_ne_without_punctuation() {
        assert_eq!(clean("você né que sabe disso"), "Você né que sabe disso");
    }

    // -----------------------------------------------------------------
    // URLs, domínios e e-mails — proteção (nova na v2)
    // -----------------------------------------------------------------

    #[test]
    fn url_internal_words_are_never_fillers() {
        assert_eq!(
            clean("acesse https://tipo.com e o site www.sabe.com.br"),
            "Acesse https://tipo.com e o site www.sabe.com.br"
        );
    }

    #[test]
    fn plain_domains_are_protected() {
        assert_eq!(
            clean("visite tipo.com e fale com o suporte"),
            "Visite tipo.com e fale com o suporte"
        );
    }

    #[test]
    fn emails_are_protected() {
        assert_eq!(
            clean("escreva para fulano@sabe.com, tá?"),
            "Escreva para fulano@sabe.com."
        );
    }

    // -----------------------------------------------------------------
    // Repetições (paridade + números, novo na v2)
    // -----------------------------------------------------------------

    #[test]
    fn dedupes_function_word_doubles() {
        assert_eq!(clean("eu eu acho que devemos"), "Eu acho que devemos");
        assert_eq!(clean("o o modelo está pronto"), "O modelo está pronto");
        assert_eq!(clean("eu vou vou testar"), "Eu vou testar");
        assert_eq!(clean("O o modelo"), "O modelo");
    }

    #[test]
    fn dedupes_three_plus_any_word() {
        assert_eq!(clean("OpenAI OpenAI OpenAI e o resto"), "OpenAI e o resto");
    }

    #[test]
    fn dedupes_number_doubles() {
        assert_eq!(clean("a reunião é 14h30 14h30"), "A reunião é 14h30");
        assert_eq!(clean("ano 2026 2026"), "Ano 2026");
    }

    #[test]
    fn keeps_repetition_separated_by_comma() {
        assert_eq!(clean("não, não, não quero"), "Não, não, não quero");
    }

    #[test]
    fn keeps_content_word_double() {
        assert_eq!(clean("muito muito bom"), "Muito muito bom");
    }

    #[test]
    fn keeps_number_repetition_separated_by_comma() {
        assert_eq!(clean("14h30, 14h30"), "14h30, 14h30");
    }

    // -----------------------------------------------------------------
    // Normalização (paridade com a v1)
    // -----------------------------------------------------------------

    #[test]
    fn fixes_space_before_punctuation_and_double_spaces() {
        assert_eq!(clean("oi ,tudo bem"), "Oi, tudo bem");
        assert_eq!(clean("  duplo    espaço  "), "Duplo espaço");
    }

    #[test]
    fn capitalizes_sentence_starts() {
        assert_eq!(clean("primeiro item. segundo item!"), "Primeiro item. Segundo item!");
    }

    #[test]
    fn cleans_comma_before_question_mark() {
        assert_eq!(clean("disso,?"), "Disso?");
    }

    #[test]
    fn keeps_existing_terminal_punctuation() {
        assert_eq!(clean("vamos lá."), "Vamos lá.");
        assert_eq!(clean("já terminamos!"), "Já terminamos!");
    }

    #[test]
    fn empty_and_whitespace_are_untouched() {
        assert_eq!(clean(""), "");
        assert_eq!(clean("   "), "   ");
    }

    // -----------------------------------------------------------------
    // Variantes do vocabulário (paridade + unicode, novo na v2)
    // -----------------------------------------------------------------

    #[test]
    fn fixes_phonetic_variants_of_vocab_terms() {
        let vocab = vec!["Sam Altman".to_string(), "Claude Code".to_string()];
        assert_eq!(
            clean_with("o sematlman usa o cloud code", &vocab, &CleanConfig::default()),
            "O Sam Altman usa o Claude Code"
        );
        assert_eq!(
            clean_with("semautman e samautiman", &vocab, &CleanConfig::default()),
            "Sam Altman e Sam Altman"
        );
    }

    #[test]
    fn fixes_case_and_spacing_of_terms() {
        let vocab = vec![
            "GitHub".to_string(),
            "ChatGPT".to_string(),
            "OpenAI".to_string(),
            "Anthropic".to_string(),
        ];
        assert_eq!(
            clean_with("sam usa github e openai", &vocab, &CleanConfig::default()),
            "Sam usa GitHub e OpenAI"
        );
        assert_eq!(
            clean_with("git hub e chat gpt e antropic", &vocab, &CleanConfig::default()),
            "GitHub e ChatGPT e Anthropic"
        );
    }

    #[test]
    fn variant_fix_respects_word_boundaries() {
        let vocab = vec!["Sam Altman".to_string(), "Claude Code".to_string()];
        assert_eq!(
            clean_with("sematlmanx e xcloud code", &vocab, &CleanConfig::default()),
            "Sematlmanx e xcloud code"
        );
    }

    #[test]
    fn variant_only_applies_when_term_is_in_vocab() {
        let vocab = vec!["Claude".to_string()];
        assert_eq!(
            clean_with("o sematlman", &vocab, &CleanConfig::default()),
            "O sematlman"
        );
    }

    #[test]
    fn keeps_english_words_intact() {
        let vocab = vec!["GitHub".to_string()];
        assert_eq!(
            clean_with("eu uso o GitHub para versionar, tipo, todos os dias né", &vocab, &CleanConfig::default()),
            "Eu uso o GitHub para versionar todos os dias."
        );
    }

    #[test]
    fn fixes_accented_vocab_terms() {
        // bug 3 corrigido: eq_ignore_ascii_case não existia para acentos
        let vocab = vec!["José".to_string(), "São Paulo".to_string()];
        assert_eq!(
            clean_with("moro em são paulo e falo com o josé", &vocab, &CleanConfig::default()),
            "Moro em São Paulo e falo com o José"
        );
    }

    #[test]
    fn user_fillers_are_removed_when_isolated() {
        let config = CleanConfig {
            user_fillers: vec!["mano".to_string()],
            ..CleanConfig::default()
        };
        assert_eq!(clean_with("mano, vamos lá", &[], &config), "Vamos lá");
        // não-isolado (seguido de palavra) não cai: conservador
        assert_eq!(clean_with("o mano veio", &[], &config), "O mano veio");
    }

    // -----------------------------------------------------------------
    // replace_word_matches (compartilhada com stt.rs) — paridade + fold
    // -----------------------------------------------------------------

    #[test]
    fn replace_word_matches_joins_spaced_variants() {
        assert_eq!(
            replace_word_matches("o modelo da Deep Seek no Git Hub", "DeepSeek", "DeepSeek"),
            "o modelo da DeepSeek no Git Hub"
        );
    }

    #[test]
    fn replace_word_matches_is_case_insensitive() {
        assert_eq!(replace_word_matches("deep seek agora", "DeepSeek", "DeepSeek"), "DeepSeek agora");
    }

    #[test]
    fn replace_word_matches_never_touches_similar_words() {
        assert_eq!(
            replace_word_matches("Cloud e Chat EPT e HTTP", "Claude", "Claude"),
            "Cloud e Chat EPT e HTTP"
        );
    }

    #[test]
    fn replace_word_matches_respects_boundaries() {
        assert_eq!(
            replace_word_matches("deepseekx e xdeepseek", "DeepSeek", "DeepSeek"),
            "deepseekx e xdeepseek"
        );
    }

    #[test]
    fn replace_word_matches_flat_matches_across_spaces() {
        // o casamento é "flat": espaços em qualquer posição não impedem
        // a variante fonética ("sem atlman" também é "sematlman")
        assert_eq!(
            replace_word_matches("o sem atlman veio", "sematlman", "Sam Altman"),
            "o Sam Altman veio"
        );
    }

    #[test]
    fn replace_word_matches_full_unicode_fold() {
        // bug 2 corrigido: folding multi-char NÃO casa parcialmente —
        // "İ" não é "i" sem regra turca; "Ç" casa com "ç" (folding 1:1)
        assert_eq!(replace_word_matches("Café ÇAÇA", "çaça", "CAÇA"), "Café CAÇA");
        assert_eq!(replace_word_matches("İstanbul", "istanbul", "ISTANBUL"), "İstanbul");
    }

    #[test]
    fn stats_are_counted_per_pass() {
        let cfg = CleanConfig::default();
        let mut t = "tipo, eu eu falo github né".to_string();
        let (t2, variants_fixed) = fix_variants(&t, &["GitHub".to_string()]);
        t = t2;
        assert_eq!(variants_fixed, 1);
        let stream = TokenStream::tokenize(&t);
        let (stream, trailing, fillers) = remove_fillers(&stream, &cfg);
        assert_eq!(fillers, 2); // "tipo," e "né"
        assert!(trailing);
        let (stream, reps) = dedupe_repetitions(&stream);
        assert_eq!(reps, 1); // "eu eu"
        assert_eq!(normalize(&stream, trailing), "Eu falo GitHub.");
    }

    #[test]
    fn filler_removal_never_glues_words() {
        // regressão real achada pelo fuzzing: a vírgula à direita de uma
        // muleta com palavra colada sem espaço NÃO é engolida — senão
        // "assim,sabe,t." viraria "assimt." (palavra inventada). A
        // vírgula residual do início é limpa pelo normalize.
        assert_eq!(clean("Étipo assim,sabe,t.U2S5"), "Étipo assim, t.U2S5");
        assert_eq!(clean("assim,sabe,t.U2S5"), "T.U2S5");
        assert_eq!(clean("tipo,o Sam"), "O Sam");
    }

    #[test]
    fn removes_filler_between_commas_both_sides() {
        // cobertura pedida na re-revisão (item B): muleta com vírgula dos
        // dois lados é um parêntese — o span consome as DUAS vírgulas
        // (consistente com "que, tipo, a gente vai" → "que a gente vai")
        assert_eq!(clean("disso, né, vamos agora"), "Disso vamos agora");
        assert_eq!(clean("bom, sabe, vamos lá"), "Bom vamos lá");
    }
}