试用光学字符识别 (OCR) 功能

本指南将引导您完成使用 Google 的 Vertex AI Vision 服务运行光学字符识别 (OCR) 测试的过程。

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。如需了解详情,请参阅 Vertex AI Python API 参考文档

  1. 创建 Python 文件 ocr_test.py。将 image_uri_to_test 值替换为源映像的 URI,如下所示:

    import os
    import requests
    import json
    
    def detect_text_rest(image_uri):
        """Performs Optical Character Recognition (OCR) on an image by invoking the Vertex AI REST API."""
    
        # Securely fetch the API key from environment variables
        api_key = os.environ.get("GCP_API_KEY")
        if not api_key:
            raise ValueError("GCP_API_KEY environment variable must be defined.")
    
        # Construct the Vision API endpoint URL
        vision_api_url = f"https://vision.googleapis.com/v1/images:annotate?key={api_key}"
    
        print(f"Initiating OCR process for image: {image_uri}")
    
        # Define the request payload for text detection
        request_payload = {
            "requests": [
                {
                    "image": {
                        "source": {
                            "imageUri": image_uri
                        }
                    },
                    "features": [
                        {
                            "type": "TEXT_DETECTION"
                        }
                    ]
                }
            ]
        }
    
        # Send a POST request to the Vision API
        response = requests.post(vision_api_url, json=request_payload)
        response.raise_for_status()  # Check for HTTP errors
    
        response_json = response.json()
    
        print("\n--- OCR Results ---")
    
        # Extract and print the detected text
        if "textAnnotations" in response_json["responses"]:
            full_text = response_json["responses"]["textAnnotations"]["description"]
            print(f"Detected Text:\n{full_text}")
        else:
            print("No text was detected in the image.")
    
        print("--- End of Results ---\n")
    
    if __name__ == "__main__":
        # URI of a publicly available image, or a storage bucket
        image_uri_to_test = "IMAGE_URI"
    
        detect_text_rest(image_uri_to_test)
    

    替换以下内容:

    • IMAGE_URI 替换为包含文本的公开可用图片的 URI,例如“https://cloud.google.com/vision/docs/images/sign.jpg”。或者,您也可以指定 Cloud Storage URI,例如“gs://your-bucket/your-image.png
  2. 创建 Dockerfile:

    ROM python:3.9-slim
    
    WORKDIR /app
    
    COPY ocr_test.py /app/
    
    # Install 'requests' for HTTP calls
    RUN pip install --no-cache-dir requests
    
    CMD ["python", "ocr_test.py"]
    
  3. 为翻译应用构建 Docker 映像:

    docker build -t ocr-app .
    
  4. 按照配置 Docker 中的说明执行以下操作:

    1. 配置 Docker,
    2. 创建 Secret,并
    3. 将映像上传到 HaaS。
  5. 登录用户集群,并使用用户身份生成其 kubeconfig 文件。确保您已将 kubeconfig 路径设置为环境变量:

    export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}
    
  6. 在终端中运行以下命令,粘贴您的 API 密钥,以创建 Kubernetes Secret:

    kubectl create secret generic gcp-api-key-secret \
      --from-literal=GCP_API_KEY='PASTE_YOUR_API_KEY_HERE'
    

    此命令会创建一个名为 gcp-api-key-secret 的 Secret,其中包含一个键 GCP_API_KEY

  7. 应用 Kubernetes 清单:

    apiVersion: batch/v1
    kind: Job
    metadata:
      name: ocr-test-job-apikey
    spec:
      template:
        spec:
          containers:
          - name: ocr-test-container
            image: HARBOR_INSTANCE_URL/HARBOR_PROJECT/ocr-app:latest # Your image path
            # Mount the API key from the secret into the container
            # as an environment variable named GCP_API_KEY.
            imagePullSecrets:
            - name: ${SECRET}
            envFrom:
            - secretRef:
                name: gcp-api-key-secret
          restartPolicy: Never
      backoffLimit: 4
    
    

    替换以下内容:

    • HARBOR_INSTANCE_URL:Harbor 实例网址。
    • HARBOR_PROJECT:Harbor 项目。
    • SECRET:为存储 Docker 凭据而创建的 Secret 的名称。
  8. 检查作业状态:

    kubectl get jobs/ocr-test-job-apikey
    # It will show 0/1 completions, then 1/1 after it succeeds
    
  9. 作业完成后,您可以在 pod 日志中查看 OCR 输出:

    kubectl logs -l job-name=ocr-test-job-apikey