Elffuss BraidHub

kikocis/online-translator public

main · 28.7 KiBRawPermalink
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4"""
5Lightweight LLM Module
6---------------------
7Provides lightweight language model functionality for semantic validation
8and text processing in the Online-Translator application.
9
10Copyright (c) 2025 Kiko Cisneros
11Licensed under the MIT License (see LICENSE file for details)
12"""
13
14import re
15import numpy as np
16from collections import Counter, deque
17
18
19class LightweightLLM:
20 """Sistema de concatenación simple basado en distancia de Mahalanobis palabra por palabra"""
21
22 def __init__(self):
23 self.model_loaded = False
24 self.model = None
25 self.tokenizer = None
26 # ✅ SIMPLIFIED APPROACH - Word-by-word Mahalanobis distance
27 self.min_text_length = 3
28 self.word_history = [] # Store recent words for Mahalanobis calculation
29 self.max_history = 50 # Keep last 50 words
30 print("🧠 Initializing Mahalanobis word-distance system...")
31 print("✅ Word-distance system ready")
32
33 def smart_concatenate_with_mahalanobis(self, accumulated_text, new_text):
34 """🧮 SIMPLE: Concatenación simple basada en solapamientos palabra por palabra"""
35 if not new_text or not new_text.strip():
36 return accumulated_text, False, "Empty new text"
37
38 new_text_clean = new_text.strip()
39
40 # ✅ 1. DETECTAR SOLAPAMIENTOS PALABRA POR PALABRA
41 if accumulated_text:
42 cleaned_text = self._find_and_merge_overlap(accumulated_text, new_text_clean)
43 else:
44 cleaned_text = new_text_clean
45
46 # ✅ 2. SOLO COMPLETAR SI LA PUNTUACIÓN ESTÁ EN MEDIO DE LA SIGUIENTE FRASE
47 # No al final, sino EN MEDIO
48 should_complete = self._has_punctuation_in_middle(cleaned_text)
49
50 # ✅ 3. SAFETY VALVE: Textos muy largos - MÁS PERMISIVO
51 if len(cleaned_text.split()) > 80: # Incrementado de 50 a 80
52 print(f"⚠️ Forzando completado por texto muy largo ({len(cleaned_text.split())} palabras)")
53 return cleaned_text, True, "Mahalanobis + complete"
54
55 return cleaned_text, should_complete, f"Mahalanobis + {'complete' if should_complete else 'continue'}"
56
57 def _find_and_merge_overlap(self, accumulated_text, new_text):
58 """Encuentra solapamientos palabra por palabra y usa la palabra más larga"""
59 acc_words = accumulated_text.split()
60 new_words = new_text.split()
61
62 if not acc_words or not new_words:
63 return accumulated_text + " " + new_text
64
65 # ✅ BUSCAR SOLAPAMIENTO EMPEZANDO DESDE EL FINAL DE ACCUMULATED
66 best_overlap_size = 0
67 best_overlap_pos = 0
68
69 # Comprobar hasta 6 palabras de solapamiento máximo
70 max_check = min(6, len(acc_words), len(new_words))
71
72 for overlap_size in range(1, max_check + 1):
73 acc_end = acc_words[-overlap_size:] # Últimas palabras de accumulated
74 new_start = new_words[:overlap_size] # Primeras palabras de new
75
76 # Comprobar si son iguales (o muy similares con Mahalanobis)
77 if self._words_match_with_mahalanobis(acc_end, new_start):
78 best_overlap_size = overlap_size
79 best_overlap_pos = overlap_size
80 print(f"🔗 Solapamiento detectado: {overlap_size} palabras: {' '.join(acc_end)}")
81
82 # ✅ MERGE CON LA PALABRA MÁS LARGA
83 if best_overlap_size > 0:
84 # Palabras que no se solapan de accumulated
85 non_overlap_acc = acc_words[:-best_overlap_size]
86
87 # Para cada palabra en el solapamiento, elegir la más larga
88 merged_overlap = []
89 for i in range(best_overlap_size):
90 acc_word = acc_words[-(best_overlap_size-i)]
91 new_word = new_words[i]
92
93 # Elegir la palabra más larga
94 longer_word = new_word if len(new_word) > len(acc_word) else acc_word
95 merged_overlap.append(longer_word)
96
97 if len(new_word) != len(acc_word):
98 print(f"🔗 Palabra más larga elegida: '{acc_word}' vs '{new_word}' -> '{longer_word}'")
99
100 # Palabras que no se solapan de new
101 non_overlap_new = new_words[best_overlap_size:]
102
103 # Combinar todo
104 result_words = non_overlap_acc + merged_overlap + non_overlap_new
105 result = ' '.join(result_words)
106
107 print(f"🧹 Merged con solapamiento: '{result}'")
108 return result
109 else:
110 # Sin solapamiento, concatenación simple
111 print(f"🔗 Sin solapamiento detectado, concatenación simple")
112 return accumulated_text + " " + new_text
113
114 def _words_match_with_mahalanobis(self, words1, words2):
115 """Comprueba si dos listas de palabras coinciden usando distancia de Mahalanobis"""
116 if len(words1) != len(words2):
117 return False
118
119 for w1, w2 in zip(words1, words2):
120 distance = self._calculate_word_mahalanobis_distance(w1.lower(), w2.lower())
121 # Umbral más permisivo para detectar palabras similares
122 if distance > 0.15: # Si la distancia es mayor, no coinciden
123 return False
124
125 return True
126
127 def _has_punctuation_in_middle(self, text):
128 """Detecta si hay puntuación EN MEDIO de la frase, no al final - MÁS CONSERVADOR"""
129 if not text:
130 return False
131
132 text = text.strip()
133
134 # ✅ BÚSQUEDA MÁS ESTRICTA DE PUNTUACIÓN EN MEDIO
135 # Solo buscar puntuación que claramente indica final de oración completa
136
137 # Remover puntuación del final para buscar en el medio
138 text_without_end_punct = text.rstrip('.!?;: ')
139
140 # ✅ SOLO COMPLETAR SI HAY MÚLTIPLES ORACIONES CLARAS
141 # Contar cuántas oraciones completas hay
142 sentence_endings = text_without_end_punct.count('.') + text_without_end_punct.count('!') + text_without_end_punct.count('?')
143
144 # Solo completar si hay al menos 2 oraciones claramente separadas
145 if sentence_endings >= 2:
146 print(f"✅ Múltiples oraciones detectadas ({sentence_endings}): completando")
147 return True
148
149 # ✅ FRASES DE DESPEDIDA EXPLÍCITAS (siempre completar)
150 goodbye_phrases = [
151 'thank you', 'thanks', 'goodbye', 'bye', 'see you later',
152 'thanks for watching', 'thanks for listening', 'that\'s it', 'that\'s all'
153 ]
154
155 text_lower = text.lower()
156 for phrase in goodbye_phrases:
157 if phrase in text_lower:
158 print(f"✅ Frase de despedida detectada: '{phrase}'")
159 return True
160
161 # ✅ MÁS CONSERVADOR: No completar en otros casos
162 return False
163
164 def _detect_repetitive_transcription(self, text):
165 """Detecta si Whisper generó bucle repetitivo (bug conocido)"""
166 if not text or len(text.strip()) < 20:
167 return False
168
169 words = text.lower().split()
170 if len(words) < 10:
171 return False
172
173 # ✅ MÉTODO 1: Detectar palabras consecutivas repetidas
174 consecutive_repeats = 0
175 max_consecutive = 0
176 for i in range(1, len(words)):
177 if words[i] == words[i-1]:
178 consecutive_repeats += 1
179 max_consecutive = max(max_consecutive, consecutive_repeats)
180 else:
181 consecutive_repeats = 0
182
183 if max_consecutive > 5: # Más de 5 repeticiones consecutivas
184 print(f"🚫 Bucle Whisper detectado: '{words[0]}' repetido {max_consecutive+1} veces")
185 return True
186
187 # ✅ MÉTODO 2: Detectar alta frecuencia de una sola palabra
188 from collections import Counter
189 word_counts = Counter(words)
190 most_common_word, count = word_counts.most_common(1)[0]
191
192 # Si una palabra aparece más del 70% del texto, es bucle
193 if count > len(words) * 0.7 and len(words) > 15:
194 print(f"🚫 Bucle Whisper detectado: '{most_common_word}' aparece {count}/{len(words)} veces")
195 return True
196
197 return False
198
199 def _is_semantic_continuation(self, accumulated_text, new_text):
200 """Check if texts are semantically related and should be continued"""
201 acc_words = set(accumulated_text.lower().split())
202 new_words = set(new_text.lower().split())
203
204 # ✅ SEMANTIC FIELD DETECTION
205 # Define semantic fields that commonly continue each other
206 tech_words = {'ai', 'robot', 'developers', 'software', 'hardware', 'applications', 'build', 'test', 'source', 'open'}
207 business_words = {'price', 'priced', 'cost', 'dollar', 'dollars', 'market', 'company', 'partnership'}
208 action_words = {'designed', 'help', 'create', 'develop', 'make', 'use', 'work'}
209
210 # Check if both texts contain words from the same semantic field
211 acc_tech = len(acc_words & tech_words)
212 new_tech = len(new_words & tech_words)
213 acc_business = len(acc_words & business_words)
214 new_business = len(new_words & business_words)
215 acc_action = len(acc_words & action_words)
216 new_action = len(new_words & action_words)
217
218 if (acc_tech > 0 and new_tech > 0) or (acc_business > 0 and new_business > 0) or (acc_action > 0 and new_action > 0):
219 print(f"🔗 Semantic field continuity: tech({acc_tech},{new_tech}) business({acc_business},{new_business}) action({acc_action},{new_action})")
220 return True
221
222 return False
223
224 def _has_clear_sentence_ending(self, text):
225 """Detect clear sentence endings that should force completion - VERY STRICT"""
226 if not text:
227 return False
228
229 # ✅ ONLY COMPLETE ON VERY OBVIOUS SENTENCE ENDINGS
230
231 # 1. Explicit conversation endings (always complete these)
232 ending_phrases = [
233 'thank you', 'thanks', 'goodbye', 'bye', 'see you', 'talk to you later',
234 'that\'s it', 'that\'s all', 'the end', 'that\'s everything',
235 'in conclusion', 'to summarize', 'to conclude', 'finally',
236 'alright', 'okay', 'good', 'perfect', 'excellent', 'great'
237 ]
238
239 text_lower = text.lower().strip()
240 for phrase in ending_phrases:
241 if phrase in text_lower:
242 print(f"✅ Clear ending phrase detected: '{phrase}'")
243 return True
244
245 # 2. Question format (questions are usually complete)
246 if text.strip().endswith('?'):
247 words = text.split()
248 if len(words) >= 3: # Minimum reasonable question length
249 print(f"✅ Complete question detected")
250 return True
251
252 # 3. Exclamations (usually complete thoughts)
253 if text.strip().endswith('!'):
254 words = text.split()
255 if len(words) >= 3: # Minimum reasonable exclamation length
256 print(f"✅ Complete exclamation detected")
257 return True
258
259 # 4. VERY SPECIFIC complete sentence patterns with periods
260 # Only complete period-ending sentences if they match specific complete patterns
261 if text.strip().endswith('.'):
262 words = text.split()
263
264 # Must be reasonably long to be considered complete
265 if len(words) < 6:
266 return False
267
268 # Pattern: Complete subject-verb-object structures
269 complete_sentence_patterns = [
270 # Declarative statements that are clearly complete
271 r'\b(this|that|it|he|she|they|we|you|i)\s+(is|are|was|were|will be|has been|have been)\b.*\.',
272 r'\b(the|a|an)\s+\w+\s+(is|are|was|were|will be|has been|have been)\b.*\.',
273
274 # Action statements that are clearly complete
275 r'\b(he|she|they|we|you|i)\s+(do|does|did|will|can|could|should|would)\b.*\.',
276 r'\b(he|she|they|we|you|i)\s+(have|has|had|will have)\b.*\.',
277
278 # Statements with clear objects/completions
279 r'\b.*\s+(designed|created|built|made|developed|launched|released)\s+.*\.',
280 r'\b.*\s+(costs|priced|worth|valued|available)\s+.*\.',
281 r'\b.*\s+(announced|revealed|showed|demonstrated|presented)\s+.*\.',
282
283 # Complete informational statements
284 r'\b(google|apple|microsoft|amazon|meta|tesla|nvidia|intel|amd)\s+.*\.',
285 r'\b.*\s+(company|corporation|organization|startup|business)\s+.*\.',
286 r'\b.*\s+(product|service|application|software|hardware|device)\s+.*\.',
287
288 # Statements with clear temporal completions
289 r'\b.*(today|yesterday|tomorrow|now|currently|recently|finally)\s*\.',
290 r'\b.*(launched|released|announced|unveiled|introduced)\s+(today|yesterday|this week|this month|this year)\s*\.'
291 ]
292
293 text_lower = text.lower()
294 for pattern in complete_sentence_patterns:
295 if re.search(pattern, text_lower):
296 print(f"✅ Complete sentence pattern detected")
297 return True
298
299 # If it doesn't match any complete patterns, it's likely a fragment
300 print(f"⏸️ Period detected but doesn't match complete sentence patterns - likely fragment")
301 return False
302
303 # 5. Quotes (often complete thoughts)
304 if text.strip().endswith('"') or text.strip().endswith("'"):
305 words = text.split()
306 if len(words) >= 4:
307 print(f"✅ Complete quoted statement detected")
308 return True
309
310 return False
311
312 def _merge_natural_continuation(self, accumulated_text, new_text):
313 """Merge texts that are natural continuations with smart overlap removal and truncated word handling"""
314 accumulated_words = accumulated_text.split()
315 new_words = new_text.split()
316
317 # ✅ HANDLE TRUNCATED WORDS FIRST
318 # Check if last word of accumulated is truncated and first word of new is complete
319 if accumulated_words and new_words:
320 last_acc_word = accumulated_words[-1]
321 first_new_word = new_words[0]
322
323 # Check for truncated word patterns
324 if self._is_truncated_word_pair(last_acc_word, first_new_word):
325 # Replace truncated word with complete word
326 longer_word = first_new_word if len(first_new_word) > len(last_acc_word) else last_acc_word
327 print(f"🔗 Truncated word detected: '{last_acc_word}' -> '{first_new_word}' -> keeping '{longer_word}'")
328
329 # Replace last word in accumulated with longer version and skip first word in new
330 accumulated_words[-1] = longer_word
331 new_words = new_words[1:] # Skip the first word since we used it
332
333 # ✅ FIND AND REMOVE STANDARD OVERLAP
334 if new_words: # Only if there are still words to process
335 max_overlap_check = min(4, len(accumulated_words), len(new_words))
336 best_overlap = 0
337
338 for overlap_size in range(max_overlap_check, 0, -1):
339 acc_ending = [w.lower() for w in accumulated_words[-overlap_size:]]
340 new_beginning = [w.lower() for w in new_words[:overlap_size]]
341
342 if acc_ending == new_beginning:
343 best_overlap = overlap_size
344 break
345
346 if best_overlap > 0:
347 # Remove overlapping words from new text
348 merged_words = accumulated_words + new_words[best_overlap:]
349 print(f"🧹 Removed {best_overlap}-word overlap")
350 else:
351 # No overlap, simple concatenation
352 merged_words = accumulated_words + new_words
353 else:
354 # All new words were handled in truncation, just return accumulated
355 merged_words = accumulated_words
356
357 return ' '.join(merged_words)
358
359 def _is_truncated_word_pair(self, word1, word2):
360 """Check if word1 is a truncated version of word2 or vice versa"""
361 if not word1 or not word2:
362 return False
363
364 # ✅ METHOD 1: Check for hyphen indicating truncation
365 if word1.endswith('-'):
366 truncated = word1[:-1].lower() # Remove hyphen
367 complete = word2.lower()
368 if complete.startswith(truncated) and len(complete) > len(truncated):
369 return True
370
371 if word2.endswith('-'):
372 truncated = word2[:-1].lower() # Remove hyphen
373 complete = word1.lower()
374 if complete.startswith(truncated) and len(complete) > len(truncated):
375 return True
376
377 # ✅ METHOD 2: Check for partial word completion (no hyphen)
378 word1_clean = word1.lower().strip('.,!?";:')
379 word2_clean = word2.lower().strip('.,!?";:')
380
381 # If one word is contained at the start of another and is significantly shorter
382 if len(word1_clean) >= 3 and len(word2_clean) >= 3:
383 if word2_clean.startswith(word1_clean) and len(word2_clean) > len(word1_clean) + 1:
384 return True
385 if word1_clean.startswith(word2_clean) and len(word1_clean) > len(word2_clean) + 1:
386 return True
387
388 # ✅ METHOD 3: Similar words with different lengths (likely transcription variants)
389 if len(word1_clean) >= 4 and len(word2_clean) >= 4:
390 # Calculate simple similarity ratio
391 similarity = self._calculate_word_similarity(word1_clean, word2_clean)
392 length_diff = abs(len(word1_clean) - len(word2_clean))
393
394 # If words are very similar but different lengths, likely one is truncated
395 if similarity > 0.7 and length_diff >= 2:
396 return True
397
398 return False
399
400 def _calculate_word_similarity(self, word1, word2):
401 """Calculate similarity ratio between two words"""
402 if not word1 or not word2:
403 return 0.0
404
405 # Simple character-based similarity
406 shorter = min(len(word1), len(word2))
407 matching_chars = 0
408
409 for i in range(shorter):
410 if word1[i] == word2[i]:
411 matching_chars += 1
412 else:
413 break # Stop at first mismatch (prefix similarity)
414
415 return matching_chars / max(len(word1), len(word2))
416
417 def _remove_mahalanobis_duplicates(self, accumulated_text, new_text):
418 """Remove duplicate words using Mahalanobis distance - EXACT MATCHES ONLY"""
419 if not accumulated_text or not new_text:
420 return new_text
421
422 acc_words = accumulated_text.lower().split()
423 new_words = new_text.lower().split()
424 original_new_words = new_text.split()
425
426 if not acc_words or not new_words:
427 return new_text
428
429 cleaned_words = []
430 duplicates_removed = 0
431
432 for i, (new_word, original_word) in enumerate(zip(new_words, original_new_words)):
433 # Check if this exact word appeared recently in accumulated text
434 is_duplicate = False
435
436 # Check last few words for exact matches
437 check_range = min(10, len(acc_words))
438 for j in range(check_range):
439 acc_word = acc_words[-(j+1)]
440 distance = self._calculate_word_mahalanobis_distance(new_word, acc_word)
441
442 if distance < 0.01: # Exact match threshold
443 print(f"🧮 Exact duplicate detected: '{new_word}' ≈ '{acc_word}' (dist: {distance:.3f})")
444 is_duplicate = True
445 duplicates_removed += 1
446 break
447
448 if not is_duplicate:
449 cleaned_words.append(original_word)
450
451 if duplicates_removed > 0:
452 print(f"🧹 Removed {duplicates_removed} duplicate words via Mahalanobis")
453
454 return ' '.join(cleaned_words) if cleaned_words else new_text
455
456 def _calculate_word_mahalanobis_distance(self, word1, word2):
457 """Calculate simple Mahalanobis-like distance between two words"""
458 # ✅ CHARACTER-BASED FEATURE VECTOR
459 # Create simple feature vectors based on character frequency
460 def word_to_vector(word):
461 # Simple feature: character frequency (a-z)
462 vector = np.zeros(26)
463 word_clean = ''.join(c.lower() for c in word if c.isalpha())
464
465 for char in word_clean:
466 if 'a' <= char <= 'z':
467 vector[ord(char) - ord('a')] += 1
468
469 # Normalize by word length
470 if len(word_clean) > 0:
471 vector = vector / len(word_clean)
472
473 return vector
474
475 v1 = word_to_vector(word1)
476 v2 = word_to_vector(word2)
477
478 # ✅ SIMPLIFIED MAHALANOBIS DISTANCE
479 # Use identity covariance matrix for simplicity (equivalent to Euclidean)
480 diff = v1 - v2
481 distance = np.sqrt(np.sum(diff ** 2))
482
483 return distance
484
485 def _are_same_word_forms(self, word1, word2):
486 """Check if two words are different forms of the same word"""
487 # Simple heuristic: if one word is contained in the other and they share significant characters
488 if word1 in word2 or word2 in word1:
489 return True
490
491 # Check if they have the same root (first 3-4 characters)
492 if len(word1) >= 4 and len(word2) >= 4:
493 if word1[:3] == word2[:3]:
494 return True
495
496 return False
497
498 def _update_word_history(self, text):
499 """Update word history for future Mahalanobis calculations"""
500 words = text.lower().split()
501 self.word_history.extend(words)
502
503 # Keep only recent words
504 if len(self.word_history) > self.max_history:
505 self.word_history = self.word_history[-self.max_history:]
506
507 def _has_very_explicit_ending(self, text):
508 """Detect VERY explicit sentence endings - extremely strict"""
509 if not text:
510 return False
511
512 # ✅ ONLY COMPLETE ON EXTREMELY OBVIOUS ENDINGS
513
514 # 1. Explicit conversation endings (always complete these)
515 explicit_endings = [
516 'thank you', 'thanks', 'goodbye', 'bye', 'see you later', 'talk to you later',
517 "that's it", "that's all", 'the end', "that's everything",
518 'in conclusion', 'to summarize', 'to conclude', 'finally',
519 'alright then', 'okay then', 'good job', 'perfect', 'excellent work',
520 'thanks for watching', 'thanks for listening'
521 ]
522
523 text_lower = text.lower().strip()
524 for phrase in explicit_endings:
525 if phrase in text_lower:
526 print(f"✅ Clear ending phrase detected: '{phrase}'")
527 return True
528
529 # 2. Question endings with clear punctuation
530 if text_lower.endswith('?') and len(text.split()) >= 4:
531 print(f"✅ Clear question detected")
532 return True
533
534 # 3. Exclamation with clear context
535 if text_lower.endswith('!') and len(text.split()) >= 4:
536 # Check if it's a complete exclamation, not a fragment
537 exclamation_starters = ['wow', 'amazing', 'incredible', 'fantastic', 'great', 'excellent', 'perfect']
538 if any(text_lower.startswith(starter) for starter in exclamation_starters):
539 print(f"✅ Clear exclamation detected")
540 return True
541
542 # 4. NEVER complete on simple periods - they are almost always fragments
543 return False
544
545 def _appears_to_be_fragment_aggressive(self, text):
546 """MENOS AGRESIVO: Detectar fragmentos pero ser más permisivo"""
547 if not text:
548 return False
549
550 words = text.lower().split()
551 if not words:
552 return False
553
554 # ✅ MENOS AGRESIVO: Solo fragmentos muy cortos son obviamente incompletos
555 # 1. Textos muy cortos son fragmentos
556 if len(words) < 5: # Reducido de 8 a 5
557 print(f"🔗 Fragment detected: too short ({len(words)} words)")
558 return True
559
560 # 2. Solo fragmentos MUY obvios
561 text_clean = text.lower().strip('.,!?;: ')
562
563 # Patrones de fragmentos MÁS ESPECÍFICOS - solo los más obvios
564 obvious_incomplete_patterns = [
565 # Solo los finales más obviamente incompletos
566 r'\b(the|a|an|and|or|but|so|for|to|of|in|on|at|with|by|from)$',
567 r'\b(is|are|was|were|has|have|had|will|would|could|should|can|may|might)$',
568
569 # Conectores que claramente indican continuación
570 r'\b(because|since|although|while|whereas|unless|until|before|after)$',
571 r'\b(which|that|who|where|when|how|why|what)$',
572 ]
573
574 for pattern in obvious_incomplete_patterns:
575 if re.search(pattern, text_clean):
576 print(f"🔗 Fragment detected: ends with incomplete word")
577 return True
578
579 return False
580
581 def correct_and_validate_text(self, text):
582 """🧮 SIMPLIFIED: Basic text validation with improved fragment detection"""
583 if not text or not text.strip():
584 return False, text, "Empty text"
585
586 text = text.strip()
587
588 # ✅ 1. BASIC LENGTH CHECK
589 words = text.split()
590 if len(words) < self.min_text_length:
591 return False, text, "Too short"
592
593 # ✅ 2. SIMPLE WORD DUPLICATE REMOVAL
594 corrected_text = self._remove_immediate_duplicates(text)
595
596 # ✅ 3. CHECK FOR COMPLETION USING NEW LOGIC
597 # Only complete if it has clear ending AND is not a fragment
598 has_clear_ending = self._has_clear_sentence_ending(corrected_text)
599 appears_to_be_fragment = self._appears_to_be_fragment_aggressive(corrected_text)
600
601 is_complete = has_clear_ending and not appears_to_be_fragment
602
603 # ✅ 4. LENGTH-BASED FALLBACK (más permisivo)
604 if not is_complete and len(words) >= 8: # Reducido de 12 a 8
605 # Solo usar longitud si no es obviamente un fragmento
606 if not appears_to_be_fragment:
607 print(f"✅ Completando por longitud ({len(words)} palabras)")
608 is_complete = True
609
610 validation_method = "Mahalanobis validation"
611
612 return is_complete, corrected_text, validation_method
613
614 def _remove_immediate_duplicates(self, text):
615 """Remove immediate word duplicates (word word -> word)"""
616 words = text.split()
617 cleaned_words = []
618
619 for i, word in enumerate(words):
620 # Only remove if the exact same word appears immediately before
621 if i > 0 and word.lower() == words[i-1].lower():
622 print(f"🧹 Removing immediate duplicate: '{word}'")
623 continue
624 cleaned_words.append(word)
625
626 return ' '.join(cleaned_words)
627
628 # ✅ COMPATIBILITY METHODS
629 def validate_text_coherence(self, text):
630 """Compatibility method"""
631 is_valid, corrected_text, reason = self.correct_and_validate_text(text)
632 return is_valid, reason
633
634 def is_sentence_complete(self, text):
635 """Compatibility method"""
636 is_valid, corrected_text, reason = self.correct_and_validate_text(text)
637 return is_valid
638
639 def extract_complete_sentences(self, text):
640 """Extract sentences based on punctuation detection"""
641 if not text or not text.strip():
642 return [], ""
643
644 sentences = []
645 remaining = text
646
647 # ✅ SPLIT BY SENTENCE PUNCTUATION
648 parts = re.split(r'([.!?。!?])\s*', text)
649
650 current_sentence = ""
651 i = 0
652 while i < len(parts):
653 part = parts[i]
654
655 if re.match(r'[.!?。!?]', part):
656 current_sentence += part
657 if current_sentence.strip():
658 is_valid, corrected_sentence, reason = self.correct_and_validate_text(current_sentence.strip())
659 if is_valid and corrected_sentence:
660 sentences.append(corrected_sentence)
661 print(f"✅ Extracted Sentence: '{corrected_sentence}' ({reason})")
662 current_sentence = ""
663 else:
664 current_sentence += part
665
666 i += 1
667
668 remaining = current_sentence.strip()
669 return sentences, remaining