Invia una richiesta di elaborazione

Dopo aver configurato il tuo Google Cloud account e creato un processore, puoi inviare una richiesta al tuo processore Document AI.

Il codice utilizzato per inviare la richiesta è uguale per tutti i processori. Vedi differenze nel funzionamento del processore nelle informazioni che ogni processore produce.

Se utilizzi la versione v1API di Document AI o la console Google Cloud , puoi inviare richieste di elaborazione a quella versione specifica del processore. Se non specifichi una versione del processore, viene utilizzata quella predefinita. Per saperne di più, consulta Gestione delle versioni del processore.

Elaborazione online

Le richieste online (sincrone) ti consentono di inviare un singolo documento per l'elaborazione. Document AI elabora immediatamente la richiesta e restituisce un document.

Inviare una richiesta a un responsabile del trattamento

I seguenti esempi di codice mostrano come inviare una richiesta a un processore.

REST

Questo esempio mostra come fornire i contenuti del documento (contenuti grezzi del documento in byte tramite una stringa con codifica base64) nell'oggetto rawDocument.

In alternativa, puoi anche specificare inlineDocument, che è lo stesso formato JSON Document restituito da Document AI. Ciò ti consente di concatenare le richieste passando avanti e indietro lo stesso formato (ad esempio, se classifichi un documento e poi ne estrai il contenuto).

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • LOCATION: la posizione del tuo processore, ad esempio:
    • us - Stati Uniti
    • eu - Unione Europea
  • PROJECT_ID: l'ID progetto Google Cloud .
  • PROCESSOR_ID: l'ID del tuo processore personalizzato.
  • skipHumanReview: Un valore booleano per disattivare la revisione umana (supportato solo dai processori Human-in-the-Loop).
    • true - skips human review
    • false: attiva la revisione da parte di persone fisiche (impostazione predefinita)
  • MIME_TYPE: una delle opzioni valide per il tipo MIME.
  • IMAGE_CONTENT: uno dei contenuti validi del documento in linea, rappresentati come un flusso di byte. Per le rappresentazioni JSON, la codifica base64 (stringa ASCII) dei dati immagine binari. Questa stringa dovrebbe essere simile alla seguente:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    Per ulteriori informazioni, consulta l'argomento Codifica Base64.
  • FIELD_MASK: specifica quali campi includere nell'output Document. Si tratta di un elenco separato da virgole di nomi completi dei campi nel formato FieldMask.
    • Esempio: text,entities,pages.pageNumber
  • INDIVIDUAL_PAGES: un elenco di singole pagine da elaborare.
    • In alternativa, fornisci il campo fromStart o fromEnd per elaborare una quantità specifica di pagine dall'inizio o dalla fine del documento.

† Questi contenuti possono essere specificati anche utilizzando contenuti codificati in base64 nell'oggetto inlineDocument.

Metodo HTTP e URL:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process

Corpo JSON della richiesta:

