我有一个 PDF,我正在尝试让 Tika 解析它。 PDF 不是 OCR。我的机器上安装了 Tesseract。
我使用ImageMagik将file.tiff转换为file.pdf,因此我正在解析的tiff文件是PDF的直接转换。
Tika 解析 TIFF 没有任何问题,但返回 PDF 的“无”内容。是什么赋予了?我正在使用 Tika 1.14.1、tesseract 3.03、leptonica-1.70
这是代码...
from tika import parser
# This works
print(parser.from_file('/from/file.tiff', 'http://localhost:9998/tika'))
# This returns "None" for content
print(parser.from_file('/from/file.pdf', 'http://localhost:9998/tika'))
最佳答案
因此,在 Chris Mattman 的一些反馈之后(他很棒,而且非常乐于助人!),我解决了这个问题。
他的回应:
Since Tika Python acts as a thin client to the REST server, you just need to make sure the REST server is started with a classpath configuration that sets the right flags for TesseractOCR, see here:
虽然我之前读过这篇文章,但直到后来进一步阅读,我才发现这个问题。 TesseractOCR 本身并不支持 PDF 的 OCR 转换 - 因此,Tika 也不支持,因为 Tika 依赖于 Tesseract 对 PDF 转换的支持(此外,tika-python 也不支持)
我的解决方案:
我将 subprocess、ImageMagick (CLI) 和 Tika 组合在 python 中,首先将 PDF 转换为 TIFF,然后允许 Tika/Tesseract 对文件执行 OCR 转换。
注释:
- 对于大型 PDF,此过程非常慢
- 需要:tika-python、tesseract、imagemagick
代码:
from tika import parser
import subprocess
import os
def ConvertPDFToOCR(file):
meta = parser.from_file(fil, 'http://localhost:9998/tika')
# Check if parsed content is NoneType and handle accordingly.
if "content" in meta and meta['content'] is None:
# Run ImageMagick via subprocess (command line)
params = ['convert', '-density', '300', u, '-depth', '8', '-strip', '-background', 'white', '-alpha', 'off', 'temp.tiff']
subprocess.check_call(params)
# Run Tika again on new temp.tiff file
meta = parser.from_file('temp.tiff', 'http://localhost:9998/tika')
# Delete the temporary file
os.remove('temp.tiff')
return meta['content']
关于Python-Tika 返回 PDF 的 "None"内容,但适用于 TIFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48103065/