繁体   English   中英

如何定义 GOOGLE_APPLICATION_CREDENTIALS?

[英]How to define GOOGLE_APPLICATION_CREDENTIALS?

我的目标是使用其中一个谷歌云 API,为此我需要将 GOOGLE_APPLICATION_CREDENTIALS 设置为 a.json 文件。

我收到此错误消息和有关如何解决它的链接:

应用程序默认凭据不可用。 如果在 Google Compute Engine 中运行,它们就可用。 否则,必须定义环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向定义凭据的文件。 有关详细信息,请参阅https://developers.google.com/accounts/docs/application-default-credentials

通过 cmd ( set GOOGLE_APPLICATION_CREDENTIALS=C:\...\...\File.json )将变量设置为 .json 文件后,我刚刚创建的完全相同的错误继续出现。

我究竟做错了什么?


编辑:

我正在使用 Eclipse JEE。 我想使用谷歌云视觉 API 从本地图像中检测 web 实体。 首先使用 html 公式我请求图像并将其发送到 servlet class: (index.html)

<!DOCTYPE html> 
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Tittle</title>
  </head>
  <body>
    <h1>Welcome!</h1>
    <h4>Upload an image: </h4>
    <div id="searchDiv">
        <form id="searchForm" action="webdetection" method="get" enctype="multipart/form-data">
            <div><input type="file" name="image" accept=".JPG, .JPEG, .PNG8, .PNG24, .GIF, .BMP, .WEBP, .RAW, .ICO, .PDF, .TIFF" required>
            </div>
            <div><input type="submit" name="searchBtn" value="Aceptar">
            </div>
        </form>
    </div>
  </body>
</html>

这些是 servlets 及其映射:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <servlet>
        <web:description></web:description>
        <servlet-name>Web Detection</servlet-name>
        <servlet-class>aiss.controller.google_vision.VisionServletController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Web Detection</servlet-name>
        <url-pattern>/webdetection</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

这是云视觉的 Servlet:

package aiss.controller.google_vision;

import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import aiss.model.CloudVision.DeteccionWeb;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;

public class VisionServletController extends HttpServlet {
    
    private static final Logger log = Logger.getLogger(VisionServletController.class.getName());
    
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        
        log.log(Level.FINE, "Processing GET request");
        PrintStream ps = new PrintStream(resp.getOutputStream());
        try {
        resp.setContentType("text/plain");
        DeteccionWeb.detectWebDetectionsGcs(req.getRequestURL().toString(),ps);
        }catch(Exception e) {
            ps.println(e.toString());//this prints the previous error message I show
        }

    }
}

以及 servlet 重定向的 web 检测 class :(大部分导入没有被使用,但由于 class 正在修改,直到它工作,我不知道哪些类需要)

package aiss.model.CloudVision;

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.AnnotateFileResponse;
import com.google.cloud.vision.v1.AnnotateFileResponse.Builder;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.AsyncAnnotateFileRequest;
import com.google.cloud.vision.v1.AsyncAnnotateFileResponse;
import com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Block;
import com.google.cloud.vision.v1.ColorInfo;
import com.google.cloud.vision.v1.CropHint;
import com.google.cloud.vision.v1.CropHintsAnnotation;
import com.google.cloud.vision.v1.DominantColorsAnnotation;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.FaceAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.GcsDestination;
import com.google.cloud.vision.v1.GcsSource;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageContext;
import com.google.cloud.vision.v1.ImageSource;
import com.google.cloud.vision.v1.InputConfig;
import com.google.cloud.vision.v1.LocalizedObjectAnnotation;
import com.google.cloud.vision.v1.LocationInfo;
import com.google.cloud.vision.v1.OperationMetadata;
import com.google.cloud.vision.v1.OutputConfig;
import com.google.cloud.vision.v1.Page;
import com.google.cloud.vision.v1.Paragraph;
import com.google.cloud.vision.v1.SafeSearchAnnotation;
import com.google.cloud.vision.v1.Symbol;
import com.google.cloud.vision.v1.TextAnnotation;
import com.google.cloud.vision.v1.WebDetection;
import com.google.cloud.vision.v1.WebDetection.WebEntity;
import com.google.cloud.vision.v1.WebDetection.WebImage;
import com.google.cloud.vision.v1.WebDetection.WebLabel;
import com.google.cloud.vision.v1.WebDetection.WebPage;
import com.google.cloud.vision.v1.WebDetectionParams;
import com.google.cloud.vision.v1.Word;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.JsonFormat;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DeteccionWeb {
    
    /**
     * Detects whether the remote image on Google Cloud Storage has features you would want to
     * moderate.
     *
     * @param gcsPath The path to the remote on Google Cloud Storage file to detect web annotations.
     * @param out A {@link PrintStream} to write the results to.
     * @throws Exception on errors while closing the client.
     * @throws IOException on Input/Output errors.
     */
    public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws Exception,
        IOException {
      List<AnnotateImageRequest> requests = new ArrayList<>();

      ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
      Image img = Image.newBuilder().setSource(imgSource).build();
      Feature feat = Feature.newBuilder().setType(Type.WEB_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;
          }

          // Search the web for usages of the image. You could use these signals later
          // for user input moderation or linking external references.
          // For a full list of available annotations, see http://g.co/cloud/vision/docs
          WebDetection annotation = res.getWebDetection();
          out.println("Entity:Id:Score");
          out.println("===============");
          for (WebEntity entity : annotation.getWebEntitiesList()) {
            out.println(entity.getDescription() + " : " + entity.getEntityId() + " : "
                + entity.getScore());
          }
          for (WebLabel label : annotation.getBestGuessLabelsList()) {
            out.format("\nBest guess label: %s", label.getLabel());
          }
        }
      }
    }
}

我的主要嫌疑人是ImageSource.newBuilder().setImageUri(gcsPath) ,因为看起来云视觉 API 可能不适用于不属于 Google 云存储的 http/https url。 似乎可以通过凭据解决,但我无法通过它。

如果您在 eclipse 中使用 Tomcat,以下线程应该会有所帮助How to set GOOGLE_APPLICATION_CREDENTIALS for Google Compute Engine? .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM