我已经为我的Java Web应用程序设置并运行了一个带有Linux实例的Amazon EC2来使用REST请求。问题是我正在尝试在此应用程序中使用Google Cloud Vision识别用户图片中的暴力/裸露。
在我的终端中访问EC2,我通过以下命令设置了GOOGLE_APPLICATION_CREDENTIALS,我在文档中找到了这个命令:
export GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
这是我的第一个问题:当我重新启动服务器并运行'echo $ GOOGLE_APPLICATION_CREDENTIALS'时,变量就消失了。好吧,我将它设置为bash_profile和bashrc,现在没问题。
但是,当我运行我的应用程序,使用上面的代码,以获得我的图片的成人和暴力状态时,我收到以下错误:
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.
我的代码如下:
控制器:
if(SafeSearchDetection.isSafe(user.getId())) {
if(UserDB.updateUserProfile(user)==false){
throw new SQLException("Failed to Update");
}
} else {
throw new IOException("Explicit Content");
}
SafeSearchDetection.isSafe(int idUser):
String path = IMAGES_PATH + idUser + ".jpg";
try {
mAdultMedicalViolence = detectSafeSearch(path);
if(mAdultMedicalViolence.get(0) > 3)
return false;
else if(mAdultMedicalViolence.get(1) > 3)
return false;
else if(mAdultMedicalViolence.get(2) > 3)
return false;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
detectSafeSearch(字符串路径):
List<AnnotateImageRequest> requests = new ArrayList<AnnotateImageRequest>();
ArrayList<Integer> adultMedicalViolence = new ArrayList<Integer>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(path));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
ImageAnnotatorClient client = ImageAnnotatorClient.create();
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.println("Error: "+res.getError().getMessage()+"\n");
return null;
}
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
adultMedicalViolence.add(annotation.getAdultValue());
adultMedicalViolence.add(annotation.getMedicalValue());
adultMedicalViolence.add(annotation.getViolenceValue());
}
for(int content : adultMedicalViolence)
System.out.println(content + "\n");
return adultMedicalViolence;
答案 0 :(得分:0)
我的REST应用程序是在Tomcat8之上构建的。运行命令后没有成功:
System.getenv("GOOGLE_APPLICATION_CREDENTIALS")
我意识到我的问题出在Tomcat安装的环境变量中。为了解决这个问题,我刚在/ bin中创建了一个新文件setenv.sh,内容为:
GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
它有效!