Ahmed-Alghamdi commited on
Commit
7918905
·
verified ·
1 Parent(s): 9c0cd8e

Update document_processor.py

Browse files
Files changed (1) hide show
  1. document_processor.py +53 -1
document_processor.py CHANGED
@@ -48,7 +48,59 @@ def split_into_chunks(text, chunk_size=400, overlap=750):
48
 
49
  return chunks
50
 
51
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def load_single_document(file_path, chunk_size=400, overlap=750):
54
  """
 
48
 
49
  return chunks
50
 
51
+ def load_documents(folder_path, chunk_size=300, overlap=100):
52
+ """
53
+ Load all .txt documents from folder and split them into chunks
54
+
55
+ Args:
56
+ folder_path: Path to folder containing .txt files
57
+ chunk_size: Size of each chunk in characters (default: 400)
58
+ overlap: Overlap between chunks in characters (default: 75)
59
+ """
60
+ documents = []
61
+ file_count = 0
62
+
63
+ txt_files = glob.glob(os.path.join(folder_path, '*.txt'))
64
+
65
+ if not txt_files:
66
+ logger.warning(f"No .txt files found in {folder_path}")
67
+ return pd.DataFrame()
68
+
69
+ for file_path in tqdm(txt_files, desc="Loading and chunking documents"):
70
+ try:
71
+ with open(file_path, 'r', encoding='utf-8') as file:
72
+ content = clean_text(file.read())
73
+
74
+ if not content:
75
+ logger.warning(f"Empty content in {file_path}")
76
+ continue
77
+
78
+ # Split into chunks
79
+ chunks = split_into_chunks(content, chunk_size, overlap)
80
+
81
+ # Create a document entry for each chunk
82
+ for i, chunk in enumerate(chunks):
83
+ documents.append({
84
+ 'path': file_path,
85
+ 'chunk_id': i,
86
+ 'total_chunks': len(chunks),
87
+ 'content': chunk,
88
+ 'content_length': len(chunk)
89
+ })
90
+
91
+ file_count += 1
92
+ logger.info(f"Loaded {os.path.basename(file_path)}: {len(chunks)} chunks")
93
+
94
+ except Exception as e:
95
+ logger.error(f"Error reading {file_path}: {e}")
96
+
97
+ df = pd.DataFrame(documents)
98
+
99
+ if not df.empty:
100
+ logger.info(f"Total: {file_count} files → {len(df)} chunks")
101
+ logger.info(f"Average chunk size: {df['content_length'].mean():.0f} characters")
102
+
103
+ return df
104
 
105
  def load_single_document(file_path, chunk_size=400, overlap=750):
106
  """