1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
| class BaseExtractor(ABC):
"""
文档提取器抽象基类
定义所有提取器的通用接口和行为
"""
def __init__(self, file_path: str, **kwargs):
"""
初始化提取器
Args:
file_path: 文件路径
**kwargs: 额外的配置参数
"""
self.file_path = file_path
self.config = kwargs
# 验证文件存在性
if not Path(file_path).exists():
raise FileNotFoundError(f"文件不存在: {file_path}")
@abstractmethod
def extract(self) -> list[Document]:
"""
提取文档内容的抽象方法
子类必须实现具体的提取逻辑
Returns:
list[Document]: 提取的文档对象列表
"""
raise NotImplementedError("子类必须实现extract方法")
def _detect_encoding(self, file_path: str) -> str:
"""
自动检测文件编码
使用chardet库进行编码检测
Args:
file_path: 文件路径
Returns:
str: 检测到的编码格式
"""
import chardet
with open(file_path, 'rb') as file:
raw_data = file.read(10000) # 读取前10KB进行检测
result = chardet.detect(raw_data)
encoding = result.get('encoding', 'utf-8')
confidence = result.get('confidence', 0)
# 如果置信度过低,使用默认编码
if confidence < 0.7:
encoding = 'utf-8'
return encoding
def _clean_text(self, text: str) -> str:
"""
清理提取的文本内容
移除多余的空白字符和特殊字符
Args:
text: 原始文本
Returns:
str: 清理后的文本
"""
# 移除多余的空白字符
text = re.sub(r'\s+', ' ', text)
# 移除文档开头和结尾的空白
text = text.strip()
# 移除特殊控制字符
text = re.sub(r'[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F-\x9F]', '', text)
return text
class PdfExtractor(BaseExtractor):
"""
PDF文档提取器
支持文本和图片混合的PDF文档处理
"""
def __init__(self, file_path: str, **kwargs):
super().__init__(file_path, **kwargs)
self.extract_images = kwargs.get('extract_images', False)
self.ocr_enabled = kwargs.get('ocr_enabled', False)
def extract(self) -> list[Document]:
"""
提取PDF文档内容
支持纯文本PDF和需要OCR的扫描版PDF
Returns:
list[Document]: 提取的文档对象列表
"""
documents = []
try:
import PyPDF2
import fitz # pymupdf
# 首先尝试使用PyPDF2提取文本
with open(self.file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page_num, page in enumerate(pdf_reader.pages):
try:
# 提取文本内容
text_content = page.extract_text()
# 如果文本内容很少且启用了OCR,使用OCR提取
if len(text_content.strip()) < 50 and self.ocr_enabled:
text_content = self._ocr_extract_page(page_num)
if text_content.strip():
# 清理文本内容
text_content = self._clean_text(text_content)
# 创建文档对象
document = Document(
page_content=text_content,
metadata={
"source": self.file_path,
"page": page_num + 1,
"total_pages": len(pdf_reader.pages),
"file_type": "pdf",
"extraction_method": "text" if len(text_content) > 50 else "ocr"
}
)
documents.append(document)
except Exception as e:
logger.warning(f"提取PDF第{page_num + 1}页失败: {e}")
continue
except Exception as e:
logger.error(f"PDF提取失败: {e}")
raise Exception(f"无法提取PDF文件 {self.file_path}: {e}")
return documents
def _ocr_extract_page(self, page_num: int) -> str:
"""
使用OCR提取页面文本
当PDF中的文本无法直接提取时使用
Args:
page_num: 页面编号
Returns:
str: OCR提取的文本内容
"""
try:
import fitz
import pytesseract
from PIL import Image
import io
# 打开PDF文档
doc = fitz.open(self.file_path)
page = doc.load_page(page_num)
# 将页面转换为图片
mat = fitz.Matrix(2.0, 2.0) # 2倍缩放提高OCR准确性
pix = page.get_pixmap(matrix=mat)
# 转换为PIL图片
img_data = pix.tobytes("ppm")
img = Image.open(io.BytesIO(img_data))
# 使用tesseract进行OCR
ocr_text = pytesseract.image_to_string(img, lang='chi_sim+eng')
doc.close()
return ocr_text
except ImportError:
logger.warning("OCR依赖库未安装,无法进行OCR提取")
return ""
except Exception as e:
logger.warning(f"OCR提取失败: {e}")
return ""
class WordExtractor(BaseExtractor):
"""
Word文档提取器
支持.docx格式的Word文档处理
"""
def __init__(self, file_path: str, tenant_id: str, user_id: str, **kwargs):
super().__init__(file_path, **kwargs)
self.tenant_id = tenant_id
self.user_id = user_id
self.extract_images = kwargs.get('extract_images', False)
def extract(self) -> list[Document]:
"""
提取Word文档内容
支持文本、表格和图片的综合提取
Returns:
list[Document]: 提取的文档对象列表
"""
try:
from docx import Document as DocxDocument
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import Table
from docx.text.paragraph import Paragraph
# 加载Word文档
doc = DocxDocument(self.file_path)
# 提取文档内容
content_blocks = []
# 遍历文档的所有元素
for element in doc.element.body:
if isinstance(element, CT_P):
# 段落处理
paragraph = Paragraph(element, doc)
text = paragraph.text.strip()
if text:
content_blocks.append({
'type': 'paragraph',
'content': text,
'style': paragraph.style.name if paragraph.style else 'Normal'
})
elif isinstance(element, CT_Tbl):
# 表格处理
table = Table(element, doc)
table_content = self._extract_table_content(table)
if table_content:
content_blocks.append({
'type': 'table',
'content': table_content,
'rows': len(table.rows),
'cols': len(table.columns) if table.rows else 0
})
# 合并内容并创建文档对象
if content_blocks:
# 将内容块组合成完整文本
full_text = self._combine_content_blocks(content_blocks)
document = Document(
page_content=full_text,
metadata={
"source": self.file_path,
"file_type": "docx",
"total_paragraphs": len([b for b in content_blocks if b['type'] == 'paragraph']),
"total_tables": len([b for b in content_blocks if b['type'] == 'table']),
"tenant_id": self.tenant_id,
"created_by": self.user_id,
"extraction_method": "docx_python"
}
)
return [document]
else:
logger.warning(f"Word文档 {self.file_path} 中未找到有效内容")
return []
except Exception as e:
logger.error(f"Word文档提取失败: {e}")
raise Exception(f"无法提取Word文件 {self.file_path}: {e}")
def _extract_table_content(self, table) -> str:
"""
提取表格内容并格式化为文本
Args:
table: python-docx表格对象
Returns:
str: 格式化的表格文本
"""
table_text = []
for row in table.rows:
row_cells = []
for cell in row.cells:
cell_text = cell.text.strip()
row_cells.append(cell_text)
# 用制表符连接单元格内容
row_text = '\t'.join(row_cells)
if row_text.strip():
table_text.append(row_text)
return '\n'.join(table_text)
def _combine_content_blocks(self, content_blocks: list) -> str:
"""
将内容块组合成完整的文档文本
Args:
content_blocks: 内容块列表
Returns:
str: 组合后的完整文本
"""
text_parts = []
for block in content_blocks:
if block['type'] == 'paragraph':
text_parts.append(block['content'])
elif block['type'] == 'table':
# 为表格添加标识
text_parts.append(f"[表格 {block['rows']}行 x {block['cols']}列]")
text_parts.append(block['content'])
text_parts.append("") # 表格后添加空行
return '\n'.join(text_parts)
class ExcelExtractor(BaseExtractor):
"""
Excel文档提取器
支持.xlsx和.xls格式的Excel文档处理
"""
def __init__(self, file_path: str, **kwargs):
super().__init__(file_path, **kwargs)
self.sheet_names = kwargs.get('sheet_names', None) # 指定工作表名称
self.max_rows = kwargs.get('max_rows', 10000) # 最大处理行数
def extract(self) -> list[Document]:
"""
提取Excel文档内容
支持多工作表和大数据量的处理
Returns:
list[Document]: 每个工作表对应一个文档对象
"""
try:
import pandas as pd
documents = []
# 读取Excel文件的所有工作表
excel_file = pd.ExcelFile(self.file_path)
# 确定要处理的工作表
sheets_to_process = (
self.sheet_names if self.sheet_names
else excel_file.sheet_names
)
for sheet_name in sheets_to_process:
try:
# 读取工作表数据
df = pd.read_excel(
self.file_path,
sheet_name=sheet_name,
nrows=self.max_rows
)
if df.empty:
continue
# 将DataFrame转换为文本格式
sheet_text = self._dataframe_to_text(df, sheet_name)
if sheet_text.strip():
document = Document(
page_content=sheet_text,
metadata={
"source": self.file_path,
"sheet_name": sheet_name,
"file_type": "excel",
"rows": len(df),
"columns": len(df.columns),
"extraction_method": "pandas"
}
)
documents.append(document)
except Exception as e:
logger.warning(f"提取Excel工作表 '{sheet_name}' 失败: {e}")
continue
return documents
except Exception as e:
logger.error(f"Excel文档提取失败: {e}")
raise Exception(f"无法提取Excel文件 {self.file_path}: {e}")
def _dataframe_to_text(self, df: 'pd.DataFrame', sheet_name: str) -> str:
"""
将DataFrame转换为结构化文本
Args:
df: pandas DataFrame对象
sheet_name: 工作表名称
Returns:
str: 格式化的文本内容
"""
text_parts = [f"工作表: {sheet_name}\n"]
# 添加列标题
headers = df.columns.tolist()
text_parts.append("列标题: " + " | ".join(str(h) for h in headers))
text_parts.append("-" * 50)
# 添加数据行
for index, row in df.iterrows():
row_values = []
for col in df.columns:
value = row[col]
# 处理空值和特殊值
if pd.isna(value):
value = ""
else:
value = str(value).strip()
row_values.append(value)
text_parts.append(" | ".join(row_values))
# 添加统计信息
text_parts.append(f"\n数据统计: {len(df)}行 x {len(df.columns)}列")
return "\n".join(text_parts)
class MarkdownExtractor(BaseExtractor):
"""
Markdown文档提取器
支持标准Markdown格式的处理和结构化提取
"""
def __init__(self, file_path: str, autodetect_encoding: bool = True, **kwargs):
super().__init__(file_path, **kwargs)
self.autodetect_encoding = autodetect_encoding
self.preserve_structure = kwargs.get('preserve_structure', True)
def extract(self) -> list[Document]:
"""
提取Markdown文档内容
可以保留文档结构或提取纯文本
Returns:
list[Document]: 提取的文档对象列表
"""
try:
# 检测并读取文件
encoding = self._detect_encoding(self.file_path) if self.autodetect_encoding else 'utf-8'
with open(self.file_path, 'r', encoding=encoding) as file:
content = file.read()
if self.preserve_structure:
# 保留Markdown结构的提取
return self._extract_with_structure(content)
else:
# 纯文本提取
return self._extract_plain_text(content)
except Exception as e:
logger.error(f"Markdown文档提取失败: {e}")
raise Exception(f"无法提取Markdown文件 {self.file_path}: {e}")
def _extract_with_structure(self, content: str) -> list[Document]:
"""
保留Markdown结构的提取方式
按章节分割内容
Args:
content: Markdown文档内容
Returns:
list[Document]: 按章节分割的文档列表
"""
import re
# 按标题分割文档
sections = self._split_by_headers(content)
documents = []
for i, section in enumerate(sections):
if section.strip():
document = Document(
page_content=section.strip(),
metadata={
"source": self.file_path,
"file_type": "markdown",
"section": i + 1,
"total_sections": len(sections),
"extraction_method": "structured"
}
)
documents.append(document)
return documents if documents else [self._create_single_document(content)]
def _extract_plain_text(self, content: str) -> list[Document]:
"""
纯文本提取方式
移除Markdown格式标记
Args:
content: Markdown文档内容
Returns:
list[Document]: 单个纯文本文档
"""
# 移除Markdown格式标记
plain_text = self._remove_markdown_formatting(content)
return [self._create_single_document(plain_text)]
def _split_by_headers(self, content: str) -> list[str]:
"""
按Markdown标题分割内容
Args:
content: Markdown内容
Returns:
list[str]: 按标题分割的段落列表
"""
import re
# 使用正则表达式查找标题
header_pattern = re.compile(r'^(#{1,6}\s+.+?)$', re.MULTILINE)
# 找到所有标题的位置
headers = list(header_pattern.finditer(content))
if not headers:
return [content]
sections = []
for i, header in enumerate(headers):
start = header.start()
end = headers[i + 1].start() if i + 1 < len(headers) else len(content)
section_content = content[start:end].strip()
sections.append(section_content)
return sections
def _remove_markdown_formatting(self, content: str) -> str:
"""
移除Markdown格式标记
Args:
content: 带格式的Markdown内容
Returns:
str: 纯文本内容
"""
import re
# 移除各种Markdown格式
# 标题
content = re.sub(r'^#{1,6}\s+', '', content, flags=re.MULTILINE)
# 粗体和斜体
content = re.sub(r'\*\*(.+?)\*\*', r'\1', content)
content = re.sub(r'\*(.+?)\*', r'\1', content)
content = re.sub(r'__(.+?)__', r'\1', content)
content = re.sub(r'_(.+?)_', r'\1', content)
# 链接
content = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', content)
# 代码块
content = re.sub(r'```[\s\S]*?```', '', content)
content = re.sub(r'`([^`]+)`', r'\1', content)
# 引用
content = re.sub(r'^>\s+', '', content, flags=re.MULTILINE)
# 列表
content = re.sub(r'^\s*[-*+]\s+', '', content, flags=re.MULTILINE)
content = re.sub(r'^\s*\d+\.\s+', '', content, flags=re.MULTILINE)
# 清理多余空行
content = re.sub(r'\n\s*\n', '\n\n', content)
return content.strip()
def _create_single_document(self, content: str) -> Document:
"""
创建单个文档对象
Args:
content: 文档内容
Returns:
Document: 文档对象
"""
return Document(
page_content=self._clean_text(content),
metadata={
"source": self.file_path,
"file_type": "markdown",
"extraction_method": "single_document"
}
)
|