大家好,我是六哥,相信很多朋友肯定都有过从各种文档里提取文本的经历,那过程可太让人头疼了!今天就给大家分享一款超实用的现代Python库——Kreuzberg,帮你轻松解决文本提取的难题。
现在很多文本提取工具,要么依赖外部API调用,要么配置特别复杂,使用起来很不方便。而Kreuzberg专为解决RAG(检索增强生成)应用里的文本提取需求而生,不过它可不止这点用处,任何文本提取场景都能完美适配。它专注于本地处理,依赖少,简单又高效。
pip install kreuzberg
extract_file()
:从文件中提取文本,可以接受字符串路径或pathlib.Path 。from pathlib import Path
from kreuzberg import extract_file, extract_bytes
# 基本文件提取
async def extract_document():
# 从PDF文件提取
pdf_result = await extract_file("document.pdf")
print(f"PDF文本: {pdf_result.content}")
# 从图像提取
img_result = await extract_file("scan.png")
print(f"图像文本: {img_result.content}")
# 从Word文档提取
docx_result = await extract_file(Path("document.docx"))
print(f"Word文本: {docx_result.content}")
- `extract_bytes()`:从字节中提取文本,接受字节字符串。比如处理上传的文件:
from kreuzberg import extract_bytes
async def process_upload(file_content: bytes, mime_type: str):
"""处理已知MIME类型的上传文件内容。"""
result = await extract_bytes(file_content, mime_type=mime_type)
return result.content
# 不同文件类型的示例用法
async def handle_uploads():
# 处理PDF上传
pdf_result = await extract_bytes(pdf_bytes, mime_type="application/pdf")
# 处理图像上传
img_result = await extract_bytes(image_bytes, mime_type="image/jpeg")
# 处理Word文档上传
docx_result = await extract_bytes(docx_bytes,
mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
from kreuzberg import extract_file
async def process_pdf():
# 对包含图像或扫描内容的PDF强制OCR
result = await extract_file("document.pdf", force_ocr=True)
# 处理扫描版PDF(自动使用OCR)
scanned = await extract_file("scanned.pdf")
- **提取结果对象**:所有提取函数返回的对象包含提取的文本(`content`)和输出格式(`mime_type`)。
from kreuzberg import ExtractionResult
async def process_document(path: str) -> tuple[str, str]:
# 作为具名元组访问
result: ExtractionResult = await extract_file(path)
print(f"内容: {result.content}")
print(f"格式: {result.mime_type}")
# 或解包为元组
content, mime_type = await extract_file(path)
return content, mime_type
- **错误处理**:Kreuzberg通过多种异常类型提供全面的错误处理,所有异常都继承自`KreuzbergError` ,每个异常都包含有助于调试的上下文信息。
from kreuzberg import extract_file
from kreuzberg.exceptions import (
ValidationError,
ParsingError,
OCRError,
MissingDependencyError
)
async def safe_extract(path: str) -> str:
try:
result = await extract_file(path)
return result.content
except ValidationError as e:
# 输入验证问题
# - 不支持或无法检测的MIME类型
# - 文件缺失
# - 无效输入参数
print(f"验证失败: {e}")
except OCRError as e:
# OCR特定问题
# - Tesseract处理失败
# - 图像转换问题
print(f"OCR失败: {e}")
except MissingDependencyError as e:
# 系统依赖问题
# - 缺少Tesseract OCR
# - 缺少Pandoc
# - 版本不兼容
print(f"依赖缺失: {e}")
except ParsingError as e:
# 一般处理错误
# - PDF解析失败
# - 格式转换问题
# - 编码问题
print(f"处理失败: {e}")
return ""
# 示例错误上下文
try:
result = await extract_file("document.xyz")
except ValidationError as e:
# 错误将包含上下文:
# ValidationError: 不支持的mime类型
# 上下文: {
# "file_path": "document.xyz",
# "supported_mimetypes": ["application/pdf",...]
# }
print(e)
try:
result = await extract_file("scan.jpg")
except OCRError as e:
# 错误将包含上下文:
# OCRError: OCR返回非0代码失败
# 上下文: {
# "file_path": "scan.jpg",
# "tesseract_version": "5.3.0"
# }
print(e)
Kreuzberg设计为在现有开源工具之上的高级异步抽象,集成了多个工具来实现强大功能:
如果你对Kreuzberg感兴趣,想深入了解或者参与开发,可以访问项目链接:https://github.com/Goldziher/kreuzberg 。
优秀不够,你是否无可替代
软件测试交流QQ群:721256703,期待你的加入!!
欢迎关注我的微信公众号:软件测试君
参与评论
手机查看
返回顶部