【问题标题】:Is there a way to pass credentials programmatically for using google documentAI without reading from a disk?有没有办法以编程方式传递凭据以使用 google documentAI 而无需从磁盘读取?
【发布时间】:2020-07-02 14:42:10
【问题描述】:

我正在尝试运行 GCP 文档 AI 的 pdf 解析中给出的演示代码。要运行代码,将 google 凭据导出为命令行可以正常工作。当代码需要在内存中运行并且因此不允许从磁盘访问凭据文件时,就会出现问题。有没有办法在文档ai解析函数中传递凭证?

google的示例代码:

def main(project_id='YOUR_PROJECT_ID',
         input_uri='gs://cloud-samples-data/documentai/invoice.pdf'):
    """Process a single document with the Document AI API, including
    text extraction and entity extraction."""

    client = documentai.DocumentUnderstandingServiceClient()
    
    gcs_source = documentai.types.GcsSource(uri=input_uri)

    # mime_type can be application/pdf, image/tiff,
    # and image/gif, or application/json
    input_config = documentai.types.InputConfig(
        gcs_source=gcs_source, mime_type='application/pdf')

    # Location can be 'us' or 'eu'
    parent = 'projects/{}/locations/us'.format(project_id)
    request = documentai.types.ProcessDocumentRequest(
        parent=parent,
        input_config=input_config)

    document = client.process_document(request=request)

    # All text extracted from the document
    print('Document Text: {}'.format(document.text))

    def _get_text(el):
        """Convert text offset indexes into text snippets.
        """
        response = ''
        # If a text segment spans several lines, it will
        # be stored in different text segments.
        for segment in el.text_anchor.text_segments:
            start_index = segment.start_index
            end_index = segment.end_index
            response += document.text[start_index:end_index]
        return response

    for entity in document.entities:
        print('Entity type: {}'.format(entity.type))
        print('Text: {}'.format(_get_text(entity)))
        print('Mention text: {}\n'.format(entity.mention_text))

【问题讨论】:

  • 您的代码在哪里运行?在 gcp 上还是在其他地方?
  • @guillaumeblaquiere,它在 GCF 上运行。由于仅在内存中计算,我如何传递凭证 json ?
  • 你没有!我正在写答案

标签: google-cloud-platform google-cloud-functions artificial-intelligence pdf-parsing


【解决方案1】:

在 GCP 上运行工作负载时,您不需要服务帐号密钥文件。千万不要!!

为什么? 2 个原因:

  1. 它没用,因为所有 GCP 产品至少都有一个默认服务帐户。大多数时候,您可以自定义它。你可以看看Cloud Function identity你的情况。
  2. 服务帐户密钥文件是一个文件。这意味着很多:您可以复制它,通过电子邮件发送它,将它提交到 Git 存储库中......许多人都可以访问它,而您可以放松对这个秘密的管理。而且因为它是一个秘密,你必须安全地存储它,你必须定期轮换它(至少每 90 天,谷歌推荐),......这是噩梦! 尽可能不要使用服务帐户密钥文件!

图书馆在做什么?

  • 正在查看 GOOGLE_APPLICATION_CREDENTIALS 环境变量是否存在。
  • 正在查看“众所周知”位置(当您执行 gcloud auth application-default login 以允许本地应用程序使用您的凭据访问 Google 资源时,会在您计算机上的“标准位置”中创建一个文件)
  • 如果不是,请检查metadata server exists (only on GCP)。此服务器向库提供身份验证信息。
  • 否则会引发错误。

因此,只需在您的函数中使用正确的服务帐户并为其提供正确的角色即可实现您想要做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多