Update utils/text_processor.py
Browse files- utils/text_processor.py +110 -109
utils/text_processor.py
CHANGED
|
@@ -1,109 +1,110 @@
|
|
| 1 |
-
import re
|
| 2 |
-
import pandas as pd
|
| 3 |
-
from typing import List, Set
|
| 4 |
-
from underthesea import word_tokenize
|
| 5 |
-
from config import Config
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
class VietnameseTextProcessor:
|
| 9 |
-
"""Vietnamese text processing utilities for legal documents"""
|
| 10 |
-
|
| 11 |
-
def __init__(self):
|
| 12 |
-
self.stopwords = self._load_stopwords()
|
| 13 |
-
|
| 14 |
-
def _load_stopwords(self) -> Set[str]:
|
| 15 |
-
"""Load Vietnamese stopwords from file"""
|
| 16 |
-
try:
|
| 17 |
-
# Try UTF-8 first
|
| 18 |
-
with open(Config.STOPWORDS_PATH, "r", encoding="utf-8") as f:
|
| 19 |
-
stopwords = set(line.strip() for line in f if line.strip())
|
| 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 |
-
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from typing import List, Set
|
| 4 |
+
from underthesea import word_tokenize
|
| 5 |
+
from config import Config
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class VietnameseTextProcessor:
|
| 9 |
+
"""Vietnamese text processing utilities for legal documents"""
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.stopwords = self._load_stopwords()
|
| 13 |
+
|
| 14 |
+
def _load_stopwords(self) -> Set[str]:
|
| 15 |
+
"""Load Vietnamese stopwords from file"""
|
| 16 |
+
try:
|
| 17 |
+
# Try UTF-8 first
|
| 18 |
+
with open(Config.STOPWORDS_PATH, "r", encoding="utf-8") as f:
|
| 19 |
+
stopwords = set(line.strip() for line in f if line.strip())
|
| 20 |
+
stopwords = set(['_'.join(word.split()) for word in list(stopwords)])
|
| 21 |
+
return stopwords
|
| 22 |
+
except UnicodeDecodeError:
|
| 23 |
+
try:
|
| 24 |
+
# Try UTF-16 if UTF-8 fails
|
| 25 |
+
with open(Config.STOPWORDS_PATH, "r", encoding="utf-16") as f:
|
| 26 |
+
stopwords = set(line.strip() for line in f if line.strip())
|
| 27 |
+
return stopwords
|
| 28 |
+
except UnicodeDecodeError:
|
| 29 |
+
try:
|
| 30 |
+
# Try with BOM detection
|
| 31 |
+
with open(Config.STOPWORDS_PATH, "r", encoding="utf-8-sig") as f:
|
| 32 |
+
stopwords = set(line.strip() for line in f if line.strip())
|
| 33 |
+
return stopwords
|
| 34 |
+
except UnicodeDecodeError:
|
| 35 |
+
print(
|
| 36 |
+
f"Warning: Unable to decode stopwords file at {Config.STOPWORDS_PATH}"
|
| 37 |
+
)
|
| 38 |
+
return set()
|
| 39 |
+
except FileNotFoundError:
|
| 40 |
+
print(f"Warning: Stopwords file not found at {Config.STOPWORDS_PATH}")
|
| 41 |
+
return set()
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Warning: Error loading stopwords file: {e}")
|
| 44 |
+
return set()
|
| 45 |
+
|
| 46 |
+
def clean_text(self, text: str) -> str:
|
| 47 |
+
"""Clean Vietnamese text for processing"""
|
| 48 |
+
if not text:
|
| 49 |
+
return ""
|
| 50 |
+
|
| 51 |
+
# Remove extra whitespace and normalize
|
| 52 |
+
text = re.sub(r"\s+", " ", text.strip())
|
| 53 |
+
|
| 54 |
+
# Remove special characters but keep Vietnamese characters
|
| 55 |
+
text = re.sub(
|
| 56 |
+
r"[^\w\s\-\.\,\;\:\!\?\(\)\[\]\"\'àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđĐ]",
|
| 57 |
+
" ",
|
| 58 |
+
text,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Remove multiple spaces
|
| 62 |
+
text = re.sub(r"\s+", " ", text.strip())
|
| 63 |
+
|
| 64 |
+
return text
|
| 65 |
+
|
| 66 |
+
def tokenize(self, text: str) -> List[str]:
|
| 67 |
+
"""Tokenize Vietnamese text using underthesea"""
|
| 68 |
+
try:
|
| 69 |
+
cleaned_text = self.clean_text(text)
|
| 70 |
+
tokens = word_tokenize(cleaned_text, format="text").split()
|
| 71 |
+
return tokens
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error tokenizing text: {e}")
|
| 74 |
+
return text.split()
|
| 75 |
+
|
| 76 |
+
def remove_stopwords(self, tokens: List[str]) -> List[str]:
|
| 77 |
+
"""Remove stopwords from token list"""
|
| 78 |
+
return [token for token in tokens if token.lower() not in self.stopwords]
|
| 79 |
+
|
| 80 |
+
def preprocess_for_search(self, text: str) -> str:
|
| 81 |
+
"""Preprocess text for search - tokenize and remove stopwords"""
|
| 82 |
+
tokens = self.tokenize(text)
|
| 83 |
+
filtered_tokens = self.remove_stopwords(tokens)
|
| 84 |
+
return " ".join(filtered_tokens)
|
| 85 |
+
|
| 86 |
+
def extract_keywords(self, text: str, min_length: int = 2) -> List[str]:
|
| 87 |
+
"""Extract keywords from text"""
|
| 88 |
+
tokens = self.tokenize(text)
|
| 89 |
+
filtered_tokens = self.remove_stopwords(tokens)
|
| 90 |
+
keywords = [token for token in filtered_tokens if len(token) >= min_length]
|
| 91 |
+
return list(set(keywords)) # Remove duplicates
|
| 92 |
+
|
| 93 |
+
def chunk_text(
|
| 94 |
+
self, text: str, chunk_size: int = None, overlap: int = None
|
| 95 |
+
) -> List[str]:
|
| 96 |
+
"""Split text into chunks with overlap"""
|
| 97 |
+
if chunk_size is None:
|
| 98 |
+
chunk_size = Config.CHUNK_SIZE
|
| 99 |
+
if overlap is None:
|
| 100 |
+
overlap = Config.CHUNK_OVERLAP
|
| 101 |
+
|
| 102 |
+
tokens = self.tokenize(text)
|
| 103 |
+
chunks = []
|
| 104 |
+
|
| 105 |
+
for i in range(0, len(tokens), chunk_size - overlap):
|
| 106 |
+
chunk_tokens = tokens[i : i + chunk_size]
|
| 107 |
+
if chunk_tokens:
|
| 108 |
+
chunks.append(" ".join(chunk_tokens))
|
| 109 |
+
|
| 110 |
+
return chunks
|