הוספת הערות לקובץ אצווה במצב אופליין

‫Vision API יכול לזהות כל תכונה של Vision API מקובצי PDF ו-TIFF שמאוחסנים ב-Cloud Storage.

כדי לבקש זיהוי תכונות מקובצי PDF ו-TIFF, צריך להשתמש בפונקציה files:asyncBatchAnnotate, שמבצעת בקשה אופליין (אסינכרונית) ומספקת את הסטטוס שלה באמצעות משאבי operations.

הפלט מבקשת PDF/TIFF נכתב לקובץ JSON שנוצר בקטגוריה של Cloud Storage שצוינה.

מגבלות

‫Vision API מקבל קובצי PDF או TIFF של עד 2,000 דפים. קבצים גדולים יותר יחזירו שגיאה.

אימות

אין תמיכה במפתחות API לבקשות files:asyncBatchAnnotate. הוראות לאימות באמצעות חשבון שירות מופיעות במאמר שימוש בחשבון שירות.

לחשבון שמשמש לאימות צריכה להיות גישה לקטגוריית Cloud Storage שציינתם לפלט (roles/editor או roles/storage.objectCreator ומעלה).

אפשר להשתמש במפתח API כדי לשלוח שאילתה לגבי סטטוס הפעולה. הוראות מפורטות זמינות במאמר שימוש במפתח API.

בקשות לזיהוי תכונות

כרגע, זיהוי מסמכי PDF/TIFF זמין רק לקבצים שמאוחסנים בקטגוריות של Cloud Storage. קובצי JSON של תגובות נשמרים באופן דומה בקטגוריה של Cloud Storage.

שורת פקודה

כדי לבצע זיהוי טקסט במסמך PDF או TIFF, שולחים בקשת POST ומספקים את גוף הבקשה המתאים:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://vision.googleapis.com/v1/files:asyncBatchAnnotate -d "{
  'requests':[
    {
      'inputConfig': {
        'gcsSource': {
          'uri': 'gs://your-source-bucket-name/folder/multi-page-file.pdf'
        },
        'mimeType': 'application/pdf'
      },
      'features': [
        {
          'type': 'DOCUMENT_TEXT_DETECTION'
        }
      ],
      'outputConfig': {
        'gcsDestination': {
          'uri': 'gs://your-bucket-name/folder/'
        },
        'batchSize': 1
      }
    }
  ]
}"

כאשר:

  • inputConfig – מחליף את השדה image שמשמש בבקשות אחרות של Vision API. הוא מכיל שני שדות צאצא:

    • gcsSource.uri – ה-URI של Cloud Storage של קובץ ה-PDF או ה-TIFF (שהמשתמש או חשבון השירות ששולחים את הבקשה יכולים לגשת אליו)
    • mimeType – אחד מסוגי הקבצים המקובלים: application/pdf או image/tiff.
  • outputConfig – מציין את פרטי הפלט. הוא מכיל שני שדות צאצא:

    • gcsDestination.uri – URI תקין של Cloud Storage. למשתמש או לחשבון השירות שמבצעים את הבקשה צריכה להיות הרשאת כתיבה בקטגוריה. שם הקובץ יהיה output-x-to-y, כאשר x ו-y מייצגים את מספרי הדפים ב-PDF או ב-TIFF שכלולים בקובץ הפלט הזה. אם הקובץ קיים, התוכן שלו יוחלף.
    • batchSize – מציין כמה דפים של פלט צריך לכלול בכל קובץ JSON של פלט.

תשובה:

בקשת asyncBatchAnnotate מוצלחת מחזירה תגובה עם שדה שם יחיד:

{
  "name": "projects/usable-auth-library/operations/1efec2285bd442df"
}

השם הזה מייצג פעולה ממושכת עם מזהה משויך (לדוגמה, 1efec2285bd442df), שאפשר לשלוח לגביו שאילתה באמצעות v1.operations API.

כדי לאחזר את תגובת ההערה של Vision, שולחים בקשת GET לנקודת הקצה (endpoint) v1.operations ומעבירים את מזהה הפעולה בכתובת ה-URL.

curl -X GET -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/operations/1efec2285bd442df

אם הפעולה מתבצעת:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "RUNNING",
    "createTime": "2019-05-15T21:10:08.401917049Z",
    "updateTime": "2019-05-15T21:10:33.700763554Z"
  }
}

בסיום הפעולה, הסמל state משתנה ל-DONE והתוצאות נכתבות לקובץ Cloud Storage שציינתם:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "DONE",
    "createTime": "2019-05-15T20:56:30.622473785Z",
    "updateTime": "2019-05-15T20:56:41.666379749Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse",
    "responses": [
      {
        "outputConfig": {
          "gcsDestination": {
            "uri": "gs://your-bucket-name/folder/"
          },
          "batchSize": 1
        }
      }
    ]
  }
}

ה-JSON בקובץ הפלט דומה ל-JSON של בקשה לזיהוי טקסט במסמך של תמונה, עם התוספת של השדה context שמציג את המיקום של קובץ ה-PDF או ה-TIFF שצוין ואת מספר הדפים בקובץ:

output-1-to-1.json

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Go API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// detectAsyncDocumentURI performs Optical Character Recognition (OCR) on a
// PDF file stored in GCS.
func detectAsyncDocumentURI(w io.Writer, gcsSourceURI, gcsDestinationURI string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	request := &visionpb.AsyncBatchAnnotateFilesRequest{
		Requests: []*visionpb.AsyncAnnotateFileRequest{
			{
				Features: []*visionpb.Feature{
					{
						Type: visionpb.Feature_DOCUMENT_TEXT_DETECTION,
					},
				},
				InputConfig: &visionpb.InputConfig{
					GcsSource: &visionpb.GcsSource{Uri: gcsSourceURI},
					// Supported MimeTypes are: "application/pdf" and "image/tiff".
					MimeType: "application/pdf",
				},
				OutputConfig: &visionpb.OutputConfig{
					GcsDestination: &visionpb.GcsDestination{Uri: gcsDestinationURI},
					// How many pages should be grouped into each json output file.
					BatchSize: 2,
				},
			},
		},
	}

	operation, err := client.AsyncBatchAnnotateFiles(ctx, request)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Waiting for the operation to finish.")

	resp, err := operation.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "%v", resp)

	return nil
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Java API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage.
 *
 * @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document
 *     text on.
 * @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the
 *     results on.
 * @throws Exception on errors while closing the client.
 */
public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath)
    throws Exception {

  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
    List<AsyncAnnotateFileRequest> requests = new ArrayList<>();

    // Set the GCS source path for the remote file.
    GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsSourcePath).build();

    // Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions)
    // types
    InputConfig inputConfig =
        InputConfig.newBuilder()
            .setMimeType(
                "application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff"
            .setGcsSource(gcsSource)
            .build();

    // Set the GCS destination path for where to save the results.
    GcsDestination gcsDestination =
        GcsDestination.newBuilder().setUri(gcsDestinationPath).build();

    // Create the configuration for the System.output with the batch size.
    // The batch size sets how many pages should be grouped into each json System.output file.
    OutputConfig outputConfig =
        OutputConfig.newBuilder().setBatchSize(2).setGcsDestination(gcsDestination).build();

    // Select the Feature required by the vision API
    Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();

    // Build the OCR request
    AsyncAnnotateFileRequest request =
        AsyncAnnotateFileRequest.newBuilder()
            .addFeatures(feature)
            .setInputConfig(inputConfig)
            .setOutputConfig(outputConfig)
            .build