|
|
|
|
|
""" |
|
|
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 |
|
|
|
|
|
|
|
|
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""" |
|
|
|
|
|
text = text.replace('\x00', '') |
|
|
|
|
|
|
|
|
text = re.sub(r'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]', '', text) |
|
|
|
|
|
|
|
|
lines = text.split('\n') |
|
|
cleaned_lines = [line.strip() for line in lines] |
|
|
text = '\n'.join(cleaned_lines) |
|
|
|
|
|
|
|
|
text = re.sub(r'\n{3,}', '\n\n', text) |
|
|
|
|
|
|
|
|
lines = text.split('\n') |
|
|
cleaned_lines = [] |
|
|
for line in lines: |
|
|
|
|
|
cleaned_line = re.sub(r' +', ' ', line) |
|
|
cleaned_lines.append(cleaned_line) |
|
|
text = '\n'.join(cleaned_lines) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
cleaned_content = clean_text(content) |
|
|
|
|
|
if not cleaned_content: |
|
|
print(f"File {input_path} rỗng sau khi làm sạch") |
|
|
return False |
|
|
|
|
|
|
|
|
input_filename = Path(input_path).stem |
|
|
output_path = os.path.join(output_dir, f"{input_filename}.txt") |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
cleaned_content = clean_text(content) |
|
|
|
|
|
|
|
|
input_filename = Path(input_path).stem |
|
|
output_path = os.path.join(output_dir, f"{input_filename}.txt") |
|
|
|
|
|
|
|
|
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 = "" |
|
|
|
|
|
|
|
|
for paragraph in doc.paragraphs: |
|
|
para_text = paragraph.text.strip() |
|
|
if para_text: |
|
|
content += para_text + "\n" |
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
cell_text = "" |
|
|
for para in cell.paragraphs: |
|
|
if para.text.strip(): |
|
|
cell_text += para.text.strip() + " " |
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
from docx.oxml import parse_xml |
|
|
|
|
|
for element in doc.element.body.iter(): |
|
|
if element.tag.endswith('}t'): |
|
|
if element.text: |
|
|
text = element.text.strip() |
|
|
if text and text not in content: |
|
|
|
|
|
pass |
|
|
except: |
|
|
pass |
|
|
|
|
|
if not content.strip(): |
|
|
print(f"Không thể extract text từ DOCX: {input_path}") |
|
|
return False |
|
|
|
|
|
|
|
|
cleaned_content = clean_text(content) |
|
|
|
|
|
|
|
|
input_filename = Path(input_path).stem |
|
|
output_path = os.path.join(output_dir, f"{input_filename}.txt") |
|
|
|
|
|
|
|
|
with open(output_path, 'w', encoding='utf-8') as f: |
|
|
f.write(cleaned_content) |
|
|
|
|
|
|
|
|
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""" |
|
|
|
|
|
os.makedirs(PROCESSED_DIR, exist_ok=True) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
processed_count = 0 |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|