【问题标题】:Reading a PDF File using google cloud vision使用谷歌云视觉读取 PDF 文件
【发布时间】:2021-08-10 16:44:42
【问题描述】:

我目前正在尝试使用谷歌云视觉 API 阅读 pdf。在我当前的代码中,我有一条通往我的谷歌云存储中的存储桶的路径。相反,我希望我的程序能够从本地存储中读取文件。我应该在我的代码中进行哪些更改才能使其正常工作?我在下面附上了我的代码。

Code part 1

Code Part 2

【问题讨论】:

  • 请以文本格式发布您的代码,以便社区成员轻松复制。

标签: google-cloud-vision


【解决方案1】:

根据您的代码,您正在使用 async_batch_annotate_files() 处理 PDF 文件。无法使用此方法处理本地 PDF 文件。 async_batch_annotate_files() 仅限于从 Google Cloud Storage 读取 PDF 文件,因为此方法旨在按照 documentation 处理巨大的 PDF 文件。

Vision API 接受最多 2000 页的 PDF/TIFF 文件。

目前 PDF/TIFF (async_batch_annotate_files) 文档检测仅适用于存储在 Cloud Storage 存储分区中的文件。响应 JSON 文件同样保存到 Cloud Storage 存储分区。


但如果你真的想在本地阅读PDF文件,可以使用batch_annotate_files(),但这有其局限性。它只能处理最多 5 页的 PDF 文件。有关详细信息,请参阅Small batch file annotation。以下是文档中的示例代码:

import io

from google.cloud import vision_v1


def sample_batch_annotate_files(file_path="local_path/to/your/document.pdf"):
    """Perform batch file annotation. Limited to PDF files up to 5 pages"""
    client = vision_v1.ImageAnnotatorClient()

    # Supported mime_type: application/pdf, image/tiff, image/gif
    mime_type = "application/pdf"
    with io.open(file_path, "rb") as f:
        content = f.read()
    input_config = {"mime_type": mime_type, "content": content}
    features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}]

    # The service can process up to 5 pages per document file. Here we specify
    # the first, second, and last page of the document to be processed.
    pages = [1, 2, -1]
    requests = [{"input_config": input_config, "features": features, "pages": pages}]

    response = client.batch_annotate_files(requests=requests)
    for image_response in response.responses[0].responses:
        print(u"Full text: {}".format(image_response.full_text_annotation.text))
        for page in image_response.full_text_annotation.pages:
            for block in page.blocks:
                print(u"\nBlock confidence: {}".format(block.confidence))
                for par in block.paragraphs:
                    print(u"\tParagraph confidence: {}".format(par.confidence))
                    for word in par.words:
                        print(u"\t\tWord confidence: {}".format(word.confidence))
                        for symbol in word.symbols:
                            print(
                                u"\t\t\tSymbol: {}, (confidence: {})".format(
                                    symbol.text, symbol.confidence
                                )
                            )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多