RAG中PDF的解析

今天新开一篇文章。前段时间一直忙于项目周期中琐碎的事情,没有好好总结和思考技术核心的东西。探索RAG的应用也有一段时间了,市面上的应用也看的不少,很多的应用包括langchain-chatchat,Dify, 都是整体搭建了一个最basic版本的RAG框架,至于很多细节点,并没有提供更精细化的实现,今天要写的这部分:PDF上传到知识库之后如何parse和chunking,直接影响后续retrival的表现,目前还没有很全面的review来总结这部分内容。这里就对我看到的一些技术做一些整理。

解析PDF文档的难点主要在于如何精确地捕捉页面的整体布局,并将包括表格标题, 段落以及图片在内的内容转译为文档的文字形式。这一过程涉及到多个技术点,布局的检测,图片中文字的抽取,表格中行与列的识别(如何正确将PDF中的表格识别成可用结构化形式表示的表格,也就是能还原出原表格来)。

目前解析PDF文档主要有三种主流方式:

  1. 基于规则的方法:这种方法根据文档的组织特性来确定每个部分的样式和内容,代表库:pypdf, 这种方法的适用性比较差,很难通过预设的规则覆盖所有PDF的情形。
  2. 基于深度学习模型的方法:一个流行的解决方案是结合了物体检测和OCR模型,代表 Chatdoc
  3. 基于多模态大模型的方法:通过这种方法可以解析PDF中复杂结构或者提取关键信息

基于规则的方法

基于规则的PDF处理库真的太多了,每一次看到一个应用使用的新的PDF解析器,都要重新看看怎么处理的。比如langchain-chatchat用的是pyMuPDF中的fitz包,见langchain-chatchat源代码,这一段处理特别粗糙,我贴上来:

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
import fitz  # pyMuPDF里面的fitz包,不要与pip install fitz混淆
import numpy as np

ocr = get_ocr()
doc = fitz.open(filepath)
resp = ""

b_unit = tqdm.tqdm(
total=doc.page_count, desc="RapidOCRPDFLoader context page index: 0"
)
for i, page in enumerate(doc):
b_unit.set_description(
"RapidOCRPDFLoader context page index: {}".format(i)
)
b_unit.refresh()
text = page.get_text("")
resp += text + "\n"

img_list = page.get_image_info(xrefs=True)
for img in img_list:
if xref := img.get("xref"):
bbox = img["bbox"]
# 检查图片尺寸是否超过设定的阈值
if (bbox[2] - bbox[0]) / (page.rect.width) < PDF_OCR_THRESHOLD[
0
] or (bbox[3] - bbox[1]) / (
page.rect.height
) < PDF_OCR_THRESHOLD[1]:
continue
pix = fitz.Pixmap(doc, xref)
samples = pix.samples
if int(page.rotation) != 0: # 如果Page有旋转角度,则旋转图片
img_array = np.frombuffer(
pix.samples, dtype=np.uint8
).reshape(pix.height, pix.width, -1)
tmp_img = Image.fromarray(img_array)
ori_img = cv2.cvtColor(np.array(tmp_img), cv2.COLOR_RGB2BGR)
rot_img = rotate_img(img=ori_img, angle=360 - page.rotation)
img_array = cv2.cvtColor(rot_img, cv2.COLOR_RGB2BGR)
else:
img_array = np.frombuffer(
pix.samples, dtype=np.uint8
).reshape(pix.height, pix.width, -1)

result, _ = ocr(img_array)
if result:
ocr_result = [line[1] for line in result]
resp += "\n".join(ocr_result)

注意它对PDF中图片的处理,是将某一页中所有的图片存入一个img_list,然后遍历这个list,用ocr算法抠出里面的文字,将这些文字都放到该页text的末尾,很大程度上丧失了图片在PDF中应该表达的语义,不仅如此,我觉得还影响了retrival的performance,加入了噪声。

再来看看Dify怎么处理的:

1
2
3
4
5
6
7
8
9
10
11
12
13
import pypdfium2
with blob.as_bytes_io() as file_path:
pdf_reader = pypdfium2.PdfDocument(file_path, autoclose=True)
try:
for page_number, page in enumerate(pdf_reader):
text_page = page.get_textpage()
content = text_page.get_text_range()
text_page.close()
page.close()
metadata = {"source": blob.source, "page": page_number}
yield Document(page_content=content, metadata=metadata)
finally:
pdf_reader.close()

