Google Gloud Vision API - Return Output as JSON Object rather than to a GCS file

Viewed 541

I am utilising the Cloud Vision API "PDF to Text" function for a Node.js app. I have mostly stuck close to the GCP docs example, with a couple of tweaks here and there: https://cloud.google.com/vision/docs/pdf

All works fine, however I would like the contents of the file to be returned to me as a JSON object so I can pass it into another funciton, rather than its current behaviour of writing the contents to a JSON file and storing it on Cloud Storage.

Does anyone know how I need to structure the outputConfig object in order to achieve this?

async function detectPdfText(bucketName, fileName) {
    // Imports the Google Cloud client libraries
    const vision = require('@google-cloud/vision').v1;

    // Creates a client
    const client = new vision.ImageAnnotatorClient({
        keyFilename: './APIKey.json'
    });

    // The directory to store the results
    const outputPrefix = 'json_output'

    const gcsSourceUri = `gs://${bucketName}/${fileName}`;
    const gcsDestinationUri = `gs://${bucketName}/${outputPrefix}/`;

    const inputConfig = {
        // Supported mime_types are: 'application/pdf' and 'image/tiff'
        mimeType: 'application/pdf',
        gcsSource: {
            uri: gcsSourceUri,
        },
    };
    const outputConfig = {
        gcsDestination: {
            uri: gcsDestinationUri,
        },
    };
    const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];
    const request = {
    requests: [
        {
            inputConfig: inputConfig,
            features: features,
            outputConfig: outputConfig,
        },
    ],
    };

    const [operation] = await client.asyncBatchAnnotateFiles(request);
    const [filesResponse] = await operation.promise();
    const destinationUri =
        filesResponse.responses[0].outputConfig.gcsDestination.uri;
    console.log(`Json output for file ${fileName} has been saved to: ${destinationUri}`);
}

module.exports = { detectPdfText };
1 Answers

You are using asyncBatchAnnotateFiles, which only writes the output to GCS: https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#outputconfig . There is no option to return the result of the LRO in the GetOperation call.

You could instead use batchAnnotateFiles and get the results synchronously, then convert to json.

If you have to use asyncBatchAnnotateFiles, then you would have to download the GCS file after the LRO finishes.

Related