RAG文檔解析器,核心技術剖析
最近,RAG技術逐漸走紅,但文檔解析這一重要環(huán)節(jié)卻鮮為人知。說到底,無論使用多么高級的檢索和生成技術,最終效果都取決于文檔本身的質量。如果文檔信息不全或格式混亂,那么再怎么優(yōu)化檢索策略、嵌入模型或大型語言模型(LLMs)也無濟于事。
本文介紹三種流行的文檔提取策略,并以亞馬遜2024年第一季度報告中的表格解析為例,展示這些策略的實際應用。
1 文本解析器:基礎工具
文本解析器已經(jīng)發(fā)展多年,這些工具能夠讀取文檔并從中提取文本。常見的工具有PyPDF、PyMUPDF和PDFMiner。接下來,重點介紹PyMUPDF,并通過LlamaIndex集成的PyMUPDF來解析特定頁面。以下是相應的代碼示例:
from llama_index.core.schema import TextNode
from llama_index.core.node_parser import SentenceSplitter
import fitz
file_path = "/content/AMZN-Q1-2024-Earnings-Release.pdf"
doc = fitz.open(file_path)
text_parser = SentenceSplitter(
chunk_size=2048,
)
text_chunks = [] #C
for doc_idx, page in enumerate(doc):
page_text = page.get_text("text")
cur_text_chunks = text_parser.split_text(page_text)
text_chunks.extend(cur_text_chunks)
nodes = [] #D
for idx, text_chunk in enumerate(text_chunks):
node = TextNode(
text=text_chunk,
)
nodes.append(node)
print(nodes[10].text)
PyMUPDF在提取文本方面表現(xiàn)優(yōu)秀,但文本的格式處理并不理想。這在后續(xù)的生成過程中可能會造成問題,尤其是當大型語言模型難以識別文檔結構時。
以下是亞馬遜公司的財務報表摘要:
AMAZON.COM, INC.
Consolidated Statements of Comprehensive Income
(in millions)
(unaudited)
Three Months Ended
March 31,
2023
2024
Net income
$
3,172 $
10,431
Other comprehensive income (loss):
Foreign currency translation adjustments, net of tax of $(10) and $30
386
(1,096)
Available-for-sale debt securities:
Change in net unrealized gains (losses), net of tax of $(29) and $(158)
95
536
Less: reclassification adjustment for losses (gains) included in “Other income
(expense), net,” net of tax of $(10) and $0
33
1
Net change
128
537
Other, net of tax of $0 and $(1)
—
1
Total other comprehensive income (loss)
514
(558)
Comprehensive income
$
3,686 $
9,873
接下來,讓我們看看OCR在文檔解析中的表現(xiàn)。
2 OCR技術:圖像識別
from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os
pages = convert_from_path(file_path)
i=10
filename = "page"+str(i)+".jpg"
pages[i].save(filename, 'JPEG')
outfile = "page"+str(i)+"_text.txt"
f = open(outfile, "a")
text= str(((pytesseract.image_to_string(Image.open(filename)))))
text = text.replace('-\n', '')
f.write(text)
f.close()
print(text)
OCR(如下所示)能更好地捕捉文檔文本和結構。
AMAZON.COM, INC.
Consolidated Statements of Comprehensive Income
(in millions)
(unaudited)
Three Months Ended
March 31,
2023 2024
Net income $ 3,172 §$ 10,431
Other comprehensive income (loss):
Foreign currency translation adjustments, net of tax of $(10) and $30 386 (1,096)
Available-for-sale debt securities:
Change in net unrealized gains (losses), net of tax of $(29) and $(158) 95 536
Less: reclassification adjustment for losses (gains) included in “Other income
(expense), net,” net of tax of $(10) and $0 33 1
Net change 128 231
Other, net of tax of $0 and $(1) _— 1
Total other comprehensive income (loss) 514 (558)
Comprehensive income $ 3,686 $ 9,873
最后,來看看智能文檔解析。
3 智能文檔解析(IDP):結構化提取
智能文檔解析(IDP)是一項新興技術,旨在從文檔中提取所有相關信息,并以結構化格式呈現(xiàn)。市面上有多種IDP工具,如LlamaParse、DocSumo、Unstructured.io以及Azure Doc Intelligence等。
這些工具的共同點在于,它們都融合了OCR(光學字符識別)、文本提取技術、多模態(tài)大型語言模型(LLMs),以及將內(nèi)容轉換為markdown格式的能力,以實現(xiàn)文本的高效提取。以LlamaIndex推出的LlamaParse為例,使用前需要先獲取API密鑰,然后便可以通過API接口來解析文檔。
import getpass
import os
from copy import deepcopy
os.environ["LLAMA_CLOUD_API_KEY"] = getpass.getpass()
from llama_parse import LlamaParse
import nest_asyncio
nest_asyncio.apply()
documents = LlamaParse(result_type="markdown").load_data(file_path)
def get_page_nodes(docs, separator="\n---\n"):
"""Split each document into page node, by separator."""
nodes = [] #C
for doc in docs:
doc_chunks = doc.text.split(separator)
for doc_chunk in doc_chunks:
node = TextNode(
text=doc_chunk,
metadata=deepcopy(doc.metadata),
)
nodes.append(node)
return nodes
nodes_lp = get_page_nodes(documents)
print(nodes_lp[10].text)
下面的內(nèi)容以markdown格式結構化,應該是目前結構最好的表示。
# 亞馬遜公司
# 綜合收益表
| |Three Months Ended March 31, 2023|Three Months Ended March 31, 2024|
|---|---|---|
|Net income|$3,172|$10,431|
|Other comprehensive income (loss):| | |
|Foreign currency translation adjustments, net of tax of $(10) and $30|386|(1,096)|
|Available-for-sale debt securities:| | |
|Change in net unrealized gains (losses), net of tax of $(29) and $(158)|95|536|
|Less: reclassification adjustment for losses (gains) included in “Other income (expense), net,” net of tax of $(10) and $0|33|1|
|Net change|128|537|
|Other, net of tax of $0 and $(1)|—|1|
|Total other comprehensive income (loss)|514|(558)|
|Comprehensive income|$3,686|$9,873|
不過,有一點需要注意,上述內(nèi)容忽略了一些關鍵的上下文信息。特別是,解析后的文檔中不再包含“millions”(百萬)這樣的單位標識,這可能會導致生成器LLM在理解時產(chǎn)生誤解。
4 結論
要提升你的RAG應用性能,重點在于選擇合適的文檔解析器。各種解析策略各有千秋,也各有局限:
- 文本解析器:使用PyPDF或PyMUPDF等工具,可以高效提取文本,但可能會丟失文檔結構,這在生成內(nèi)容時可能會讓你的語言模型感到困惑。
- OCR技術:選擇Pytesseract等OCR工具,能更精準地捕捉文本及其結構,更好地保留原始文檔的格式和上下文。但OCR處理通常耗時較長,且效果很大程度上取決于具體應用場景。你需要權衡準確性提升是否值得增加的處理時間。
- 智能文檔解析(IDP):采用LlamaParse等高級IDP工具,可以整合OCR、文本提取和多模態(tài)語言模型,將文檔轉換為結構化的markdown格式。但要注意,這種方法有時會丟失關鍵的上下文信息,如度量單位。此外,IDP技術尚在成熟過程中,可能面臨可擴展性和延遲問題。在部署IDP時,要充分考慮這些限制,并為可能的系統(tǒng)瓶頸做好準備。
最終,選擇哪種解析器,需要根據(jù)你的具體應用場景來決定。最佳做法是嘗試不同的解析器,評估它們在你的應用中的表現(xiàn),然后選擇最滿足你需求的那一個。有時候,結合多種方法可能會更有效。不斷試驗和調整,以期達到最佳的RAG應用效果。
本文轉載自 ??AI科技論談??,作者: AI科技論談
