Update document_processor.py
Browse files6 unmodified lines78910111213141516176 unmodified lineslogger = setup_logger('document_processor')def load_single_document(file_path):try:with open(file_path, 'r', encoding='utf-8') as file:content = clean_text(file.read())return pd.DataFrame([{'path': file_path, 'content': content}])except Exception as e:logger.error(f"Error reading {file_path}: {e}")return pd.DataFrame()6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401416 unmodified lineslogger = setup_logger('document_processor')def split_into_chunks(text, chunk_size=400, overlap=75):"""Split text into overlapping chunksArgs:text: The text to splitchunk_size: Number of characters per chunkoverlap: Number of characters to overlap between chunks"""chunks = []start = 0text_length = len(text)while start < text_length:end = start + chunk_sizechunk = text[start:end]# Try to break at sentence boundary for better contextif end < text_length:# Look for sentence endingslast_period = chunk.rfind('.')last_question = chunk.rfind('؟') # Arabic question marklast_exclamation = chunk.rfind('!')last_newline = chunk.rfind('\n')# Find the best break pointbreak_point = max(last_period, last_question, last_exclamation, last_newline)# Only break if we're past halfway through the chunkif break_point > chunk_size * 0.5:chunk = chunk[:break_point + 1]end = start + break_point + 1chunk = chunk.strip()if chunk: # Only add non-empty chunkschunks.append(chunk)start = end - overlap # Move start with overlapreturn chunksdef load_documents(folder_path, chunk_size=400, overlap=75):"""Load all .txt documents from folder and split them into chunksArgs:folder_path: Path to folder containing .txt fileschunk_size: Size of each chunk in characters (default: 400)overlap: Overlap between chunks in characters (default: 75)"""documents = []file_count = 0txt_files = glob.glob(os.path.join(folder_path, '*.txt'))if not txt_files:logger.warning(f"No .txt files found in {folder_path}")return pd.DataFrame()for file_path in tqdm(txt_files, desc="Loading and chunking documents"):try:with open(file_path, 'r', encoding='utf-8') as file:content = clean_text(file.read())if not content:logger.warning(f"Empty content in {file_path}")continue# Split into chunkschunks = split_into_chunks(content, chunk_size, overlap)# Create a document entry for each chunkfor i, chunk in enumerate(chunks):documents.append({'path': file_path,'chunk_id': i,'total_chunks': len(chunks),'content': chunk,'content_length': len(chunk)})file_count += 1logger.info(f"Loaded {os.path.basename(file_path)}: {len(chunks)} chunks")except Exception as e:logger.error(f"Error reading {file_path}: {e}")df = pd.DataFrame(documents)if not df.empty:logger.info(f"Total: {file_count} files → {len(df)} chunks")logger.info(f"Average chunk size: {df['content_length'].mean():.0f} characters")return dfdef load_single_document(file_path, chunk_size=400, overlap=75):"""Load a single document and split it into chunksArgs:file_path: Path to the .txt filechunk_size: Size of each chunk in charactersoverlap: Overlap between chunks in characters"""try:with open(file_path, 'r', encoding='utf-8') as file:content = clean_text(file.read())if not content:logger.warning(f"Empty content in {file_path}")return pd.DataFrame()# Split into chunkschunks = split_into_chunks(content, chunk_size, overlap)# Create dataframe with chunksdocuments = []for i, chunk in enumerate(chunks):documents.append({'path': file_path,'chunk_id': i,'total_chunks': len(chunks),'content': chunk,'content_length': len(chunk)})logger.info(f"Loaded {os.path.basename(file_path)}: {len(chunks)} chunks")return pd.DataFrame(documents)except Exception as e:logger.error(f"Error reading {file_path}: {e}")return pd.DataFrame()
document_processor.py+127-3