bilalRHCH commited on
Commit
bf9e91e
·
verified ·
1 Parent(s): c9523f7

Upload text_preprocessor.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. text_preprocessor.py +66 -0
text_preprocessor.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def chunk_text(text: str, max_chunk_length: int = 300) -> list[str]:
4
+ """
5
+ Splits text into chunks, prioritizing paragraph breaks, then sentence terminators,
6
+ then commas, and finally spaces. Ensure no word is chopped midway.
7
+ """
8
+ if not text:
9
+ return []
10
+
11
+ # Helper function to split by a delimiter and respect max length
12
+ def _split_respecting_length(text_part, delimiter_pattern, sep=" "):
13
+ parts = re.split(delimiter_pattern, text_part)
14
+ res = []
15
+ current = ""
16
+ for p in parts:
17
+ p = p.strip()
18
+ if not p: continue
19
+
20
+ if len(current) + len(p) + 1 <= max_chunk_length:
21
+ current = f"{current}{sep}{p}" if current else p
22
+ else:
23
+ if current:
24
+ res.append(current)
25
+ current = p
26
+ if current:
27
+ res.append(current)
28
+ return res
29
+
30
+ # 1. Paragraphs
31
+ paragraphs = [p for p in re.split(r'\n+', text) if p.strip()]
32
+
33
+ chunks = []
34
+ for para in paragraphs:
35
+ if len(para) <= max_chunk_length:
36
+ chunks.append(para)
37
+ continue
38
+
39
+ # 2. Sentences
40
+ sentences = []
41
+ for p in _split_respecting_length(para, r'(?<=[.!?؟])\s+'):
42
+ if len(p) <= max_chunk_length:
43
+ sentences.append(p)
44
+ else:
45
+ # 3. Commas
46
+ commas = []
47
+ for c in _split_respecting_length(p, r'(?<=[,،])\s+'):
48
+ if len(c) <= max_chunk_length:
49
+ commas.append(c)
50
+ else:
51
+ # 4. Words
52
+ words_split = _split_respecting_length(c, r'\s+')
53
+ commas.extend(words_split)
54
+ sentences.extend(commas)
55
+ chunks.extend(sentences)
56
+
57
+ return chunks
58
+
59
+ # Quick test if run directly
60
+ if __name__ == "__main__":
61
+ test_text = "مرحباً بكم. هذا هو النص الأول! وهذا هو النص الثاني، الذي سنقوم بتقسيمه. " * 10
62
+ print(f"Original text length: {len(test_text)}")
63
+ res = chunk_text(test_text, max_chunk_length=100)
64
+ for i, c in enumerate(res):
65
+ print(f"Chunk {i+1} (len={len(c)}): {c}")
66
+