Google Document AI OCR处理希伯来语PDF段落序号位置异常求助
解决希伯来语PDF段落编号顺序颠倒问题
针对你遇到的Google Document AI/Vision AI处理希伯来语PDF时段落编号跑到正文前的问题,核心原因是AI对从右到左(RTL)语言与LTR元素(如阿拉伯数字编号)的混合布局识别偏差,可以通过以下几个方案解决:
1. 明确指定文档语言为希伯来语
默认自动检测语言可能导致RTL处理精度不足,调用API时显式设置language_code为"he",让模型优先按照希伯来语的RTL规则解析布局。
Document AI 请求示例(Python):
from google.cloud import documentai_v1 as documentai client = documentai.DocumentProcessorServiceClient() request = documentai.ProcessRequest( name="你的处理器名称", raw_document=documentai.RawDocument(content=pdf_content, mime_type="application/pdf"), # 显式指定希伯来语 process_options=documentai.ProcessOptions(language_codes=["he"]) ) response = client.process_document(request)
2. 基于Bounding Box手动修正行内文本顺序
AI返回的token布局虽显示位置"不正确",但可通过每个token的bounding box坐标重新排序:希伯来语RTL文本的视觉顺序是从右到左,对应页面x坐标(从左到右递增)的从大到小排列。遍历每行的token,按x_max降序排序后拼接文本,即可修正编号与正文的顺序。
修改你的代码实现:
# documents - output of the Documents API for document in documents: for page in document.pages: if page.page_number <= 10: for line in page.lines: # 按token在页面的x坐标降序排序,匹配RTL阅读顺序 sorted_tokens = sorted(line.tokens, key=lambda t: t.layout.bounding_poly.vertices[0].x, reverse=True) # 拼接排序后的token文本 line_text = "".join([ document.text[t.layout.text_anchor.text_segments[0].start_index:t.layout.text_anchor.text_segments[0].end_index] for t in sorted_tokens ]) print(line_text)
注:顶点坐标的
x值越大,代表该token在页面上越靠右,符合希伯来语从右到左的阅读逻辑。
3. 使用Document AI的布局专用模型
基础OCR模型对复杂RTL布局支持有限,切换到LAYOUT_PARSER或FORM_PARSER模型,这类模型专门优化了多语言布局识别,能更准确区分RTL文本与LTR编号的位置关系。
4. 后处理规则修正
如果以上方法仍有偏差,可添加后处理逻辑:识别段落开头的数字编号,将其移动到段落末尾(符合希伯来语段落编号的常规排版位置)。示例逻辑:
import re def fix_paragraph_order(text): # 匹配开头的阿拉伯数字编号(如"1. " "2 "等格式) match = re.match(r"^(\d+[\. ]+)(.*)", text.strip()) if match: number, content = match.groups() # 将编号移到段落末尾 return f"{content}{number}" return text # 在输出前调用修正函数 print(fix_paragraph_order(line_text))
内容的提问来源于stack exchange,提问作者Julia Grobman
相关产品推荐
相关产品推荐

