Search in sources :

Example 1 with AnnotateFileResponse

use of com.google.cloud.vision.v1.AnnotateFileResponse in project spring-cloud-gcp by spring-cloud.

the class OcrPageRange method parseJsonBlob.

private static List<TextAnnotation> parseJsonBlob(Blob blob) throws InvalidProtocolBufferException {
    AnnotateFileResponse.Builder annotateFileResponseBuilder = AnnotateFileResponse.newBuilder();
    String jsonContent = new String(blob.getContent());
    JsonFormat.parser().ignoringUnknownFields().merge(jsonContent, annotateFileResponseBuilder);
    AnnotateFileResponse annotateFileResponse = annotateFileResponseBuilder.build();
    return annotateFileResponse.getResponsesList().stream().map(AnnotateImageResponse::getFullTextAnnotation).collect(Collectors.toList());
}
Also used : AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse)

Example 2 with AnnotateFileResponse

use of com.google.cloud.vision.v1.AnnotateFileResponse in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method extractTextFromFile.

/**
 * Extract the text out of a file and return the result as a String.
 *
 * @param fileResource the file one wishes to analyze
 * @param mimeType the mime type of the fileResource. Currently, only "application/pdf",
 *     "image/tiff" and "image/gif" are supported.
 * @return the text extracted from the pdf as a string per page
 * @throws CloudVisionException if the image could not be read or if text extraction failed
 */
