-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLouFormatter.py
More file actions
1547 lines (1377 loc) · 47.1 KB
/
Copy pathLouFormatter.py
File metadata and controls
1547 lines (1377 loc) · 47.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections.abc import Iterable
import re
_GIF_PATTERN = re.compile(r"(GIF:[\w-]+)", re.IGNORECASE)
# Split after sentence-ending punctuation followed by whitespace
_SENTENCE_SPLIT_PATTERN = re.compile(r"(?<=[.?!…])\s+")
# Split when …/?/! is immediately followed by uppercase (no space between)
_SENTENCE_SPLIT_NO_SPACE = re.compile(r"(?<=[?!…])(?=[A-ZÁ-Ú])")
_MAJUSCULE_SPLIT_PATTERN = re.compile(r"(?<=[a-zá-úç0-9,])\s+(?=[A-ZÁ-ÚÇ])")
# Comma followed by a transition/conjunction word — good split point for long chunks
_COMMA_TRANSITION_RE = re.compile(
r',\s+(?=(?:'
r'mas|porém|porem|então|entao|só|so|tipo|pois|enfim|aliás|alias|'
r'porque|inclusive|aí|ai|daí|dai|já|ja|até|ate|ainda|agora|depois|'
r'quando|enquanto|nem|ou'
r')\b)',
re.IGNORECASE,
)
# Maximum length for a single chunk before forced splitting
_MAX_CHUNK_LENGTH = 120
# Matches context-injection brackets that the LLM may regurgitate.
_CONTEXT_BRACKET_RE = re.compile(
r'\['
r'(?:'
r'Contexto|Ferramentas|GIFs?\s*[Dd]ispon|Instruções|Instrucoes|'
r'Lembretes|Estilo|Gírias|Girias|Foco|Atenção|Atencao|'
r'INSTRUÇÕES|Contexto Pessoal|Contexto de Tempo|'
r'[A-ZÁ-Ú][^\]]{8,}'
r')'
r'[^\]]*\]',
re.IGNORECASE,
)
# Matches a "Lou:" / "Louise:" role prefix at the start of a line.
_ROLE_PREFIX_RE = re.compile(r'^\s*(?:Lou|Louise)\s*:\s*', re.IGNORECASE)
_EMOJI_PATTERN = re.compile(
"["
"\U0001F600-\U0001F64F"
"\U0001F300-\U0001F5FF"
"\U0001F680-\U0001F6FF"
"\U0001F700-\U0001FAFF"
"\U00002702-\U000027B0"
"\U000024C2-\U0001F251"
"]+",
flags=re.UNICODE,
)
_PREPOSITIONS = {"de", "da", "do", "dos", "das", "pra", "pro", "para", "no", "na", "nos", "nas", "em"}
_PROPER_JOINERS = {"the", "los", "las", "san", "santa", "são"}
_ARTICLE_CONNECTORS = {"o", "a", "os", "as", "um", "uma", "uns", "umas"}
_INTERJECTION_SPLITS = {
"hehe",
"haha",
"hihi",
"eita",
"opa",
"ah",
"ai",
"uai",
"ixi",
"vish",
"aff",
"afff",
"hmm",
"hmmm",
"hmmmm",
"humm",
"hummm",
"hummmm",
"oxe",
"oxi",
"oba",
"bah",
}
_DYNAMIC_INTERJECTION_PATTERN = re.compile(r"^([a-zá-úç]{2,8})([!….,]*)\s+(.*)$", re.IGNORECASE)
_INTERJECTION_VOCATIVE_PATTERN = re.compile(r"^([a-zá-úç]{1,8}),\s*(.+)$", re.IGNORECASE)
_INTERJECTION_SOLO_PATTERN = re.compile(r"^([a-zá-úç]{1,8})$", re.IGNORECASE)
_SENTENCE_STARTERS = {
"agora",
"hoje",
"entao",
"então",
"mas",
"quando",
"onde",
"enquanto",
"porém",
"porem",
"entretanto",
"depois",
"ate",
"até",
"bom",
"olha",
}
_HARD_SENTENCE_BREAKERS = {
"sem",
"isso",
"essa",
"esse",
"essas",
"esses",
"assim",
"inclusive",
"entao",
"então",
"mas",
"só",
"so",
"tipo",
"pois",
"enfim",
"aliás",
"bora",
"partiu",
}
_EMPHASIS_LEADS = {
"ta",
"tá",
"to",
"tô",
"tava",
"tando",
"tamo",
"esta",
"está",
"esta",
"estao",
"estão",
"fica",
"ficou",
"ficando",
"ficar",
"é",
"eh",
"foi",
"vai",
"segue",
"parece",
"pareceu",
"tava",
}
_UPPERCASE_RESTART_TOKENS = (
"A",
"O",
"As",
"Os",
"Esse",
"Essa",
"Esses",
"Essas",
"Este",
"Esta",
"Estes",
"Estas",
"Aquele",
"Aquela",
"Aqueles",
"Aquelas",
"Isto",
"Isso",
"Aquilo",
)
_ACRONYM_EXCEPTIONS = {
"nasa",
"html",
"http",
"https",
"cpu",
"gpu",
"ai",
"lol",
"br",
"sp",
}
_TITLE_CONNECTORS = {
"da",
"de",
"do",
"das",
"dos",
"vs",
"vs.",
"x",
"feat",
"ft",
"and",
"the",
"of",
"&",
"by",
}
_TITLE_LOWER_JOINERS = _TITLE_CONNECTORS | {
"del",
"della",
"van",
"von",
"der",
"den",
"para",
"por",
}
# Matches bullet-point / numbered list patterns typical of assistant-mode output
_BULLET_LIST_RE = re.compile(r'^\s*(?:\d+[.)\-]|[-•*])\s+', re.MULTILINE)
_NAME_STOPWORDS = {"pai", "lou", "mateus", "mãe", "mae"}
# Common uppercase words that are NOT proper nouns (pronouns, articles, etc.)
# Prevent them from being title-merged with the previous chunk
_UPPERCASE_NON_TITLE_WORDS = {
"você", "voce", "ele", "ela", "eles", "elas", "nós", "nos",
"eu", "tu", "isso", "esse", "essa", "este", "esta", "aqui",
"ali", "lá", "la", "já", "ja", "não", "nao", "sim", "bem",
"muito", "mais", "menos", "tudo", "nada", "sempre", "nunca",
"agora", "hoje", "ontem", "amanhã", "amanha", "depois",
"quando", "onde", "como", "quem", "qual", "quanto",
}
_SPLIT_PREFERRED_STARTERS = {
"lembra",
"queria",
"quero",
"vamos",
"vamo",
"bora",
"olha",
"pensa",
}
_COMMA_LOWERCASE_WORDS = {
"mas",
"mais",
"que",
"call",
"boa",
"boas",
"bom",
"bons",
"só",
"so",
"olha",
"ai",
"aí",
"pai",
"tipo",
"bora",
"vamo",
"vamos",
"e",
"ou",
"pra",
"pro",
"porém",
"porem",
"então",
"entao",
}
_QUE_LOWERCASE_WORDS = {"call", "boa", "boas", "bom", "bons"}
_DE_DESCRIPTOR_WORDS = {
"boa",
"boas",
"bom",
"bons",
"linda",
"lindas",
"lindo",
"lindos",
"maravilhosa",
"maravilhoso",
"maravilhosas",
"maravilhosos",
"absurda",
"absurdas",
"absurdo",
"absurdos",
"doida",
"doidas",
"doido",
"doidos",
"massa",
"top",
"suave",
"incrível",
"incriveis",
"incrivel",
"incríveis",
"braba",
"brabo",
}
_QUESTION_STARTERS = {
"cadê",
"cade",
"qual",
"quais",
"quando",
"onde",
"como",
"quem",
"que",
"quanto",
"quantos",
"quantas",
}
_QUESTION_LEAD_INS = {"ai", "aí", "aii", "opa", "olha", "tipo", "eita", "aff", "oxe", "oxi", "ei", "vish"}
_QUESTION_VOCATIVES = {"pai"}
# Short affirmation/interjection words that expect a comma before the next clause
_COMMA_AFTER_SHORT_WORDS = {
"ok", "okay", "sim", "não", "nao", "claro", "certo", "bom",
"beleza", "tá", "ta", "tô", "to", "pronto", "enfim", "aliás",
"alias", "verdade", "exato", "obvio", "óbvio", "pois", "aham",
"uhum", "hmm", "hm", "ah", "oh", "putz", "vixi", "eita",
"opa", "oxe", "uai", "ué", "ue", "mano", "real", "sério",
"serio", "talvez", "tipo", "olha", "vish", "ata", "atá",
}
_QUESTION_PREFIX_PHRASES = (
"por que",
"pra que",
"será que",
"sera que",
)
_QUESTION_SUFFIXES = (
"cadê",
"cadê você",
"cadê voce",
"cadê vc",
"cade",
"cade você",
"cade voce",
"cade vc",
"onde",
"quando",
"como",
"qual",
"quais",
"tá aí",
"ta ai",
"tá por aí",
"ta por ai",
"ainda aí",
"ainda ai",
"me responde",
"fala comigo",
"pra onde",
"por que",
"pra que",
"o que",
)
_QUESTION_MID_MARKERS = (
" o que ",
" pra que ",
" por que ",
" será que",
" sera que",
" tá aí",
" ta ai",
" tá por aí",
" ta por ai",
" cadê ",
" cade ",
" que horas",
)
def _clean_llm_artifacts(text: str) -> str:
"""Remove common artefacts that local LLMs leak into their output.
This runs *before* any splitting so that noisy tokens never reach the
chunk pipeline. The cleaning covers:
* Context-bracket injections the model echoes from the history
(e.g. ``[GIFs Disponíveis: happy, lol, wow]``)
* ``Lou:`` / ``Louise:`` role prefixes the model emits at the start
of a line or at the very beginning.
* Template tokens from Llama-2, ChatML, etc.
* Stray whitespace / blank lines that remain after stripping.
"""
if not text:
return ""
# 1. Strip bracketed context injections
cleaned = _CONTEXT_BRACKET_RE.sub("", text)
# 2. Strip per-line "Lou:" or "Louise:" role prefixes
lines = cleaned.split("\n")
stripped_lines: list[str] = []
for line in lines:
line = _ROLE_PREFIX_RE.sub("", line)
stripped = line.strip()
if stripped:
stripped_lines.append(stripped)
cleaned = "\n".join(stripped_lines)
# 3. Remove common template tokens that may survive earlier cleaning
for tok in ("[INST]", "[/INST]", "<<SYS>>", "<</SYS>>",
"<s>", "</s>", "<|im_start|>", "<|im_end|>"):
cleaned = cleaned.replace(tok, "")
# 4. Strip bullet-point / numbered-list prefixes (assistant-mode)
cleaned = _BULLET_LIST_RE.sub("", cleaned)
# 5. Remove garbage lines (e.g. "- Lou", "Lou", bare role names, list bullets with just a name)
final_lines: list[str] = []
for ln in cleaned.split("\n"):
ln = ln.strip()
# Skip lines that are just "- Lou", "* Lou", "Lou", "Louise", etc.
bare = re.sub(r'^[\-\*•]\s*', '', ln).strip()
if bare.lower() in ('lou', 'louise', 'pai', 'mateus', ''):
continue
# Skip lines that look like markdown headers
if re.match(r'^#{1,4}\s', ln):
continue
final_lines.append(ln)
cleaned = "\n".join(final_lines)
# 6. Strip stray quote marks the LLM may leak
cleaned = re.sub(r'["\\"]+', '', cleaned)
# Clean up leftover whitespace from removed quotes
cleaned = re.sub(r' +', ' ', cleaned)
# 7. Fix broken greetings early (before splitting can fragment them)
cleaned = _fix_broken_greetings(cleaned)
# 8. Collapse residual whitespace
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
return cleaned.strip()
def sanitize_and_split_response(text: str, style_terms: Iterable[str] | None = None) -> list:
"""Normalizer that mimics the legacy Lou formatter while fixing edge cases."""
if not text:
return []
# --- LLM artifact pre-cleaning ---
text = _clean_llm_artifacts(text)
# --- Fix broken greetings BEFORE any splitting ---
# Must run here so "Boa, Noite" → "Boa noite" before
# _MAJUSCULE_SPLIT_PATTERN fragments on comma+uppercase.
text = _fix_broken_greetings(text)
if "GIF:" in text:
return _split_gif_segments(text, style_terms=style_terms)
cleaned = _EMOJI_PATTERN.sub("", text)
cleaned = cleaned.strip()
if not cleaned:
return []
# --- Fix missing commas after short words BEFORE splitting ---
# Must run here so "Ok Se" → "Ok, se" before _MAJUSCULE_SPLIT_PATTERN
# would fragment them into separate chunks.
cleaned = _fix_comma_after_short_words_global(cleaned)
style_tokens = _prepare_style_tokens(style_terms)
lines = [line.strip() for line in cleaned.split("\n") if line.strip()]
rough_chunks: list[str] = []
for line in lines:
# First split on punctuation + whitespace, then on punctuation + uppercase (no space)
sentence_chunks = _SENTENCE_SPLIT_PATTERN.split(line)
expanded: list[str] = []
for sc in sentence_chunks:
expanded.extend(_SENTENCE_SPLIT_NO_SPACE.split(sc))
for sentence in expanded:
sentence = sentence.strip()
if not sentence:
continue
# Split on comma + transition words ("mas", "então", etc.)
comma_parts = _COMMA_TRANSITION_RE.split(sentence)
for cp in comma_parts:
cp = cp.strip()
if not cp:
continue
sub_chunks = _MAJUSCULE_SPLIT_PATTERN.split(cp)
for chunk in sub_chunks:
stripped = chunk.strip()
if not stripped:
continue
if stripped.startswith(",") and rough_chunks:
rough_chunks[-1] = f"{rough_chunks[-1]} {stripped.lstrip(', ').strip()}".strip()
else:
rough_chunks.append(stripped)
# Re-attach chunks that start with a vocative (Pai, Lou, etc.)
# so "Boa noite," + "Pai, como vai?" becomes "Boa noite, pai, como vai?"
rough_chunks = _merge_vocative_chunks(rough_chunks)
# Force-split any remaining overly long chunks at natural break points
rough_chunks = _split_long_chunks(rough_chunks)
repaired = _merge_proper_nouns(rough_chunks)
repaired = _merge_dangling_fragments(repaired)
final_chunks: list[str] = []
for chunk in repaired:
normalized = _normalize_chunk(chunk)
if not normalized:
continue
style_segments = _split_on_style_terms(normalized, style_tokens)
for segment in style_segments:
for emphasis_chunk in _split_uppercase_emphasis(segment):
for restart_chunk in _split_uppercase_restart_chunks(emphasis_chunk):
final_chunks.extend(_split_interjection_chunk(restart_chunk, style_tokens))
composed_chunks: list[str] = []
for chunk in final_chunks:
composed_chunks.extend(_split_after_question_marks(chunk))
ensured_chunks: list[str] = []
for segment in composed_chunks:
ensured = _ensure_question_punctuation(segment)
if ensured:
ensured_chunks.append(ensured)
return ensured_chunks
def _merge_vocative_chunks(chunks: list[str]) -> list[str]:
"""Re-attach chunks that start with a vocative like 'Pai', 'Lou', 'Mateus'.
When _MAJUSCULE_SPLIT_PATTERN splits 'Boa noite, Pai, como vai?' into
['Boa noite,', 'Pai, como vai?'], this function merges them back.
Also strips trailing commas from the left chunk after merge.
"""
if not chunks:
return chunks
merged: list[str] = []
for chunk in chunks:
stripped = chunk.strip()
if not stripped:
continue
if merged:
first_word = _clean_token_edges(stripped.split()[0]).lower() if stripped.split() else ""
prev = merged[-1]
# Merge when previous chunk ends with comma and current starts with vocative
if first_word in _NAME_STOPWORDS and prev.rstrip().endswith(","):
merged[-1] = f"{prev} {stripped}"
continue
merged.append(stripped)
# Strip any trailing commas that remain after other processing
return [c.rstrip(",").strip() if c.endswith(",") else c for c in merged if c.strip()]
def _split_gif_segments(text: str, style_terms: Iterable[str] | None = None) -> list[str]:
segments = _GIF_PATTERN.split(text)
tokens: list[str] = []
for segment in segments:
stripped = (segment or "").strip()
if not stripped:
continue
if stripped.upper().startswith("GIF:"):
tokens.append(stripped)
else:
tokens.extend(sanitize_and_split_response(stripped, style_terms=style_terms))
return tokens
def _split_long_chunks(chunks: list[str]) -> list[str]:
"""Force-split chunks that exceed _MAX_CHUNK_LENGTH at a natural break point."""
result: list[str] = []
for chunk in chunks:
if len(chunk) <= _MAX_CHUNK_LENGTH:
result.append(chunk)
continue
# Try splitting at comma + transition word first
parts = _COMMA_TRANSITION_RE.split(chunk)
if len(parts) > 1:
result.extend(p.strip() for p in parts if p.strip())
continue
# Try splitting at any comma near the midpoint
mid = len(chunk) // 2
best_comma = -1
for i, ch in enumerate(chunk):
if ch == ',':
if best_comma == -1 or abs(i - mid) < abs(best_comma - mid):
best_comma = i
if best_comma > 15 and best_comma < len(chunk) - 15:
left = chunk[:best_comma].strip()
right = chunk[best_comma + 1:].strip()
if left:
result.append(left)
if right:
result.append(right)
continue
# Try splitting at a conjunction/preposition word boundary near the midpoint
_SPLIT_WORDS = {'que', 'pra', 'pro', 'tipo', 'porque', 'ou', 'e', 'nem'}
best_split = -1
words_iter = re.finditer(r'\b(\w+)\b', chunk)
for m in words_iter:
if m.group(1).lower() in _SPLIT_WORDS and m.start() > 15 and m.start() < len(chunk) - 15:
if best_split == -1 or abs(m.start() - mid) < abs(best_split - mid):
best_split = m.start()
if best_split > 0:
left = chunk[:best_split].strip()
right = chunk[best_split:].strip()
if left and right:
result.append(left)
result.append(right)
continue
# No good split point — keep as-is
result.append(chunk)
return result
def _prepare_style_tokens(style_terms: Iterable[str] | None) -> list[str]:
if not style_terms:
return []
normalized: list[str] = []
seen: set[str] = set()
for term in style_terms:
cleaned = _normalize_style_term(term)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
normalized.append(cleaned)
normalized.sort(key=len, reverse=True)
return normalized
def _normalize_style_term(term: str | None) -> str:
if not term:
return ""
cleaned = re.sub(r"\s+", " ", term.strip())
return cleaned.lower()
def _split_on_style_terms(text: str, style_tokens: list[str]) -> list[str]:
if not text or not style_tokens:
return [text] if text else []
lowered = text.lower()
split_points: set[int] = set()
for token in style_tokens:
token_len = len(token)
if token_len == 0:
continue
start = 0
while start < len(text):
idx = lowered.find(token, start)
if idx == -1:
break
before_char = text[idx - 1] if idx > 0 else " "
after_index = idx + token_len
after_char = text[after_index] if after_index < len(text) else " "
if idx > 0 and _is_style_boundary_char(before_char) and _is_style_boundary_char(after_char):
split_points.add(idx)
start = idx + max(1, token_len)
if not split_points:
return [text]
ordered_points = sorted(split_points)
segments: list[str] = []
last_index = 0
for point in ordered_points:
if point <= last_index:
continue
segment = text[last_index:point].strip()
if segment:
segments.append(segment)
last_index = point
tail = text[last_index:].strip()
if tail:
segments.append(tail)
return segments if segments else [text]
def _is_style_boundary_char(char: str) -> bool:
if not char:
return True
if char.isspace():
return True
return char in ",.;!?…:()[]{}'\"-—"
def _clean_token_edges(token: str) -> str:
if not token:
return ""
return re.sub(r"^[^0-9A-Za-zÁ-Úá-úçÇ]+|[^0-9A-Za-zÁ-Úá-úçÇ]+$", "", token)
def _match_dynamic_interjection(text: str) -> list[str] | None:
snippet = text.strip()
if not snippet:
return None
match = _DYNAMIC_INTERJECTION_PATTERN.match(snippet)
if not match:
return None
word, punctuation, tail = match.groups()
tail = (tail or "").strip()
if not tail:
return None
if punctuation and "," in punctuation:
return None
if not _looks_like_dynamic_interjection(word or ""):
return None
head = f"{word}{punctuation or ''}".strip()
return [head, tail]
def _looks_like_dynamic_interjection(word: str) -> bool:
if not word:
return False
lower = word.lower()
if lower in _INTERJECTION_SPLITS:
return True
if len(lower) <= 6 and re.search(r"(.)\1{2,}", lower):
return True
if len(lower) <= 6 and re.search(r"([aeiouáéíóú])\1+$", lower):
return True
dynamic_prefixes = ("hum", "hmm", "aff", "ah", "oxe", "oxi", "bah", "eita", "opa")
if any(lower.startswith(prefix) for prefix in dynamic_prefixes):
return True
return False
def _extract_title_like_run(tokens: list[str]) -> list[str]:
run: list[str] = []
started = False
for token in tokens:
cleaned = _clean_token_edges(token)
if not cleaned:
continue
lower = cleaned.lower()
if cleaned.isdigit():
run.append(cleaned)
started = True
continue
if lower in _TITLE_LOWER_JOINERS:
if started:
run.append(lower)
continue
break
if cleaned[0].isupper():
run.append(cleaned)
started = True
continue
break
if run and any(part[0].isupper() or part.isdigit() for part in run):
return run
return []
def _should_force_merge_title(previous: str, current: str) -> bool:
prev = previous.rstrip()
curr = current.strip()
if not prev or not curr:
return False
curr_tokens = curr.split()
if not curr_tokens:
return False
first = _clean_token_edges(curr_tokens[0]).lower()
if first and first in _SENTENCE_STARTERS:
return False
if first and first in _UPPERCASE_NON_TITLE_WORDS:
return False
title_run = _extract_title_like_run(curr_tokens)
if not title_run:
return False
first_word = _clean_token_edges(curr_tokens[0]).lower()
if first_word in _SPLIT_PREFERRED_STARTERS:
return False
if any(part.isdigit() for part in title_run):
return True
return len(title_run) >= 2
def _merge_proper_nouns(chunks: list[str]) -> list[str]:
merged: list[str] = []
for chunk in chunks:
if merged and _should_merge_with_previous(merged[-1], chunk):
merged[-1] = f"{merged[-1]} {chunk}".strip()
else:
merged.append(chunk)
return merged
def _merge_dangling_fragments(chunks: list[str]) -> list[str]:
merged: list[str] = []
for index, chunk in enumerate(chunks):
candidate = chunk
if merged:
candidate = _build_title_candidate(chunks, index)
if merged and _looks_like_dangling_fragment(merged[-1], candidate):
merged[-1] = f"{merged[-1]} {chunk}".strip()
else:
merged.append(chunk)
return merged
def _build_title_candidate(chunks: list[str], start_index: int) -> str:
combined: list[str] = []
title_started = False
max_window = 3
for offset in range(start_index, min(len(chunks), start_index + max_window)):
token = chunks[offset].strip()
if not token:
break
words = token.split()
if not words:
break
first_clean = _clean_token_edges(words[0])
if not first_clean:
break
lower_first = first_clean.lower()
if lower_first in _SENTENCE_STARTERS and not title_started:
break
if first_clean[0].isupper() or first_clean.isdigit():
combined.append(token)
title_started = True
continue
if title_started and (lower_first in _TITLE_LOWER_JOINERS or first_clean.isdigit()):
combined.append(token)
continue
break
return " ".join(combined).strip() if combined else chunks[start_index]
def _should_merge_with_previous(previous: str, current: str) -> bool:
current = current.strip()
previous = previous.rstrip()
if not previous or not current:
return False
if not current[0].isupper():
return False
# Common pronouns/adverbs that start with uppercase after a split should NOT be merged
curr_first_word = current.split()[0]
curr_first_clean = _clean_token_edges(curr_first_word).lower()
if curr_first_clean in _UPPERCASE_NON_TITLE_WORDS:
return False
prev_last_word = previous.split()[-1]
prev_token = prev_last_word.lower()
if prev_token in _PREPOSITIONS:
return True
if prev_last_word.lower() in _PROPER_JOINERS:
return True
if _looks_like_title_stitch(previous, current):
return True
if _looks_like_compound_title_bridge(previous, current):
return True
if _should_merge_short_fragment(previous, current):
return True
return False
def _looks_like_title_stitch(previous: str, current: str) -> bool:
prev = previous.rstrip()
curr = current.strip()
if not prev or not curr:
return False
if prev[-1] in ".?!…":
return False
prev_words = prev.split()
if not prev_words:
return False
prev_last = _clean_token_edges(prev_words[-1])
curr_words = curr.split()
if not prev_last or not curr_words:
return False
curr_first = _clean_token_edges(curr_words[0])
if not curr_first:
return False
if prev_last.lower() in _NAME_STOPWORDS or curr_first.lower() in _NAME_STOPWORDS:
return False
# Common pronouns/adverbs should NOT be treated as title words
if curr_first.lower() in _UPPERCASE_NON_TITLE_WORDS:
return False
if not prev_last[0].isupper() or not curr_first[0].isupper():
return False
if len(curr_words) == 1:
return True
lookahead = curr_words[1:3]
for token in lookahead:
cleaned = _clean_token_edges(token)
if not cleaned:
continue
if cleaned[0].islower() or cleaned.lower() in _TITLE_LOWER_JOINERS:
return True
return False
def _looks_like_compound_title_bridge(previous: str, current: str) -> bool:
prev_tokens = previous.split()
curr_tokens = current.split()
if not prev_tokens or not curr_tokens:
return False
# If the first word of current is a common pronoun/adverb, never merge
first_curr = _clean_token_edges(curr_tokens[0]).lower()
if first_curr in _UPPERCASE_NON_TITLE_WORDS:
return False
window = [*prev_tokens[-3:], *curr_tokens[:3]]
if not window:
return False
started = False
uppercase_hits = 0
run: list[str] = []
for raw in window:
token = _clean_token_edges(raw)
if not token:
continue
lower = token.lower()
# Skip non-title words from counting as title parts
if lower in _UPPERCASE_NON_TITLE_WORDS:
if started:
break
continue
if token[0].isupper() or token.isdigit():
run.append(token)
uppercase_hits += 1
started = True
continue
if started and lower in _TITLE_LOWER_JOINERS:
run.append(lower)
continue
if started:
break
if uppercase_hits < 2 or len(run) < 2:
return False
if run[-1].lower() in _TITLE_LOWER_JOINERS:
return False
return True
def _looks_like_dangling_fragment(previous: str, current: str) -> bool:
prev = previous.rstrip()
curr = current.strip()
if not prev or not curr:
return False
if prev[-1] in ".?!…":
return False
if _should_force_merge_title(prev, curr):
return True
# Coloned titles like "Detroit: Become" should merge with continuation words
if ":" in prev:
head, tail = prev.rsplit(":", 1)
tail_words = tail.strip().split()
if tail.strip() and len(tail_words) <= 2:
first_curr = curr.split()[0]
if first_curr and first_curr[0].isupper():
return True
prev_last = prev.split()[-1]
if not prev_last:
return False
# Se a frase anterior termina com um artigo e a próxima começa em maiúscula, deve unir
if prev_last.lower() in _ARTICLE_CONNECTORS and curr.split()[0][0].isupper():
return True
if not prev_last[0].isupper():
return False
curr_words = curr.split()
if not curr_words:
return False
starter_token = curr_words[0].rstrip(",.!?…").lower()
if starter_token and starter_token in _SPLIT_PREFERRED_STARTERS:
return False
if starter_token in _HARD_SENTENCE_BREAKERS:
return False
if len(curr_words) <= 3 and curr_words[0][0].isupper():
return True
if _looks_like_title_stitch(prev, curr):
return True
if _looks_like_compound_title_bridge(prev, curr):
return True
if _should_merge_short_fragment(prev, curr):
return True
first_token = curr_words[0]
if first_token.endswith(",") and first_token[0].isupper():
return True
return False
# Fix greetings where the model inserts stray commas / quotes: "Boa, noite" → "Boa noite"
_BROKEN_GREETING_RE = re.compile(
r'\b(Bo[am])[\s,"\']*(dia|tarde|noite)\b',
re.IGNORECASE,
)
def _fix_broken_greetings(text: str) -> str:
"""Normalize common Portuguese greetings that the model may break with commas.