#!/usr/bin/env python3 """ Script để xử lý và làm sạch dữ liệu từ thư mục raw/ """ import os import glob from pathlib import Path import re # Cấu hình RAW_DIR = "raw/documents" PROCESSED_DIR = "processed" SUPPORTED_EXTENSIONS = [".txt", ".md"] def clean_text(text): """Làm sạch văn bản nhưng giữ lại cấu trúc""" # Loại bỏ ký tự null text = text.replace('\x00', '') # Loại bỏ các ký tự điều khiển không cần thiết (nhưng giữ lại \n và \t) text = re.sub(r'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]', '', text) # Loại bỏ khoảng trắng thừa ở đầu và cuối mỗi dòng (nhưng giữ lại xuống dòng) lines = text.split('\n') cleaned_lines = [line.strip() for line in lines] text = '\n'.join(cleaned_lines) # Loại bỏ nhiều dòng trống liên tiếp (chỉ giữ tối đa 2 dòng trống) text = re.sub(r'\n{3,}', '\n\n', text) # Loại bỏ khoảng trắng thừa trong cùng một dòng (nhưng không ảnh hưởng xuống dòng) lines = text.split('\n') cleaned_lines = [] for line in lines: # Loại bỏ nhiều khoảng trắng liên tiếp trong dòng cleaned_line = re.sub(r' +', ' ', line) cleaned_lines.append(cleaned_line) text = '\n'.join(cleaned_lines) # Loại bỏ khoảng trắng ở đầu và cuối toàn bộ văn bản text = text.strip() return text def process_text_file(input_path, output_dir): """Xử lý một file text""" try: with open(input_path, 'r', encoding='utf-8') as f: content = f.read() except UnicodeDecodeError: # Thử với encoding khác try: with open(input_path, 'r', encoding='latin-1') as f: content = f.read() except Exception as e: print(f"Lỗi khi đọc file {input_path}: {e}") return False # Làm sạch văn bản cleaned_content = clean_text(content) if not cleaned_content: print(f"File {input_path} rỗng sau khi làm sạch") return False # Tạo tên file output input_filename = Path(input_path).stem output_path = os.path.join(output_dir, f"{input_filename}.txt") # Lưu file đã xử lý with open(output_path, 'w', encoding='utf-8') as f: f.write(cleaned_content) print(f"Đã xử lý: {input_path} -> {output_path}") return True def process_pdf_file(input_path, output_dir): """Xử lý file PDF""" try: import pdfplumber except ImportError: print("Cần cài đặt pdfplumber: pip install pdfplumber") return False try: content = "" with pdfplumber.open(input_path) as pdf: for page in pdf.pages: page_text = page.extract_text() if page_text: content += page_text + "\n" if not content.strip(): print(f"Không thể extract text từ PDF: {input_path}") return False # Làm sạch văn bản cleaned_content = clean_text(content) # Tạo tên file output input_filename = Path(input_path).stem output_path = os.path.join(output_dir, f"{input_filename}.txt") # Lưu file đã xử lý with open(output_path, 'w', encoding='utf-8') as f: f.write(cleaned_content) print(f"Đã xử lý PDF: {input_path} -> {output_path}") return True except Exception as e: print(f"Lỗi khi xử lý PDF {input_path}: {e}") return False def process_docx_file(input_path, output_dir): """Xử lý file DOCX - Extract toàn bộ nội dung""" try: from docx import Document from docx.oxml.text.paragraph import CT_P from docx.oxml.table import CT_Tbl from docx.table import _Cell, Table from docx.text.paragraph import Paragraph except ImportError: print("Cần cài đặt python-docx: pip install python-docx") return False try: doc = Document(input_path) content = "" # Extract text từ tất cả paragraphs (bao gồm cả trong headers/footers) for paragraph in doc.paragraphs: para_text = paragraph.text.strip() if para_text: content += para_text + "\n" # Extract text từ headers for section in doc.sections: if section.header: for paragraph in section.header.paragraphs: para_text = paragraph.text.strip() if para_text: content += para_text + "\n" if section.footer: for paragraph in section.footer.paragraphs: para_text = paragraph.text.strip() if para_text: content += para_text + "\n" # Extract text từ tables (bao gồm cả nested tables) def extract_table_text(table): """Recursively extract text from table including nested tables""" table_text = "" for row in table.rows: row_texts = [] for cell in row.cells: # Extract text from paragraphs in cell cell_text = "" for para in cell.paragraphs: if para.text.strip(): cell_text += para.text.strip() + " " # Check for nested tables in cell for nested_table in cell.tables: cell_text += extract_table_text(nested_table) + " " if cell_text.strip(): row_texts.append(cell_text.strip()) if row_texts: table_text += " | ".join(row_texts) + "\n" return table_text for table in doc.tables: table_content = extract_table_text(table) if table_content.strip(): content += "\n" + table_content + "\n" # Extract text từ inline shapes (text boxes) nếu có # Lưu ý: python-docx không hỗ trợ extract text boxes trực tiếp # Nhưng chúng ta có thể thử extract từ XML try: from docx.oxml import parse_xml # Tìm text trong các phần tử khác for element in doc.element.body.iter(): if element.tag.endswith('}t'): # Text element if element.text: text = element.text.strip() if text and text not in content: # Chỉ thêm nếu chưa có trong content (tránh duplicate) pass except: pass # Bỏ qua nếu không extract được if not content.strip(): print(f"Không thể extract text từ DOCX: {input_path}") return False # Làm sạch văn bản (nhưng giữ lại cấu trúc) cleaned_content = clean_text(content) # Tạo tên file output input_filename = Path(input_path).stem output_path = os.path.join(output_dir, f"{input_filename}.txt") # Lưu file đã xử lý with open(output_path, 'w', encoding='utf-8') as f: f.write(cleaned_content) # Thống kê original_size = os.path.getsize(input_path) processed_size = len(cleaned_content.encode('utf-8')) print(f"Đã xử lý DOCX: {input_path} -> {output_path}") print(f" - Kích thước gốc: {original_size:,} bytes") print(f" - Kích thước text: {processed_size:,} bytes ({len(cleaned_content):,} ký tự)") print(f" - Số dòng: {len(cleaned_content.split(chr(10)))}") return True except Exception as e: print(f"Lỗi khi xử lý DOCX {input_path}: {e}") import traceback traceback.print_exc() return False def main(): """Hàm chính""" # Tạo thư mục processed nếu chưa có os.makedirs(PROCESSED_DIR, exist_ok=True) # Kiểm tra thư mục raw if not os.path.exists(RAW_DIR): print(f"Thư mục {RAW_DIR} không tồn tại!") print("Vui lòng tạo thư mục và đặt file dữ liệu vào đó.") return # Đếm số file đã xử lý processed_count = 0 # Xử lý file .txt và .md for ext in SUPPORTED_EXTENSIONS: pattern = os.path.join(RAW_DIR, f"**/*{ext}") for file_path in glob.glob(pattern, recursive=True): if process_text_file(file_path, PROCESSED_DIR): processed_count += 1 # Xử lý file .pdf pdf_pattern = os.path.join(RAW_DIR, "**/*.pdf") for file_path in glob.glob(pdf_pattern, recursive=True): if process_pdf_file(file_path, PROCESSED_DIR): processed_count += 1 # Xử lý file .docx docx_pattern = os.path.join(RAW_DIR, "**/*.docx") for file_path in glob.glob(docx_pattern, recursive=True): if process_docx_file(file_path, PROCESSED_DIR): processed_count += 1 print(f"\nHoàn thành! Đã xử lý {processed_count} file.") print(f"Dữ liệu đã xử lý được lưu tại: {PROCESSED_DIR}/") if __name__ == "__main__": main()