{
  "skipHumanReview": skipHumanReview,
  "rawDocument": {
    "mimeType": "MIME_TYPE",
    "content": "IMAGE_CONTENT"
  },
  "fieldMask": "FIELD_MASK",
  "processOptions": {
    "individualPageSelector" {
      "pages": [INDIVIDUAL_PAGES]
    }
  }
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process" | Select-Object -Expand Content

Se la richiesta riesce, il server restituisce un codice di stato HTTP 200 OK e la risposta in formato JSON. Il corpo della risposta contiene un'istanza di Document.

Inviare una richiesta a una versione del processore

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • LOCATION: la posizione del tuo processore, ad esempio:
    • us - Stati Uniti
    • eu - Unione Europea
  • PROJECT_ID: l'ID progetto Google Cloud .
  • PROCESSOR_ID: l'ID del tuo processore personalizzato.
  • PROCESSOR_VERSION: l'identificatore della versione del processore. Per saperne di più, consulta Selezionare una versione del processore. Ad esempio:
    • pretrained-TYPE-vX.X-YYYY-MM-DD
    • stable
    • rc
  • skipHumanReview: Un valore booleano per disattivare la revisione umana (supportato solo dai processori Human-in-the-Loop).
    • true - salta la revisione umana
    • false: attiva la revisione da parte di persone fisiche (impostazione predefinita)
  • MIME_TYPE: una delle opzioni valide per il tipo MIME.
  • IMAGE_CONTENT: uno dei contenuti validi del documento in linea, rappresentati come un flusso di byte. Per le rappresentazioni JSON, la codifica base64 (stringa ASCII) dei dati immagine binari. Questa stringa dovrebbe essere simile alla seguente:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    Per ulteriori informazioni, consulta l'argomento Codifica Base64.
  • FIELD_MASK: specifica quali campi includere nell'output Document. Si tratta di un elenco separato da virgole di nomi completi dei campi nel formato FieldMask.
    • Esempio: text,entities,pages.pageNumber

† Questi contenuti possono essere specificati anche utilizzando contenuti codificati in base64 nell'oggetto inlineDocument.

Metodo HTTP e URL:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process

Corpo JSON della richiesta:

{
  "skipHumanReview": skipHumanReview,
  "rawDocument": {
    "mimeType": "MIME_TYPE",
    "content": "IMAGE_CONTENT"
  },
  "fieldMask": "FIELD_MASK"
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process" | Select-Object -Expand Content

Se la richiesta riesce, il server restituisce un codice di stato HTTP 200 OK e la risposta in formato JSON. Il corpo della risposta contiene un'istanza di Document.

C#

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI C#.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


using Google.Cloud.DocumentAI.V1;
using Google.Protobuf;
using System;
using System.IO;

public class QuickstartSample
{
    public Document Quickstart(
        string projectId = "your-project-id",
        string locationId = "your-processor-location",
        string processorId = "your-processor-id",
        string localPath = "my-local-path/my-file-name",
        string mimeType = "application/pdf"
    )
    {
        // Create client
        var client = new DocumentProcessorServiceClientBuilder
        {
            Endpoint = $"{locationId}-documentai.googleapis.com"
        }.Build();

        // Read in local file
        using var fileStream = File.OpenRead(localPath);
        var rawDocument = new RawDocument
        {
            Content = ByteString.FromStream(fileStream),
            MimeType = mimeType
        };

        // Initialize request argument(s)
        var request = new ProcessRequest
        {
            Name = ProcessorName.FromProjectLocationProcessor(projectId, locationId, processorId).ToString(),
            RawDocument = rawDocument
        };

        // Make the request
        var response = client.ProcessDocument(request);

        var document = response.Document;
        Console.WriteLine(document.Text);
        return document;
    }
}

Java

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Java.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.ProcessRequest;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.cloud.documentai.v1.RawDocument;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ProcessDocument {
  public static void processDocument()
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-project-location"; // Format is "us" or "eu".
    String processerId = "your-processor-id";
    String filePath = "path/to/input/file.pdf";
    processDocument(projectId, location, processerId, filePath);
  }

  public static void processDocument(
      String projectId, String location, String processorId, String filePath)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // 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.
    String endpoint = String.format("%s-documentai.googleapis.com:443", location);
    DocumentProcessorServiceSettings settings =
        DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();
    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      // The full resource name of the processor, e.g.:
      // projects/project-id/locations/location/processor/processor-id
      // You must create new processors in the Cloud Console first
      String name =
          String.format("projects/%s/locations/%s/processors/%s", projectId, location, processorId);

      // Read the file.
      byte[] imageFileData = Files.readAllBytes(Paths.get(filePath));

      // Convert the image data to a Buffer and base64 encode it.
      ByteString content = ByteString.copyFrom(imageFileData);

      RawDocument document =
          RawDocument.newBuilder().setContent(content).setMimeType("application/pdf").build();

      // Configure the process request.
      ProcessRequest request =
          ProcessRequest.newBuilder().setName(name).setRawDocument(document).build();

      // Recognizes text entities in the PDF document
      ProcessResponse result = client.processDocument(request);
      Document documentResponse = result.getDocument();

      // Get all of the document text as one big string
      String text = documentResponse.getText();

      // Read the text recognition output from the processor
      System.out.println("The document contains the following paragraphs:");
      Document.Page firstPage = documentResponse.getPages(0);
      List<Document.Page.Paragraph> paragraphs = firstPage.getParagraphsList();

      for (Document.Page.Paragraph paragraph : paragraphs) {
        String paragraphText = getText(paragraph.getLayout().getTextAnchor(), text);
        System.out.printf("Paragraph text:\n%s\n", paragraphText);
      }

      // Form parsing provides additional output about
      // form-formatted PDFs. You must create a form
      // processor in the Cloud Console to see full field details.
      System.out.println("The following form key/value pairs were detected:");

      for (Document.Page.FormField field : firstPage.getFormFieldsList()) {
        String fieldName = getText(field.getFieldName().getTextAnchor(), text);
        String fieldValue = getText(field.getFieldValue().getTextAnchor(), text);

        System.out.println("Extracted form fields pair:");
        System.out.printf("\t(%s, %s))\n", fieldName, fieldValue);
      }
    }
  }

  // Extract shards from the text field
  private static String getText(Document.TextAnchor textAnchor, String text) {
    if (textAnchor.getTextSegmentsList().size() > 0) {
      int startIdx = (int) textAnchor.getTextSegments(0).getStartIndex();
      int endIdx = (int) textAnchor.getTextSegments(0).getEndIndex();
      return text.substring(startIdx, endIdx);
    }
    return "[NO TEXT]";
  }
}

Node.js

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Node.js.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
// const processorId = 'YOUR_PROCESSOR_ID'; // Create processor in Cloud Console
// const filePath = '/path/to/local/pdf';

const {DocumentProcessorServiceClient} =
  require('@google-cloud/documentai').v1;

// Instantiates a client
const client = new DocumentProcessorServiceClient();

async function processDocument() {
  // The full resource name of the processor, e.g.:
  // projects/project-id/locations/location/processor/processor-id
  // You must create new processors in the Cloud Console first
  const name = `projects/${projectId}/locations/${location}/processors/${processorId}`;

  // Read the file into memory.
  const fs = require('fs').promises;
  const imageFile = await fs.readFile(filePath);

  // Convert the image data to a Buffer and base64 encode it.
  const encodedImage = Buffer.from(imageFile).toString('base64');

  const request = {
    name,
    rawDocument: {
      content: encodedImage,
      mimeType: 'application/pdf',
    },
  };

  // Recognizes text entities in the PDF document
  const [result] = await client.processDocument(request);
  const {document} = result;

  // Get all of the document text as one big string
  const {text} = document;

  // Extract shards from the text field
  const getText = textAnchor => {
    if (!textAnchor.textSegments || textAnchor.textSegments.length === 0) {
      return '';
    }

    // First shard in document doesn't have startIndex property
    const startIndex = textAnchor.textSegments[0].startIndex || 0;
    const endIndex = textAnchor.textSegments[0].endIndex;

    return text.substring(startIndex, endIndex);
  };

  // Read the text recognition output from the processor
  console.log('The document contains the following paragraphs:');
  const