En esta guía se explica cómo realizar una prueba de reconocimiento óptico de caracteres (OCR) con el servicio Vertex AI Vision de Google.
Antes de probar este ejemplo, sigue las instrucciones de configuración de Python que se indican en la guía de inicio rápido de Vertex AI con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API de Python de Vertex AI.
Crea un archivo de Python
ocr_test.py. Sustituye el valorimage_uri_to_testpor el URI de una imagen de origen, como se muestra a continuación: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)Haz los cambios siguientes:
IMAGE_URIcon el URI de una imagen disponible públicamente que contenga texto. Por ejemplo, "https://cloud.google.com/vision/docs/images/sign.jpg". También puede especificar un URI de Cloud Storage. Por ejemplo, "gs://your-bucket/your-image.png".
Crea un 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"]Compila la imagen Docker de la aplicación de traducción:
docker build -t ocr-app .Sigue las instrucciones de Configurar Docker para hacer lo siguiente:
- Configurar Docker
- Crea un secreto y
- Sube la imagen a HaaS.
Inicia sesión en el clúster de usuarios y genera su archivo kubeconfig con una identidad de usuario. Asegúrate de definir la ruta de kubeconfig como variable de entorno:
export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}Crea un secreto de Kubernetes ejecutando el siguiente comando en tu terminal y pegando tu clave de API:
kubectl create secret generic gcp-api-key-secret \ --from-literal=GCP_API_KEY='PASTE_YOUR_API_KEY_HERE'Este comando crea un secreto llamado
gcp-api-key-secretcon una claveGCP_API_KEY.Aplica el manifiesto de 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: 4Haz los cambios siguientes:
HARBOR_INSTANCE_URL: la URL de la instancia de Harbor.HARBOR_PROJECT: el proyecto de Harbor.SECRET: el nombre del secreto creado para almacenar las credenciales de Docker.
Comprueba el estado del trabajo:
kubectl get jobs/ocr-test-job-apikey # It will show 0/1 completions, then 1/1 after it succeedsUna vez que se haya completado el trabajo, puedes ver el resultado del OCR en los registros del pod:
kubectl logs -l job-name=ocr-test-job-apikey