איך מנסים את זיהוי התווים האופטי (OCR)

זיהוי תווים אופטי (OCR) באמצעות Cloud Vision API מאפשר לחלץ טקסט מודפס וכתוב בכתב יד מתמונות. במדריך הזה תכניסו לקונטיינר לקוח Python שמריץ OCR על תמונה, ותפרסו אותו כמשימה בארגז החול של Google Distributed Cloud (GDC).

כדי להריץ את עומס העבודה הזה, צריך פרויקט פעיל ב- Google Cloud עם Cloud Vision API מופעל, מפתח API תקין וגישה למכונה של GDC Sandbox ול-Container Registry ב-Harbor. לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך התחלה מהירה: שימוש בספריות לקוח ב-Vertex AI. מידע נוסף מופיע במאמר שימוש ב-Vertex AI ובמאמרי העזרה של ה-API בשפת Python של Vertex AI.

  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". לחלופין, אפשר לציין URI של Cloud Storage, לדוגמה, "gs://your-bucket/your-image.png"
  2. יוצרים קובץ Docker:

    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. נכנסים לאשכול המשתמש ויוצרים את קובץ ה-kubeconfig שלו עם זהות משתמש. חשוב לוודא שהגדרתם את הנתיב של kubeconfig כמשתנה סביבה:

    export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}
    
  6. כדי ליצור סוד של Kubernetes, מריצים את הפקודה הבאה בטרמינל ומדביקים את מפתח ה-API:

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

    הפקודה הזו יוצרת סוד בשם gcp-api-key-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: כתובת ה-URL של המכונה של Harbor.
    • ‫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. אחרי שהמשימה מסתיימת, אפשר לראות את פלט ה-OCR ביומני ה-pod:

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