光学式文字認識(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. シークレットを作成する。
    3. イメージを HaaS にアップロードします。
  5. ユーザー クラスタにログインし、ユーザー ID を使用して 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 を含む gcp-api-key-secret という名前のシークレットを作成します。

  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 インスタンスの URL。
    • HARBOR_PROJECT: Harbor プロジェクト。
    • SECRET: Docker 認証情報を保存するために作成されたシークレットの名前。
  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