Cloud Vision API 的光學字元辨識 (OCR) 功能可讓您從圖片中擷取印刷和手寫文字。在本教學課程中,您會將對圖片執行 OCR 的 Python 用戶端容器化,並在 Google Distributed Cloud (GDC) 沙箱中部署為工作。
如要執行這項工作負載,您必須具備已啟用 Cloud Vision API 的有效 Google Cloud 專案、有效的 API 金鑰,以及 GDC 沙箱執行個體和 Harbor Container Registry 的存取權。在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱「使用 Vertex AI」和 Vertex AI Python API 參考文件。
建立 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」
- 將
建立 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"]建構翻譯應用程式的 Docker 映像檔:
docker build -t ocr-app .請按照「設定 Docker」中的指示操作,完成下列事項:
- 設定 Docker
- 建立密鑰,
- 將圖片上傳至 HaaS。
登入使用者叢集,並使用使用者身分產生其 kubeconfig 檔案。請務必將 kubeconfig 路徑設為環境變數:
export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}在終端機執行下列指令,並貼上 API 金鑰,建立 Kubernetes 密鑰:
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。套用 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 名稱。
查看工作狀態:
kubectl get jobs/ocr-test-job-apikey # It will show 0/1 completions, then 1/1 after it succeeds工作完成後,您可以在 Pod 記錄中查看 OCR 輸出內容:
kubectl logs -l job-name=ocr-test-job-apikey