public List<String> extractTextFromFile(Resource fileResource, String mimeType) {
    AnnotateFileResponse response = analyzeFile(fileResource, mimeType, Type.DOCUMENT_TEXT_DETECTION);
    List<AnnotateImageResponse> annotateImageResponses = response.getResponsesList();
    if (annotateImageResponses.isEmpty()) {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
    List<String> result = annotateImageResponses.stream().map(annotateImageResponse -> annotateImageResponse.getFullTextAnnotation().getText()).collect(Collectors.toList());
    if (result.isEmpty() && response.getError().getCode() != Code.OK.getNumber()) {
        throw new CloudVisionException(response.getError().getMessage());
    }
    return result;
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ByteString(com.google.protobuf.ByteString)

Example 3 with AnnotateFileResponse

use of com.google.cloud.vision.v1.AnnotateFileResponse in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method analyzeFile.

/**
 * Analyze a file and extract the features of the image specified by {@code featureTypes}.
 *
 * <p>A feature describes the kind of Cloud Vision analysis one wishes to perform on a file, such
 * as text detection, image labelling, facial detection, etc. A full list of feature types can be
 * found in {@link Feature.Type}.
 *
 * @param fileResource the file one wishes to analyze. The Cloud Vision APIs support image formats
 *     described here: https://cloud.google.com/vision/docs/supported-files. Documents with more
 *     than 5 pages are not supported.
 * @param mimeType the mime type of the fileResource. Currently, only "application/pdf",
 *     "image/tiff" and "image/gif" are supported.
 * @param featureTypes the types of image analysis to perform on the image
 * @return the results of file analyse
 * @throws CloudVisionException if the file could not be read or if a malformed response is
 *     received from the Cloud Vision APIs
 */
public AnnotateFileResponse analyzeFile(Resource fileResource, String mimeType, Feature.Type... featureTypes) {
    ByteString imgBytes;
    try {
        imgBytes = ByteString.readFrom(fileResource.getInputStream());
    } catch (IOException ex) {
        throw new CloudVisionException(READ_BYTES_ERROR_MESSAGE, ex);
    }
    InputConfig inputConfig = InputConfig.newBuilder().setMimeType(mimeType).setContent(imgBytes).build();
    List<Feature> featureList = Arrays.stream(featureTypes).map(featureType -> Feature.newBuilder().setType(featureType).build()).collect(Collectors.toList());
    BatchAnnotateFilesRequest request = BatchAnnotateFilesRequest.newBuilder().addRequests(AnnotateFileRequest.newBuilder().addAllFeatures(featureList).setInputConfig(inputConfig).build()).build();
    BatchAnnotateFilesResponse response = this.imageAnnotatorClient.batchAnnotateFiles(request);
    List<AnnotateFileResponse> annotateFileResponses = response.getResponsesList();
    if (!annotateFileResponses.isEmpty()) {
        return annotateFileResponses.get(0);
    } else {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) ByteString(com.google.protobuf.ByteString) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) IOException(java.io.IOException) Feature(com.google.cloud.vision.v1.Feature)

Example 4 with AnnotateFileResponse

use of com.google.cloud.vision.v1.AnnotateFileResponse in project spring-cloud-gcp by GoogleCloudPlatform.

the class OcrPageRange method parseJsonBlob.

private static List<TextAnnotation> parseJsonBlob(Blob blob) throws InvalidProtocolBufferException {
    AnnotateFileResponse.Builder annotateFileResponseBuilder = AnnotateFileResponse.newBuilder();
    String jsonContent = new String(blob.getContent(), StandardCharsets.UTF_8);
    JsonFormat.parser().ignoringUnknownFields().merge(jsonContent, annotateFileResponseBuilder);
    AnnotateFileResponse annotateFileResponse = annotateFileResponseBuilder.build();
    return annotateFileResponse.getResponsesList().stream().map(AnnotateImageResponse::getFullTextAnnotation).collect(Collectors.toList());
}
Also used : AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse)

Example 5 with AnnotateFileResponse

use of com.google.cloud.vision.v1.AnnotateFileResponse in project java-vision by googleapis.

the class Detect method detectDocumentsGcs.

// [END vision_fulltext_detection_gcs]
// [START vision_text_detection_pdf_gcs]
/**
 * 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 {
    // 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(// Supported MimeTypes: "application/pdf", "image/tiff"
        "application/pdf").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();
        requests.add(request);
        // Perform the OCR request
        OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = client.asyncBatchAnnotateFilesAsync(requests);
        System.out.println("Waiting for the operation to finish.");
        // Wait for the request to finish. (The result is not used, since the API saves the result to
        // the specified location on GCS.)
        List<AsyncAnnotateFileResponse> result = response.get(180, TimeUnit.SECONDS).getResponsesList();
        // Once the request has completed and the System.output has been
        // written to GCS, we can list all the System.output files.
        Storage storage = StorageOptions.getDefaultInstance().getService();
        // Get the destination location from the gcsDestinationPath
        Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)");
        Matcher matcher = pattern.matcher(gcsDestinationPath);
        if (matcher.find()) {
            String bucketName = matcher.group(1);
            String prefix = matcher.group(2);
            // Get the list of objects with the given prefix from the GCS bucket
            Bucket bucket = storage.get(bucketName);
            com.google.api.gax.paging.Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix));
            Blob firstOutputFile = null;
            // List objects with the given prefix.
            System.out.println("Output files:");
            for (Blob blob : pageList.iterateAll()) {
                System.out.println(blob.getName());
                // the first two pages of the input file.
                if (firstOutputFile == null) {
                    firstOutputFile = blob;
                }
            }
            // Get the contents of the file and convert the JSON contents to an AnnotateFileResponse
            // object. If the Blob is small read all its content in one request
            // (Note: the file is a .json file)
            // Storage guide: https://cloud.google.com/storage/docs/downloading-objects
            String jsonContents = new String(firstOutputFile.getContent());
            Builder builder = AnnotateFileResponse.newBuilder();
            JsonFormat.parser().merge(jsonContents, builder);
            // Build the AnnotateFileResponse object
            AnnotateFileResponse annotateFileResponse = builder.build();
            // Parse through the object to get the actual response for the first page of the input file.
            AnnotateImageResponse annotateImageResponse = annotateFileResponse.getResponses(0);
            // Here we print the full text from the first page.
            // The response contains more information:
            // annotation/pages/blocks/paragraphs/words/symbols
            // including confidence score and bounding boxes
            System.out.format("%nText: %s%n", annotateImageResponse.getFullTextAnnotation().getText());
        } else {
            System.out.println("No MATCH");
        }
    }
}
Also used : GcsSource(com.google.cloud.vision.v1.GcsSource) Matcher(java.util.regex.Matcher) AsyncAnnotateFileResponse(com.google.cloud.vision.v1.AsyncAnnotateFileResponse) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Builder(com.google.cloud.vision.v1.AnnotateFileResponse.Builder) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) Feature(com.google.cloud.vision.v1.Feature) AsyncBatchAnnotateFilesResponse(com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) AsyncAnnotateFileResponse(com.google.cloud.vision.v1.AsyncAnnotateFileResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) OperationMetadata(com.google.cloud.vision.v1.OperationMetadata) Pattern(java.util.regex.Pattern) Blob(com.google.cloud.storage.Blob) OutputConfig(com.google.cloud.vision.v1.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) AsyncAnnotateFileRequest(com.google.cloud.vision.v1.AsyncAnnotateFileRequest) GcsDestination(com.google.cloud.vision.v1.GcsDestination)

Aggregations

AnnotateFileResponse (com.google.cloud.vision.v1.AnnotateFileResponse)5 ByteString (com.google.protobuf.ByteString)4 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)3 Feature (com.google.cloud.vision.v1.Feature)3 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)3 InputConfig (com.google.cloud.vision.v1.InputConfig)3 ArrayList (java.util.ArrayList)3 AnnotateFileRequest (com.google.cloud.vision.v1.AnnotateFileRequest)2 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)2 BatchAnnotateFilesRequest (com.google.cloud.vision.v1.BatchAnnotateFilesRequest)2 BatchAnnotateFilesResponse (com.google.cloud.vision.v1.BatchAnnotateFilesResponse)2 BatchAnnotateImagesRequest (com.google.cloud.vision.v1.BatchAnnotateImagesRequest)2 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)2 Type (com.google.cloud.vision.v1.Feature.Type)2 Image (com.google.cloud.vision.v1.Image)2 ImageContext (com.google.cloud.vision.v1.ImageContext)2 AnnotateFileRequest (com.google.cloud.vision.v1p4beta1.AnnotateFileRequest)2 AnnotateFileResponse (com.google.cloud.vision.v1p4beta1.AnnotateFileResponse)2 BatchAnnotateFilesRequest (com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest)2 BatchAnnotateFilesResponse (com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse)2