|
"""
|
|
خدمة استخراج النصوص من المستندات
|
|
"""
|
|
|
|
import os
|
|
import PyPDF2
|
|
import docx
|
|
import pandas as pd
|
|
from pathlib import Path
|
|
import config
|
|
|
|
class TextExtractor:
|
|
"""استخراج النصوص من المستندات المختلفة"""
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
def extract_from_pdf(self, file_path):
|
|
"""استخراج النص من ملف PDF"""
|
|
text = ""
|
|
|
|
try:
|
|
with open(file_path, 'rb') as file:
|
|
pdf_reader = PyPDF2.PdfReader(file)
|
|
for page_num in range(len(pdf_reader.pages)):
|
|
page = pdf_reader.pages[page_num]
|
|
text += page.extract_text() + "\n\n"
|
|
except Exception as e:
|
|
print(f"خطأ في استخراج النص من PDF: {str(e)}")
|
|
return ""
|
|
|
|
return text
|
|
|
|
def extract_from_docx(self, file_path):
|
|
"""استخراج النص من ملف Word"""
|
|
text = ""
|
|
|
|
try:
|
|
doc = docx.Document(file_path)
|
|
for para in doc.paragraphs:
|
|
text += para.text + "\n"
|
|
except Exception as e:
|
|
print(f"خطأ في استخراج النص من DOCX: {str(e)}")
|
|
return ""
|
|
|
|
return text
|
|
|
|
def extract_from_excel(self, file_path):
|
|
"""استخراج البيانات من ملف Excel"""
|
|
try:
|
|
|
|
excel_data = pd.read_excel(file_path, sheet_name=None)
|
|
|
|
|
|
text = ""
|
|
for sheet_name, sheet_data in excel_data.items():
|
|
text += f"صفحة: {sheet_name}\n"
|
|
text += sheet_data.to_string(index=False) + "\n\n"
|
|
except Exception as e:
|
|
print(f"خطأ في استخراج النص من Excel: {str(e)}")
|
|
return ""
|
|
|
|
return text
|
|
|
|
def extract_from_text(self, file_path):
|
|
"""استخراج النص من ملف نصي"""
|
|
try:
|
|
with open(file_path, 'r', encoding='utf-8') as file:
|
|
text = file.read()
|
|
except Exception as e:
|
|
print(f"خطأ في استخراج النص من الملف النصي: {str(e)}")
|
|
return ""
|
|
|
|
return text
|
|
|
|
def extract_text(self, file_path):
|
|
"""استخراج النص من أي نوع ملف مدعوم"""
|
|
file_ext = Path(file_path).suffix.lower()
|
|
|
|
if file_ext == '.pdf':
|
|
return self.extract_from_pdf(file_path)
|
|
elif file_ext in ['.docx', '.doc']:
|
|
return self.extract_from_docx(file_path)
|
|
elif file_ext in ['.xlsx', '.xls']:
|
|
return self.extract_from_excel(file_path)
|
|
elif file_ext == '.txt':
|
|
return self.extract_from_text(file_path)
|
|
else:
|
|
print(f"نوع الملف غير مدعوم: {file_ext}")
|
|
return "" |