Jeevant10 commited on
Commit
c95a8f6
·
1 Parent(s): dff2c1e

Add: implement DocumentCleaner class for text cleaning and normalization

Browse files
Files changed (1) hide show
  1. src/cleaner.py +50 -0
src/cleaner.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import List, Any
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ class DocumentCleaner:
8
+ def __init__(self, min_length: int = 50):
9
+ self.min_length = min_length
10
+ # Regex for common PDF artifacts or excessive whitespace
11
+ self.whitespace_pattern = re.compile(r'\s+')
12
+ self.control_chars_pattern = re.compile(r'[\x00-\x1f\x7f-\x9f]')
13
+
14
+ def clean_text(self, text: str) -> str:
15
+ if not text:
16
+ return ""
17
+
18
+ # Safely remove surrogate code points that crash Windows terminals
19
+ text = text.encode('utf-8', 'ignore').decode('utf-8')
20
+
21
+ # Remove control characters
22
+ text = self.control_chars_pattern.sub('', text)
23
+
24
+ # Normalize whitespace (replace newlines/tabs with space and collapse)
25
+ text = self.whitespace_pattern.sub(' ', text).strip()
26
+
27
+ return text
28
+
29
+ def clean_documents(self, documents: List[Any]) -> List[Any]:
30
+ """
31
+ Cleans a list of LangChain Document objects.
32
+ Filters out documents that are too short after cleaning.
33
+ """
34
+ cleaned_docs = []
35
+ for doc in documents:
36
+ if not hasattr(doc, 'page_content') or doc.page_content is None:
37
+ continue
38
+
39
+ cleaned_text = self.clean_text(str(doc.page_content))
40
+
41
+ if len(cleaned_text) >= self.min_length:
42
+ # Update the document content with cleaned version
43
+ doc.page_content = cleaned_text
44
+ cleaned_docs.append(doc)
45
+
46
+ print(f"[INFO] Data Cleaning: {len(documents)} -> {len(cleaned_docs)} documents (filtered {len(documents) - len(cleaned_docs)})")
47
+ return cleaned_docs
48
+
49
+ def get_default_cleaner():
50
+ return DocumentCleaner()