换了一个pypdfium2的库,图片完全舍弃。我也去搜了有没有对两者的比较,见pypdf or pymupdf?,更有作者做了一个repo用于比较各种library的效果:传送门。结论是如果单论文本抽取的质量,pypdfium2是第一

对于RAG中PDF的处理,我觉得最理想的目标应该是,query能够link到PDF中的图片,不仅如此,这张图片也应该作为reference,目前市面上的reference只能link到相应文件的纯文本。远远不够精细,不过做起来确实有点困难,也需要一点耐心。

image-20240628100839214

更多其他工具的比较可参考A Benchmark and Evaluation for Text Extraction from PDF

image-20240628101040870

基于规则的方法有一个最大的缺点就是:它会将每一行视为由换行符“”分隔的序列,如果那一行确实是以句号为结尾,影响还稍微小一点,但是如果下一行还在表述这句话,语义上就完全断掉了。要知道在chunking的阶段,大部分的做法是以\n作分隔符的。

基于深度学习模型的方法

这种方法的又是是它能准确识别整个文档的布局,包括表格和段落。它甚至能理解表格内的结构。这意味着解析出来的表格能完整的解析成表格原本的样子。局限性就在于对象检测和OCR的识别两个阶段可能会耗时。这时候可以考虑采用GPU加速或者多进程和多线程的方式进行处理。

这里有几个开源的代表框架:

  • Unstructured:它是langchain官方推荐的方式。在启用infer_table_structure=True的hi_res策略下,表格的识别效果良好。fast策略下表现不佳
  • Layout-parser:如果需要识别复杂结构的PDF,建议使用最大的模型,虽然可能会稍慢一点
  • PP-StructureV2: 采用多种模型组合进行文档的分析,性能优于平均水平。这是百度的飞桨出品的文档智能模型。

另外有一些闭源付费的工具诸如ChatDoc和LLama Parse, 这些在现实的落地中存在一定阻碍,毕竟调用API是一定会存在数据上传到别人服务器的风险的,如果是处理非敏感数据,付费API可以做考虑。

这里对Unstructured处理PDF做一些探索。

Unstructured对PDF的处理首先是对layout进行检测(detectron2模型),然后使用tesseract实现OCR的功能,用table transformer处理table。

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
from unstructured.partition.pdf import partition_pdf
# Get elements
raw_pdf_elements = partition_pdf(
filename=test_file,
# Using pdf format to find embedded image blocks
extract_images_in_pdf=True,
# Use layout model (YOLOX) to get bounding boxes (for tables) and find titles
# Titles are any sub-section of the document
infer_table_structure=True,
# Post processing to aggregate text once we have the title
chunking_strategy="by_title",
# Chunking params to aggregate text blocks
# Attempt to create a new chunk 3800 chars
# Attempt to keep chunks > 2000 chars
# Hard max on chunks
max_characters=4000,
new_after_n_chars=3800,
combine_text_under_n_chars=2000,
)

tables = [el for el in raw_pdf_elements if el.category == 'Table']

print(tables[0].text)

print(tables[0].metadata.text_as_html)

上述的第二个输出:将表格转化为html格式,如果将其保存为html,它可以在浏览器中打开,打开后还是一个完整的表格。unstructured的好处就在于它保证了一个表格的完整性。官方给出的示例代码中就是将每一个element的text去做embedding,对于表格来说就是将表格的text去做embedding。但是我测试了两个例子发现,它把表格的标题以及表格的注解给弄到其他element里去了,这些文本本应该和表格一起,比如下面的表格:

image-20240628160939056

它抽取出来的表格element就只包含纯表格那部分,上面关于Table1的介绍都包含在了上面一个element里

1
2
3
4
5
6
7
8
9
3.5 Positional Encoding

Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the

5

Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.
--------------------------------- 上面是另一个element的内容
Layer Type Self-Attention Recurrent Convolutional Self-Attention (restricted) Complexity per Layer O(n2 · d) O(n · d2) O(k · n · d2) O(r · n · d) Sequential Maximum Path Length Operations O(1) O(n) O(1) O(1) O(1) O(n) O(logk(n)) O(n/r)

基于多模态大模型的方法