借助 Cloud Vision API 的光学字符识别 (OCR) 功能,您可以从图片中提取印刷文本和手写文本。在本教程中,您将容器化一个对图片运行 OCR 的 Python 客户端,并将其作为作业部署到 Google Distributed Cloud (GDC) Sandbox 中。
如需运行此工作负载,您需要一个已启用 Cloud Vision API 的有效 Google Cloud 项目、一个有效的 API 密钥,以及对 GDC Sandbox 实例和 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,
- 创建 Secret,以及
- 将映像上传到 HaaS。
登录用户集群,并使用用户身份生成其 kubeconfig 文件。请务必将 kubeconfig 路径设置为环境变量:
export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}在终端中运行以下命令,粘贴您的 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。应用 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