Google Vision API: Buckets ничего не возвращает, и в ImageAnnotatorClient появляется ошибка - PullRequest
0 голосов
/ 25 февраля 2019

У меня есть этот код для Google Vision API.У меня есть учетные данные Google в качестве пути, а также в качестве переменной среды, но Page<Bucket> buckets = storage.list(); ничего не возвращает и появляется ошибка try (ImageAnnotatorClient client = ImageAnnotatorClient.create())

Вот код:

 public static void main(String... args) throws Exception {
        authExplicit("D:\\bp-mihalova\\2\\apikey.json");
        detectLabels("D:\\bp-mihalova\\2\\Jellyfish.jpg", System.out);
    }

    public static void detectLabels(String filePath, PrintStream out) throws Exception, IOException {
        List<AnnotateImageRequest> requests = new ArrayList<>();

        ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));

        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
        AnnotateImageRequest request =
                AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
        requests.add(request);

        try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
            BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = response.getResponsesList();

            for (AnnotateImageResponse res : responses) {
                if (res.hasError()) {
                    out.printf("Error: %s\n", res.getError().getMessage());
                    return;
                }

                // For full list of available annotations, see http://g.co/cloud/vision/docs
                for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                    annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString()));
                }
            }
        }
    }

    static void authExplicit(String jsonPath) throws IOException {
        // You can specify a credential file by providing a path to GoogleCredentials.
        // Otherwise credentials are read from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
        GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
                .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
        Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

        System.out.println("Buckets:");
        Page<Bucket> buckets = storage.list();
        for (Bucket bucket : buckets.iterateAll()) {
            System.out.println(bucket.toString());
        }
    }

А вот консоль спусто Buckets и ошибка:

Buckets:
Exception in thread "main" java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
    at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:132)
    at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:127)
    at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:100)
    at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:59)
    at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:132)
    at com.google.cloud.vision.v1.stub.GrpcImageAnnotatorStub.create(GrpcImageAnnotatorStub.java:84)
    at com.google.cloud.vision.v1.stub.ImageAnnotatorStubSettings.createStub(ImageAnnotatorStubSettings.java:120)
    at com.google.cloud.vision.v1.ImageAnnotatorClient.<init>(ImageAnnotatorClient.java:136)
    at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:117)
    at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:108)
    at sk.Google.detectLabels(Google.java:40)
    at sk.Google.main(Google.java:26)

Process finished with exit code 1

1 Ответ

0 голосов
/ 26 февраля 2019

Эта ошибка возникает из-за того, что ImageAnnotatorClient client = ImageAnnotatorClient.create() ожидает учетные данные по умолчанию или учетную запись службы, заданную в переменной среды.

Я успешно выполнил запрос со следующим кодом:

package com.example.vision;

import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.PrintStream;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import com.google.api.gax.core.FixedCredentialsProvider;

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Sample {
 public static void main(String...args) throws Exception {
  String jsonPath = "../../key.json";
  authExplicit(jsonPath);
  detectLabels(jsonPath, "../wakeupcat.jpg", System.out);
 }
 static void authExplicit(String jsonPath) throws IOException {
  GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
   .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
  Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

  System.out.println("Buckets:");
  Page < Bucket > buckets = storage.list();
  for (Bucket bucket: buckets.iterateAll()) {
   System.out.println(bucket.toString());
  }
 }
 public static void detectLabels(String jsonPath, String filePath, PrintStream out) throws Exception, IOException {
  GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
   .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
  List < AnnotateImageRequest > requests = new ArrayList < > ();

  ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));

  Image img = Image.newBuilder().setContent(imgBytes).build();
  Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
  AnnotateImageRequest request =
   AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
  requests.add(request);
//Setting the credentials:
  ImageAnnotatorSettings imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
   .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
   .build();
  try (ImageAnnotatorClient client = ImageAnnotatorClient.create(imageAnnotatorSettings)) {
   BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
   List < AnnotateImageResponse > responses = response.getResponsesList();

   for (AnnotateImageResponse res: responses) {
    if (res.hasError()) {
     out.printf("Error: %s\n", res.getError().getMessage());
     return;
    }

    // For full list of available annotations, see http://g.co/cloud/vision/docs
    for (EntityAnnotation annotation: res.getLabelAnnotationsList()) {
     annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString()));
    }
   }
  }
 }
}
...